How to authenticate user after redirect from google?

1k Views Asked by At

I'm implementing google OAuth2 with passport.js, nest.js and React.

In my React app it will redirect the user to this endpoint http://localhost:<PORT_NUMBER>/auth/google

// React 
<button label="login" onClick={window.location.href('http://localhost:<PORT_NUMBER>/auth/google')}/>


// Nest.js endpoint
  @Get('google')
  @UseGuards(GoogleOAuthGuard)
  async googleAuth() {}

Once the user authenicates, google redirect's the user to another endpoint (http://localhost:<PORT_NUMBER>/auth/google/redirect) in my Nest.js API. Note: I have set this up as the redirect url in google developer console.

// get's the user data from the redirect, create tokens, saves in the DB etc...
  @Get('google/redirect')
  @UseGuards(GoogleOAuthGuard)
  async googleAuthRedirect(@Req() req: Request): Promise<User & Tokens> {
    const user = <UserType>req.user;

    return this.authService.googleAuth(user);
  }

// My passport.js google strategy setup
export class GoogleOAuthStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(private readonly configService: ConfigService) {
    super({
      clientID: configService.get<string>('OAUTH_GOOGLE_CLIENT_ID'),
      clientSecret: configService.get<string>('OAUTH_GOOGLE_CLIENT_SECRET'),
      callbackURL: configService.get<string>('OAUTH_GOOGLE_REDIRECT_URL'),
      scope: ['email', 'profile'],
    });
  }

My question is what happens afterwards? How will my React app get access to the object that is returned from http://localhost:<PORT_NUMBER>/auth/google/redirect? (NOTE: this is an api endpoint, not a React path). Should my React app call http://localhost:<PORT_NUMBER>/auth/google/redirect?

I land here after redirect: enter image description here

port 3000 is my api route, my React app is on port 3001. How would I get the data into my React app?

1

There are 1 best solutions below

6
Rodericus Ifo Krista On

After you do login via google auth, via this Endpoint 'http://localhost:<PORT_NUMBER>/auth/google', your server application will automatically redirect to this endpoint http://localhost:<PORT_NUMBER>/auth/google/redirect, and after that you will get any information from google oauth such as profile user, access token, and refresh token (which was returned by redirect endpoint). so you don't need to call http://localhost:<PORT_NUMBER>/auth/google/redirect on your react app