use*_*300 7 node.js express passport.js
我目前正在使用 typescript、WebStorm、passport 和 jwt 为 node.js 微服务应用程序开发身份验证服务。在尝试将路由添加到“/api/login”时,我注意到智能感知似乎没有获取 req.user 的用户对象或 req.header.authorization 的授权对象。例如,以下方法不起作用,因为它找不到用户对象:
private generateToken(req: Request, res: Response, next: NextFunction){
req.token = jwt.sign({
id: req.user.id,
firstname: req.user.firstname,
lastname: req.user.lastname,
roles: req.user.roles
}, process.env.AUTH_KEY, {
expiresIn: "7d"
});
return next();
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 express 中的 Request 对象:
import { NextFunction, Request, Response, Router } from "express";
Run Code Online (Sandbox Code Playgroud)
我需要使用不同的 Request 对象吗?
另外,如果我需要强制对某些 api 路由进行身份验证但锁定其他路由,应该如何使用passport-jwt 来完成?我知道有一个 express-unless 包可以用于 express-jwt。
不知道为什么这个问题被否决了,也许是因为它应该是两个单独的问题。
您可以为 Express 扩展类型声明。
扩展 express 类型定义
library-ext.d.ts
使用此将文件添加到您的源目录中。
declare module 'express' {
export interface Request {
user?: any;
}
}
Run Code Online (Sandbox Code Playgroud)
对于req.header.authorization
尝试:req.headers['authorization']。注意's'。
关于一般认证
这取决于您的注册用户是否也可以使用这些guest
路由。如果您从不需要访客路由上的身份,那么只需在经过身份验证的路由上注册护照身份验证中间件,或者将路由拆分为单独的路由器。这很简单,只需搜索堆栈溢出或查看文档即可。
更复杂的情况是当您需要经过身份验证和未经身份验证的用户访问路线时 - 想想访客或经过身份验证的客户向购物车添加东西。不幸的是passport-jwt
,当令牌不在授权标头中时,会以 401 拒绝,所以我找到的最简单的方法,而不是分叉项目或滚动我自己的策略,是使用中间件添加一个已知值来表示否则匿名请求。然后只需确保中间件在受影响的路线中的护照身份验证之前。这里有一个片段可以让你继续:
核心控制
class CoreCtrl {
simulateAnonymous(req, res, next) {
if (!req.headers.authorization) {
req.headers.authorization = 'Bearer guest-token';
}
return next();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的 Express Setup 中的某处
setupRouters() {
// the public and admin routers are bound to the application
const coreCtrl = new CoreCtrl(this.serverOpts);
const anonymousCtrl = coreCtrl.simulateAnonymous.bind(coreCtrl);
this.routers.admin.use(anonymousCtrl);
this.routers.admin.use(passport.authenticate('UserBearer', { session: false }));
this.routers.public.use(anonymousCtrl);
this.routers.public.use(passport.authenticate('CustomerBearer', { session: false }));
}
Run Code Online (Sandbox Code Playgroud)
请注意,我在这里为公共和管理员设置了单独的路由器,这不是必需的,只是为了说明如何做到这一点。
然后在承载策略中,您将拥有一些与此类似的代码。
/**
* Run the strategy
*
* @param token {String} The JWT Token
* @param done {Callback} Callback function
*/
exec(token:string, done):Promise<any> {
// this is the workaround to support not passing a token for guest users.
if (token === 'guest-token') {
return done(null, {
userId: 'guest',
roles: ['guest']
});
}
// otherwise decode the token and find the user.
}
Run Code Online (Sandbox Code Playgroud)
最后,在稍后的一些中间件中,您可以检查“来宾”角色是否可以访问受保护的资源。我建议使用acl
模块来管理基于角色的 ACL 列表。
归档时间: |
|
查看次数: |
5159 次 |
最近记录: |