0

我有 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 策略中返回的有效负载呢?

4

1 回答 1

2

返回/解析的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

于 2021-09-05T16:28:50.483 回答