Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJs JWT Authentication returns 401

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 {

}
like image 944
Arsene Avatar asked Apr 23 '19 23:04

Arsene


People also ask

What is AuthGuard in Nestjs?

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.

How does Nestjs implement refresh token?

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 ...

What is Nestjs passport?

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.


2 Answers

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.

like image 124
Kim Kern Avatar answered Nov 15 '22 09:11

Kim Kern


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.

like image 40
All2Pie Avatar answered Nov 15 '22 10:11

All2Pie