日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

以Attribute加上Header验证

發布時間:2025/7/14 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 以Attribute加上Header验证 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

建立新FilterAttribute繼承AuthorizationFilterAttribute,覆寫OnAuthorization攔截傳入的HttpActionContext內容判斷是否有傳入指定的資料

public override void OnAuthorization(HttpActionContext filterContext) { var identity = FetchAuthHeader(filterContext); //取得資料內容 if (identity == null) { ChallengeAuthRequest(filterContext); //回傳錯誤訊息 return; } var genericPrincipal = new GenericPrincipal(identity, null); //針對目前連線的使用者做授權 Thread.CurrentPrincipal = genericPrincipal; if (!OnAuthorizeUser(identity.Name, identity.Password, filterContext)) //驗證 { ChallengeAuthRequest(filterContext); return; } base.OnAuthorization(filterContext); }

解析HttpActionContext內容取得指定的資料

protected virtual BasicAuthenticationIdentity FetchAuthHeader(HttpActionContext filterContext) { string customer = ""; string pwd = ""; IEnumerable<string> authRequest = filterContext.Request.Headers.GetValues("指定的資料名稱"); IEnumerable<string> authRequest2 = filterContext.Request.Headers.GetValues("指定的資料名稱2"); try { customer = authRequest.FirstOrDefault(); pwd = authRequest2.FirstOrDefault(); } catch { } return new BasicAuthenticationIdentity(customer, pwd); }

驗證解析出來的資料是否符合需求

protected override bool OnAuthorizeUser(string username, string password, HttpActionContext actionContext) { if (username == "驗證資料" && password == "驗證碼") return true; return false; }

建立驗證失敗時要回傳的訊息

private static void ChallengeAuthRequest(HttpActionContext filterContext) { var dnsHost = filterContext.Request.RequestUri.DnsSafeHost; filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.Unauthorized); filterContext.Response.Headers.Add("WWW-Authenticate", string.Format("validate failed", dnsHost)); }

于WebApiConfig.cs中注冊新增的Filter

public static class WebApiConfig { public static void Register(HttpConfiguration config) { GlobalConfiguration.Configuration.Filters.Add(new WebApi.Filters.ApiAuthenticationFilter()); } }

最后在需要驗證的API加上該Filter即可

[WebApi.Filters.ApiAuthenticationFilter] public object QueryApi(string pInput) { return null; }

轉載自:AlenWu的程式學習筆記

轉載于:https://www.cnblogs.com/hnsongbiao/p/9381303.html

總結

以上是生活随笔為你收集整理的以Attribute加上Header验证的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。