简体   繁体   中英

How to get “validated Body” and “authenticated user” in a request of a NestJS Controller Handler?

I working with a NestJS application that uses "AuthGuard" with 'jwt' strategy.

I would like to receive an authenticated POST from the user.

So I added the @Request() request decorated attribute then i get request.user to get the user. as describe here

I also added the @Body() body decorated attribute to get the body.

But I noticed that I cannot use both. Only the first one is defined.

For instance if I define @Body() body first::

@Post()
@UsePipes(new ValidationPipe({ transform: true })
public create(@Body() body, @Request() request) {
    console.log(body); // { name: 'test'}
    console.log(request); //undefined
}

and if I define @Request() request first:

@Post()
@UsePipes(new ValidationPipe({ transform: true })
public create(@Request() request, @Body() body) {
    console.log(body); // undefined
    console.log(request); //  {name: 'test'}
}

And Without Body and validation

@Post()
public create(@Request() request) {
    console.log(request); //  {name: 'test'}
}

How can I get the authenticated user and the validated body from the same request in this Handler?

Strange that @Request() request is actually returning the Body, not the request itself

Obs, Why do I not use request.body ? because of a custom validation pipe.

Bit confused but pretty sure you need to add the AuthGuard to enable to auth middlewares

@AuthGuard(JwtGuard)
@Controller()
export class TestContoller {
  @Post('something')
  doTheThing(@Body(new ValidationPipe) body: SomeModelDTO, @Req() request): User {
     return request.user;
  }
}
  • User will probably only be set in the auth middleware if you've created a guard correctly etc.
  • Validation pipe requires a class/DTO with class-validator metadata applied to properties

Example DTO

export class SomeModelDTO {
  @IsString()
  name: string;

  @IsArray()
  @IsOptional()
  arr: string[];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM