【问题标题】:How to get payload from jwt strategy?如何从 jwt 策略中获取有效载荷?
【发布时间】:2021-11-02 23:18:07
【问题描述】:

我有 jwt 策略:

export class JwtStrategy extends PassportStrategy(Strategy, "jwt") {
    constructor() {
        super({
            ignoreExpiration: false,
            secretOrKey: "secret",
            jwtFromRequest: ExtractJwt.fromExtractors([
                (request: Request) => {
                let data = request.cookies['access'];
                    return data;
                }
            ]),
        });
    }

    async validate(payload: any){
        return payload;
    }
}

这是我的控制器:

export class AuthController {
    constructor(private authService: AuthService) {}

    @UseGuards(AuthGuard("jwt"))
    @Get()
    getPayload() {
        //here I need to get the payload that was returned in jwt strategy
    }
}

那么我怎样才能在控制器中获取 jwt 策略中返回的有效负载呢?

【问题讨论】:

    标签: node.js jwt nestjs nestjs-jwt


    【解决方案1】:

    JwtStrategy#validate 返回/解析的值将是req.user 的值

    import { Req } from '@nestjs/common'
    // ...
        @UseGuards(AuthGuard("jwt"))
        @Get()
        getPayload(@Req() req: any) {
           console.log(req.user)
        }
    

    https://docs.nestjs.com/security/authentication#login-route

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2020-04-26
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多