OAuth2 登录后重定向到前端(在不同的 URL 上) [英] Redirect to Frontend ( On A Different URL ) after OAuth2 Login
问题描述
我正在尝试按如下方式设置我的应用程序:
- Angular 7 前端,例如 http://localhost:4200
- Express 后端,服务于,例如 http://localhost:3500
- 用于 OAuth2 身份验证的 Passport 库
我正在从服务器端 (Express/Node.js) 设置 OAuth2 流.在前端点击登录按钮,请求被发送到服务器,它被重定向到 Google 以要求提供用户凭据/权限等.
我的回调 URL 是:http://localhost:3500/auth/callback.>
登录成功后,什么是重定向回前端 URL 的好方法,即 http://localhost:4200/ ??由于回调 URL 在服务器端
我最终决定采用以下策略:
Passport Strategy 设置如下:
/*** 用于 Google oauth2 身份验证的路由处理程序.* 第一个处理程序启动身份验证流程.* 第二个处理程序接收来自 Google 的响应.如果失败,我们将* 重定向到预先确定的可配置路由.如果成功,我们会发出一个 Json* Web 令牌,并重定向到预先确定的、可配置的路由.*/this.router.get('/google', (req: Request, res: Response, next: NextFunction) => {护照.认证('谷歌',{范围: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 定义如下:
/*** 用于将 JWT 作为身份验证流程的一部分发布的中间件.* @param req Express HttpRequest 对象* @param res Express HttpResponse 对象*/issueJWTEnhanced(req: any, res: Response, loginMech: string ) {this.logger.info('内部 JWT 发行服务');this.logger.info('UserID:' + req.user._id);jwt.sign({userId: req.user._id, loginMethod: loginMech}, process.env.JWT_SECRET, {expiresIn: '5 min'}, (err, token) => {如果(错误){this.logger.error('尝试发出 JWT 时出错:' + err);this.logger.error(JSON.stringify(err));返回 res.redirect(process.env.AUTH_FAILURE_REDIRECT);}别的{this.logger.info('成功发布JWT');this.logger.info('JWT 已发布:' + 令牌);返回 res.redirect(process.env.AUTH_SUCCESS_REDIRECT + '/' + token);}});}
哪里,
AUTH_SUCCESS_REDIRECT='http://localhost:4200/login-success一个>'AUTH_FAILURE_REDIRECT='http://localhost:4200/login/'>
I am trying to setup my application as follow :
- Angular 7 frontend, served at, say http://localhost:4200
- Express backend, served at, say http://localhost:3500
- Passport library for OAuth2 Authentication
I am setting up OAuth2 flow from the serverside (Express / Node.js). On clicking the Login button from the frontend, request is sent to the server, which gets redirected to Google to ask for user credentials / permissions etc.
My callback URL is : http://localhost:3500/auth/callback.
Post successful login, what is a good way to redirect back to the Frontend URL i.e. http://localhost:4200/ ?? Since the callback URL is on the serverside
I finally decided to go with the following strategy:
Passport Strategy setup as follows:
/**
* 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 is defined as follows:
/**
* 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);
}
});
}
Where,
AUTH_SUCCESS_REDIRECT='http://localhost:4200/login-success' AUTH_FAILURE_REDIRECT='http://localhost:4200/login/'
这篇关于OAuth2 登录后重定向到前端(在不同的 URL 上)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!