我正在尝试在我的django应用中实施google oauth2身份验证.我按照文档按照所有步骤操作.
在浏览器地址栏上,如果我浏览此https://foo.bar.net/api/v1/auth/login/google-oauth2/网址,它会通过谷歌正确验证并返回google-auth-token到提到的redirect-url,然后获取auth-token并将其转换为普通令牌,然后发送以json格式提供给用户或前端.
但是如果我试图从我的js代码向上面提到的URL发出GET请求,它会显示出来
Reason: CORS header 'Access-Control-Allow-Origin' missing
Run Code Online (Sandbox Code Playgroud)
前端的完整回溯看起来像,
GET https://foo.bar.net/api/v1/auth/login/google-oauth2/ 302 Found 718ms
polyfil...ndle.js (line 7507)
GET https://accounts.google.com/o/oauth2/auth?client_...DW&response_type=code&scope=openid+email+profile 200 OK
Login Failed Response { _body=Event error, status=0, ok=false, more...}
main.bundle.js (line 367)
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://accounts.google.com/o/oauth2/auth?client_id=kguygvh868697-khgkhvkgvkgkgv.apps.googleusercontent.com&redirect_uri=https://foo.bar.net/api/v1/auth/complete/google-oauth2/&state=Cbms1QhSQVzjO3xkjhkyuu&response_type=code&scope=openid+email+profile. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Run Code Online (Sandbox Code Playgroud)
我搜索了谷歌,它提示我安装djang-CORS-headers.我已经安装并配置了上面的包.但是出现了同样的错误.
我的一部分settings.py看起来像,
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
]
INSTALLED_APPS = [
'django.contrib.admin', …Run Code Online (Sandbox Code Playgroud) 尝试使用Google Strategy OAuth2将Vue + Axios应用程序与带有Passport的快速后端结合使用时遇到问题。
我的express服务器已打开,localhost:5000而vue-cli webpack开发服务器已打开localhost:3000。我正在使用webpack proxyTable选项代理从/api到的请求localhost:5000/api。据说它也处理cors。如果我在Vue应用程序中使用常规的超链接,如<a href="/api/auth/google">Auth with Google</a>,它会按预期工作,但是,如果我尝试使用axios,例如:
async authGoogle() {
const response = await axios.get('/api/auth/google')
console.log(response)
}
Run Code Online (Sandbox Code Playgroud)
我从Google api回调中收到此错误:
Failed to load https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fapi%2Fauth%2Fgoogle%2Fcallback&scope=profile%20email&client_id={client_id}:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)
这些是api路由:
app.get(
'/api/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
)
app.get(
'/api/auth/google/callback',
passport.authenticate('google'),
function(req, res) {
res.json({ success: true })
}
)
Run Code Online (Sandbox Code Playgroud)
在这种情况下如何使axios正常工作?
我使用服务帐户访问 Google 日历。这意味着不会提示日历所有者进行授权。
这在 Python 中工作得很好,我在其中使用特定的主体进行requests调用。https://accounts.google.com/o/oauth2/token这让我取回了一个稍后可以使用的令牌。
我现在需要在独立浏览器(Chrome - 无需用户交互)中运行一个应用程序,并尝试直接将此调用移植为
fetch('https://accounts.google.com/o/oauth2/token',
{
method: 'POST',
body: JSON.stringify(body),
})
.then(function(res) { return res.json(); })
.then(function(data) { alert(JSON.stringify(data)) })
Run Code Online (Sandbox Code Playgroud)
但我得到了谷歌的回复
无法加载https://accounts.google.com/o/oauth2/token:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问来源“ http://devd.io ”。响应的 HTTP 状态代码为 400。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
我对 CORS 的有限理解(之前的答案非常好读)是
请求的资源上不存在“Access-Control-Allow-Origin”标头
意味着它不存在于响应标头中,这意味着 Google 不希望我在从浏览器运行时通过 JS 访问其资源(它指向其他内容https://accounts.google.com)。
这可能是一个好主意,但我控制从代码到浏览器的所有元素,并且希望以与在非浏览器环境中获取令牌相同的方式获取该令牌,特别是我的工作 Python 代码。
我怎样才能告诉https://accounts.google.com我发回一个Access-Control-Allow-Origin标头,告诉我的浏览器可以接受呼叫?
我正在尝试使用 Google OAuth 身份验证设置 React/Redux - NodeJs Express 堆栈。我的问题是控制台中的 COR 错误。我发现了一些我认为正是我的问题的 Stack Overflow 问题,但解决方案没有产生任何结果。特别是这两个:CORS与谷歌的OAuth和CORS / CORB问题与之反应/节点/ Express和谷歌的OAuth。
因此,我尝试了各种修复方法,这些修复方法似乎都使我回到了相同的错误。这是其中最直接的:
const corsOptions = {
origin: 'http://localhost:3000',
optionsSuccessStatus: 200,
credentials: true
}
app.use(cors(corsOptions));
Run Code Online (Sandbox Code Playgroud)
这是在我的API.js文件的根目录中。我收到的控制台错误状态:
访问 XMLHttpRequest ' https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fapi%2Foauth%2Fgoogle%2Freturn&scope=profile&client_id=PRIVATE_CLIENT_ID。 .googleusercontent.com '(重定向自 ' http://localhost:5000/api/oauth/google ')来自原点 'null' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 '请求的资源上存在 Access-Control-Allow-Origin 标头。
因此,如果我在开发工具中查看我的网络日志,我会查看我对 API 路径的请求,并查看我希望看到的内容:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: http://localhost:3000
Run Code Online (Sandbox Code Playgroud)
所以在我看来,我的问题不在于我的前后沟通。这让我相信这可能是 Passport 令牌验证的问题。以下是我的简化路线:
router.post('/oauth/google', passport.authenticate('googleVerification', {
scope: ['profile']
}), (req, res) => {
console.log('Passport has verified …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Spring security 进行 CORS。这是我的 WebSecurityConfigurerAdapter :
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.oauth2Login();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("*"));
configuration.setAllowedMethods(List.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 WebMvcCofigurer :
@EnableWebSecurity
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer
{
@Override
public void …Run Code Online (Sandbox Code Playgroud) 上下文
我正在使用Angular,Express和PassportJS 构建无状态应用程序,并希望使用他们的Google帐户对用户进行身份验证.在对用户进行身份验证后,我的目标是使用JWT令牌来拥有无状态应用程序.
角2侧
点击Google登录按钮后,我的服务中会执行以下代码:
login() {
return this.http.get('http://localhost:3000/api/auth/google');
}
Run Code Online (Sandbox Code Playgroud)
表达方面
在Express上,执行以下操作:
// This gets executed first after clicking the sign in using Google button.
router.get('/api/auth/google', passport.authenticate('google', {
session: false,
scope: ['profile', 'email']
}));
// Google sends me back here (callback).
passport.use(new GoogleStrategy({
clientID: 'omitted',
clientSecret: 'omitted',
callbackURL: '/api/auth/google/callback'
}, function (accessToken, refreshToken, profile, cb) {
// Here, I obtain the profile and create a JWT token which I send back to the user.
let jwtToken = generateToken(); …Run Code Online (Sandbox Code Playgroud) cors ×6
javascript ×3
passport.js ×3
express ×2
google-oauth ×2
node.js ×2
oauth-2.0 ×2
angular ×1
axios ×1
django ×1
google-api ×1
oauth ×1
python ×1
reactjs ×1
spring-boot ×1