使用 Guards(角色,JWT)获取用户数据

bon*_*low 18 javascript node.js typescript nestjs

这里的文档有点薄,所以我遇到了一个问题。我尝试使用 Guards 来保护 Controller 或它的 Actions,所以我会要求经过身份验证的请求的作用(通过 JWT)。在我的 auth.guard.ts 中,我要求“request.user”但它是空的,所以我无法检查用户角色。我不知道如何定义“request.user”。这是我的 auth 模块和它的导入。

auth.controller.ts

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { RolesGuard } from './auth.guard';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Get('token')
  async createToken(): Promise<any> {
    return await this.authService.signIn();
  }

  @Get('data')
  @UseGuards(RolesGuard)
  findAll() {
    return { message: 'authed!' };
  }
}
Run Code Online (Sandbox Code Playgroud)

角色.guard.ts

这里 user.request 是空的,因为我从来没有定义过它。文档没有显示如何或在哪里。

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const user = request.user; // it's undefined
    const hasRole = () =>
      user.roles.some(role => !!roles.find(item => item === role));
    return user && user.roles && hasRole();
  }
}
Run Code Online (Sandbox Code Playgroud)

auth.module.ts

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { HttpStrategy } from './http.strategy';
import { UserModule } from './../user/user.module';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    UserModule,
  ],
  providers: [AuthService, HttpStrategy],
  controllers: [AuthController],
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)

auth.service.ts

import { Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  async signIn(): Promise<object> {
    // In the real-world app you shouldn't expose this method publicly
    // instead, return a token once you verify user credentials
    const user: any = { email: 'user@email.com' };
    const token: string = this.jwtService.sign(user);
    return { token };
  }

  async validateUser(payload: any): Promise<any> {
    // Validate if token passed along with HTTP request
    // is associated with any registered account in the database
    return await this.userService.findOneByEmail(payload.email);
  }
}
Run Code Online (Sandbox Code Playgroud)

jwt.strategy.ts

import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secretKey',
    });
  }

  async validate(payload: any) {
    const user = await this.authService.validateUser(payload);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
Run Code Online (Sandbox Code Playgroud)

文档:https : //docs.nestjs.com/guards

谢谢你的帮助。

Kim*_*ern 10

此外,您RolesGuard还需要使用AuthGuard.

标准

您可以使用将AuthGuard用户对象附加到请求的标准实现。当用户未经身份验证时,它会引发 401 错误。

@UseGuards(AuthGuard('jwt'))
Run Code Online (Sandbox Code Playgroud)

延期

如果因为需要不同的行为而需要编写自己的守卫,请扩展原始AuthGuard方法并覆盖需要更改的方法(handleRequest在示例中):

@Injectable()
export class MyAuthGuard extends AuthGuard('jwt') {

  handleRequest(err, user, info: Error) {
    // don't throw 401 error when unauthenticated
    return user;
  }

}
Run Code Online (Sandbox Code Playgroud)

为什么要这样做?

如果您查看 的源代码AuthGuard您可以看到它将用户附加到请求中作为对通行证方法的回调。如果您不想使用/扩展AuthGuard,则必须实现/复制相关部分。

const user = await passportFn(
  type || this.options.defaultStrategy,
  options,
  // This is the callback passed to passport. handleRequest returns the user.
  (err, info, user) => this.handleRequest(err, info, user)
);
// Then the user object is attached to the request
// under the default property 'user' which you can change by configuration.
request[options.property || defaultOptions.property] = user;
Run Code Online (Sandbox Code Playgroud)


bal*_*hna 9

您可以将多个守卫连接在一起(@UseGuards(AuthGuard('jwt'), RolesGuard))以在它们之间传递上下文。然后您将可以访问“RolesGuard”内的“req.user”对象。