webapi里的特性
/// <summary>/// Basic验证 /// </summary>/// <remarks>/// /// </remarks>public class BasicAuthorizeAttibute : AuthorizeAttribute{public override void OnAuthorization(HttpActionContext actionContext){var authorization = actionContext.Request.Headers.Authorization; //HTTP标头的Authorization值//ActionDescriptor方法上,ActionDescriptor.ControllerDescriptor 类上//有[AllowAnonymousAttribute] 的情况下if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != 0|| actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != 0){base.OnAuthorization(actionContext);}else if (authorization != null && authorization.Parameter != null){//用户逻辑验证if (ValidateTicket(authorization.Parameter)){base.IsAuthorized(actionContext);}else{this.HandleUnauthorizedRequest(actionContext);}}else{this.HandleUnauthorizedRequest(actionContext);}}/// <summary>/// 验证用户逻辑 /// </summary>/// <param name="encryptTicket" type="string">/// /// </param>/// private bool ValidateTicket(string encryptTicket){// var strTicket = FormsAuthentication.Decrypt(encryptTicket.Remove(encryptTicket.Length - 1).Remove(0, 1));var strTicket = FormsAuthentication.Decrypt(encryptTicket);return string.Equals(strTicket.UserData, string.Format("{0}&{1}", "admin", "123"));}}
获取ticket
[AllowAnonymous][HttpGet]public HttpResponseMessage Login(string account, string password){Model.User user = new User();if (account == "admin" && password == "123"){FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0, account, DateTime.Now,DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", account, password),FormsAuthentication.FormsCookiePath);return Success(user = new User() { name = account, pass = password, ticket = FormsAuthentication.Encrypt(ticket) });}else{return Msg("登录失败");}}
MVC里面请求头(后台请求)
public string GetApi(string method, string queryString){var result = ApiHelper.Instance.RequestApi(method, queryString, GetApiHeader());return result;}private WebHeaderCollection GetApiHeader(){string key = string.Format(GlobalVar.UserTiketCacheKey);var result = CacheHelper.CacheReader(key);WebHeaderCollection header = new WebHeaderCollection();header.Add(HttpRequestHeader.Authorization, "BasicAuth " + result);return header;}