NestJs parse user if authenticated
up vote
1
down vote
favorite
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 |
up vote
1
down vote
favorite
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 at 14:15
add a comment |
up vote
1
down vote
favorite
up vote
1
down vote
favorite
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 at 14:23
Kim Kern
7,26922243
7,26922243
asked Nov 11 at 14:42
karim
1,33841936
1,33841936
1
If you have not already, have a look at: docs.nestjs.com/techniques/authentication
– Rich Duncan
Nov 12 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 at 14:15
1
1
If you have not already, have a look at: docs.nestjs.com/techniques/authentication
– Rich Duncan
Nov 12 at 14:15
If you have not already, have a look at: docs.nestjs.com/techniques/authentication
– Rich Duncan
Nov 12 at 14:15
add a comment |
1 Answer
1
active
oldest
votes
up vote
3
down vote
accepted
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 at 14:14
add a comment |
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
3
down vote
accepted
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 at 14:14
add a comment |
up vote
3
down vote
accepted
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 at 14:14
add a comment |
up vote
3
down vote
accepted
up vote
3
down vote
accepted
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 at 14:13
answered Nov 12 at 14:22
Kim Kern
7,26922243
7,26922243
I've updated my answer with a better solution.
– Kim Kern
Nov 14 at 14:14
add a comment |
I've updated my answer with a better solution.
– Kim Kern
Nov 14 at 14:14
I've updated my answer with a better solution.
– Kim Kern
Nov 14 at 14:14
I've updated my answer with a better solution.
– Kim Kern
Nov 14 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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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 at 14:15