Search code examples
node.jsexpresstokenjwtexpress-jwt

express-jwt handling specific secret passphrase by routes


Here is my use case.

In my express app using express-jwt module, I have 2 mains routes. I would like to secure my routes with 2 distincts passphrase.

app.use('/api/v1/admin', jwt({secret: "blabla1"}).unless({path:['/api/v1/admin/login']}));
app.use('/api/v1', jwt({secret: "blabla2"}).unless({path: ['/api/v1/login']}));

In this case, it doesn't work as I was expecting to... Is there a way to achieve this in only one express app ?

Thanks in advance for your helps guys!


Solution

  • Your syntax is a little off, what you are doing above is setting the secret for the whole app. If you wanted to protect a certain route you could do something like below.

    app.all('/api/v1', jwt({secret: "blabla2"}).unless({path: ['/api/v1/login']}));
    app.all('/api/v1/admin', jwt({secret: "blabla1"}).unless({path:['/api/v1/admin/login']}));
    

    The above code allows you define different secrets for a particular route. The call to app.all catches every type of HTTP call.