简体   繁体   中英

No authorization token was found - Express-JWT and Auth0

I'm working on integrating Auth0 into a MERN Stack app. The flow should look like this:

  1. User clicks the login button which triggers Auth0Lock.show()
  2. User fills in their credentials and clicks the submit button
  3. The callback URL of the API is hit which logs the user in and redirects them back to the front-end app

(everything looks like it's working fine up to this point)

  1. The front-end requests user information from the API
  2. The front-end receives the information and redirects

This seems to be a fairly standard authentication flow. The problem is that when the front-end asks the back-end for user information, there's an error:

UnauthorizedError: No authorization token was found

My setup looks essentially like this:

// client-side config
const lock = new Auth0Lock(clientID, domain, {
  auth: {
    responseType: 'token',
    audience: 'https://${domain}/userinfo',
    redirectUrl: API_URL + '/api/users/callback', 
    params: {
      scope: 'openid profile email' // no change
    }
  }
})


// server.js

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// [DB setup]

var sessConfig = {
  secret: "[random string]",
  cookie: {
    sameSite: false
  },
  resave: false,
  saveUninitialized: true
};
if(app.get('env') === 'production') sessConfig.cookie.secure = true;

app.use(session(sessConfig));

const {domain, clientID, clientSecret, callbackURL} = require('./config/auth0');
const passportStrategy = new Auth0Strategy(
  {domain, clientID, clientSecret, callbackURL},
  (accessToken, refreshToken, extraParams, profile, done) => done(null, profile)
)
passport.use(passportStrategy);
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
app.use(passport.initialize());
app.use(passport.session());

// [routing]



// routes/users.js
router.get('/callback', (req, res, next) => {
  passport.authenticate('auth0', (err, user, info) => {
    if(err) return next(err);
    if(!user) return next(info);

    req.logIn(user, err => {
      if(err) return next(err);

      const returnTo = req.session.returnTo;
      delete req.session.returnTo;
      res.redirect(returnTo || clientRootURL + '/callback');
    })
  })(req, res, next);
})

router.get(
  '/current',
  require('cors')(),
  authenticate,
  (req, res) => {
    res.json({
      id: req.user.id,
      name: req.user.name,
      email: req.user.email
    });
  }
);


// authenticate.js
module.exports = jwt({
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://${domain}/.well-known/jwks.json`
  }),
  audience: clientID,
  issuer: `https://${domain}/`,
  algorithms: ['RS256']
});

The vast majority of comes straight out of the Auth0 documentation. I'm trying to get the user info from the /users/current endpoint after logging in and it says it can't find authorization. Does anyone have any idea how to get this to work?

You should be calling the /userinfo endpoint to get the user profile, or getting the info from the id_token. Take a look at this doc

https://auth0.com/docs/api/authentication#get-user-info

Every authenticated frontend call should contain:

headers: {
    Authorization: `Bearer ${token}`,
},

where token should be:

const token = await getAccessTokenSilently();

getAccessTokenSilently is a public function of auth0 lib.

See: getAccessTokenSilently doc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM