Code Monkey home page Code Monkey logo

Comments (7)

wenfujie avatar wenfujie commented on June 10, 2024 1

@Azleal

登录之后,业务中需要拿到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.

abigmiu avatar abigmiu commented on June 10, 2024

export class JwtAuthGuard extends AuthGuard('jwt') 这样也拿不到 token 里面的数据

from blog.

devmsg avatar devmsg commented on June 10, 2024

export class JwtAuthGuard extends AuthGuard('jwt') 这样也拿不到 token 里面的数据

你拿token干啥呢,JwtAuthGuard只是个守卫,在auth module 注入PassportStrategy

from blog.

abigmiu avatar abigmiu commented on June 10, 2024

export class JwtAuthGuard extends AuthGuard('jwt') 这样也拿不到 token 里面的数据

你拿token干啥呢,JwtAuthGuard只是个守卫,在auth module 注入PassportStrategy

忘了当初为啥提出这个问题了。 现在我在请求头里面拿到了

from blog.

abigmiu avatar abigmiu commented on June 10, 2024

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.

devmsg avatar devmsg commented on June 10, 2024

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.

Azleal avatar Azleal commented on June 10, 2024

登录之后,业务中需要拿到jwt中payload包含的用户信息。这个怎么获取呢?request中没有user这个属性。

from blog.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.