如何在Nest.js中获取用户信息? [英] How to get user's information in Nest.js?

查看:832
本文介绍了如何在Nest.js中获取用户信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular + Nest开发一个网站.我创建了一个服务(Angular),以便客户端可以在项目启动时从服务器获取用户的信息(与新的一样).某些操作不需要登录,因此登录是可选的.

I am using Angular+Nest to develop a website. I have created a service(Angular) so that client can get user's information from server when project start up(the same as fresh). Some actions don't need to login, so the login is optional.

我想要的是如果用户已经登录,那么客户端应该发送请求以获取用户信息.

What I want is if user has logined, then client should send a request to get user's information.

服务器代码如下:

export const RequestUser = createParamDecorator((data, req): RequestUserDTO => {
    return req.user;
});

@Controller('auth')
export class AuthController {
  @Get('getUserInfoByToken')
  async getUserInfoByToken(@RequestUser() user: User): Promise<any> {
    if (user) {
      return {
        nickname: user.nickname,
        level: user.level
      };
    }
  }
}

但是,我发现如果不添加@UseGuards(AuthGuard())作为装饰器,将没有任何回报.但是,如果我添加它,则在项目启动时,此请求将返回401作为状态代码.然后网络将转到登录页面.

Howerver, I find there's nothing be return if I don't add @UseGuards(AuthGuard()) as decorator. But if I add it, when project start, this request return 401 as status code. Then the web will turn to login page.

我应该怎么做才能避免这种情况?并非每个动作都需要登录.

What should I do to avoid this situation? Not every action need login.

推荐答案

如果您想到的是完全不同的方法,请告诉我-会尽力提供帮助.

If you got totally different approach in mind, let me know - will try to help.

将尝试提供更详细的示例,其中包括passport.假定使用了passport并且正在发送Authorization令牌.

Will try to serve a bit more detailed example, which includes passport under the hood. It assumes that passport is used and that Authorization token is being sent.

  • const RegisteredPassportModule = PassportModule.register({ defaultStrategy: 'bearer' })
  • HttpStrategy添加到某些AuthModule
  • PassportModule.register({ defaultStrategy: 'bearer' })添加到AuthModule
  • 的导入中
  • const RegisteredPassportModule = PassportModule.register({ defaultStrategy: 'bearer' })
  • adding HttpStrategy to some AuthModule
  • adding PassportModule.register({ defaultStrategy: 'bearer' }) to imports to AuthModule

然后:

AuthService是一项服务(也是AuthModule的一部分),允许直接通过数据库通过通过Authorization头传递的令牌发送的令牌来查找给定用户.

AuthService is a service (and a part of AuthModule) that allows to find given user via token sent via token passed via Authorization header, directly from the database.

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

@Injectable()
export class HttpStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super()
  }

  async validate(token: string) {
    const user = await this.authService.findUserByToken(token);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

用法毕竟很简单(您可以为控制器的任何一种方法设置防护罩):

Usage is after all quite simple (you can put the guard for either method of controller):

@UseGuards(AuthGuard())
@Get()
someMethod(@Req() request: RequestWithUser, ...) {
  // ...
}

RequestWithUser所在的位置:

import { User as UserEntity } from '../../models/user.entity'

export type RequestWithUser = Request & { user: UserEntity }

/user端点将仅返回request.user

我希望这会有所帮助!

这篇关于如何在Nest.js中获取用户信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