Node.js JWT Passport的NestJS身份验证不起作用

Node.js JWT Passport的NestJS身份验证不起作用,node.js,angular,jwt,nestjs,passport-local,Node.js,Angular,Jwt,Nestjs,Passport Local,我正在尝试使用JWTPassport和nestjs建立一个非常简单的登录系统。我遵循了这个教程:但我就是不能让它工作。我真的是新手,如果有人能给我指路,我将不胜感激 将登录名发送到服务器的方式: this.clientAuthService.login(this.userName, this.password).then(response => { this.clientAuthService.setToken(response.access_token);

我正在尝试使用JWTPassport和nestjs建立一个非常简单的登录系统。我遵循了这个教程:但我就是不能让它工作。我真的是新手,如果有人能给我指路,我将不胜感激

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

    this.clientAuthService.login(this.userName, this.password).then(response => {
        this.clientAuthService.setToken(response.access_token);
        this.router.navigate(['/backend']);
    });
我的客户授权服务:

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();
  }

}

我的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);
  }
}
以及本地的.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 };
  }
}

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;
  }
}

导出类LocalStrategy扩展了PassportStrategy(策略){
构造函数(专用只读authService:authService){
超级();
}
异步验证(用户名:字符串,密码:字符串):承诺{
const user=wait this.authService.validateUser(用户名、密码);
如果(!用户){
抛出新的UnauthorizedException();
}
返回用户;
}
}
大多数情况下,我只是遵循教程,自己为客户端添加了一些东西。 我错过了登录路径的
UseGuard('local')
部分,但是在我添加它之后,我总是得到401错误。 当我不使用
UseGuard('local')
时,我在登录表单中键入什么并不重要。在我提交详细信息后,我可以访问后端,即使它不正确

另外,值得一提的是,jwt.strategy.ts和local.strategy.ts中的validate方法在WebStorm中标记为
未使用

我知道这里有很多代码,但我需要帮助,因为我找不到其他最新的NestJS auth配置源。对于初学者来说,我觉得我遵循的教程遗漏了很多步骤

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

为了添加更多的上下文,在上图中,您可以找到指定签名实现的细节。因此,必须在正文中发送准确的“用户名”和“密码”属性

注意:如果要自定义本地策略服务的签名,只需在
super()
中传递一个新对象即可指定新属性:

constructor(){
超级({usernameField:'email'});
}

Ref:

非常感谢您的回复。我仍然不知道是什么问题,但我创建了一个新项目,严格按照教程进行操作,现在它可以正常工作了。之前,我没有像教程中提到的那样创建单独的模块。也许这就是问题所在。
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;
  }
}