Mike K
Mike K

Reputation: 6511

Getting a CORS error when trying to authenticate user with Auth0

Edit

Reproducible repo here

I'm aware that these creds should never hit the internet, but I'm getting desperate here + I'll delete the client/tenant afterward anyway.


I have a route set up:

router.get('/login', cors, async (req, res) => {
    try {
        console.log('Entered')
        await auth0.handleLogin(req, res)
    } catch (err) {
        return res.status(500).end()
})

The line Entered gets printed, however I keep catching a cors error,

Access to XMLHttpRequest at 'https://dev-..' (redirected from 'http://localhost:3000/login')
 from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've been pulling my hair out for several h̶o̶u̶r̶s̶ days now.

I'm not sure why the error No 'Access-Control-Allow-Origin' header is present on the requested resource is showing up, as I've added the cors package to my custom Express server.

What am I doing wrong here? I've followed this tutorial which uses passport-auth0 and I've followed these docs (which is the package used in the repository above) as well -- both approaches show the same error.

In my Auth0 dashboard, I've set up my allowed origins as follows (ie, I followed this: img1

I have no idea where to go from here. If I manually paste the URL from the console error, https://dev-.. then it takes me to the auth page and successfully redirects me to localhost:3000/.

Here are my init Auth0 settings.

I've seen some similar questions online, like this one, but creating a new client hasn't helped me, and the other answers haven't either. I've crawled through nearly every relevant question on the Auth0 Community forum.

I've also cloned and ran the example here, and it worked with their pages API. I'm starting to think, that I can't use this nextjs-auth0 package with a custom server.

Upvotes: 1

Views: 2724

Answers (1)

Dipen Shah
Dipen Shah

Reputation: 26085

Instead of using browser redirect, you are sending asynchronous request which is the reason why Auth0 is not working for you and is giving you CORS error.

Update your Home view with following code and it will fix your issue:

import React from 'react';
import axios from 'axios';

export default function Home() {
    return (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <a href='/login'>login</a>
        </div>
    );
}

P.S: I tried this changes with forking your repo and it is working as expected for me, let me know if you still see the issue.

Upvotes: 5

Related Questions