Reputation: 493
I have a project requirement in which I want to disallow some of the API endpoints will not need the authentication. From search, I found that I need to use setMetadata from NestJS library. As I am using @nestjs/passport
for the authentication I don't know how to implement setMetadata.
I have the following code:
sessionKey.guard.ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class SessionKeyAuthGuard extends AuthGuard('sessionKey') {}
In controller file
@Controller('api/deployments')
// comment the line below to stop authentication
@UseGuards(SessionKeyAuthGuard)
@UseInterceptors(PreRequestCacheInterceptor)
@UseInterceptors(PostRequsetCachingInterceptor)
export class AppDeployController {
// API methods
}
What can I try next?
Upvotes: 1
Views: 723
Reputation: 162
Create a decorator to set metadata
export const Public = () => SetMetadata('IS_PUBLIC', true);
In your controller, use the decorator on the route to allow public access
export class AuthController {
@Public()
@Post('/login')
login() {
}
}
In your guard, check the metadata via:
const isPublic = this.reflector.getAllAndOverride<boolean>('IS_PUBLIC', [
context.getHandler(),
]);
Upvotes: 2