Asp.net-Web-Api

如何在 Swagger 中顯示 WebApi OAuth 令牌端點

  • August 23, 2015

我創建了一個新的 Web Api 項目,添加了 Asp.Net Identity 並配置了 OAuth,如下所示:

OAuthOptions = new OAuthAuthorizationServerOptions
{
   TokenEndpointPath = new PathString("/Token"),
   Provider = new ApplicationOAuthProvider(PublicClientId),
   AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
   AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
   AllowInsecureHttp = true
};

這一切都很好,我可以呼叫 /Token 端點並取回不記名令牌。

問題是這在我假設的 Swagger 中是不可發現的,因為它不在控制器上,因此沒有為它生成 xml 文件。

有誰知道在我的 Swagger 文件中顯示此登錄端點的方法?

謝謝。

另外,我應該說 Swagger 文件適用於我所有的控制器,只是我缺少一個明顯的方法 - 如何登錄。

ApiExplorer 不會自動為您的端點生成任何資訊,因此您需要添加自定義 DocumentFilter 才能手動描述令牌端點。

在https://github.com/domaindrivendev/Swashbuckle/issues/332有一個例子:

class AuthTokenOperation : IDocumentFilter
{
   public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
   {
       swaggerDoc.paths.Add("/auth/token", new PathItem
       {
           post = new Operation
           {
               tags = new List<string> { "Auth" },
               consumes = new List<string>
               {
                   "application/x-www-form-urlencoded"
               },
               parameters = new List<Parameter> {
                   new Parameter
                   {
                       type = "string",
                       name = "grant_type",
                       required = true,
                       @in = "formData"
                   },
                   new Parameter
                   {
                       type = "string",
                       name = "username",
                       required = false,
                       @in = "formData"
                   },
                   new Parameter
                   {
                       type = "string",
                       name = "password",
                       required = false,
                       @in = "formData"
                   }
               }
           }
       });
   }
}

httpConfig.EnableSwagger(c =>
{
   c.DocumentFilter<AuthTokenOperation>();
});

引用自:https://stackoverflow.com/questions/32164117