如何从嵌套中的Request获取用户?

Ale*_*ler 1 javascript typescript nestjs

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

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

应用程序模块:

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

路线方法:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*iel 5

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