MrD*_*t0r 0 node.js jwt nestjs passport-jwt
我有一个 NestJS 后端,由 JWT 保护。我想知道存储实际用户或将其传递给我的服务的最佳方式是什么?
我有一个 JwtAuthGuard
@Injectable()
export class JwtAuthGuard extends AuthGuard( 'jwt' ) {
canActivate(context: ExecutionContext) {
return super.canActivate( context );
}
handleRequest(err, user, info) {
if ( err || !user ) {
throw err || new UnauthorizedException();
}
return user;
}
}
Run Code Online (Sandbox Code Playgroud)
我的实际用户 ID 位于 handleRequest 中的 user var 中,但我不知道在哪里“存储”它以便能够在某些模块中访问它。有人可以帮助我吗?
谢谢
JWT 本身是存储用户 ID(或用户的任何识别详细信息)的位置。
如果您使用用户 ID ( { id: 123, ... }) 创建 JWT 有效负载,则护照会将user成员设置为request对象。
重要提示:不要在 JWT 中存储敏感数据。
@AuthGuard( 'jwt' )
@Get('profile')
getUserId(@Request() req: any) {
return req.user.id;
}
Run Code Online (Sandbox Code Playgroud)
您可以req.user.id根据需要将其传递给服务。
请参阅:https://docs.nestjs.com/techniques/authentication#implement-protected-route-and-jwt-strategy-guards
最后一件事:如果你喜欢请求对象的类型,你可以这样做
import { Request as HttpRequest } from 'express';
interface UserJwtPayload {
id: string,
}
type AuthRequest = HttpRequest & { user: UserJwtPayload }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9665 次 |
| 最近记录: |