WebApi身份验证
一、通过Http请求(不通过过滤器)
public static UserDTO GetAuthInfo() { var cur = HttpContext.Current; var account= cur.Request.Headers.GetValues(Consts.HTTP_HEADER_AUTH_USER); var key = cur.Request.Headers.GetValues(Consts.HTTP_HEADER_AUTH_KEY); if (account!=null && key!=null) { if (account.Any() && key.Any()) { string strName = account.First(); string strKey = key.First(); string actionUri = cur.Request.Url.OriginalString; var userInfo = UserService.GetPrivateKey(strName); if (userInfo != null && WebApiServerHelper.VerifyAuthKey(strName, strKey, actionUri, userInfo.Token)) { return userInfo; } } } return null; }
二、通过过滤器
public class WebApiAuthFilterAttribute : AuthorizeAttribute { public override void OnAuthorization(HttpActionContext actionContext) { 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); if (arrCustomAuthName.Any() && arrCustomAuthKey.Any()) { WebApiPrincipal principal = GetWebApiPrincipal(arrCustomAuthName.First(), arrCustomAuthKey.First(), actionContext.Request.RequestUri.ToString()); if (principal != null) { HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; } } } //判断用户是否登录 if (!HttpContext.Current.User.Identity.IsAuthenticated) throw new WebApiException(EnumException.身份验证失败); } } } public class WebApiIdentity : IIdentity { public UserDTO Owner { get; set; } public string Name { get; set; } public string Role { get; set; } /// 表示用的验证方式是自定义验证 public string AuthenticationType { get { return "Custom"; } } public bool IsAuthenticated { get { return true; } } } public static class ApiControlerExtension { //方便获取用户的扩展方法 public static UserDTO GetUser(this ApiController controller) { if (controller.User is WebApiPrincipal) { return ((WebApiIdentity)controller.User.Identity).Owner; } else { return null; } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步