.Net JWT验证


1、nuget搜索JWT并安装

2、创建ApiAuthorizeAttribute,作为验证特性

 /// 
    /// 身份认证拦截器
    /// 
    public class ApiAuthorizeAttribute: AuthorizeAttribute
    {
        /// 
        /// 指示指定的控件是否已获得授权
        /// 
        /// 
        /// 
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            //前端请求api时会将token存放在名为"auth"的请求头中
            var authHeader = from t in actionContext.Request.Headers where t.Key == "Authorization" select t.Value.FirstOrDefault();
            if (authHeader != null)
            {
                const string secretKey = "Hello World";//加密秘钥
                string token = authHeader.FirstOrDefault();//获取token
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        byte[] key = Encoding.UTF8.GetBytes(secretKey);
                        IJsonSerializer serializer = new JsonNetSerializer();
                        IDateTimeProvider provider = new UtcDateTimeProvider();
                        IJwtValidator validator = new JwtValidator(serializer, provider);
                        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                        IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                        //解密
                        var json = decoder.DecodeToObject(token, key, verify: true);
                        if (json != null)
                        {
                            //判断口令过期时间
                            if (json.ExpiryDateTime < DateTime.Now)
                            {
                                return false;
                            }
                            actionContext.RequestContext.RouteData.Values.Add("Authorization", json);
                            return true;
                        }
                        return false;
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
            }
            return false;
        }

        /// 
        /// 处理授权失败的请求
        /// 
        /// 
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            var erModel = new
            {
                Success = "false",
                ErrorCode = "401"
            };
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, erModel, "application/json");
        }
 

3、新建3个类,

 /// 
    /// 身份验证信息 模拟JWT的payload
    /// 
    public class AuthInfo
    {
        /// 
        /// 用户名
        /// 
        public string UserName { get; set; }

        /// 
        /// 角色
        /// 
        public List Roles { get; set; }

        /// 
        /// 是否管理员
        /// 
        public bool IsAdmin { get; set; }

        /// 
        /// 口令过期时间
        /// 
        public DateTime? ExpiryDateTime { get; set; }
    }
/// 
    /// 登录用户信息
    /// 
    public class LoginRequest
    {
        /// 
        /// 用户名
        /// 
        public string UserName { get; set; }

        /// 
        /// 密码
        /// 
        public string Password { get; set; }
    }
 /// 
    /// 生成的口令信息
    /// 
    public class TokenInfo
    {
        /// 
        /// 是否成功
        /// 
        public bool Success { get; set; }
        /// 
        /// 令牌
        /// 
        public string Token { get; set; }
        /// 
        /// 错误信息
        /// 
        public string Message { get; set; }
    }

4、新建一个获取token的controller

/// 
        /// 登录
        /// 
        /// 
        /// 
        [HttpPost]
        [Route("Login")]
        public TokenInfo Login([FromBody] LoginRequest loginRequest)
        {
            TokenInfo tokenInfo = new TokenInfo();//需要返回的口令信息
            if (loginRequest != null)
            {
                string userName = loginRequest.UserName;
                string passWord = loginRequest.Password;
                bool isAdmin = (userName == "admin") ? true : false;
                //模拟数据库数据,真正的数据应该从数据库读取
                //身份验证信息
                AuthInfo authInfo = new AuthInfo { UserName = userName, Roles = new List { "admin", "commonrole" }, IsAdmin = isAdmin, ExpiryDateTime = DateTime.Now.AddHours(2) };
                const string secretKey = "Hello World";//口令加密秘钥
                try
                {
                    byte[] key = Encoding.UTF8.GetBytes(secretKey);
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
                    IJsonSerializer serializer = new JsonNetSerializer();//序列化Json
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
                    IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);//JWT编码
                    var token = encoder.Encode(authInfo, key);//生成令牌
                    //口令信息
                    tokenInfo.Success = true;
                    tokenInfo.Token = token;
                    tokenInfo.Message = "OK";
                }
                catch (Exception ex)
                {
                    tokenInfo.Success = false;
                    tokenInfo.Message = ex.Message.ToString();
                }
            }
            else
            {
                tokenInfo.Success = false;
                tokenInfo.Message = "用户信息为空";
            }
            return tokenInfo;
        }

5、新建一个验证controller

/// 
        /// 获取用户信息
        /// 
        /// 
        [ApiAuthorize]
        [HttpGet]
        [Route("api/GetUserInfo")]
        public string GetUserInfo()
        {
            var userInfo = new
            {
                UserName = "test",
                Tel = "123456789",
                Address = "testddd"
            };
            return JsonConvert.SerializeObject(userInfo);
        }

6、获取token 

7、调用

转载:https://www.cnblogs.com/jackielyj/p/12112022.html