Authentication & Roles with Guards/Decorators: How to pass user object? - nestjs

With the help of Guards/Decorators I try to check a JWT first and then the roles a user has.
I have read the documentation regarding Authentication, Guards and Decorators and understand the principles behind them.
However, what I cannot do is to somehow make the authenticated user from JWT-Guard available to Roles-Guards.
In every example that I found, exactly this part that is interesting for me is skipped / left out...
Grateful for every tip!
This is my latest try:
jwt.strategy.ts
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '#nestjs/passport';
import { Injectable } from '#nestjs/common';
import { JwtPayload } from './jwt.model';
#Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
passReqToCallback: true,
ignoreExpiration: false,
secretOrKey: '0000',
expiresIn: '3 days'
});
}
async validate(payload: JwtPayload) {
return {
id: payload.id,
email: payload.email,
username: payload.username
};
}
}
roles.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '#nestjs/common';
import { Reflector } from '#nestjs/core';
#Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {
}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return false;
}
const request = context.switchToHttp().getRequest();
const user = request.user ??? // THIS is what is missing
return roles.some((role) => {
return role === user.role;
});
}
}
roles.decorator.ts
import { SetMetadata } from '#nestjs/common';
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
users.controller.ts
#UseGuards(AuthGuard('jwt'))
#Roles('admin', 'member')
#Get('/')
async doSomething(#Req() req): Promise<User> {
return await this.usersService.doSomething(req.user.id);
}

Your decorator and guards look fine, but from the snippet of your users.controller.ts file it is not clear whether the roles guard is actually applied for the GET / route.
I do, however, have an NestJS app with a quite similar setup based on the guards documentation. The following code in users.controller.ts works as intended:
#UseGuards(JwtAuthGuard, RolesGuard)
#Controller('/users')
export class UserController {
constructor(private readonly userService: UserService) {}
#Get()
#Roles(UserRole.ADMIN)
public async index(): Promise<User[]> {
return this.userService.findAll();
}
// ...
}
Note how both the auth and roles guard are activated in the same scope and that JwtAuthGuard is added before RolesGuard. If I were to change the sequence of the guards then the RolesGuard would not be able to retrieve the user of the request.
Also, you might want to have a look at a similar question from some time ago which contains some details on the order of guards in different scopes.

Related

req.user if undefined in guards whileusing nest js + jwt + passport

I've implemented passport + jwt in my simple nestjs app for authentication. it's working fine. Now I want to use role-based authentication for routes but in my role.guard.ts , req.user is undefined. Please help me solve this issue.
auth.guard.ts
import { Injectable } from '#nestjs/common';
import { AuthGuard } from '#nestjs/passport';
#Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
jwt.strategy.ts
import { Injectable } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { PassportStrategy } from '#nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UserService } from 'src/user/user.service';
import { AuthService } from './auth.service';
#Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
public authService: AuthService,
public configService: ConfigService,
public userService: UserService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get('JWT_SECRET'),
// passReqToCallback: true,
// secretOrKey: authService.getConfig('JWT_SECRET'),
});
}
async validate(payload: any) {
const user = await this.userService.getOne(payload._id);
console.log('user', user);
return user;
// return { id: payload._id };
}
}
user.controller.ts
#Controller('users')
export class UserController {
constructor(private userService: UserService) {}
#Get('/')
#UseGuards(AuthGuard('jwt'))
#UseGuards(RolesGuard)
getAllUsers(): any {
return this.userService.getAll();
}
}
role.guard.ts
import { Injectable, CanActivate, ExecutionContext } from '#nestjs/common';
import * as jwt from '#nestjs/jwt';
import { promisify } from 'util';
#Injectable()
export class RolesGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean | Promise<boolean> {
const req = context.switchToHttp().getRequest();
console.log('req.user', req.user);
return true;
}
}
Don't use two #UseGuards(), use a single one and order the guards in the order you want them to execute:
#UseGuards(AuthGuard('jwt'), RolesGuard)

user is undefined in request pipeline - Nestjs

I have a controller which has an authentication guard and a RBAC authorization guard
#Get('get-framework-lists')
#UseGuards(JwtAuthGuard) // authentication guard
#Roles(Role.SO) // RBAC authorization guard
getFrameworkListsByCompany() {
return this.dashboardService.getFrameworkListsByCompany();
}
JwtAuthGuard look like this -
#Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(#InjectModel(User.name) private userModel: Model<UserDocument>) {
super({
ignoreExpiration: false,
secretOrKey: 'SECRET',
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
});
}
async validate(payload: any) {
const user = await this.userModel.findById(payload.sub);
return {
_id: payload.sub,
name: payload.name,
...user,
};
}
}
I have created a custom Roles.guard.ts for #Roles decorator
#Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRole = this.reflector.getAllAndOverride<Role>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRole) {
return true;
}
console.log({ requiredRole });
const { user } = context.switchToHttp().getRequest();
return requiredRole === user.role;
}
}
In the controller, I can access req.user as user is added to the request object.
However, I am not getting the user as undefined in roles.guard.ts.
What am I doing wrong here?
I think that simple add RolesGuard inside the #UseGuards() decorator, so that both guards can run, will solve your problem.
Like this:
#Get('get-framework-lists')
#UseGuards(JwtAuthGuard, RolesGuard) // here is the change
#Roles(Role.SO)
getFrameworkListsByCompany() {
return this.dashboardService.getFrameworkListsByCompany();
}

