当我尝试通过我的前端(vite React)通过google oauth2(passport + Nestjs)登录时,我遇到了CORS策略问题
==========问题描述==========
背景:
domain_name/:1 获取访问权限 'https://accounts.google.com/o/oauth2/v2/auth? [...]' (重定向自“https://domain_name/api/auth/google/login”)来自 来源“https://domain_name”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。如果不透明的响应满足您的需求,请设置请求的 模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
我很困惑,我不知道应该如何处理这种情况(如何通过后端代理请求?也许与前端以不同的方式处理请求?为什么nestjs的cors规则不能处理这个问题?...
==========问题总结==========
如何处理由于react和nestjs之间的passport google oauth2重定向而导致的CORS错误?
==========如何获取并运行代码==========
我的代码可在 CORS 分支的公共 github 页面上找到:https://github.com/PliegerNicolas/default_nestjs_app/tree/CORS
您可以在这里找到所有相关的后端身份验证代码:https://github.com/PliegerNicolas/default_nestjs_app/tree/CORS/srcs/requirements/backend/app/src/modules/authentication
/!\ 当您克隆我的存储库时,您必须设置 .env 文件来测试并生成自签名 ssl_certificates https://github.com/PliegerNicolas/default_nestjs_app/tree/CORS/srcs /requirements/nginx/config/ssl_certificates 带有域名。
==========谢谢==========
我不习惯 stackoverflow,所以如果某些数据丢失或者这个请求不清楚请告诉我!预先感谢您的帮助。
@Backend > 身份验证.controller.ts
@Get('google/login')
@UseGuards(AuthGuard('google'))
async loginWithGoogle() {
// Handled by google oauth 2 service
}
@Get('google/callback')
@UseGuards(AuthGuard('google'))
async loginWithGoogleCallback(
@Request() req: any,
@Res() res: Response,
) {
const userPayload: UserPayload = req.user;
await this.authenticationService.login(userPayload, res);
return (res.status(HttpStatus.OK).json(userPayload));
}
因此当访问 google/login 时,会触发后端的重定向。默认情况下,这是由 Passport google oauth2 (nestjs 包)处理的,因此它应该是预期的行为。
@Frontend > App.tsx
const loginWithGoogle = async (
url: string,
) => {
const requestOptions: RequestInit = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
mode: 'cors',
credentials: 'include',
}
try {
const response = await fetch(url, requestOptions);
if (response.redirected) {
window.location.href = response.url;
} else {
console.log('Error redirection');
}
} catch(error) {
console.log('Error: ', error);
}
};
这就是我在 React 应用程序中提出请求的方式。这是一个需要重定向的获取请求。如果有一个 => href 它。
但这并不能处理 CORS 错误。
最好的解决方案是什么?手动打开前端中的链接,而不依赖于后端服务器,谷歌将为我处理到 /google/callback 的重定向,从那里我必须手动将用户重定向到前端?
或者是否有更标准化的方法来利用我的后端的谷歌/登录控制器?
如果前端直接向google的auth页面发出请求。无论哪种方式,Google ID 都会在链接中公开,因此这不是问题。对吗?