zoukankan      html  css  js  c++  java
  • 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'));
    
                    }
                });  
     }
    

     

    参考文档链接:http://www.jianshu.com/p/3329b4126886

  • 相关阅读:
    设计模式研究
    requests模块请求常用参数的写法整理
    python程序打包exe文件
    爬虫响应信息乱码解决方式
    Vue-cli父子组件之间传参
    MYSQL事件隔离级别以及复读,幻读,脏读的理解
    [NOIP2009] 提高组 洛谷P1073 最优贸易
    [NOIP2009] 提高组 洛谷P1071 潜伏者
    [NOIP2009] 普及组
    洛谷P3386 【模板】二分图匹配
  • 原文地址:https://www.cnblogs.com/WangJunZzz/p/7284573.html
Copyright © 2011-2022 走看看