angular - 如何在 Nest.js 中获取用户信息?

标签 angular nestjs

我正在使用 Angular+Nest 开发一个网站。我创建了一个服务(Angular),以便客户端可以在项目启动时从服务器获取用户信息(与新鲜相同)。有些 Action 不需要登录,所以登录是可选的。

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

服务器代码如下:

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作为状态码。然后网页将转到登录页面。

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

最佳答案

如果您有完全不同的方法,请告诉我 - 会尽力提供帮助。

将尝试提供更详细的示例,其中包括 passport在引擎盖下。它假设 passport被使用并且Authorization正在发送 token 。

  • const RegisteredPassportModule = PassportModule.register({ defaultStrategy: 'bearer' })
  • 添加 HttpStrategy给一些 AuthModule
  • 添加 PassportModule.register({ defaultStrategy: 'bearer' })导入到 AuthModule

  • 然后:
    AuthService是一项服务(也是 AuthModule 的一部分),它允许通过通过 Authorization 传递的 token 发送的 token 来查找给定用户。标题,直接来自数据库。
    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;
      }
    }
    
    

    用法毕竟非常简单(您可以为 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
    我希望这有帮助!

    关于angular - 如何在 Nest.js 中获取用户信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57921758/

    相关文章:

    angular - 在 Angular 中添加图像文件

    angular - Windows 点击需要很长时间才能响应

    css - Angular Material 默认样式/动画在自定义主题后不起作用

    angular - 在 Angular 2 的页面之间移动数据

    sql - Typeorm - 通过多对多关系查找条目

    typescript - 共享自定义 NestJS 模块出现 "not a part of the currently processed module"错误

    typescript - 在生产模式下运行 nestjs 时出错,找不到模块

    javascript - 鼠标在整个 SPA Angular 上向上/向下

    azure - Cosmos DB : Retryable writes are not supported. 请通过指定禁用可重试写入

    node.js - NestJS项目架构: how to avoid dependencies between modules