Comments (7)
登录之后,业务中需要拿到jwt中payload包含的用户信息。这个怎么获取呢?request中没有user这个属性。
首先你要确定 jwt 策略中的 validate 有返回用户信息
// jwt.strategy.ts
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
确定有了,授权登录后通过 @Request
就可以拿到
getUser(@Request() req) {
return req.user;
}
要优雅一点,可以写个获取用户的装饰器 @User
// user.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const User = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.user;
},
);
@Post('GetUserInfo')
//通过 @User 获取用户信息
getUser(@User() user) {
return user;
}
from blog.
export class JwtAuthGuard extends AuthGuard('jwt') 这样也拿不到 token 里面的数据
from blog.
export class JwtAuthGuard extends AuthGuard('jwt') 这样也拿不到 token 里面的数据
你拿token干啥呢,JwtAuthGuard只是个守卫,在auth module 注入PassportStrategy
from blog.
export class JwtAuthGuard extends AuthGuard('jwt') 这样也拿不到 token 里面的数据
你拿token干啥呢,JwtAuthGuard只是个守卫,在auth module 注入PassportStrategy
忘了当初为啥提出这个问题了。 现在我在请求头里面拿到了
from blog.
export class JwtAuthGuard extends AuthGuard('jwt') 这样也拿不到 token 里面的数据
你拿token干啥呢,JwtAuthGuard只是个守卫,在auth module 注入PassportStrategy
忘了当初为啥提出这个问题了。 现在我在请求头里面拿到了
记起来了。 是因为这个
@Injectable()
export class RbacAuthGuard extends AuthGuard('jwt') {
constructor(
@InjectRedis() private readonly redis: Redis,
private authService: AuthService,
private reflector: Reflector,
) {
super();
}
async canActivate(context: ExecutionContext): Promise<any> {
const isPublic = this.reflector.get<boolean>('isPublic', context.getHandler());
if (isPublic) return true;
const request = context.switchToHttp().getRequest();
const token = ExtractJwt.fromAuthHeaderAsBearerToken()(request);
return this.authService.validate(token);
// 原来会在 req 上挂载一个 user 属性, 自定义的canActive 的时候。 后续的 controller拿不到这个 user 字段
}
}
from blog.
export class JwtAuthGuard extends AuthGuard('jwt') 这样也拿不到 token 里面的数据
你拿token干啥呢,JwtAuthGuard只是个守卫,在auth module 注入PassportStrategy
忘了当初为啥提出这个问题了。 现在我在请求头里面拿到了
记起来了。 是因为这个
@Injectable() export class RbacAuthGuard extends AuthGuard('jwt') { constructor( @InjectRedis() private readonly redis: Redis, private authService: AuthService, private reflector: Reflector, ) { super(); } async canActivate(context: ExecutionContext): Promise<any> { const isPublic = this.reflector.get<boolean>('isPublic', context.getHandler()); if (isPublic) return true; const request = context.switchToHttp().getRequest(); const token = ExtractJwt.fromAuthHeaderAsBearerToken()(request); return this.authService.validate(token); // 原来会在 req 上挂载一个 user 属性, 自定义的canActive 的时候。 后续的 controller拿不到这个 user 字段 } }
感觉对AuthGurad理解不到位哈,我习惯通过SetMetadata进行设置变量,然后从this.reflector.getAllAndOverride(NO_AUTH,[]),然后在各自的模块内进行你上面的操作
export const noAuth = () => SetMetadata('NO_AUTH', true);
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor(private reflector: Reflector) {
super();
}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const noAuthInterception = this.reflector.getAllAndOverride(NO_AUTH, [
context.getHandler(),
context.getClass(),
]);
if (noAuthInterception) return true;
return super.canActivate(context);
}
handleRequest(err, user) {
if (err || !user) {
throw new ApiException('登录状态已过期', 401);
}
return user;
}
}
然后通过通过noAuth进行给控制器
from blog.
登录之后,业务中需要拿到jwt中payload包含的用户信息。这个怎么获取呢?request中没有user这个属性。
from blog.
Related Issues (20)
- 时间分片(Time Slicing)
- Nodejs文件上传、监听上传进度
- docker简单实操
- 好用的webpack插件:webpack-oss-upload-plugin
- Object.defineProperty 与 Proxy
- React Hooks优化
- JavaScript的内存模型
- React Hooks Immutable
- Jenkins
- git ssh秘钥
- @babel/preset-env与@babel/plugin-transform-runtime
- ES6设计模式
- nestjs模块
- 观察者模式
- 策略模式
- 状态模式
- RPC入门理解
- gRPC的简单使用
- 话说MySQL的那部分写的不错,是自己的写的吗博主? 同为前端
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog.