【问题标题】:Securing NestJS API for Angular App with Auth0使用 Auth0 保护 Angular 应用程序的 NestJS API
【发布时间】:2021-10-26 05:30:12
【问题描述】:

我正在开发一个使用 NestJS 作为后端的 Angular 应用程序。我们在 Angular 应用程序中进行了身份验证,登录到 Auth0 并重定向回我们的应用程序。我可以在网络选项卡中看到/token 调用,并查看响应。这一切都很好。

我的问题在于 NestJS 应用程序,以及在将守卫添加到路由时从中获取数据的问题。我关注了this guide directly from the Auth0 site,但我仍然遇到问题。我有 auth 模块、jwt.strategy.ts 服务和所有东西。但是,我无法到达受保护的路线。

在 Auth0 的网站上,我为 Angular 应用程序创建了一个应用程序,并为 NestJS 应用程序创建了一个 API。我从 Angular 应用程序中获取令牌并将其插入 Insomnia 以调用路由 http://localhost:3333/api/hello,这只是一个简单的起始路由。但是,我每次只收到 401 个响应。在尝试了几次之后,我使用来自 Auth0 的测试代码作为 API,并使用 cURL 获得了一个令牌,然后使用该令牌发出请求(再次使用 cURL,但我仍然得到 401。

似乎我做错了什么,我的 Angular 应用程序和 Nest 应用程序之间的通信不正确。我也显然没有正确阅读教程。任何指针将不胜感激。

// jwt.strategy.ts
import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { passportJwtSecret } from "jwks-rsa";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    console.log("constructor called");
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `${"https://my-domain.auth0.com/"}.well-known/jwks.json`,
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: "http://localhost:3333/",
      issuer: "https://my-domain.auth0.com/",
      algorithms: ["RS256"],
    });
  }

  validate(payload: unknown): unknown {
    console.log(payload);
    return payload;
  }
}

注意

上面的构造函数中的console.log 在应用启动时被调用。但是,这个validate 方法似乎永远不会被调用,因为console.log 没有被命中。

// app.controller.ts
export class AppController {
  constructor(private readonly appService: AppService) {}

  @UseGuards(AuthGuard('jwt'))
  @Get('hello')
  getData(): Message {
    return this.appService.getData();
  }
}

另外,当我转到 Auth0 的日志部分时,我没有看到任何失败的事务,所以我认为它实际上并不是在尝试验证令牌。

【问题讨论】:

  • 如果您收到 401,您可能发送的令牌无效。这可能是由于配置无效或令牌已过期。您可以使用jwt.io 来调试令牌

标签: angular nestjs auth0


【解决方案1】:

花了一点时间才弄清楚这个问题,结果很简单。

首先,浏览器缓存某些数据似乎存在潜在问题,从而导致了一些问题。其次,我在 NestJS 文件中的 audience 值上有一个斜杠。在 Auth0 的仪表板中,标识符为 http://localhost:3333。在 TypeScript 文件中,我有 http://localhost:3333/。这种不匹配导致了问题。

有助于解决该问题的另一件事是,在 Angular 应用程序中,我们还需要在初始化身份验证模块时提供 audience

有了这些细微的变化,现在似乎一切正常了。

【讨论】:

    猜你喜欢
    • 2015-08-12
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2021-06-25
    • 2017-02-27
    • 2021-06-23
    相关资源
    最近更新 更多