webapi JWT 认证

第一步 使用ng安装JWT组件

第二步 编写登录和生成token代码

            byte[] key = Encoding.UTF8.GetBytes("123456789aaaaaaa");
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
            IJsonSerializer serializer = new JsonNetSerializer();//序列化Json
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密

            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);//JWT编码    

            var payload = new Dictionary<string, object>() {
                { "sub","121212"},
                { "name","胜多负少多送点"},
                { "uid","587345"},
                { "exp",DateTime.Now.AddDays(1)},
            };

            var token = encoder.Encode(payload, key);//生成令牌
            return token;

第三部编写  基于 AuthorizeAttribute 的请求筛选

  public class ApiAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {

            var authHeader = from h in actionContext.Request.Headers where h.Key == "token" select h.Value.FirstOrDefault();
            byte[] key = Encoding.UTF8.GetBytes("123456789aaaaaaa");
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
            IJsonSerializer serializer = new JsonNetSerializer();//序列化Json
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
            IDateTimeProvider provider1 = new UtcDateTimeProvider();
            IJwtValidator validator1 = new JwtValidator(serializer, provider1);
            JwtDecoder jwtDecoder = new JwtDecoder(serializer, validator1, urlEncoder);
            //解密,在这里可以做互斥登录、或者做token 有效性验证
            var jwt = jwtDecoder.Decode(authHeader.Single());
            return false;
            //  return base.IsAuthorized(actionContext);
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);

            var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.Forbidden;
            var content = new
            {
                success = false,
                errs = new[] { "您暂无权限" }
            };
            response.Content = new StringContent(Json.Encode(content), Encoding.UTF8, "application/json");
        }
    }

 

使用的时候只需要在  Controller 或者 action 上加上特性 [ApiAuthorize] 不需要验证的增加特性 [AllowAnonymous]

posted @ 2019-04-23 16:45  伤心木乃伊  阅读(191)  评论(0编辑  收藏  举报