Swashbuckle OAuth2使用客户端凭据流授权

时间:2017-03-02 14:26:04

标签: javascript c# swagger swagger-ui swashbuckle

我使用Swashbuckle来记录WebAPI控制器。我还使用OAuth2和Client Credentials Flow。因此,要授权我需要传递client_idclient_secret

我有以下代码:

config.EnableSwagger(c => {
    c.SingleApiVersion("v1", "My API");
    c.OAuth2("oauth2")
        .Flow("application")
        .TokenUrl("/oauth2/token");
    c.OperationFilter<AssignOAuthSecurityRequirements>();
})
.EnableSwaggerUi(c => {
    c.EnableOAuth2Support(clientId: "clientIdValue", clientSecret:"clientSecretValue", "", "");
    c.CustomAsset("index", Assembly.GetExecutingAssembly(), "WebAPI.Swagger.UI.index.html");
});

授权正常但我的client_idclient_secret值是硬编码的(clientIdValue,clientSecretValue)。如何在此对话框中添加用户输入值的可能性?任何人都可以帮助我吗?

enter image description here

如果我还需要发布AssignOAuthSecurityRequirements的代码,请与我们联系。提前全部谢谢

1 个答案:

答案 0 :(得分:0)

不确定您的代码到底出了什么问题,可能缺少范围定义。

我已成功使用ASP.NET Core和当前版本的Swashbuckle.AspNetCore(https://github.com/domaindrivendev/Swashbuckle.AspNetCore

客户端凭据流称为“应用程序”,因此,在Startup.cs文件中,您需要按如下方式配置Swagger:

        services.AddSwaggerGen(c => {

            //other configs...

            c.AddSecurityDefinition("oauth2", new OAuth2Scheme {
                Type = "oauth2",
                Flow = "application",
                TokenUrl = "<token_endpoint_url>",
                Scopes = new Dictionary<string, string>
                {
                    { "first-scope", "First scope description" },
                    { "second-scope", "Second scope description" }
                    //define as many scopes as you want...
                }
            });
        });

TokenUrl参数必须指向有效的OAuth 2.0兼容令牌端点(checkout http://docs.identityserver.io/en/release/endpoints/token.html以获取端点应如何表现/看起来的示例)。绝对和相对URL都在我的测试中起作用。

之后,授权对话框应该如下所示:

Authorize popup

  • 请注意,在授权按钮实际提交任何内容之前,您需要选择至少一个范围(应更改oauth组件以添加免责声明IMHO)。

SwaggerUI部分不需要其他配置。

相关问题