【发布时间】:2022-08-11 06:21:38
【问题描述】:
我正在尝试创建一个共享 Guard 作为外部库,以便跨服务导入和使用。我没有做任何比what is described in some guides 更特别的事情,而是代码将驻留在共享库中的特殊性。一切正常,但异常返回 401 错误。
我的后卫看起来像这样:
import { Injectable } from \'@nestjs/common\';
import { AuthGuard } from \'@nestjs/passport\';
@Injectable()
export class MainGuard extends AuthGuard(\'jwt\') {}
没有其他的。如果我在服务文件夹中使用它,它可以工作,但是当我像在他们自己的库中一样移动时,响应会发生变化。
我在服务中使用的方式没有什么特别的:
import { MainGuard } from \'shared-guard-library\';
import { Controller, Get, UseGuards } from \'@nestjs/common\';
import { SomeService } from \'./some.service\';
@Controller()
export class SomeController {
constructor(private someService: SomeService) {}
@Get(\'/foo\')
@UseGuards(MainGuard)
async getSomething(): Promise<any> {
return this.someService.getSomething();
}
}
客户端收到错误 500:
http :3010/foo
HTTP/1.1 500 Internal Server Error
Connection: keep-alive
Content-Length: 52
Content-Type: application/json; charset=utf-8
Date: Thu, 09 Dec 2021 04:11:42 GMT
ETag: W/\"34-rlKccw1E+/fV8niQk4oFitDfPro\"
Keep-Alive: timeout=5
Vary: Origin
X-Powered-By: Express
{
\"message\": \"Internal server error\",
\"statusCode\": 500
}
在日志中显示:
[Nest] 93664 - 12/08/2021, 10:11:42 PM ERROR [ExceptionsHandler] Unauthorized
UnauthorizedException: Unauthorized
at MainGuard.handleRequest (/sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:68:30)
at /sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:49:128
at /sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:86:24
at allFailed (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:101:18)
at attempt (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:174:28)
at Object.strategy.fail (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:296:9)
at Object.JwtStrategy.authenticate (/sharedGuardLibrary/node_modules/passport-jwt/lib/strategy.js:96:21)
at attempt (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:360:16)
at authenticate (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:361:7)
at /sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:91:3
日志告诉我抛出了正确的异常,但在某些时候被忽略了,我不知道原因。再次:同一个项目中的相同代码有效。
我看了一下原来的类和I don\'t see any particular way to treat the exception
任何线索或指南将不胜感激。
-
如果同一项目中的相同代码有效,请尝试
rm -rf node_modules并再次安装(不要触摸锁定文件) -
已经尝试过类似的相关事情,例如使用服务和库清理 npm 缓存;结果相同
标签: nestjs nestjs-passport nestjs-jwt