Nest: NestJs parse user if authenticated

Created on 11 Nov 2018  路  5Comments  路  Source: nestjs/nest

i want to know if there is a decorator that make req.user object available in a controller method, if the user is logged in (Authaurization header sent), if not then just let the req.user be null.

The AuthGuard decorator will return 401 if the user is not logged, so it's not suitable for my case.

Most helpful comment

AuthGuard throw UnauthorizedException when there鈥檚 no User. You can always create a custom AuthGuard and instead of throwing exception, you can just return null :)

All 5 comments

You can create your own parameter decorators using createParamDecorator

import { createParamDecorator } from '@nestjs/common';

export const User = createParamDecorator((, req) => req.user);

Related: https://github.com/nestjs/nest/issues/830

@marcus-sa i think that not the problem, the problem i have with the user is that if the route don't have a AuthGuard decorator, the user is not parsed from the jwt token, so req.user is always null.

i have a special requirement for an api endpoint, if the user is logged, then there is a special code for this case. but if not, then the method should be working without returning 401 error ( Authorization required).

And i can't do that with the AuthGuard decorator

Then you just assign the user object to the express request when you're logging the user in?

AuthGuard throw UnauthorizedException when there鈥檚 no User. You can always create a custom AuthGuard and instead of throwing exception, you can just return null :)

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FranciZ picture FranciZ  路  3Comments

breitsmiley picture breitsmiley  路  3Comments

KamGor picture KamGor  路  3Comments

VRspace4 picture VRspace4  路  3Comments

rafal-rudnicki picture rafal-rudnicki  路  3Comments