K
K
keyotor2021-09-05 19:13:26
JSON Web Token
keyotor, 2021-09-05 19:13:26

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 here is my controller
export class AuthController {
    constructor(private authService: AuthService) {}

    @UseGuards(AuthGuard("jwt"))
    @Get()
    getPayload() {
       // здесь мне нужно получить payload который был возвращен из jwt стратегии.
    }
}

How can I get the payload in the controller that was returned in the jwt strategy?
I use nestjs

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2021-09-05
@keyotor

Create your @User decorator:

// user.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { JWTPayload } from '@/api/auth/auth.service';

export const User = createParamDecorator(
  (userField: keyof JWTPayload, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user: JWTPayload | undefined = request.user;

    return userField ? user?.[userField] : user;
  },
);

We use it like this:
export class AuthController {
    constructor(private authService: AuthService) {}

    @UseGuards(AuthGuard("jwt"))
    @Get()
    getPayload(@User() user: JWTPayload) {
       // здесь мне нужно получить payload который был возвращен из jwt стратегии.
    }

    @UseGuards(AuthGuard("jwt"))
    @Get(':id')
    getUserId(@User('id') userId: string) {
       // здесь мне нужно получить payload который был возвращен из jwt стратегии.
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question