node.js - 使用 JWT Passport 的 NestJS 身份验证不起作用

标签 node.js angular jwt nestjs passport-local

我正在尝试使用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']);
    });

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

}

我的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);
  }

}

我的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);
  }
}

然后我有 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 };
  }
}

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

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

此外,可能值得一提的是,jwt.strategy.ts 和 local.strategy.ts 中的验证方法在 WebStorm 中被标记为未使用

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

最佳答案

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

关于node.js - 使用 JWT Passport 的 NestJS 身份验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58101722/

相关文章:

oauth-2.0 - 如何防止刷新被盗的访问 token

reactjs - 如何在reactjs中获取服务器发送的JWT cookie

javascript - 通过 POST 将文件传递给 NodeJS,然后传递给另一个 API,而不保存在磁盘上

angular - 如何使用 RxJS 调整重试超时时间?

node.js - 检索nodejs中的最后一个mongodb条目

angular - Angular|Ionic 中“未找到 [自定义组件] 的组件工厂”

angular - 使用具有多路径代理匹配的 angular-cli

reactjs - Flask 和 React - Spotify 授权后处理 token

node.js - typescript "error: no pg_hba.conf entry for host "x",用户 "x",数据库 "x",SSL 关闭"

node.js - FireBase 错误解析错误 : Unexpected token return