Yash
Yash

Reputation: 1018

How to force authentication with Passport

I have implemented 2 routes: app.post('/login', passport.authenticate....); app.get('/admin', myfunction);

If the user first posts to login, I have got him redirected to /admin.

What if the user goes straight to get /admin? How do I ensure that unless he is logged in, he is not allowed to access /admin and is redirected to the login screen?

Also for APIs that are accessed from the application, how do I send 401 if the user is not authenticated by passport?

Upvotes: 2

Views: 1901

Answers (1)

Matthew Bakaitis
Matthew Bakaitis

Reputation: 11990

Passport is middleware that needs to be included where you need route protection

Passport.js is middleware for Express. You include it on any routes that need to be protected, not just on the login route/page.

As a refresher, the approved answer to What does middleware and app.use actually mean in Expressjs? and this link to the off-site page A short guide to Connect Middleware can also help.

Protecting an API route

First, to repeate what was said above...Passport is middleware so you need to include it on the routes defining the API. Additionally, see:

As for the 401, Passport will generate these for you upon failure if you haven't written your own handler for these.

Upvotes: 3

Related Questions