I have implemented a jwt authentication in nestJs. However whenever I attempt to authenticate using the following authorization headers:
Bearer <token> or JWT <token>
I got 401. These are my authentication files
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: `${process.env.SECRET}`,
});
}
async validate(payload: Credentials) {
const user: Account = await this.authService.validateAccount(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
handleRequest(err, user, info) {
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;
}
}
and this my auth module
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: `${process.env.SECRET}`,
}),
AccountModule,
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
exports: [PassportModule, AuthService],
})
export class AuthModule {
}
Authorization guard The AuthGuard that we'll build now assumes an authenticated user (and that, therefore, a token is attached to the request headers). It will extract and validate the token, and use the extracted information to determine whether the request can proceed or not.
We need to save both tokens in localStorage even though we only use the accessToken to authorize the user to access private routes, when its expiration time is complete we will need to update this last token, we will create a route in our endpoint called /refresh to receive a new token, so it won't be possible for the ...
Passport is the most popular node.js authentication library, well-known by the community and successfully used in many production applications. It's straightforward to integrate this library with a Nest application using the @nestjs/passport module.
validate
will only be called when you pass a valid jwt token. When the token is signed with a different secret or is expired, validate
will never be called. Make sure you have a valid token. You can check your token for example with the jwt debugger.
I was facing similar issue, the nestjs passport jwt module was working perfectly on my local machine but was not working on the live server. After researching half a day i found that my token header was not reaching the live server, the reason for that is that i am using nginx (proxy_pass) on live server and my header field name was "access_token" so for some reason nginx removed it.
Make a simple global middle-ware and check whether you are receiving the token in the header.
Hope that helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With