NestJS and passport-local : AuthGuard('local') validate() never get called

I've followed the official Nest doc (https://docs.nestjs.com/security/authentication) step by step, but I can't get validate() method called when using #AuthGuard('local') or #AuthGuard(LocalAuthGuard) on login action.
If I don't use that guard decorator, all works as expected (but I need to use it to get my token added to request object).
auth.controller.ts
#UseGuards(AuthGuard('local')) // or AuthGuard(LocalAuthGuard)
#Post('login')
async login(
#Request() req
) {
const { access_token } = await this.authService.login(req.user);
return access_token;
}
}
local.strategy.ts
#Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'email' });
}
async validate(email: string, password: string): Promise<any> { // class is constructed but this method is never called
const user: UserDto = await this.authService.login({
email,
password,
});
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
auth.module.ts
#Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: "bidon",
signOptions: {
expiresIn: '3600',
},
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService, PassportModule, JwtModule],
controllers: [AuthController],
})
export class AuthModule {}
PS : I've already read all stack overflow related posts (for exemple : NestJS' Passport Local Strategy "validate" method never called) but they didn't help me.
I found that if we don't pass email or password, also the wrong value of both, the guard will response Unauthorized message. The problem is how to ensure that validation of the required field before run guard logic if it not defined, In other words, frontend not pass it to server. If we add #Body() data: loginDto in controller method, it won't validate the body params.
to solve it, I add some validation code in local.guard.ts file. Here is my code in my project:
import { HttpException, HttpStatus, Injectable, UnauthorizedException } from "#nestjs/common";
import { AuthGuard } from "#nestjs/passport";
#Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
handleRequest(err, user, info, context, status) {
const request = context.switchToHttp().getRequest();
const { mobile, password } = request.body;
if (err || !user) {
if (!mobile) {
throw new HttpException({ message: '手机号不能为空' }, HttpStatus.OK);
} else if (!password) {
throw new HttpException({ message: '密码不能为空' }, HttpStatus.OK);
} else {
throw err || new UnauthorizedException();
}
}
return user;
}
}
ValidationPipe doesn't validate your request. Because, Gurads are executed before any interceptor or pipe. But, guards are executed after middleware. So, we can create a validation middleware to solve this issue. Here is my solution. Hope it will help somebody.
login.dto.ts
import { ApiProperty } from '#nestjs/swagger';
import { IsEmail, IsNotEmpty } from 'class-validator';
export class LoginDto {
#ApiProperty({ required: true })
#IsNotEmpty()
#IsEmail()
username: string;
#ApiProperty({ required: true })
#IsNotEmpty()
password: string;
}
authValidationMiddleware.ts
import {
Injectable,
NestMiddleware,
BadRequestException,
} from '#nestjs/common';
import { Response, NextFunction } from 'express';
import { validateOrReject } from 'class-validator';
import { LoginDto } from '../dto/login.dto';
#Injectable()
export class AuthValidationMiddleware implements NestMiddleware {
async use(req: Request, res: Response, next: NextFunction) {
const body = req.body;
const login = new LoginDto();
const errors = [];
Object.keys(body).forEach((key) => {
login[key] = body[key];
});
try {
await validateOrReject(login);
} catch (errs) {
errs.forEach((err) => {
Object.values(err.constraints).forEach((constraint) =>
errors.push(constraint),
);
});
}
if (errors.length) {
throw new BadRequestException(errors);
}
next();
}
}
auth.module.ts
import { MiddlewareConsumer, RequestMethod } from '#nestjs/common';
import { AuthController } from './auth.controller';
import { AuthValidationMiddleware } from './middleware/authValidationMiddleware';
#Module({
imports: ['.. imports'],
controllers: [AuthController],
})
export class AuthModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(AuthValidationMiddleware)
.forRoutes({ path: 'auth/login', method: RequestMethod.POST });
}
}
This local strategy expects your body to have username and password fields, on your code change email to username
When you use NestJs Guard then it executed before Pipe therefore ValidationPipe() doesn't validate your request.
https://docs.nestjs.com/guards
Guards are executed after all middleware, but before any interceptor or pipe.
My use case requires only one parameter.
import { Injectable, UnauthorizedException, BadRequestException } from '#nestjs/common'
import { PassportStrategy } from '#nestjs/passport'
import { Request } from 'express'
import { Strategy } from 'passport-custom'
import { AuthService } from '../auth.service'
#Injectable()
export class CustomStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super()
}
async validate(req: Request): Promise<any> {
// req.body.xxx can verify any parameter
if (!req.body.code) {
throw new BadRequestException('Missing code parameters!')
// Using the above, this is how the response would look:
// {
// "message": "Missing code parameters!",
// "error": "Bad Request",
// "statusCode": 400,
// }
}
const user = await this.authService.validateUser(req.body.code)
console.log('user', user)
if (!user) {
throw new UnauthorizedException()
}
return user
}
}

