0

I'm having an error on my front-end when trying to authenticate with Auth0 login. My back-end should be able to authorize users using social providers (i.e. Auth0 or Google) and authenticate them using JSON Web Tokens (JWTs).

I created all the back-end using passportJS and added a Auth0 passport strategy as well as Google strategy. When testing the endpoints for both strategies, it works fine with Postman.

But then comes the front-end part where I make an API call to localhost:3000/auth/auth0, and the following error occurs:

Access to XMLHttpRequest at 'https://mydomain.auth0.com/authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fauth0%2Fcallback&scope=openid%20profile&state=7cQWAAvioTLCniVqAy4ghHXK&client_id=cDB1F0gO9QWyNqHh1TGuVl7It5nYQrs9' (redirected from 'http://localhost:3000/auth/auth0') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Code on back-end:

File main.ts

async function bootstrap() {

// Nest App
const app = await NestFactory.create(ApplicationModule, { cors: true });


    // Body parser middleware with increase limits
app.use(bodyParser.urlencoded({limit: '5mb', extended: true}));
app.use(bodyParser.json({limit: '5mb'}));

app.enableCors();

app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());


const port: number = +process.env.PORT || 3000;
await app.listen(port, () => {
    // tslint:disable-next-line:no-console
    console.log(`Nest app is listening on port ${port}.`);
});
}
bootstrap();

File auth0.strategy.ts

@Injectable()
export class Auth0Strategy extends PassportStrategy(Strategy, 'auth0')
{

  constructor(private readonly authService: AuthService) {
    super({
      domain: config.auth0.domain,
      clientID: config.auth0.clientID,
      clientSecret: config.auth0.clientSecret,
      callbackURL: 'http://localhost:3000/auth/auth0/callback',
      passReqToCallback: true,
      audience: config.auth0.audience,
      scope: 'openid profile',
    })
  }

  async validate(_request: any, _accessToken: string, _refreshToken: string, profile: any, done: Function) {
    try {

      const jwt: string = await this.authService.validateOAuthLogin(profile.id, Provider.AUTH0);
      const user = { jwt };

      done(null, user);
    }
    catch (err) {
      done(err, false);
    }
  }

}

File auth.controller.ts

@Get('auth0')
@UseGuards(AuthGuard('auth0'))
auth0Login() {
  // initiates the Auth0 OAuth2 login flow
}

@Get('auth0/callback')
@UseGuards(AuthGuard('auth0'))
async auth0Callback(@Req() req, @Res() res) {
  const jwt: string = req.user.jwt;
  if (jwt) {
    res.redirect('http://localhost:4200/login/succes/' + jwt);
  } else {
    res.redirect('http://localhost:4200/login/failure');
  }
}

Code on front-end:

File authentication.service.ts

public login(): void {
  this.apiService.get('auth/auth0').subscribe(
    (res) => {
        console.log('result', res);
    }, (err) => {
        console.log('error', err);
    });
}

I expect the Auth0 login page to pop-up, so the user has to be redirected to this login page, but nothing happens because of CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

C00kieMonsta
  • 338
  • 3
  • 20
  • add Access-Control-Allow-Origin true in header so it will work – TheParam Feb 07 '19 at 16:50
  • Already tried this, but other error occurs: Response to preflight request doesn't pass access control check – C00kieMonsta Feb 07 '19 at 16:58
  • try run browser from run window - chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security – TheParam Feb 07 '19 at 17:03
  • It has nothing to with Angular. You should allow `localhost` on the server side. https://auth0.com/docs/cross-origin-authentication – Harun Yilmaz Feb 07 '19 at 17:03
  • @HarunYılmaz thanks for your answer, but what do you mean by "allow `localhost` on the server", how can this be achieved? – C00kieMonsta Feb 07 '19 at 17:10
  • You can find how to allow `localhost` here: https://auth0.com/docs/dev-lifecycle/local-testing-and-development#use-local-domains-with-auth0 And useful info here: https://www.codecademy.com/articles/what-is-cors – Harun Yilmaz Feb 08 '19 at 07:10
  • @HarunYılmaz thanks again. That is not the problem I am facing, because I already whitlisted localhost as an allowed callback url. In addition I already added 'Access-Control-Allow-Origin', '*' on the server... – C00kieMonsta Feb 08 '19 at 09:04
  • Someone says it might be about Chrome. If you are using Chrome, maybe this could help you: https://stackoverflow.com/questions/28547288/no-access-control-allow-origin-header-is-present-on-the-requested-resource-err – Harun Yilmaz Feb 08 '19 at 09:11
  • @HarunYılmaz this link was helpful, but it does not solve the issue, am I still getting errors. Just so you know, what I am trying to achieve, is "triggering" the hosted login page of `Auth0` from the back-end and retrieve the token on the back-end. My code is inpired from this `Medium` post: https://medium.com/@nielsmeima/auth-in-nest-js-and-angular-463525b6e071 – C00kieMonsta Feb 08 '19 at 10:20

0 Answers0