.Net WebApi接口之Swagger配置請求頭apiKey驗證


兩種方式配置分別如下:修改SwaggerConfig.cs

1. 直接在SwaggerConfig中設置請求頭,這里請求頭用的默認值apiKey,也可以自己定義一個

  public class SwaggerConfig
  {
    public static void Register()
    {
      var thisAssembly = typeof(SwaggerConfig).Assembly;

      GlobalConfiguration.Configuration
        .EnableSwagger(c =>
        {           
          c.SingleApiVersion("v1", "Project.Example.WebApi在線文檔接口");          
             
          //取消注釋是為了請求驗證
          c.BasicAuth("basic").Description("Basic HTTP Authentication");
          //將swagger中輸入的api-key添加到請求頭中     
          // NOTE: You must also configure 'EnableApiKeySupport' below in the SwaggerUI section
          c.ApiKey("apiKey")
              .Description("API Key Authentication")
              .Name("apiKey")
              .In("header");           
        
          // 在接口類、方法標記屬性 [HiddenApi],可以阻止【Swagger文檔】生成  
          //c.DocumentFilter<HiddenApiFilter>();
              
          //c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider));
          c.IncludeXmlComments(string.Format("{0}/Doc/Project.Example.Web.XML", System.AppDomain.CurrentDomain.BaseDirectory));
          c.IncludeXmlComments(string.Format("{0}/Doc/Project.Example.Model.XML", System.AppDomain.CurrentDomain.BaseDirectory));

          //設置控制器上的注釋顯示
          var xmlFile = string.Format("{0}/Doc/Project.Example.Web.XML", System.AppDomain.CurrentDomain.BaseDirectory);
          c.CustomProvider((defaultProvider) => new SwaggerControllerDescProvider(defaultProvider, xmlFile));
        })
        .EnableSwaggerUi(c =>
        {       
          // Use the "DocumentTitle" option to change the Document title.
          // Very helpful when you have multiple Swagger pages open, to tell them apart.
          //
          c.DocumentTitle("Project.Example Swagger UI");      
        
          //注入自定義的js文件
          //定義一個JS文件,設置屬性成嵌入資源,這個js文件的功能主要有兩個,一個是漢化,另一個就是在界面上顯示控制器的描述文字
          c.InjectJavaScript(thisAssembly, "Project.Example.Web.Scripts.Swagger.Swagger-Custom.js");

          //取消注釋是為了請求驗證,設置JS文件屬性成嵌入資源
          //c.InjectJavaScript(thisAssembly, "Project.Example.Web.Scripts.Swagger.api-key-header-auth.js");

          // If your API supports ApiKey, you can override the default values.
          // "apiKeyIn" can either be "query" or "header"
          //
          c.EnableApiKeySupport("apiKey", "header");
        });
    }
  }

2. 通過注入自定義的js文件來設置請求頭apiKey

 public class SwaggerConfig
  {
    public static void Register()
    {
      var thisAssembly = typeof(SwaggerConfig).Assembly;

      GlobalConfiguration.Configuration
        .EnableSwagger(c =>
        {           
          c.SingleApiVersion("v1", "Project.Example.WebApi在線文檔接口");          
             
          //取消注釋是為了請求驗證
          c.BasicAuth("basic").Description("Basic HTTP Authentication");
          //將swagger中輸入的api-key添加到請求頭中     
          // NOTE: You must also configure 'EnableApiKeySupport' below in the SwaggerUI section
          //c.ApiKey("apiKey")
          //    .Description("API Key Authentication")
          //    .Name("apiKey")
          //    .In("header");           
        
          // 在接口類、方法標記屬性 [HiddenApi],可以阻止【Swagger文檔】生成  
          //c.DocumentFilter<HiddenApiFilter>();
              
          //c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider));
          c.IncludeXmlComments(string.Format("{0}/Doc/Project.Example.Web.XML", System.AppDomain.CurrentDomain.BaseDirectory));
          c.IncludeXmlComments(string.Format("{0}/Doc/Project.Example.Model.XML", System.AppDomain.CurrentDomain.BaseDirectory));

          //設置控制器上的注釋顯示
          var xmlFile = string.Format("{0}/Doc/Project.Example.Web.XML", System.AppDomain.CurrentDomain.BaseDirectory);
          c.CustomProvider((defaultProvider) => new SwaggerControllerDescProvider(defaultProvider, xmlFile));
        })
        .EnableSwaggerUi(c =>
        {       
          // Use the "DocumentTitle" option to change the Document title.
          // Very helpful when you have multiple Swagger pages open, to tell them apart.
          //
          c.DocumentTitle("Project.Example Swagger UI");      
        
          //注入自定義的js文件
          //定義一個JS文件,設置屬性成嵌入資源,這個js文件的功能主要有兩個,一個是漢化,另一個就是在界面上顯示控制器的描述文字
          c.InjectJavaScript(thisAssembly, "Project.Example.Web.Scripts.Swagger.Swagger-Custom.js");

          //取消注釋是為了請求驗證,設置JS文件屬性成嵌入資源
          c.InjectJavaScript(thisAssembly, "Project.Example.Web.Scripts.Swagger.api-key-header-auth.js");

          // If your API supports ApiKey, you can override the default values.
          // "apiKeyIn" can either be "query" or "header"
          //
          //c.EnableApiKeySupport("apiKey", "header");
        });
    }
  }

在項目的Scripts文件夾中添加api-key-header-auth.js文件,JS代碼如下:

(function () {
  $(function () {
    $('#input_apiKey').show();
    $('#input_apiKey').on('change', function () {
      var key = this.value;
      if (key && key.trim() !== '') {
        //將swagger中輸入的api-key添加到請求頭中
        swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", key, "header"));       
      }
    });
  });
})();

注意需要設置該JS文件的屬性成嵌入資源:

運行項目swagger接口文檔效果如圖,在api_Key中輸入需要驗證的Token


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM