node.js - OAuth2 登录后重定向到前端(在不同的 URL 上)
问题描述
我正在尝试按如下方式设置我的应用程序:
- Angular 7 前端,服务于http://localhost:4200
- Express 后端,服务于http://localhost:3500
- 用于 OAuth2 身份验证的护照库
我正在从服务器端(Express / Node.js)设置 OAuth2 流。在从前端单击登录按钮时,请求被发送到服务器,该服务器被重定向到谷歌以询问用户凭据/权限等。
我的回调 URL 是:http://localhost:3500/auth/callback。
成功登录后,重定向回前端 URL 的好方法是什么,即http://localhost:4200/?由于回调 URL 在服务器端
解决方案
我最终决定采用以下策略:
护照策略设置如下:
/**
* Route handlers for Google oauth2 authentication.
* The first handler initiates the authentication flow.
* The second handler receives the response from Google. In case of failure, we will
* redirect to a pre-determined configurable route. In case of success, we issue a Json
* Web Token, and redirect to a pre-determined, configurable route.
*/
this.router.get('/google', (req: Request, res: Response, next: NextFunction) => {
passport.authenticate('google', {
scope: process.env.GOOGLE_OAUTH2_SCOPES.split(",")
})(req, res, next);
});
this.router.get('/google/callback',
passport.authenticate('google', { failureRedirect:process.env.AUTH_FAILURE_REDIRECT }), (req, res) => this.jwtAuthService.issueJWTEnhanced(req, res, 'google'));
issueJwtEnhanced 定义如下:
/**
* Middleware for issuing JWT as part of the authentication flow.
* @param req Express HttpRequest Object
* @param res Express HttpResponse Object
*/
issueJWTEnhanced(req: any, res: Response, loginMech: string ) {
this.logger.info('Inside JWT issuing service');
this.logger.info('UserID: ' + req.user._id);
jwt.sign({userId: req.user._id, loginMethod: loginMech}, process.env.JWT_SECRET, {expiresIn: '5 min'}, (err, token) => {
if(err){
this.logger.error('Error while trying to issue JWT: ' + err);
this.logger.error(JSON.stringify(err));
return res.redirect(process.env.AUTH_FAILURE_REDIRECT);
}else{
this.logger.info('Successfully issued JWT');
this.logger.info('JWT Issued: ' + token);
return res.redirect(process.env.AUTH_SUCCESS_REDIRECT + '/' + token);
}
});
}
在哪里,
AUTH_SUCCESS_REDIRECT =' http://localhost:4200/login-success ' AUTH_FAILURE_REDIRECT =' http://localhost:4200/login/ '
推荐阅读
- php - PHP在变量中存储数组键路径
- sql - 如何在 SQL Server 查询中执行 while 循环
- flutter - 使用颤动向下滚动时如何隐藏bottomAppBar
- python - 使用熊猫(python)根据以前的值添加列
- c++ - UE4工程打包时找不到动画类
- reactjs - React + typeScript + bugsnag 可能吗?
- java - 顺序程序的并行化(迷宫)
- asp.net - 热重载不适用于 Blazor 应用
- keras - 在 Keras 中创建具有可变输入大小的自定义数据生成器
- ruby-on-rails - 如何使用夹具测试带有 Mongoid 的 Rails 5 应用程序