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

编程入门 行业动态 更新时间:2024-10-24 04:44:27
本文介绍了OAuth2 登录后重定向到前端(在不同的 URL 上)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

  • Angular 7 前端,例如 localhost:4200
  • Express 后端,服务于,例如 localhost:3500
  • 用于 OAuth2 身份验证的 Passport 库
  • 我正在从服务器端 (Express/Node.js) 设置 OAuth2 流.在前端点击登录按钮,请求被发送到服务器,它被重定向到 Google 以要求提供用户凭据/权限等.

    我的回调 URL 是:localhost:3500/auth/callback.>

    登录成功后,什么是重定向回前端 URL 的好方法,即 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='localhost:4200/login-success'AUTH_FAILURE_REDIRECT='localhost:4200/login/'

    I am trying to setup my application as follow :

  • Angular 7 frontend, served at, say localhost:4200
  • Express backend, served at, say 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 : localhost:3500/auth/callback.

    Post successful login, what is a good way to redirect back to the Frontend URL i.e. 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='localhost:4200/login-success' AUTH_FAILURE_REDIRECT='localhost:4200/login/'

    更多推荐

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

    本文发布于:2023-11-15 03:45:29,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1590852.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:重定向   URL

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!