Search code examples
iosnode.jsexpressjwtauth0

Why is my Auth0 token always coming back as invalid when sent from iOS to node.js server?


I'm using Auth0's service for an iOS app with a server built on node.js and express.js. I've followed Auth0's docs and seed projects as best I can, but the server keeps complaining that the tokens I'm sending from my iOS application are invalid. Here's some of my code:

From the server - the authentication and route declarations, as specified in the Auth0 documentation

var authenticate = jwt({
  secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
  audience: process.env.AUTH0_CLIENT_ID
});


app.use('/api', authenticate);
app.use('/api/userquery', queries);

And from iOS, setting the header for a request (using AFNetworking):

request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

I know for a fact the request is being sent properly because it works fine for paths that don't require authentication. Lastly, here's the error I receive on the server side:

GET /api/userquery/currentUser 401 7.185 ms - 436
UnauthorizedError: invalid token
    at /node_modules/express-jwt/lib/index.js:100:22
    at /node_modules/jsonwebtoken/index.js:155:18
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

Solution

  • The issue was just that I failed to unwrap the token after pulling it out of keychain. Instead of sending "Bearer [token]" in the Authorization header, I was sending "Bearer [Optional(token)]".