My purpose is make a role guard to verify the permission of user. I trying to extract authorization header to get the role information which is include on JWT. I implemented canActivate interface to check role of use but i don't know how to get the role info from JWT to verify it.
export class RolesGuard implements CanActivate {
constructor(private readonly _reflector: Reflector) {
}
canActivate(context: ExecutionContext): boolean {
const roles = this._reflector.get<UserRole[]>(
'roles',
context.getHandler(),
);
if (!roles || roles.length === 0) {
return true;
}
const request = context.switchToHttp().getRequest();
const user: InstanceType<User> = request.headers.role;
// i want to get the role from JWT in here
const hasRole = () => roles.indexOf(user.role) >= 0;
if (user && user.role && hasRole()) {
return true;
}
throw new HttpException(
'You do not have permission (Roles)',
HttpStatus.UNAUTHORIZED,
);
}
}
I tried extends PassportStrategy, but it can't work together with CanActive
One option is to use the JwtService from the JwtModule and use jwtService.decode(myJwt) to get the decoded JWT and get the role from there. The other is to use the built Passport Guard (AuthGuard), extend the functionality, and call super.canActivate(context) before your custom logic. Store he result and immediately check if the user has passport access before continuing with your custom logic.
// the mention of jwt in the AuthGuard is only needed if not working with defaultStrategy
export class RolesGuard extends AuthGuard('jwt') {
constructor(private readonly _reflector: Reflector) {
super()
}
canActivate(context: ExecutionContext): boolean {
const passportActive = super.canActivate(context);
if (!passportActivate) {
throw new HttpException(
'You do not have permission (Roles)',
HttpStatus.UNAUTHORIZED,
);
}
const roles = this._reflector.get<UserRole[]>(
'roles',
context.getHandler(),
);
if (!roles || roles.length === 0) {
return true;
}
const request = context.switchToHttp().getRequest();
// this should come from passport
const user: InstanceType<User> = request.user;
// i want to get the role from JWT in here
const hasRole = () => roles.indexOf(user.role) >= 0;
if (user && user.role && hasRole()) {
return true;
}
throw new HttpException(
'You do not have permission (Roles)',
HttpStatus.UNAUTHORIZED,
);
}
}
Related
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();
}
I am using nestjs, graphql, & prisma. I am trying to figure out how to pass my jwt token for each database request to the prisma service iv created. Iv tried an object to the constructor but then wont compile saying I am missing a dependency injection for whatever I reference in the constructor paramter.
#Injectable()
export class PrismaService
extends PrismaClient
implements OnModuleDestroy {
constructor() {
super();
//TODO how do I pass my jwt token to this for each request?
this.$use(async (params, next) => {
if (params.action === 'create') {
params.args.data['createdBy'] = 'jwt username goes here';
}
if (params.action === 'update') {
params.args.data['updatedBy'] = 'jwt username goes here';
}
const result = await next(params);
return result;
});
}
async onModuleDestroy() {
await this.$disconnect();
}
}
Are you using a nest middleware?
JWT is normally passed to a Controller, not a service.
Example:
#Injectable()
export class MyMiddleware implements NestMiddleware {
private backend: any // This is your backend
constructor() {
this.backend = null // initialize your backend
}
use(req: Request, res: Response, next: any) {
const token = <string>req.headers.authorization
if (token != null && token != '') {
this.backend
.auth()
.verifyIdToken(<string>token.replace('Bearer ', ''))
.then(async (decodedToken) => {
const user = {
email: decodedToken.email,
uid: decodedToken.uid,
tenantId: decodedToken.tenantId,
}
req['user'] = user
next()
})
.catch((error) => {
log.info('Token validation failed', error)
this.accessDenied(req.url, res)
})
} else {
log.info('No valid token provided', token)
return this.accessDenied(req.url, res)
}
}
private accessDenied(url: string, res: Response) {
res.status(403).json({
statusCode: 403,
timestamp: new Date().toISOString(),
path: url,
message: 'Access Denied',
})
}
}
So every time I get an API call with a valid token, the token is added to the user[] in the request.
In my Controller Class I can then go ahead and use the data:
#Post()
postHello(#Req() request: Request): string {
return 'Hello ' + request['user']?.tenantId + '!'
}
I just learned about an update in Nest.js which allows you to easily inject the header also in a Service. Maybe that is exactly what you need.
So in your service.ts:
import { Global, INestApplication, Inject, Injectable, OnModuleInit, Scope } from '#nestjs/common'
import { PrismaClient } from '#prisma/client'
import { REQUEST } from '#nestjs/core'
#Global()
#Injectable({ scope: Scope.REQUEST })
export class PrismaService extends PrismaClient implements OnModuleInit {
constructor(#Inject(REQUEST) private readonly request: any) {
super()
console.log('request:', request?.user)
}
async onModuleInit() {
// Multi Tenancy Middleware
this.$use(async (params, next) => {
// Check incoming query type
console.log('params:', params)
console.log('request:', this.request)
return next(params)
})
await this.$connect()
}
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close()
})
}
}
As you can see in the log output, you have access to the entire request object.
I have two microservices one for authentication and another for users. I can log in and get a token, and i can use protected routes only when logged in. However I want to use the userId which i get in the AuthGuard's canActivate function, but i cant reach it in the controller. What is the best way to do it?
My auth guard:
import { CanActivate, ExecutionContext, Inject, Logger } from '#nestjs/common';
import { ClientProxy } from '#nestjs/microservices';
export class JwtAuthGuard implements CanActivate {
constructor(
#Inject('AUTH_CLIENT')
private readonly client: ClientProxy,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
try {
const res = await this.client
.send(
{ role: 'auth', cmd: 'check' },
{ jwt: req.headers['authorization']?.split(' ')[1] },
)
.toPromise<boolean>();
return res;
} catch (err) {
Logger.error(err);
return false;
}
}
}
The controller:
#UseGuards(JwtAuthGuard)
#Get('greet')
async greet(#Request() req): Promise<string> {
return 'AUTHENTICATED!' + req;
}
The response:
AUTHENTICATED![object Object]
Attach the userId that you get in the AuthGuard to the req object and then you can access it in the controller:
// after fetching the auth user in the AuthGuard, attach its ID like this
req.userId = authUser.id
And in the controller, you can access it like this:
#UseGuards(JwtAuthGuard)
#Get('greet')
async greet(#Request() req): Promise<string> {
return 'AUTHENTICATED USER ID!' + req.userId;
}
I just started using nestjs for a project. I have successfully logged in users and token returned. Now using the token to authorize users is the problem. Trying to get all users has been returning "unauthorized access"
I am also thinking I didn't put the token correctly or so. In the swagger authorization UI, I supplied
Bearer someTokenGoesHere into the input box
Image below
This is my code
main.ts
Swagger configuration in main.ts
const options = new DocumentBuilder().addBearerAuth()
.setTitle('My app')
.setDescription('My app API description')
.setVersion('1.0')
.addTag('Tags')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('', app, document);
User controller
import { Controller, Post, Body, Get, Param, UseGuards } from '#nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './create-user.dto';
import { LoginUserDto } from './login-user.dto';
import { AuthService } from 'src/auth/auth.service';
import { AuthGuard } from '#nestjs/passport';
import { AdminGuard } from 'src/guards/admin.guard';
import { ApiBearerAuth, ApiBasicAuth } from '#nestjs/swagger';
#Controller('user')
export class UserController {
constructor(private userService: UserService,
private authService: AuthService) { }
#Post('login')
async login(#Body() loginDTO: LoginUserDto) {
const user = await this.userService.login(loginDTO);
const newob = {
id: user._id
}
const payload = {
userId: user._id,
email: user.Email,
}
const token = await this.authService.signPayLoad(payload);
return { newob, token };
}
#Post('register')
async register(#Body() createDTO: CreateUserDto) {
const user = await this.userService.register(createDTO);
const newob = {
id: user._id
}
const payload = {
firstname: user.FirstName,
lastname: user.LastName
};
const token = await this.authService.signPayLoad(payload);
return newob;
}
#Get('all')
#ApiBearerAuth()
#UseGuards(AuthGuard('jwt'))
async getAllUsers() {
return await this.userService.getAllUsers();
}
#Post('confirm/:token')
async confirmEmail(#Param() token: string) {
const user = await this.userService.ConfirmEmail(token);
return user;
}
}
Can someone please help me out
Thanks
I was able to fix it, I appreciate your suggestions. I was extracting email that wasn't present in the payload. so I decided to log it and discovered it was null. Then I logout payload, I discovered I was passing User Id into the payload. So I change to id.
The result is
async findByPayLoad(payload: any) {
const { userId } = payload;
return await this.userModel.findById(userId)
}
I'm trying to implement a passport strategy (passport-headerapikey), I was able to make it work and I can secure my routes.
But the request is empty and cannot access the logged in user ?
import { HeaderAPIKeyStrategy } from "passport-headerapikey";
import { PassportStrategy } from "#nestjs/passport";
import { Injectable, NotFoundException } from "#nestjs/common";
import { CompanyService } from "../../companies/companies.service";
#Injectable()
export class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy, "api-key") {
constructor(private readonly companyService: CompanyService) {
super(
{
header: "Authorization",
prefix: "Api-Key "
},
true,
async (apiKey, done) => {
return this.validate(apiKey, done);
}
);
}
public async validate(apiKey: string, done: (error: Error, data) => {}) {
const company = await this.companyService.findByApiKey(apiKey);
if (company === null) {
throw new NotFoundException("Company not found");
}
return company;
}
}
#UseGuards(AuthGuard("api-key"))
export class CompaniesController {
constructor(private companyService: CompanyService) {}
#Get()
#ApiOperation({ title: "Get company information" })
public getCompany(#Request() req) {
// here request is empty, so i cannot access the user..
console.log("request", req);
return [];
}
}
Thanks for your help !
To access the logged user, you can inject the object in the request. To do that, in your ApiKeyStrategy constructor, change the third parameter to something like this:
async (apiKey, verified, req) => {
const user = await this.findUser(apiKey);
// inject the user in the request
req.user = user || null;
return verified(null, user || false);
}
Now, you can access the logged user:
getCompany(#Request() req) {
console.log(req.user);
}
I hope that could help you.
As show in the documentation you should do some works to get the current user : here the documetation
First of all in the app.module make sure that the context is set :
context: ({ req }) => ({ req })
Then you can add this in the controller/resolver, this example use the Gql (GraphQL):
export const CurrentUser = createParamDecorator(
(data: unknown, context: ExecutionContext) => {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req.user;
},
);
if this one doesnt work for you try this one instead :
export const CurrentUser = createParamDecorator(
(data: unknown, context: ExecutionContext) => {
const ctx = GqlExecutionContext.create(context);
const request = ctx.getContext();
request.body = ctx.getArgs();
return request.user;
},
);
Modify your validate method like so:
public async validate(apiKey: string, done: (error: Error, data) => {}) {
const company = await this.companyService.findByApiKey(apiKey);
if (company === null) {
return done(new NotFoundException("Company not found"), null);
}
return done(null, company);
}