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

标签 node.js oauth-2.0 passport.js passport-google-oauth2

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

  1. Angular 7 前端,服务于 http://localhost:4200
  2. Express 后端,服务于 http://localhost:3500
  3. 用于 OAuth2 身份验证的 Passport 库

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

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

登录成功后,重定向回前端 URL 的好方法是什么,即 http://localhost:4200/ ??由于回调 URL 在服务器端

最佳答案

我最终决定采用以下策略:

Passport 策略设置如下:

/**
 * 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/ '

关于node.js - OAuth2 登录后重定向到前端(在不同的 URL 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56653139/

相关文章:

node.js - 在 swagger nodejs restful 应用程序中集成 Passport 中间件?

javascript - 只是无法让 Passport.js 工作

java - 如何在不使用任何库的情况下验证 id_token

asp.net - 使用 thinktecture IdentityServer v2 进行单点登录

python - 如何注册一个oauth2客户端?

node.js - 使用 Passport 在 express 中找不到用户的凭据

java - 将 Android 客户端连接到 NodeJS 中的套接字服务器时出错

javascript - Intellisense : view file as browser JavaScript, 不是 Node.js?

javascript - 尝试使用锐利的 Node.js 调整流图像的大小

node.js - 尝试创建新用户