You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS Swagger配置OAuth2(Auth0)后如何将返回token自动注入请求头

解决方案

步骤1:修正OAuth2重定向地址

你当前配置的重定向地址http://localhost:4200/不符合Swagger的回调要求,Swagger UI内置了专门的OAuth2回调处理页面,会自动解析URL中的Token参数并存储,需将地址改为:
http://localhost:4200/oauth2-redirect.html

注意:需要将该回调地址同步添加到Auth0后台的Allowed Callback URLs列表中,否则会出现回调权限错误。

步骤2:为接口添加OAuth2安全标识

需要给需要OAuth2鉴权的接口添加标识,告诉Swagger这些接口需要用你配置的OAuth2认证:

  • 全局生效:在DocumentBuilder构建配置时追加.addSecurityRequirements('oauth2'),所有接口默认走OAuth2鉴权
  • 单个接口/模块生效:在对应的Controller类或者路由方法上添加@ApiSecurity('oauth2')装饰器

步骤3:补充授权范围配置(可选)

如果你的Auth0需要指定授权范围,需要在scopes字段中配置对应的权限项,同时在swaggerOptions的oauth配置中指定默认选中的scope。


修改后的完整配置代码

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerCustomOptions, SwaggerModule } from '@nestjs/swagger';
import * as config from 'config';
import * as  crypto from 'crypto';

async function bootstrap() {
    const serverConfig = config.get('conf');
    console.log(`Environment:` + serverConfig.env);
    console.log(`Running Port:` + serverConfig.server.port);
    const teanat = 'MY_AUTH0_DOMAIN'
    const app = await NestFactory.create(AppModule);
    const nonce = crypto.randomBytes(16).toString('base64');
    const docBuilderConfig = new DocumentBuilder()
        .setTitle('Awesome Middleware')
        .setDescription('Represents the middleware api services')
        .setVersion('1.0')
        .addOAuth2(
            {
                type: 'oauth2',
                flows: {
                    implicit: {
                        tokenUrl: `${teanat}/oauth/token`,
                        authorizationUrl: `${teanat}/authorize?audience=${`${teanat}/api/v2/`}&nonce=${nonce}`,
                        // 按需配置授权范围,示例:
                        scopes: {
                            'openid': 'OpenID 身份信息',
                            'profile': '用户基础信息'
                        }
                    },
                },
            },
            'oauth2' // 显式指定安全方案名称
        )
        // 全局所有接口默认使用oauth2鉴权,不需要可以删除这行
        .addSecurityRequirements('oauth2')
        .build()
    const document = SwaggerModule.createDocument(app, docBuilderConfig);
    const swaggerCustomOptions: SwaggerCustomOptions = {
        'customSiteTitle': 'Middle Api',
        'explorer': true,
        'swaggerOptions': {
            persistAuthorization: true,
            // 修改为Swagger内置回调地址
            oauth2RedirectUrl: 'http://localhost:4200/oauth2-redirect.html',
            oauth: {
                clientId: 'CLIENT_ID',
                // 按需指定默认选中的授权范围
                scopes: ['openid', 'profile']
            }
        }
    }
    SwaggerModule.setup('/', app, document, swaggerCustomOptions);
    app.enableCors();
    app.use((req, res, next) => {
        res.header("X-powered-by", "My Company");
        res.header("Server", "My Server");
        next();
    });
    await app.listen(4200);
}
bootstrap();

验证方式

配置完成后重启服务,点击Swagger页面的授权按钮完成Auth0登录,回调后会自动回到Swagger页面,此时调用加了OAuth2标识的接口,会自动在请求头中带上Authorization: Bearer <获取到的Token>,无需手动注入。

内容的提问来源于stack exchange,提问作者Mor Bargig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:54:02