node.jsjwtnestjsnestjs-jwt

How to get payload from jwt strategy?


I have jwt strategy:

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

and this is my controller:

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
    }
}

So how can I get the payload in controller that was returned in jwt strategy?


Solution

  • the value returned/resolved by JwtStrategy#validate will be the value of 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