NestJs JWT Authentication returns 401

雨燕双飞 提交于 2020-03-05 04:01:54

问题


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 {

}

回答1:


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.




回答2:


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.




回答3:


i was stuck in the same problem. Here my code (working) for you to compare:

src/auth/auth.module.ts

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { UserModule } from 'src/user/user.module';
import { PassportModule } from '@nestjs/passport';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: '1d',
      },
    }),
    UserModule,
  ],
  providers: [AuthService, JwtStrategy],
  exports: [PassportModule, AuthService],
})
export class AuthModule {}

src/auth/auth.service.ts

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from './interfaces/jwt-payload.interface';
import { UserService } from 'src/user/user.service';

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly userService: UserService,
  ) {}

  makeToken(payload: JwtPayload) {
    const { email } = payload;
    return this.jwtService.sign({ email });
  }

  checkToken(token: string) {
    return this.jwtService.verify(token);
  }

  async validateUser(payload: JwtPayload) {
    return await this.userService.read(payload.email);
  }
}

src/auth/jwt.strategy.ts

import { Strategy, ExtractJwt, VerifiedCallback } from 'passport-jwt';
import { AuthService } from './auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtPayload } from './interfaces/jwt-payload.interface';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secretKey',
    });
  }

  async validate(payload: JwtPayload, done: VerifiedCallback) {
    const user = await this.authService.validateUser(payload);
    if (!user) {
      done(new UnauthorizedException(), false);
    }
    return done(null, user);
  }
}

src/auth/interfaces/jwt-payload.interface.ts

export interface JwtPayload {
  email: string;
}

src/account/account.module.ts

import { Module } from '@nestjs/common';
import { AccountController } from './account.controller';
import { PassportModule } from '@nestjs/passport';
import { AuthModule } from 'src/auth/auth.module';

@Module({
  imports: [AuthModule],
  controllers: [AccountController],
})
export class AccountModule {}

src/account/account.controller.ts

import { Controller, UseGuards, Post } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('account')
export class AccountController {
  @Post('skills')
  @UseGuards(AuthGuard())
  updateSkills() {
    return console.log('something');
  }
}

P.S.: I did not do a JwtAuthGuard.

I hope it helped you :)




回答4:


You can view a minimum working example with passport and NestJS

https://github.com/leosuncin/nest-auth-example

Main differences with your code:

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }), // I don't do this because I explicity call every stratategy
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: '1d',
      },
    }),
    UserModule,
  ],
  providers: [AuthService, JwtStrategy],
  exports: [PassportModule, AuthService], // I don't do this
})

I don't use any JwtAuthGuard just use the default one.



来源:https://stackoverflow.com/questions/55820591/nestjs-jwt-authentication-returns-401

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!