Home > database >  Redirect with Nestjs not working with external URL
Redirect with Nestjs not working with external URL

Time:07-01

I have an issue with redirecting to an external URL, while implementing an SSO Server with NestJs, to authenticate some of my frontend applications as well as some API.

The authentication flow has these steps:

  • External UI redirects to SSO Server with redirect URL, for authentication.
  • SSO redirects to the login page.
  • User logs in with personal information.
  • SSO verify user and uses the previous URL sent by UI, to redirect with JWT and profile.

In my Auth controller, I have this endpoint setup that gets called with the information to log in.

@Post('auth/login')
  async login(@Body() body, @Res() res: Response) {
    const authResponse = await this.authService.login(body.user, body.password);

    if (authResponse.error) {
      return res.render('login', {
        title: '',
        redirect: body.redirect,
        errors: [{ msg: authResponse.error }],
      });
    } else {
      res.redirect(`${body.redirect}?token=${authResponse.token}`);
    }
  }

When a user is validated and the redirect is called, nothing happens in the log of Nestjs and the page doesn't redirect anywhere.

Some of the URL strings I've tested are:

Things I've tried:

  • I tried using HTTP code 200 before the URL in the redirect method and when I do, it gets redirected to a blank page with the message "OK, redirecting to URL"
  • I also tried with the @Redirect() decorator with the same results.
  • If I try to redirect to another endpoint of the SSO server it works fine, but the external URLs look like it doesn't work.
  • I also tried appending the return before the res. redirect to the method. Example: return res.redirect(${body.redirect}?token=${authResponse.token});

EDIT

Other things I've done that don't work either:

  • Initially redirect to another internal method and use the new method to only redirect to external URL.
  • Giving different HTTP codes in the redirect. 301, 302, 304, 200.

My cors configuration is setup like this:

app.enableCors({
    origin: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  });

does anybody have had this problem before?

CodePudding user response:

So after trying with different browsers I found that the issue was happening only in Chrome even in incognito mode and even after removing cache and hard reset.

I realized that I was getting another error saying:

Refused to send form data to 'http://localhost:3000/auth/login' because it violates the following Content Security Policy directive: "form-action 'self'".

since the error is talking about content security policy, I decided to remove Helmet from the Nestjs and that did the trick.

Since I'll be needing Helmet anyways, I'll have to find a way to handle this error by configuring Helmet correctly, but at least now the redirect is working fine.

  • Related