'Passport-nestjs Github oauth: how to send access tokens from request object in callback url to client side application hosted in different origin?

Nest js auth controller


      // route to access github oauth
      @Get('/')
      @Public()
      @UseGuards(AuthGuard('github'))
      async githubAuth() {}

      // callback url called after github strategy validates the user
      @Get('/github/callback')
      @Public()
      @UseGuards(AuthGuard('github'))
      async githubAuthRedirect(
        @Req() req,
        @Res({ passthrough: true }) res: Response,
      ) {
        req.user.tokens = await this.authService.login(req.user);
        const authData = JSON.stringify(
          await this.authService.githubLogin({ ...req }),
        );

        // send this data to react app on a different origin
        res.cookie('auth-data', authData);
        res.redirect('http://localhost:3000');
      }

Client side react code

function Login({}: Props) {
  const handleLoginWithGithub = () => {
    window.open("http://127.0.0.1:5000/auth/", "_self");
  };

  return (
    <div>
     ...
    
          <button onClick={handleLoginWithGithub}>
            Login With GitHub
          </button>
...
</div>
)

Problem

auth route called in the client side is called with window.open() function which doesn't allow to set withCredentials like in axios. This leads to Set-cookie header being set but the cookie doesn't get set as the server and client are from different origins.

Image of response headers with Set-cookie header

Image of cookie not being set



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source