How to pass api key as query string on request url using passport and nestjs

I have developed api-key strategy following https://www.stewright.me/2021/03/add-header-api-key-to-nestjs-rest-api/
and it works, I pass api-key in header and it authorize it.
Now for some cases I need to pass api-key as query params to url instead of header. I wasn't able to figure it out.
example mysite.com/api/book/5?api-key=myapikey
my current code is
api-key-strategy.ts
#Injectable()
export class ApiKeyStrategy extends PassportStrategy(Strategy, 'api-key') {
constructor(private configService: ConfigService) {
super({ header: 'api-key', prefix: '' }, true, async (apiKey, done) =>
this.validate(apiKey, done)
);
}
private validate(apiKey: string, done: (error: Error, data) => any) {
if (
this.configService.get(AuthEnvironmentVariables.API_KEY) === apiKey
) {
done(null, true);
}
done(new UnauthorizedException(), null);
}
}
api-key-auth-gurad.ts
import { Injectable } from '#nestjs/common';
import { AuthGuard } from '#nestjs/passport';
#Injectable()
export class ApiKeyAuthGuard extends AuthGuard('api-key') {}
app.controller
...
#UseGuards(ApiKeyAuthGuard)
#Get('/test-api-key')
testApiKey() {
return {
date: new Date().toISOString()
};
}
...
I found a solution in case someone else has same problem.
I added canActivate method to my guard, then read the api key from request.query, and add it to header. Then the rest of code is working as before and checking header
#Injectable()
export class ApiKeyAuthGuard extends AuthGuard('api-key') {
canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest();
if (request && request.query['api-key'] && !request.header('api-key')) {
(request.headers['api-key'] as any) = request.query['api-key'];
}
return super.canActivate(context);
}
}

How to implement multiple passport jwt authentication strategies in Nestjs

I have an existing authentication for users which is already working fine. The token for user authentication expires within an hour.
I want to implement another separate authentication strategy a third API that is consuming my Nestjs API. There are separate endpoints for the third-party API, the token should expire with 24 hours. The API has to stay connected to my app for 24 hours.
I don't mind using additional package to achieve this.
I also need to create a guard called thirdParty Guard so that the 3rd part API alone will have access to that endpoint.
This is my jwt.strategy.ts
#Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.SECRETKEY
});
}
async validate(payload: any, done: VerifiedCallback) {
const user = await this.authService.validateUser(payload);
if (!user) {
return done(
new HttpException('Unauthorised access', HttpStatus.UNAUTHORIZED),
false,
);
}
//return user;
return done(null, user, payload.iat)
}
}
ApiKey.strategy.ts
#Injectable()
export class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy) {
constructor(private authService: AuthService) {
super({
header: 'api_key',
prefix: ''
}, true,
(apikey: string, done: any, req: any, next: () => void) => {
const checkKey = this.authService.validateApiKey(apikey);
if (!checkKey) {
return done(
new HttpException('Unauthorized access, verify the token is correct', HttpStatus.UNAUTHORIZED),
false,
);
}
return done(null, true, next);
});
}
}
and this is the auth.service.ts
#Injectable()
export class AuthService {
constructor(private userService: UserService) { }
async signPayLoad(payload: any) {
return sign(payload, process.env.SECRETKEY, { expiresIn: '1h' });
}
async validateUser(payload: any) {
const returnuser = await this.userService.findByPayLoad(payload);
return returnuser;
}
validateApiKey(apiKey: string) {
const keys = process.env.API_KEYS;
const apiKeys = keys.split(',');
return apiKeys.find(key => apiKey === key);
}
}
With the above setup, If you are using Passport-HeaderAPIKey then try adding headerapikey in the Guard. The below code worked for me.
Ref: NestJS extending guard
import { ExecutionContext, Injectable } from '#nestjs/common';
import { Reflector } from '#nestjs/core';
import { AuthGuard as NestAuthGuard } from '#nestjs/passport';
#Injectable()
export class AuthGuard extends NestAuthGuard(['jwt', 'headerapikey']) {
constructor(private readonly reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true;
}
return super.canActivate(context);
}
}

Resources