Swagger中添加Token验证
1、该连接链接到api中基本的swagge功能:http://www.cnblogs.com/hhhh2010/p/5234016.html
2.在swagger中使用验证(这里使用密码验证模式)http://www.cnblogs.com/WJ--NET/p/7195124.html <---搭建自己的web api验证服务器
3.在项目中会自动生成SwaggerConfig和Startup文档,如果是有验证服务器的话,swagger的配置就不需要在swaggerconfi中配置了,直接在Startup中配置swagger;
using System; using System.IO; using System.Reflection; using System.Web.Http; using Microsoft.Owin; using Microsoft.Owin.Security.OAuth; using Owin; using Swashbuckle.Application; [assembly: OwinStartup(typeof(LogicServer.ResourceServer.Startup))] namespace LogicServer.ResourceServer { /// <summary> /// The assebmly should use owin middleware and start at running the Startup method. /// </summary> public class Startup { /// <summary> /// Configuration /// </summary> /// <param name="app">app</param> public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); config.EnableSwagger("docs/{apiVersion}/swagger", c => { c.SingleApiVersion("v1", "昊天企业端接口"); var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var fileName = Assembly .GetExecutingAssembly() .GetName() .Name + ".XML"; var commentsFile = Path.Combine(baseDirectory, "bin", fileName); c.IncludeXmlComments(commentsFile); }).EnableSwaggerUi(c => { var thisAssembly = typeof(SwaggerConfig).Assembly; c.InjectJavaScript(thisAssembly, "LogicServer.bearerAuth.BearerAuth.js"); //注入js,在js中写入根据用户名和密码获取token然后添加到接口的Http header中 c.DisableValidator(); }); ConfigureOAuth(app); // set api authentication schema. UnityConfig.RegisterComponents(config); // Use unity as ioc container. Global dependency resolver. WebApiConfig.Register(config); // Setup web api route policy. // SwaggerConfig.Register(); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // Use Cors in message handling. app.UseWebApi(config); } private void ConfigureOAuth(IAppBuilder app) { // Token Consumption app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { }); } } }
$(function () { var basicAuthUI = '<div class ="input"> 用户名:<input placeholder ="username" id ="input_username" onchange="addAuthorization();" name ="username" type ="text" size ="15"> </ div>' + '<div class ="input"> 密码:<input placeholder ="password" id ="input_password" onchange="addAuthorization();" name ="password" type ="password" size ="20"> </ div>'; $('#input_apiKey').hide(); $('#api_selector').html(basicAuthUI); }); function addAuthorization() { var username = document.getElementById("input_username").value; var password = document.getElementById("input_password").value; var data = "grant_type=password&username=" + username + "&password=" + password; $.ajax({ url: "http://168.33.162.189:8889/token", type: "post", contenttype: 'x-www-form-urlencoded', data:data, success: function (response) { var bearerToken = 'Bearer ' + response.access_token; console.log(bearerToken); swaggerUi.api.clientAuthorizations.add('key', new SwaggerClient.ApiKeyAuthorization('Authorization', bearerToken, 'header')); } }); }