//自定义的过滤器类,必须继承AuthorizeAttribute类(用于验证请求的 IPrincipal 的授权筛选器) public class NjtAuthorizeFilter : AuthorizeAttribute { //OnAuthorization(HttpActionContext actionContext):为操作授权时调用。 //HttpActionContext:包含HTTP正在执行的操作的信息。 public override void OnAuthorization(HttpActionContext actionContext) { //actionContext.Request.Headers:可以获取HTTP向服务器发出的请求,包含在Header里的所有信息。 if (actionContext.Request.Headers.Contains(Consts.HTTP_HEADER_AUTH_USER) && actionContext.Request.Headers.Contains(Consts.HTTP_HEADER_AUTH_KEY)) { IEnumerable<string> arrCustomAuthName = actionContext.Request.Headers.GetValues(Consts.HTTP_HEADER_AUTH_USER); IEnumerable<string> arrCustomAuthKey = actionContext.Request.Headers.GetValues(Consts.HTTP_HEADER_AUTH_KEY); //.Any():检查序列是否包含元素return true/false if (arrCustomAuthName.Any() && arrCustomAuthKey.Any()) { /* GetNjtZlPrincipal():这一步是身份验证的关键,是否通过验证都这里实现 * NjtZlPrincipal类继承了IPrincipal接口(定义基本功能主体对象),并加以扩展。 */ NjtZlPrincipal principal = GetNjtZlPrincipal(arrCustomAuthName.First(), arrCustomAuthKey.First(), actionContext); if (principal != null) { //HttpContext.Current:获取或设置当前HTTP请求的System.Web.HttpContext对象。 //HttpContext.Current.User:获取或设置为当前HTTP请求的安全信息。 HttpContext.Current.User = principal; //★这步是必须的缺少这步的话,整个过滤器就不起作用【获取或设置线程的当前主体(对基于角色的安全性)】。 Thread.CurrentPrincipal = principal; } } } //判断用户是否登录 if (!HttpContext.Current.User.Identity.IsAuthenticated) throw new NjtWebException(NjtWebExceptionCode.Unauthorized, "身份验证失败"); } protected NjtZlPrincipal GetNjtZlPrincipal(string strName, string strKey, HttpActionContext actionContext) { SimUser_BLL userBll = Managers.s_userManager.GetSimUser(strName); if (userBll!=null) { try { Guid guidRequest = Guid.Empty; if (!WebApiServerHelper.VerifyAuthKey(strName, strKey, actionContext.Request.RequestUri.ToString(), userBll.Password, ref guidRequest)) return null; //判断GUID防止重发攻击 if (!GlobalServerData.s_guidsetRequest.IsExistAndAdd(guidRequest)) return null; return new NjtZlPrincipal(new NjtZlIdentity { Name = userBll.UserName, DispName = userBll.RealName, Password = userBll.Password, Role = userBll.Role }); } catch (Exception) { //Ignore any exception } } return null; } } //NjtZlPrincipal类 public class NjtZlPrincipal : IPrincipal { private readonly NjtZlIdentity m_identity; public NjtZlPrincipal(NjtZlIdentity identity) { m_identity = identity; } //身份 public IIdentity Identity { get { return m_identity; } } //角色判断 public bool IsInRole(string role) { return m_identity.Role==role; } } public class NjtZlIdentity : IIdentity { public string AuthenticationType { get { return "Custom"; } } public bool IsAuthenticated { get { return true; } } public string Name { get; set; } public string DispName { get; set; } public string Password { get; set; } public string Role { get; set; } }