在Swashbuckle中启用Oauth2客户端凭据流 [英] Enable Oauth2 client credentials flow in Swashbuckle

查看:136
本文介绍了在Swashbuckle中启用Oauth2客户端凭据流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用IdentityServer3通过客户端凭据授予来保护Web API.对于文档,我正在使用Swashbuckle,但无法弄清楚如何在SwaggerConfig中为客户端凭据(应用程序)流启用Oauth2.任何帮助将不胜感激!

Im using IdentityServer3 to secure a Web API with the client credentials grant. For documentation Im using Swashbuckle but can't figure out how to enable Oauth2 in the SwaggerConfig for the client credentials (application) flow. Any help would be appreciated!

推荐答案

我能够使它正常工作.大部分答案都可以找到这里.

I was able to get this working. Most of the answer can be found here.

我必须更改一些部分才能使client_credential许可起作用. 第一部分在EnableSwagger和EnableSwaggerUi调用中:

There were a few parts I had to change to get the client_credential grant to work. The first part is in the EnableSwagger and EnableSwaggerUi calls:

config.EnableSwagger(c => 
  {
    c.SingleApiVersion("v1", "sample api");
    c.OAuth2("oauth2")
     .Description("client credentials grant flow")
     .Flow("application")
     .Scopes(scopes => scopes.Add("sampleapi", "try out the sample api"))
     .TokenUrl("http://authuri/token");
    c.OperationFilter<AssignOAuth2SecurityRequirements>();
  }).EnableSwaggerUi(c =>
  {
    c.EnableOAuth2Support("sampleapi", "samplerealm", "Swagger UI");
  });

这里的重要更改是.Flow("application")我还使用了.TokenUrl调用而不是.AuthorizationUrl,这仅取决于您设置的特定授权方案.

The important change here is .Flow("application") I also used the .TokenUrl call instead of .AuthorizationUrl This is just dependent on your particular authorization scheme is set up.

我还使用了稍微不同的AssignOAuth2SecurityRequirements

I also used a slightly different AssignOAuth2SecurityRequirements class

public class AssignOAuth2SecurityRequirements : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
      var authorized = apiDescription.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();
      if (!authorized.Any()) return;

      if (operation.security == null)
          operation.security = new List<IDictionary<string, IEnumerable<string>>>();

      var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
      {
          {"oauth2", Enumerable.Empty<string>()}
      };

      operation.security.Add(oAuthRequirements);
    }
}

这足以显示身份验证开关.对我来说,另一个问题是设置了默认的身份验证对话框,因此用户只需要选择一个作用域,然后单击授权即可.就我而言,由于我设置了身份验证的方式,因此无法正常工作.我必须用swagger-oauth.js脚本重新编写对话框,然后将其注入SwaggerUI.

This should be sufficient to get the authentication switch to show. The other problem for me was that the default authentication dialog is set up so a user just has to select a scope and then click authorize. In my case this didn't work due to the way I have authentication set up. I had to re-write the dialog in the swagger-oauth.js script and inject it into the SwaggerUI.

这篇关于在Swashbuckle中启用Oauth2客户端凭据流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