webapi JWT 认证

2021-06-07 05:03

阅读:482

标签:algo   override   权限   col   dict   div   第一步   new   基于   

第一步 使用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 Dictionarystring, 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]

webapi JWT 认证

标签:algo   override   权限   col   dict   div   第一步   new   基于   

原文地址:https://www.cnblogs.com/sxmny/p/10757337.html


评论


亲,登录后才可以留言!