【问题标题】:How to get user from Request in nest?如何从请求中获取用户?
【发布时间】:2020-05-21 13:46:45
【问题描述】:

我无法从装饰巢的请求中获取用户,请帮助我。 中间件运行良好,它通过令牌找到用户并将用户保存在请求中 我的中间件:

import { Injectable, NestMiddleware, HttpStatus } from '@nestjs/common';
import { HttpException } from '@nestjs/common/exceptions/http.exception';
import { Request, Response } from 'express';
import { AuthenticationService } from '../modules/authentication-v1/authentication.service';

@Injectable()
export class AuthenticationMiddleware implements NestMiddleware {
    constructor(
        private readonly authenticationService : AuthenticationService
    ) {
    }
    async use(req: Request, res: Response, next: Function) {
        let token = req.headers;

        if(!token) {
            throw new HttpException('token is required', 401);
        }

        if (!token.match(/Bearer\s(\S+)/)) {
            throw new HttpException('Unsupported token', 401);
        }
        const [ tokenType, tokenValue ] = token.split(' ');
        try {
            const result = await this.authenticationService.getAccessToken(tokenValue);
            req.user = result;
            next();
        } catch (e) {
            throw new HttpException(e.message, 401);
        }
    }
}

但是这里的请求没有属性用户,我不知道为什么 用户装饰器:

export const User = createParamDecorator((data: any, req) => {
    return req.user; // but here user undefined
});

应用模块:

export class AppModule {
    configure(consumer: MiddlewareConsumer) {
        consumer
            .apply(AuthenticationMiddleware)
            .forRoutes({ path: 'auto-reports-v1', method: RequestMethod.GET });
    }
}

路由方式:

@UseInterceptors(LoggingInterceptor)
@Controller('auto-reports-v1')
@ApiTags('auto-reports-v1')
export class AutoReportsController {
    constructor(private readonly autoReportsService: AutoReportsService) {}

    @Get()
    async findAll(
        @Query() filter: any,
        @User() user: any): Promise<Paginated> {
        return this.autoReportsService.findPaginatedByFilter(filter, user);
    }
}

【问题讨论】:

  • 你的 Nest common 和 core 版本是什么?
  • @JayMcDoniel 6.11.11
  • 嗯,那是那个工厂的正确版本。你检查过你的req 在装饰器中是什么吗?我看不出有什么问题。
  • 是的,在用户装饰器中我有另一个请求,但我不知道为什么
  • 我发现,用户是在 req.raw.user 中设置的

标签: javascript typescript nestjs


【解决方案1】:

在带有 Fastify 的 NestJS 中,中间件将值附加到 req.raw。这是因为中间件在请求被FastifyRequest 对象包装之前运行,因此所有值附件都对IncomingRequest 对象进行(与Express Request 对象相同)。然后,Fastify 会将IncomingRequest 包装在它自己的FastifyRequest 对象中,并通过req.raw 暴露IncomingRequest,这意味着您要查找的用户是req.raw.user 而不是req.user。如果你想在 Express 和 Fastify 上拥有相同的功能,我建议使用 Guard。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 2014-10-23
    • 2015-05-23
    • 2013-05-30
    • 1970-01-01
    • 2019-08-10
    • 2021-03-07
    • 1970-01-01
    相关资源
    最近更新 更多