最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

NestJS : Jwt with AsyncLocalStorage For User Authentication - Stack Overflow

programmeradmin1浏览0评论

I have a JwtAuthGuard from passport package. I want to use AsyncLocalStorage to access the logged-in-user information across application.

My current Approach: Create a Middleware and pass empty store with setter. On the JwtAuthGuard validate method access the store and the store using the setter in the store.

@Injectable()
export class UserAlsMiddleware implements NestMiddleware {
constructor(
private readonly userAls: AsyncLocalStorage<UserContext>
) { }
use(req: any, res: any, next: (error?: Error | any) => void) {
this.userAls.run(new UserContext(), next);
 }
}
export class JwtStrategy extends PassportStrategy(Strategy){
constructor(    private readonly userAls: AsyncLocalStorage<UserContext>)
validate(params){
// other code
this.userAls.getStore().setContext(userContext) }

}
export class UserContext {
user: User;
setContext(ctx: UserContext) {
Object.assign(this, ctx);
}
}

Does it cause any side effects? Is there any alternate approach?, Thanks.

Please share your thoughts!

发布评论

评论列表(0)

  1. 暂无评论