Swagger與OAuth 手動搭建WebApi 操做筆記

一、建立一個空的Web應用程序api

二、經過nuget 安裝如下插件清單,有部分會在安裝其餘插件時候自動安裝:跨域

 

三、安裝完Swagger 會生成一個目錄App_Start,在這個目錄中增長文件ApiConfig.cs 配置路由相關信息瀏覽器

 

  public static void Register(HttpConfiguration config)
        {
            var appsettings = ConfigurationManager.AppSettings;

            //跨域配置
            var corsAttr = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(corsAttr);
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
               name: "Default",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
        }

 

  添加文件 CustomApiExplorer.cs 重寫ApiExplorer中的ShouldExploreController方法,對路由進行重定向app

    
        /// <summary>
        /// 構造方法
        /// </summary>
        /// <param name="configuration"></param>
        public CustomApiExplorer(HttpConfiguration configuration) : base(configuration)
        {
        }
        //public override bool ShouldExploreAction(string actionVariableValue, HttpActionDescriptor actionDescriptor, IHttpRoute route)
        //{
        //    return base.ShouldExploreAction(actionVariableValue, actionDescriptor, route);
        //}
        public override bool ShouldExploreController(string controllerVariableValue, HttpControllerDescriptor controllerDescriptor, IHttpRoute route)
        {
            return base.ShouldExploreController(controllerVariableValue, controllerDescriptor, route);
        }

  修改 SwaggerConfig中代碼; WebApi.xml 中記錄Swagger接口的描述信息cors

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

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {
                        c.SingleApiVersion("v1", "WebApi");

                        c.IncludeXmlComments(GetXmlCommentsPath());

                    })
                .EnableSwaggerUi(c =>
                    {
                    });
        }
        private static string GetXmlCommentsPath()
        {
            return System.String.Format(@"{0}\bin\WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory);
        }

修改工程配置信息async

 

 使用 OWIN 方式實現 建立 Startup 文件:ide

 

建立完成後修改代碼:ui

 public void Configuration(IAppBuilder app)
        {


            HttpConfiguration config = new HttpConfiguration();
            ApiConfig.Register(config);
            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(config);


            //初始化
            GlobalConfiguration.Configure(ApiConfig.Register);
            //重訂路由
            GlobalConfiguration.Configuration.Services.Replace(typeof(IApiExplorer), new CustomApiExplorer(GlobalConfiguration.Configuration));
        }

 

 

 使用Global.asax實現;添加全局文件Global.asax,在Application_Start方法中對路由進行重訂this

        protected void Application_Start(object sender, EventArgs e)
        {
            //初始化
            GlobalConfiguration.Configure(ApiConfig.Register);
            //重訂路由
            GlobalConfiguration.Configuration.Services.Replace(typeof(IApiExplorer), new CustomApiExplorer(GlobalConfiguration.Configuration));
        }

 

到這裏配置相關已經處理完成,建立Controller文件夾配置接口,在文件夾中建立文件DemoController.csspa

 [RoutePrefix("api/DemoTest")]
    public class DemoController : ApiController
    {
        [HttpGet]
        [Route("Hello")]
        public string GetList()
        {
            return "Hello";
        }
    }

到這裏Swagger配置以及所有完成,直接運行,在瀏覽器中輸入http://localhost:58360/swagger 便可查看結果

 

開始配置驗證功能,這裏我使用的是OAuth ;

首先在Nuget中安裝 Microsoft.Owin.Security.OAuth

安裝完成後建立 SimpleAuthorizationServerProvider 文件,在這個文件中重寫Oauth方法, 在此文件中作用戶驗證等操做

 public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {


        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult<object>(null);
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var isLogin = false;// UsersBase.Login(context.UserName, context.Password);
            if (!isLogin)
            {
                context.SetError("Error", "帳號密碼驗證失敗");
                return;
            }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
            context.Validated(identity);
            
        }
    }

建立 SimpleRefreshTokenProvider 文件 重寫OauthToken生成規則

    public class SimpleRefreshTokenProvider : AuthenticationTokenProvider
    {
        private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>();

        /// <summary>
        /// 生成 refresh_token
        /// </summary>
        public override void Create(AuthenticationTokenCreateContext context)
        {
            context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;
            context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60);

            context.SetToken(Guid.NewGuid().ToString("n"));
            _refreshTokens[context.Token] = context.SerializeTicket();
        }

        /// <summary>
        /// 由 refresh_token 解析成 access_token
        /// </summary>
        public override void Receive(AuthenticationTokenReceiveContext context)
        {
            string value;
            if (_refreshTokens.TryRemove(context.Token, out value))
            {
                context.DeserializeTicket(value);
            }
        }
    }

 

 

修改 Startup1文件中代碼

  public void Configuration(IAppBuilder app)
        {

            ConfigAuth(app);
            HttpConfiguration config = new HttpConfiguration();
            ApiConfig.Register(config);
            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(config);


            //初始化
            GlobalConfiguration.Configure(ApiConfig.Register);
            //重訂路由
            GlobalConfiguration.Configuration.Services.Replace(typeof(IApiExplorer), new CustomApiExplorer(GlobalConfiguration.Configuration));
        }
        public void ConfigAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"), //獲取 access_token 受權服務請求地址
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), //access_token 過時時間
                Provider = new SimpleAuthorizationServerProvider(), //access_token 相關受權服務
                RefreshTokenProvider = new SimpleRefreshTokenProvider() //refresh_token 受權服務
            };
            app.UseOAuthAuthorizationServer(option);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }

 

接口啓用驗證;[Authorize] 表明此模塊須要身份驗證, [AllowAnonymous] 表明此方法不須要驗證

    [RoutePrefix("api/DemoTest")]
    [Authorize]
    public class DemoController : ApiController
    {
        [HttpGet]
        [Route("Hello")]
        [AllowAnonymous]
        public string GetList()
        {
            return "Hello";
        }
        [HttpPost]
        [Route("Hello2")]
        public string GetToken(string userName,string userPwd)
        {
            //new SimpleRefreshTokenProvider().Create(new AuthenticationTokenCreateContext(Owin.IAppBuilder) context);
            return "Hello";
        }
    }

 

Oauth已經配置完成,如今直接運行項目,因爲是Post請求我這邊使用Postman進行驗證接口

相關文章
相關標籤/搜索