如何在 Swagger-ui 发出的 oauth2/token 调用中发送 "audience" 字段?

How can I send "audience" field in oauth2/token call made by Swagger-ui?

我正在使用 Swagger-UI 和 Swashbuckle v5.6 来记录 Auth0 (OAuth2) 安全 .NET Web API。 我一直在尝试配置 Swagger 以从 Auth0 服务获取 UI 中的令牌。到目前为止,我已经设法做到了,但问题是我需要在 POST /token 请求的正文中发送 "audience" 字段,我正在努力寻找如何做到这一点SwaggerConfig.cs.

到目前为止,我的 SwaggerConfig.cs 看起来像这样:

public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;
        string appName = "myApi";
        var audience = System.Configuration.ConfigurationManager.AppSettings["AuthAudience"];
        string tokenUrl = "somethingsomething/oauth/token";

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "myApi");
                    c.IncludeXmlComments(string.Format(@"{0}\bin\myApi.XML", System.AppDomain.CurrentDomain.BaseDirectory));
                    c.DescribeAllEnumsAsStrings();

                    c.OAuth2("oauth2")
                        .Description("client credentials grant flow")
                        .Flow("password")
                        .TokenUrl(tokenUrl)
                        .Scopes(scopes =>
                        {
                            scopes.Add("myapi", "openid profile email address phone");
                        });

                    c.OperationFilter<AssignOperationFilters>();
                    c.DocumentFilter<SecurityRequirementsDocumentFilter>();
                })
            .EnableSwaggerUi(c =>
            {
                var clientId =  System.Configuration.ConfigurationManager.AppSettings["Auth0ApiClientId"];
                var clientSecret = System.Configuration.ConfigurationManager.AppSettings["Auth0ApiClientSecret"];

                var additionalParams = new Dictionary<string, string>{ {"audience", audience } };

                c.EnableOAuth2Support(clientId,
                                    clientSecret,
                                    appName,
                                    "tmdq",
                                    additionalQueryStringParams: additionalParams);

            });
    }
}

从 6.0.0 版开始,您可以像这样使用请求拦截器:

 app.UseSwaggerUI(options =>
                {
                        options.UseRequestInterceptor("(req) => { if (req.url.endsWith('oauth/token') && req.body) req.body += '&audience=" + appsettings.Audience + "'; return req; }");

                });

您可以使用 OAuthAdditionalQueryStringParams...

   app.UseSwaggerUI(options =>
            {
                options.OAuthClientId("YOUR_CLIENT_ID");  
                options.SwaggerEndpoint("v1/swagger.json", "v1");
                options.OAuthAdditionalQueryStringParams(new Dictionary<string, string>() { {"audience","YOUR_AUDIENCE"}});
            });