Koder
Koder

Reputation: 1914

Using Passport JS Bearer Authenticate Globally

I have the following code written in NodeJS that uses Passport JS Bearer Authentication in Route Middleware.

app.put('/api/customers/:id', passport.authenticate('bearer', {session : false}),      handlers.putCustomers);
app.put('/api/products/:id', passport.authenticate('bearer', {session:false}), handlers.putProducts);

Instead of using passport.authenticate for every endpoint, i want to apply this globally for every endpoint.

I tried with the following order of middleware with no luck

var app = express();
app.use(bodyParser());
app.use(session({ store: new RedisStore({client:client}),secret: 'keyboard cat' }));
app.use(passport.initialize());
passport.use(new BearerStrategy(){....

app.use(passport.authenticate('bearer', {session:false}));

app.put('/api/customers/:id',  handlers.putCustomers);
app.put('/api/products/:id', handlers.putProducts);

I am getting a 401 when i hit the endpoint.. I am seeing it for 'OPTIONS' type instead of 'PUT' if that helps or makes sense.( Using chrome to test my endpoint from my app's UI).

Upvotes: 0

Views: 928

Answers (1)

Koder
Koder

Reputation: 1914

Answering my question: i managed to solve this by using a wildcard route as mentioned here : app.use()

app.put("/api/*",passport.authenticate('bearer', {session:false}));

Upvotes: 1

Related Questions