Asp.net-Web-Api

使用 Swagger / Swashbuckle 和 OAUTH 的 Web API

  • May 17, 2020

我正在嘗試讓我的 Web API 項目使用 Swagger 的“漂亮”文件等(<http://swagger.io/>)

我正在使用 Swashbuckle for .NET,從 NuGet 安裝,我使用的版本是 4.0.1

我已經能夠安裝和使用 Swagger。在這一點上,一切似乎都很正常。我唯一的障礙是禁用 API 密鑰並能夠使用 OAuth,就像在 PetStore 範例中一樣 ( <http://petstore.swagger.wordnik.com/#!/pet/addPet> )

我已經嘗試了所有可以在網上找到的東西。讓我在下面列出它們:

首先,這是我的 Startup.cs

public void Configuration(IAppBuilder app)
{
   var config = new HttpConfiguration();

   WebApiConfig.Register(config);

   Swashbuckle.Bootstrapper.Init(config);
}

現在,我的 SwaggerConfig.cs:

public static void Register()
{
   Swashbuckle.Bootstrapper.Init(GlobalConfiguration.Configuration);

   SwaggerSpecConfig.Customize(c =&gt;
   {
       c.IgnoreObsoleteActions();

       c.IncludeXmlComments(GetXmlCommentsPath());

       c.ApiInfo(new Info
       {
           Title = "Work you",
           Description = "testing some stuffs",
           Contact = "Email@email.com"
       });

       c.Authorization("oauth2", new Authorization
       {
           Type = "oauth2",
           Scopes = new List&lt;Scope&gt;
               {
                   new Scope { ScopeId = "products.read", Description = "View products" },
                   new Scope { ScopeId = "products.manage", Description = "Manage products" }
               },
           GrantTypes = new GrantTypes
           {
               ImplicitGrant = new ImplicitGrant
               {
                   LoginEndpoint = new LoginEndpoint
                   {
                       Url = "https://www.mysecure.website.com"
                   },
                   TokenName = "access_token"
               }
           }
       });
   });


   SwaggerUiConfig.Customize(c =&gt;
   {
       c.EnableOAuth2Support("client_id", "test-realm", "app Name");

       var thisAssembly = typeof(SwaggerConfig).Assembly;

       c.SupportHeaderParams = true;
       c.DocExpansion = DocExpansion.List;
       c.SupportedSubmitMethods = new[] { HttpMethod.Get, HttpMethod.Post, HttpMethod.Put, HttpMethod.Head };
       c.EnableDiscoveryUrlSelector();

   });

}

我有一個 SwaggerExtensions 文件夾,裡面有應該需要的文件。例如:

SwaggerExt 的文件

我的課程裝飾有:

[ScopeAuthorize("this.scope")]

但是,OAuth 選項永遠不會在招搖頁面上為我顯示。我也看不到應該在哪裡輸入自定義標題。

我確實看到正在從 SwaggerConfig.cs 中讀取標題和文件描述、電子郵件地址等,所以我知道它至少正在被讀取。

我想不通。:(

有任何想法嗎?

我得到了我的解決方案。這很強大,只是不是 100% 直接配置。

以下是我採取的步驟:

安裝我使用的 NuGet 包,PM&gt; Install-Package Swashbuckle -Version 4.1.0但連結位於<https://www.nuget.org/packages/Swashbuckle/>,我建議獲取最新版本,但我知道 4.1.0 有效。編輯我剛剛更新到 5.X,它打破了它。4.1.0 有效,但最新版本無效。我還沒有更多地研究為什麼。

一旦你安裝了這個,你就差不多完成了。

安裝將創建一個 SwaggerConfig.cs 文件。這是我使用的程式碼(從 github master 複製)

public class SwaggerConfig
   {
       public static void Register()
       {
           Swashbuckle.Bootstrapper.Init(GlobalConfiguration.Configuration);

           SwaggerSpecConfig.Customize(c =&gt;
           {
               c.IgnoreObsoleteActions();

               //c.SupportMultipleApiVersions(
               //    new[] { "1.0", "2.0" },
               //    ResolveVersionSupportByRouteConstraint);

               //c.PolymorphicType&lt;Animal&gt;(ac =&gt; ac
               //    .DiscriminateBy(a =&gt; a.Type)
               //    .SubType&lt;Kitten&gt;());

               c.OperationFilter&lt;AddStandardResponseCodes&gt;();
               c.OperationFilter&lt;AddAuthResponseCodes&gt;();
               c.OperationFilter&lt;AddOAuth2Scopes&gt;();

               //c.IncludeXmlComments(GetXmlCommentsPath());

               c.ApiInfo(new Info
               {
                   Title = "Swashbuckle Dummy",
                   Description = "For testing and experimenting with Swashbuckle features",
                   Contact = "someone@somewhere.com"
               });

               c.Authorization("oauth2", new Authorization
               {
                   Type = "oauth2",
                   Scopes = new List&lt;Scope&gt;
                       {
                           new Scope { ScopeId = "test1", Description = "test1" },
                           new Scope { ScopeId = "test2", Description = "test2" }
                       },
                   GrantTypes = new GrantTypes
                   {
                       ImplicitGrant = new ImplicitGrant
                       {
                           LoginEndpoint = new LoginEndpoint
                           {
                               Url = "https://your.Oauth.server/Authorize"
                           },
                           TokenName = "access_token"
                       }
                   }
               });
           });

           SwaggerUiConfig.Customize(c =&gt;
           {
               var thisAssembly = typeof(SwaggerConfig).Assembly;

               c.SupportHeaderParams = true;
               c.DocExpansion = DocExpansion.List;
               c.SupportedSubmitMethods = new[] { HttpMethod.Get, HttpMethod.Post, HttpMethod.Put, HttpMethod.Head };
               //c.InjectJavaScript(typeof(SwaggerConfig).Assembly, "WebApplication4.SwaggerExtensions.onComplete.js");
               //c.EnableDiscoveryUrlSelector();
               //c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js");
               //c.InjectStylesheet(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css");

               c.EnableOAuth2Support("client_id", "realm", "Swagger UI");
           });
           // NOTE: If you want to customize the generated swagger or UI, use SwaggerSpecConfig and/or SwaggerUiConfig here ...
       }
       private static string GetXmlCommentsPath()
       {
           return String.Format(@"{0}\XmlComments.xml", AppDomain.CurrentDomain.BaseDirectory);
       }

現在我們已經告訴 Swagger 我們想要使用 OAuth,這就是我們想要使用它的方式。完成了,對吧?沒有。

您需要將此文件夾和文件添加到您的解決方案中:https ://github.com/domaindrivendev/Swashbuckle/tree/master/Swashbuckle.Dummy.Core/SwaggerExtensions

(您只需要 .cs 文件)

確保你的命名空間是正確的……

然後,您需要在 WebAPI 中裝飾您的類,如下所示:

[ScopeAuthorize("test1")]

現在,當您執行它並進入 swagger 頁面時,您會看到每個具有該聲明的操作都會在右上角具有 OAuth 開關。點擊它時,您可以使用隱式授權流並獲取將添加到您的請求中的令牌。

這僅適用於我發現的隱式授權。看起來他們確實試圖讓 AuthorizationCode Grant 繼續下去,但是他們建構的 js 文件只支持我所看到的隱式。

希望這可以幫助某人。這是一個強大的工具,我希望我們看到更多的網站使用這樣的東西。

謝謝,祝你好運!

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