Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine passport with routing-controller?

I'm currently trying to implement passport-ldap and passport-jwt to my rest API. For routing I use pleerock/routing-controllers, which has a way for authorization, but it works with booleans and passport works with I honestly don't know. I'm not even sure if its possible to combine the two.

Currently AuthorizationChecker returns false because I don't know how to make passport.authenticate into a boolean.

useExpressServer(app, {
controllers: [UserController, IssueController, LoginController],
authorizationChecker: async (action: Action) => {
     return false;
}
@Authorized()
@Get("/test")
test(@Res() response: Response){
    response.send("Test done.")
}

How to use passport.authenticate() with routing-controlls authorization?

like image 689
Kristóf Horváth Avatar asked Sep 02 '25 02:09

Kristóf Horváth


1 Answers

Yes, It's possible to combine passport with routing-controller.

The easiest way is to use passport as middleware with @UseBefore decorator before controllers classes or route methods:

@JsonController()
@UseBefore(passport.authenticate('jwt'))
export class MyController { ... }

However you may want to use @Authorized() decorator. It little bit more complicated, but can be done with authorizationChecker configuration:

import express from 'express';
import { Action, useExpressServer } from 'routing-controllers';

const app = express();

useExpressServer(app, {
  authorizationChecker: (action: Action) => new Promise<boolean>((resolve, reject) => {
    passport.authenticate('jwt', (err, user) => {
      if (err) {
        return reject(err);
      }
      if (!user) {
        return resolve(false);
      }
      action.request.user = user;
      return resolve(true);
    })(action.request, action.response, action.next);
  }),
  currentUserChecker: (action: Action) => action.request.user,
});

Then you'll be able to use both @Authorized() and @CurrentUser decorators.

Check passport authenticate and routing-controllers auth features for more details.

like image 140
DimaIT Avatar answered Sep 04 '25 19:09

DimaIT