Search code examples
expressjwtexpress-jwt

using jwt with jwt-express with middleware in express js


In express-jwt home page introduce a function for getting json web token from header or query that we can use as express middle wear and this is the function :

app.use(jwt({
secret: 'hello world !',
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')
[0] === 'Bearer') {
    return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
  return req.query.token;
}
return null;
}
}));

And I use express.Route() like this :

app.use('/user',userRoute);
app.use('/apps',appsRouter);

My question is how can I use getToken() function or how can I access to the token in authorization of header.

Thanks in advance.


Solution

  • finally i find the solution. with middle ware (jwt) can verify the token in header and if can it set in req.user so , in req.user we have all information of deceded jwt, according to this:

    By default, the decoded token is attached to req.user but can be configured with the requestProperty option. jwt({ secret: publicKey, requestProperty: 'auth' });