Reputation: 563
Good morning everyone,
I wanted to ask this as I am new to Nest.js and haven't found an answer to my problem, I have an application that has the authentication from Azure B2C and I need to guard the endpoints for the application. I am trying to use passport to validate the token and see if the user can use the endpoint or not. But I keep getting this error:
Error: Unknown authentication strategy "jwt"
So I have been going everywhere with it and I still can't find a solution, tried all the nest.js official documentation and some samples here as well. I might be missing something but sometimes someone who has done this has a clearer insight.
This is the files I used for the implementation of passport, so any pointer or idea is greatly appreciated.
app.module.ts
import { PassportModule } from '@nestjs/passport'
import { JwtModule } from '@nestjs/jwt'
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule
]
endpoint.guard.ts
import { ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Injectable()
export class EndpointGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
// Add your custom authentication logic here
// for example, call super.logIn(request) to establish a session.
return super.canActivate(context);
}
handleRequest(err: any, user: any, info: any) {
// You can throw an exception based on either "info" or "err" arguments
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;
}
}
endpoint.strategy.ts
import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
@Injectable()
export class EndpointStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'INSERT WEIRD KEY HERE'
})
}
async validate(payload: any) {
return { userId: payload.sub, email: payload.email, idp: payload.idp };
}
}
And the controller only has the @UseGuard(EndpointGuard) decorator to use the guard I created. But I only get this weird error here. Any help or idea is greatly appreciated and thank you all very much in advance.
Upvotes: 0
Views: 852
Reputation: 70510
The EndpointStrategy
was not added to a providers
array, so the strategy was never registered with passport
Upvotes: 0