//control action
public class TestController : ApiController{ [MyAuthFilter] public string test(string str) { return str.Trim(); }}
//过虑器类 public class MyAuthFilter : ActionFilterAttribute { const string SecurityKeyName = "MySecurityKey";//http头的name public object _EBACLS = new object(); public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { if (EBPermission == "1")//判断权限 { if (EBACLS == null) { lock (_EBACLS) { EBACLS = SetEBACLSData(); } } bool isAuth = false; bool isPermission = false; EBSecurityData EBSecurityData = null;//自定义对象 IEnumerable<string> lists; if (actionContext.Request.Headers.TryGetValues(SecurityKeyName, out lists)) { string securityKey = lists.FirstOrDefault(); LogUtility.WriteLog(SecurityKeyName + securityKey);//写日志文件 try { EBSecurityData = EBSecurityUtility.GetSecurityData(securityKey);//解密得到的加密串 LogUtility.WriteLog("EBSecurityData:" + (EBSecurityData != null ? EBSecurityData.ObjectToJson() : "")); } catch (Exception) { } if (EBSecurityData != null && EBSecurityData.Expire > DateTime.Now && EBSecurityData.ProviderId > 0) { GenericIdentity identity = new GenericIdentity(EBSecurityData.ProviderId.ToString(), "Forms"); GenericPrincipal principal = new GenericPrincipal(identity, new string[] { }); HttpContext.Current.User = principal; isAuth = true; string actionName = actionContext.ActionDescriptor.ActionName.ToLower(); string actionNo; EBACLS.TryGetValue(actionName, out actionNo); if (!string.IsNullOrWhiteSpace(EBSecurityData.Acl) && !string.IsNullOrWhiteSpace(actionNo)) { string acl = string.Format(",{0},", EBSecurityData.Acl); isPermission = acl.Contains("," + actionNo + ","); } } } if (!isAuth) { throw new BusinessException("登录验证失败", 401); } else if (!isPermission) { throw new BusinessException("未授权", 403); } } } public static Dictionary<string, string> EBACLS { get; set; } Dictionary<string, string> SetEBACLSData() { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("getorderitemoperaterecords", "01"); dic.Add("getorderitemchangedetail", "02"); return dic; } }
http头请求示例:
User-Agent: Fiddler
Host: localhost
Content-Length: 478
Content-Type: text/json
MySecurityKey: roxnQNJLa0voulfXMcGugvhKJT1njtDV1Hmu67MbGPIU0UlEVmKXjXkPJ5d7dn1HdD%2BPDM%2Fsa9IJn36NksxQE1MdQ8Mqt1JqhvTTvQfG3zhrSFYgMQVAe3AuYcEN%2F9873lIjXXyuK%2FUQ75vJ3kH3bYIZykRmSvR4fPMbxNVWhVHuhO%2BdVJJQDpLS2Pihy1KbjffkcMNYBZJWdPu%2FLzYCIesaLh%2FDC85IOUi9OOdWzaPMjbvPXoBN7ahN%2Fj%2BkmWNJiYBxPPVO3IU%3D
拿到了 MySecurityKey 的值 ,想怎么处理就怎么处理,我这里只是一样示例,有效增加api安全系数。
如果哪个方法很重要,要使用权限,只要在上面加[MyAuthFilter] 标签,就能实现权限验证,当然,如果不同的方法 ,也可以使用不同的过虑器~自己可以随便定义。