首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在OAuth2登录后重定向到前端(在不同的URL上)

问在OAuth2登录后重定向到前端(在不同的URL上)
EN

Stack Overflow用户
提问于 2019-06-18 16:07:50
回答 1查看 3K关注 0票数 3

我正在尝试按以下方式设置我的应用程序:

  1. 角7前部,http://localhost:4200说
  2. 快速后端,服务于,比如http://localhost:3500
  3. 用于OAuth2身份验证的护照库

我正在从服务器端设置OAuth2流(Express / Node.js)。在从前端单击Login按钮时,将请求发送到服务器,服务器将被重定向到Google,以请求用户凭据/权限等。

我的回调网址是:http://localhost:3500/auth/callback。

张贴成功的登录,什么是一个好的方式重定向回前端网址,即http://localhost:4200/ ??因为回调URL位于服务器端

EN

回答 1

Stack Overflow用户

发布于 2019-11-11 11:24:14

最后,我决定采取以下策略:

护照策略设置如下:

代码语言:javascript
复制
/**
 * 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的定义如下:

代码语言:javascript
复制
/**
 * 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/’

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56653139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档