基于Token认证的多点登录和WebApi保护
在文章中有错误的地方,或是有建议或意见的地方,请大家多多指正,邮箱: linjie.rd@gmail.com
一天张三,李四,王五,赵六去动物园,张三没买票,李四制作了个假票,王五买了票,赵六要直接FQ进动物园
到了门口,验票的时候,张三没有买票被拒绝进入动物园,李四因为买假票而被补,赵六被执勤人员抓获,只有张三进去了动物园
后来大家才知道,当一个用户带着自己的信息去买票的时候,验证自己的信息是否正确,那真实的身份证(正确的用户名和密码),验证通过以后通过身份证信息和票据打印时间(用户登录时间)生成一个新的动物园参观票(Token令牌),给了用户一个,在动物园门口也保存了票据信息(相当与客户端和服务端都保存一份),在进动物园的时候两个票据信息对比,正确的就可以进动物园玩了
这就是我理解的Token认证.当然可能我的比喻不太正确,望大家多多谅解
下面是我们在服务端定义的授权过滤器
思路是根据切面编程的思想,相当于二战时期城楼门口设立的卡,当用户想api发起请求的时候,授权过滤器在api执行动作之前执行,获取到用户信息
如果发现用户没有登录,我们会判断用户要访问的页面是否允许匿名访问
用户没有登录但是允许匿名访问,放行客户端的请求
用户没有登录且不允许匿名访问,不允许通过,告诉客户端,状态码403或401,请求被拒绝了
如果发现用户登录,判断用户的良民证(Token令牌)是真的还是假的
用户登录,且良民证是真的,放行
发现良民证造价,抓起来,不允许访问
当然,这里可以加权限,验证是否有某个操作的权限
1 public class UserTokenAttribute : AuthorizeAttribute 2 { 3 protected override void HandleUnauthorizedRequest(HttpActionContext filterContext) 4 { 5 6 base.HandleUnauthorizedRequest(filterContext); 7 var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage(); 8 response.StatusCode = HttpStatusCode.Forbidden; 9 ResultModel model = new ResultModel(); 10 11 model.result_code = ResultCode.Error; 12 model.result_data = null; 13 model.result_mess = "您没有授权!"; 14 15 response.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"); 16 } 17 public override void OnAuthorization(HttpActionContext actionContext) 18 { 19 //从http请求的头里面获取身份验证信息,验证token值是否有效 20 string token = GetToken(actionContext); 21 22 if (!string.IsNullOrEmpty(token)) 23 { 24 if (UserService.Instance.ValidateToken(token)) 25 { 26 base.IsAuthorized(actionContext); 27 } 28 else 29 { 30 HandleUnauthorizedRequest(actionContext); 31 } 32 } 33 34 else//如果取不到token值,并且不允许匿名访问,则返回未验证401 35 { 36 var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>(); 37 bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);//验证当前动作是否允许匿名访问 38 if (isAnonymous) 39 { 40 base.OnAuthorization(actionContext); 41 } 42 else 43 { 44 HandleUnauthorizedRequest(actionContext); 45 } 46 } 47 } 48 public string GetToken(HttpActionContext actionContext) 49 { 50 if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request["token"])) 51 return System.Web.HttpContext.Current.Request["token"].ToString(); 52 if (System.Web.HttpContext.Current.Request.InputStream.Length > 0) 53 { 54 string json = new System.IO.StreamReader(System.Web.HttpContext.Current.Request.InputStream).ReadToEnd(); 55 Dictionary<string, object> di = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(json); 56 if (di.Keys.Contains("token")) return di["token"].ToString(); 57 } 58 return ""; 59 } 60 61 62 }
好了,服务端有验证了,客户端也不能拉下啊,客户端使用了动作过滤器,在用户操作之前或用户操作之后验证登录信息(这里可以加权限,验证是否有某个操作的权限)
客户端验证思路和服务端验证差不多
下面是客户端验证代码:
1 public class LoginVerificationAttribute : ActionFilterAttribute 2 { 3 public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) 4 { 5 #region 是否登录 6 var userInfo = UserManager.GetLoginUser(); 7 if (userInfo != null) 8 { 9 base.OnActionExecuting(filterContext); 10 } 11 else 12 { 13 if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) 14 || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) 15 { 16 base.OnActionExecuting(filterContext); 17 } 18 else 19 { 20 System.Web.HttpContext.Current.Session["token"] = null; 21 filterContext.HttpContext.Response.Redirect("/Common/Login", true); 22 filterContext.HttpContext.Response.End(); 23 } 24 } 25 #endregion 26 } 27 }
但是有良民证也不能也不能无限制的待在城里啊,我们做了一个时效性,在城市里什么时也不做到达一定的时长后得驱逐出城啊(类似与游戏中的挂机超过一定时间后T出本局游戏)
在这里使用的Redis记录良民证(Token),思路是用户登录之后生成的新的Token保存在Redis上,设定保存时间20分钟,当有用户有动作之后更新Redis保存有效期
下面是服务端验证token的,token有效,从新写入到Redis
1 public UserInfoDetail GetUserIdInCachen(string token) 2 { 3 SimpleTokenInfo tokenInfo = JwtUtil.Decode<SimpleTokenInfo>(token); 4 if (tokenInfo == null) return null; 5 RedisHelper redisHelper = new RedisHelper(); 6 string userJson = redisHelper.Get<string>(tokenInfo.UserName); 7 if (!string.IsNullOrEmpty(userJson)) 8 { 9 10 UserAndToken userAndToken = JsonConvert.DeserializeObject<UserAndToken>(userJson); 11 if (userAndToken.Token.Equals(token)) 12 { 13 redisHelper.Set(tokenInfo.UserName, userJson, DateTime.Now.AddSeconds(expireSecond)); 14 return userAndToken; 15 } 16 17 return null; 18 } 19 return null; 20 }
以上就是Token认证
现在说说单点登录的思路
张三登录了qq:123456,生成了一个Token以键值对的方式保存在了数据库,键就是qq号,值就是qq信息和登录时间生成的一个Token
李四也登录了qq123456,qq信息是一致的,但是qq登录时间不同,生成了一个新的Token,在保存的时候发现Redis里已经存在这个qq的键了,说明这是已经有人登录了,在这里可以判断是否继续登录,登录后新的Token信息覆盖了张三登录QQ生成的Token,张三的Token失效了,当他再次请求的时候发现Token对应不上,被T下线了
多点登录也是,可以通过qq号加客户端类型作为键,这样手机qq登录的键是 123456_手机,电脑登录的键是123456_电脑,这样在保存到Redis的时候就不会发生冲突,可以保持手机和电脑同时在线
但是有一个人用手机登录qq 123456了,就会覆盖redis中键为123456_手机的Token信息,导致原先登录那个人的信息失效,被强制下线
来展示代码
判断是否可以登录
1 public string GetToken(string userName, string passWord, ClientType clientType) 2 { 3 UserInfoDetail user = GetModel(userName); 4 if (user != null) 5 { 6 if (user.Pwd.ToUpper() == StringMd5.Md5Hash32Salt(passWord).ToUpper()) 7 { 8 return GetToken(user, clientType); 9 } 10 } 11 return ""; 12 }
客户端类型实体
这是我们的客户端类型:
1 public enum ClientType 2 { 3 /// <summary> 4 /// 主站 5 /// </summary> 6 MasetSize, 7 /// <summary> 8 /// 微信小程序 9 /// </summary> 10 WeChatSmallProgram, 11 /// <summary> 12 /// WinForm端 13 /// </summary> 14 WinForm, 15 /// <summary> 16 /// App端 17 /// </summary> 18 App 19 }
获取token需要的用户信息和登录时间的实体Model
这是我们的用户Model
1 public partial class UserInfoDetail 2 { 3 public UserInfoDetail() 4 { } 5 public string Admin{ get; set; } 6 public string Pwd { get; set; } 7 }
生成Token用的实体
1 public class SimpleTokenInfo 2 { 3 public SimpleTokenInfo() 4 { 5 CreateTimeStr = DateTime.Now.ToString("yyyyMMddhhmmss"); 6 7 } 8 /// <summary> 9 /// 创建日期 10 /// </summary> 11 public string CreateTimeStr { get; set; } 12 /// <summary> 13 /// 用户账户 14 /// </summary> 15 public string UserName { get; set; } 16 }
登录成功,通过JWT非对称加密生成Token
1 /// <summary> 2 /// 获取token 3 /// </summary> 4 /// <param name="user">用户</param> 5 /// <returns></returns> 6 public string GetToken(UserInfoDetail user, ClientType clientType) 7 { 8 RedisHelper redisHelper = new RedisHelper(); 9 SimpleTokenInfo tokenInfo = new SimpleTokenInfo(); 10 tokenInfo.UserName = user.Admin + "_" + ((int)clientType).ToString(); 11 string token = JwtUtil.Encode(tokenInfo); 12 UserAndToken userAndToken = new UserAndToken(); 13 userAndToken.Token = token; 14 ModelCopier.CopyModel(user, userAndToken); 15 string userJson = JsonConvert.SerializeObject(userAndToken); 16 redisHelper.Set(tokenInfo.UserName, userJson, DateTime.Now.AddSeconds(expireSecond)); 17 return token; 18 }
下面是JWT加密和解密的代码
1 public class JwtUtil 2 { 3 private static string secret = "***********";//这个服务端加密秘钥 属于私钥 4 5 public static string Encode(object obj) 6 { 7 IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); 8 IJsonSerializer serializer = new JsonNetSerializer(); 9 IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); 10 IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); 11 var token = encoder.Encode(obj, secret); 12 return token; 13 } 14 public static T Decode<T>(string token) 15 { 16 string json; 17 try 18 { 19 IJsonSerializer serializer = new JsonNetSerializer(); 20 IDateTimeProvider provider = new UtcDateTimeProvider(); 21 IJwtValidator validator = new JwtValidator(serializer, provider); 22 IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); 23 IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); 24 json = decoder.Decode(token, secret, verify: false);//token为之前生成的字符串 25 T model = JsonConvert.DeserializeObject<T>(json); 26 //对时间和用户账户密码进行认证 27 return model; 28 } 29 catch (Exception) 30 { 31 return default(T); 32 } 33 34 } 35 }
将获取到的Token保存到Redis
1 /// <summary> 2 /// 存储数据到hash表 3 /// </summary> 4 public bool Set(string key, string value, DateTime tmpExpire) 5 { 6 try 7 { 8 9 Redis.Set(key, value, tmpExpire); 10 Save(); 11 } 12 catch 13 { 14 return false; 15 } 16 return true; 17 }
展示一下,在服务端,继承控制器实现登录验证:
1 /// <summary> 2 /// 验证登录,继承此控制器限制登录才可以访问 3 /// </summary> 4 [UserToken] 5 public class LoginVerificationController : BaseApiController 6 { 7 8 }
在服务端的验证方法,在方法前加[AllowAnonymous]是允许匿名访问,也就是不登录访问,
下面以用户中心控制器为例
1 public class UserController : LoginVerificationController 2 { 3 4 /// <summary> 5 /// 用户登录,获取token 6 /// </summary> 7 /// <param name="userName">用户名</param> 8 /// <param name="passWord">密码</param> 9 /// <param name="clientType">客户端类型</param> 10 /// <returns></returns> 11 [HttpGet] 12 [AllowAnonymous] 13 public ResultModel GetToken(string userName, string passWord, int clientType) 14 { 15 ResultModel model = new ResultModel(); 16 17 if (!Enum.IsDefined(typeof(ClientType), clientType)) 18 { 19 model.result_code = ResultCode.Error; 20 model.result_data = ""; 21 model.result_mess = "客户端类型不正确!"; 22 return model; 23 } 24 string token = UserService.Instance.GetToken(userName, passWord, (ClientType)clientType); 25 if (string.IsNullOrEmpty(token)) 26 { 27 model.result_code = ResultCode.Fail; 28 model.result_data = ""; 29 model.result_mess = "获取token失败!"; 30 } 31 else 32 { 33 model.result_code = ResultCode.Ok; 34 model.result_data = token; 35 model.result_mess = "获取token成功!"; 36 } 37 38 return model; 39 } 40 /// <summary> 41 /// 获取用户 42 /// </summary> 43 /// <param name="token">令牌</param> 44 /// <returns></returns> 45 public ResultModel GetUserInfo(string token) 46 { 47 ResultModel model = new ResultModel(); 48 try 49 { 50 UserInfoDetail user = UserService.Instance.GetUser(token); 51 if (user != null) 52 { 53 model.result_code = ResultCode.Ok; 54 model.result_data = user; 55 model.result_mess = "获取用户成功!"; 56 } 57 else 58 { 59 model.result_code = ResultCode.Fail; 60 model.result_data = ""; 61 model.result_mess = "获取用户失败!"; 62 63 } 64 } 65 catch (Exception ex) 66 { 67 model.result_code = ResultCode.Error; 68 model.result_data = null; 69 model.result_mess = ex.ToString(); 70 } 71 return model; 72 } 73 74 /// <summary> 75 /// 验证用户名有效性 76 /// </summary> 77 /// <param name="user">用户model 包含用户名和token</param> 78 /// <returns></returns> 79 [HttpPost] 80 public ResultModel VUserName([FromBody]User user) 81 { 82 ResultModel model = new ResultModel(); 83 try 84 { 85 86 if (string.IsNullOrEmpty(user.username)) 87 { 88 model.result_code = ResultCode.Ok; 89 model.result_data = ""; 90 model.result_mess = "用户名可以使用!"; 91 } 92 else 93 { 94 model.result_code = ResultCode.Fail; 95 model.result_data = ""; 96 model.result_mess = "用户名已经存在!"; 97 } 98 } 99 catch (Exception ex) 100 { 101 model.result_code = ResultCode.Error; 102 model.result_data = null; 103 model.result_mess = ex.ToString(); 104 } 105 return model; 106 } 107 }
1 public class User 2 { 3 public string username { get; set; } 4 public string token { get; set; } 5 }
客户端使用也类似,在方法前加[AllowAnonymous]是该方法允许匿名访问,下面是客户端我封装的Base控制器
1 public class BaseController : Controller 2 { 3 public BaseController() 4 { 5 UserInfoDetail userinfo= GetUserInfo(); 6 ViewBag.User=userinfo?.Admin??"请登陆"; 7 ViewBag.UserId = GetToken(); 8 } 9 public string GetAPI(string method, string uri,object o=null) 10 { 11 12 string str = string.Empty; 13 HttpContent content = new StringContent(JsonConvert.SerializeObject(o)); 14 using (HttpClient client = new HttpClient()) 15 { 16 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 17 content.Headers.ContentType =new MediaTypeHeaderValue("application/json"); 18 HttpResponseMessage response=null; 19 if(method.ToLower()=="get") 20 { 21 response = client.GetAsync(uri).Result; 22 } 23 else if(method.ToLower()=="post") 24 { 25 response = client.PostAsync(uri, content).Result; 26 } 27 else if(method.ToLower()=="put") 28 { 29 response = client.PutAsync(uri, content).Result; 30 } 31 else if(method.ToLower()=="delete") 32 { 33 response = client.DeleteAsync(uri).Result; 34 } 35 if(response.IsSuccessStatusCode) 36 { 37 str = response.Content.ReadAsStringAsync().Result; 38 } 39 } 40 return str; 41 } 42 43 /// <summary> 44 /// 获取用户信息 45 /// </summary> 46 /// <returns></returns> 47 public UserInfoDetail GetUserInfo() 48 { 49 return UserManager.GetLoginUser(); 50 } 51 52 /// <summary> 53 /// 获取Token 54 /// </summary> 55 /// <returns></returns> 56 public string GetToken() 57 { 58 return UserManager.GetLoginToken(); 59 } 60 }
使用方法如下
1 /// <summary> 2 /// 继承此控制器表示登录验证 3 /// </summary> 4 [LoginVerification] 5 public class LoginVerificationController : BaseController 6 { 7 8 //[AllowAnonymous]//该特性表示允许匿名访问该方法 9 //public void Test() 10 //{ 11 12 //} 13 }
看了自己写写的东西,现在想起来,为什么小学语文是体育老师教的啊