Redirect to Frontend ( On A Different URL ) after OAuth2 Login

和自甴很熟 提交于 2020-01-16 22:54:27

问题


I am trying to setup my application as follow :

  1. Angular 7 frontend, served at, say http://localhost:4200
  2. Express backend, served at, say http://localhost:3500
  3. 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


回答1:


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



来源:https://stackoverflow.com/questions/56653139/redirect-to-frontend-on-a-different-url-after-oauth2-login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!