【发布时间】: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 来调试令牌