NestJs parse user if authenticated
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
add a comment |
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
1
If you have not already, have a look at: docs.nestjs.com/techniques/authentication
– Rich Duncan
Nov 12 '18 at 14:15
add a comment |
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
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
javascript node.js typescript passport.js nestjs
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
add a comment |
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
add a comment |
1 Answer
1
active
oldest
votes
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;
I've updated my answer with a better solution.
– Kim Kern
Nov 14 '18 at 14:14
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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;
I've updated my answer with a better solution.
– Kim Kern
Nov 14 '18 at 14:14
add a comment |
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;
I've updated my answer with a better solution.
– Kim Kern
Nov 14 '18 at 14:14
add a comment |
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;
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;
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
1
If you have not already, have a look at: docs.nestjs.com/techniques/authentication
– Rich Duncan
Nov 12 '18 at 14:15