NestJs parse user if authenticated










1















I want to know if there is a decorator that makes the 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 in, so it's not suitable for my case.










share|improve this question



















  • 1





    If you have not already, have a look at: docs.nestjs.com/techniques/authentication

    – Rich Duncan
    Nov 12 '18 at 14:15















1















I want to know if there is a decorator that makes the 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 in, so it's not suitable for my case.










share|improve this question



















  • 1





    If you have not already, have a look at: docs.nestjs.com/techniques/authentication

    – Rich Duncan
    Nov 12 '18 at 14:15













1












1








1








I want to know if there is a decorator that makes the 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 in, so it's not suitable for my case.










share|improve this question
















I want to know if there is a decorator that makes the 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 in, so it's not suitable for my case.







javascript node.js typescript passport.js nestjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 14:23









Kim Kern

8,43732649




8,43732649










asked Nov 11 '18 at 14:42









karimkarim

1,35942037




1,35942037







  • 1





    If you have not already, have a look at: docs.nestjs.com/techniques/authentication

    – Rich Duncan
    Nov 12 '18 at 14:15












  • 1





    If you have not already, have a look at: docs.nestjs.com/techniques/authentication

    – Rich Duncan
    Nov 12 '18 at 14:15







1




1





If you have not already, have a look at: docs.nestjs.com/techniques/authentication

– Rich Duncan
Nov 12 '18 at 14:15





If you have not already, have a look at: docs.nestjs.com/techniques/authentication

– Rich Duncan
Nov 12 '18 at 14:15












1 Answer
1






active

oldest

votes


















3














There is no built-in decorator but you can easily create one yourself. See the example from the docs:



import createParamDecorator from '@nestjs/common';
import AuthGuard from '@nestjs/passport';

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


Since the built-in AuthGuard throws an exception, you can create your own version and overwrite the request handler:



@Injectable()
export class MyAuthGuard extends AuthGuard('jwt')

handleRequest(err, user, info)
// no error is thrown if no user is found
// You can use info for logging (e.g. token is expired etc.)
// e.g.: if (info instanceof TokenExpiredError) ...
return user;





Make sure that you are not throwing errors in your JwtStrategy:



@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy)
constructor(private readonly authService: AuthService)
super(
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
);


async validate(payload)
const user = await this.authService.validateUser(payload);
// in the docs an error is thrown if no user is found
return user;




Then you can use it in your Controller like this:



@Get()
@UseGuards(MyAuthGuard)
getUser(@User() user)
return user;






share|improve this answer

























  • I've updated my answer with a better solution.

    – Kim Kern
    Nov 14 '18 at 14:14










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249800%2fnestjs-parse-user-if-authenticated%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














There is no built-in decorator but you can easily create one yourself. See the example from the docs:



import createParamDecorator from '@nestjs/common';
import AuthGuard from '@nestjs/passport';

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


Since the built-in AuthGuard throws an exception, you can create your own version and overwrite the request handler:



@Injectable()
export class MyAuthGuard extends AuthGuard('jwt')

handleRequest(err, user, info)
// no error is thrown if no user is found
// You can use info for logging (e.g. token is expired etc.)
// e.g.: if (info instanceof TokenExpiredError) ...
return user;





Make sure that you are not throwing errors in your JwtStrategy:



@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy)
constructor(private readonly authService: AuthService)
super(
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
);


async validate(payload)
const user = await this.authService.validateUser(payload);
// in the docs an error is thrown if no user is found
return user;




Then you can use it in your Controller like this:



@Get()
@UseGuards(MyAuthGuard)
getUser(@User() user)
return user;






share|improve this answer

























  • I've updated my answer with a better solution.

    – Kim Kern
    Nov 14 '18 at 14:14















3














There is no built-in decorator but you can easily create one yourself. See the example from the docs:



import createParamDecorator from '@nestjs/common';
import AuthGuard from '@nestjs/passport';

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


Since the built-in AuthGuard throws an exception, you can create your own version and overwrite the request handler:



@Injectable()
export class MyAuthGuard extends AuthGuard('jwt')

handleRequest(err, user, info)
// no error is thrown if no user is found
// You can use info for logging (e.g. token is expired etc.)
// e.g.: if (info instanceof TokenExpiredError) ...
return user;





Make sure that you are not throwing errors in your JwtStrategy:



@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy)
constructor(private readonly authService: AuthService)
super(
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
);


async validate(payload)
const user = await this.authService.validateUser(payload);
// in the docs an error is thrown if no user is found
return user;




Then you can use it in your Controller like this:



@Get()
@UseGuards(MyAuthGuard)
getUser(@User() user)
return user;






share|improve this answer

























  • I've updated my answer with a better solution.

    – Kim Kern
    Nov 14 '18 at 14:14













3












3








3







There is no built-in decorator but you can easily create one yourself. See the example from the docs:



import createParamDecorator from '@nestjs/common';
import AuthGuard from '@nestjs/passport';

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


Since the built-in AuthGuard throws an exception, you can create your own version and overwrite the request handler:



@Injectable()
export class MyAuthGuard extends AuthGuard('jwt')

handleRequest(err, user, info)
// no error is thrown if no user is found
// You can use info for logging (e.g. token is expired etc.)
// e.g.: if (info instanceof TokenExpiredError) ...
return user;





Make sure that you are not throwing errors in your JwtStrategy:



@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy)
constructor(private readonly authService: AuthService)
super(
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
);


async validate(payload)
const user = await this.authService.validateUser(payload);
// in the docs an error is thrown if no user is found
return user;




Then you can use it in your Controller like this:



@Get()
@UseGuards(MyAuthGuard)
getUser(@User() user)
return user;






share|improve this answer















There is no built-in decorator but you can easily create one yourself. See the example from the docs:



import createParamDecorator from '@nestjs/common';
import AuthGuard from '@nestjs/passport';

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


Since the built-in AuthGuard throws an exception, you can create your own version and overwrite the request handler:



@Injectable()
export class MyAuthGuard extends AuthGuard('jwt')

handleRequest(err, user, info)
// no error is thrown if no user is found
// You can use info for logging (e.g. token is expired etc.)
// e.g.: if (info instanceof TokenExpiredError) ...
return user;





Make sure that you are not throwing errors in your JwtStrategy:



@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy)
constructor(private readonly authService: AuthService)
super(
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
);


async validate(payload)
const user = await this.authService.validateUser(payload);
// in the docs an error is thrown if no user is found
return user;




Then you can use it in your Controller like this:



@Get()
@UseGuards(MyAuthGuard)
getUser(@User() user)
return user;







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 14 '18 at 14:13

























answered Nov 12 '18 at 14:22









Kim KernKim Kern

8,43732649




8,43732649












  • I've updated my answer with a better solution.

    – Kim Kern
    Nov 14 '18 at 14:14

















  • I've updated my answer with a better solution.

    – Kim Kern
    Nov 14 '18 at 14:14
















I've updated my answer with a better solution.

– Kim Kern
Nov 14 '18 at 14:14





I've updated my answer with a better solution.

– Kim Kern
Nov 14 '18 at 14:14

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249800%2fnestjs-parse-user-if-authenticated%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế