【问题标题】:How to combine passport with routing-controller?如何将护照与路由控制器结合起来?
【发布时间】:2018-01-24 11:48:36
【问题描述】:

我目前正在尝试将 passport-ldap 和 passport-jwt 实现到我的其余 API。对于路由,我使用pleerock/routing-controllers,它有一种授权方式,但它适用于布尔值,而护照适用于我真的不知道。我什至不确定是否可以将两者结合起来。

目前 AuthorizationChecker 返回 false,因为我不知道如何将 passport.authenticate 设置为布尔值。

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

如何使用passport.authenticate() 与路由控制授权?

【问题讨论】:

  • 你想出解决方案了吗?我正在尝试做同样的事情。我正在考虑为此使用全球中间件,使用 passport-jwt。
  • @ØysteinAmundsen 我编辑了我的答案

标签: node.js typescript express jwt passport.js


【解决方案1】:

是的,可以将护照与路由控制器结合使用。

最简单的方法是在控制器类或路由方法之前使用带@UseBefore装饰器的护照作为中间件:

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

但是您可能想使用@Authorized() 装饰器。稍微复杂一点,但可以通过authorizationChecker 配置来完成:

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,
});

然后你就可以同时使用@Authorized() 和@CurrentUser 装饰器了。

查看passport authenticaterouting-controllers auth features 了解更多详情。

【讨论】:

    【解决方案2】:

    要使用authenticate(),您必须将其用作中间件。这是路由控制器上的link 如何使用中间件。对于 authenticationChecker

    import * as jwt from 'jwt-simple'; 
    
    currentUserChecker: async (action: Action) => {
            const token = action.request.headers["authorization"];
            console.log(token)
            let key= jwt.decode(token, "Banana");
            console.log(key)
            let user = await mongoose.model("users").findOne({'key': key.key});
            if (user != null && token != null) return user;
        }
    

    这是使用 passport-jwt 进行 jwt 身份验证的设置

    【讨论】:

    • 是否可以共享路由控制器中间件的全部代码?
    • 遗憾的是不再
    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 2015-02-13
    • 2016-09-25
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2015-12-26
    相关资源
    最近更新 更多