gpt4 book ai didi

nestjs - 如何将jwt传递给nestjs中的prisma中间件

转载 作者:行者123 更新时间:2023-12-05 08:04:55 25 4
gpt4 key购买 nike

我正在使用 nestjs、graphql 和 prisma。我想弄清楚如何将每个数据库请求的 jwt token 传递给创建的 prisma 服务 iv。我尝试了一个对象到构造函数,但随后编译说我缺少对构造函数参数中引用的任何内容的依赖注入(inject)。

@Injectable()
export class PrismaService
extends PrismaClient
implements OnModuleDestroy {
constructor() {
super();
//TODO how do I pass my jwt token to this for each request?
this.$use(async (params, next) => {
if (params.action === 'create') {
params.args.data['createdBy'] = 'jwt username goes here';
}
if (params.action === 'update') {
params.args.data['updatedBy'] = 'jwt username goes here';
}

const result = await next(params);
return result;
});
}

async onModuleDestroy() {
await this.$disconnect();
}
}

最佳答案

你在使用 nest 中间件吗?

JWT 通常传递给 Controller ​​,而不是服务。

例子:


@Injectable()
export class MyMiddleware implements NestMiddleware {
private backend: any // This is your backend

constructor() {
this.backend = null // initialize your backend
}

use(req: Request, res: Response, next: any) {
const token = <string>req.headers.authorization


if (token != null && token != '') {
this.backend
.auth()
.verifyIdToken(<string>token.replace('Bearer ', ''))
.then(async (decodedToken) => {
const user = {
email: decodedToken.email,
uid: decodedToken.uid,
tenantId: decodedToken.tenantId,
}
req['user'] = user
next()
})
.catch((error) => {
log.info('Token validation failed', error)
this.accessDenied(req.url, res)
})
} else {
log.info('No valid token provided', token)
return this.accessDenied(req.url, res)
}
}

private accessDenied(url: string, res: Response) {
res.status(403).json({
statusCode: 403,
timestamp: new Date().toISOString(),
path: url,
message: 'Access Denied',
})
}
}

因此,每次我使用有效 token 进行 API 调用时, token 都会添加到请求中的 user[]

在我的 Controller 类中,我可以继续使用数据:


@Post()
postHello(@Req() request: Request): string {
return 'Hello ' + request['user']?.tenantId + '!'
}

关于nestjs - 如何将jwt传递给nestjs中的prisma中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66880725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com