使用 JWT Passport 进行 NestJS 身份验证不起作用

xDr*_*ago 3 node.js jwt passport-local angular nestjs

我正在尝试使用 jwt-passport 和 nestjs 来设置一个非常简单的登录系统。我遵循了本教程:https : //docs.nestjs.com/techniques/authentication但我无法让它工作。我对这些东西真的很陌生,如果有人能给我指路,我将不胜感激。

我将登录名发送到服务器的方式:

    this.clientAuthService.login(this.userName, this.password).then(response => {
        this.clientAuthService.setToken(response.access_token);
        this.router.navigate(['/backend']);
    });
Run Code Online (Sandbox Code Playgroud)

我的 ClientAuthService:

export class ClientAuthService {

  constructor(private http: HttpClient, @Inject(PLATFORM_ID) private platformId) {
  }

  getToken(): string {
    if (isPlatformBrowser(this.platformId)) {
      return localStorage.getItem(TOKEN_NAME);
    } else {
      return '';
    }
  }

  setToken(token: string): void {
    if (isPlatformBrowser(this.platformId)) {
      localStorage.setItem(TOKEN_NAME, token);
    }
  }

  removeToken() {
    if (isPlatformBrowser(this.platformId)) {
      localStorage.removeItem(TOKEN_NAME);
    }
  }

  getTokenExpirationDate(token: string): Date {
    const decoded = jwt_decode(token);

    if (decoded.exp === undefined) {
      return null;
    }

    const date = new Date(0);
    date.setUTCSeconds(decoded.exp);
    return date;
  }

  isTokenExpired(token?: string): boolean {
    if (!token) {
      token = this.getToken();
    }
    if (!token) {
      return true;
    }

    const date = this.getTokenExpirationDate(token);
    if (date === undefined) {
      return false;
    }
    return !(date.valueOf() > new Date().valueOf());
  }

  login(userName: string, password: string): Promise<any> {
    const loginData = {username: userName, password};
    return this.http
      .post(Constants.hdaApiUrl + 'user/login', loginData, {headers: new HttpHeaders({'Content-Type': 'application/json'})})
      .toPromise();
  }

}

Run Code Online (Sandbox Code Playgroud)

我的 user.controller.ts

@Controller('user')
export class UserController {

  constructor(private readonly authService: AuthService) {
  }

  @UseGuards(AuthGuard('local'))
  @Post('login')
  authenticate(@Request() req) {
    return this.authService.login(req);
  }

}

Run Code Online (Sandbox Code Playgroud)

我的 user.service.ts

export class UsersService {
  private readonly users: User[];

  constructor() {
    this.users = [
      {
        userId: 1,
        username: 'test',
        password: '12345',
      }
    ];
  }

  async findOne(username: string): Promise<User | undefined> {
    return this.users.find(user => user.username === username);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我有 jwt.strategy.ts

export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: Constants.jwtSecret,
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}

Run Code Online (Sandbox Code Playgroud)

和 local.strategy.ts

export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super();
  }

  async validate(username: string, password: string): Promise<any> {
    const user = await this.authService.validateUser(username, password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

Run Code Online (Sandbox Code Playgroud)

大多数情况下,我只是按照教程并自己为客户端添加了一些东西。我错过了UseGuard('local')登录路由的部分,但是在我添加它之后,我总是收到 401 错误。当我不使用时UseGuard('local'),我在登录表单中输入什么并不重要。提交详细信息后,即使它不正确,我也可以访问后端。

此外,值得一提的是 jwt.strategy.ts 和 local.strategy.ts 中的验证方法在 WebStorm 中标记为not used

我知道这里有很多代码,但我需要帮助,因为我找不到任何其他最新的 NestJS 身份验证配置来源。感觉就像我遵循的教程错过了很多初学者的步骤。

小智 5

确保您的帖子正文(有效负载)与验证方法的签名相同(实际上必须是用户名和密码)。