public object GetJwtStr(string name, string pass) { string jwtStr = string.Empty; bool suc = false; //这里就是用户登录以后,通过数据库去调取数据,分配权限的操作 //这里直接写死了 if (name == "admin" && pass == "123456") { TokenModel tokenModel = new TokenModel(); tokenModel.Uid = "1"; tokenModel.Roles = UtilConvert.StringToList("admin"); tokenModel.Users = UtilConvert.StringToList(name); tokenModel.ExpiryDateTime = DateTime.Now.AddMinutes((Convert.ToDouble(ConfigHelper.GetValue("EffectiveMin")))); jwtStr = JwtHelper.IssueJwt(tokenModel); suc = true; } else { jwtStr = "login fail!!!"; } var result = new { data = new { success = suc, token = jwtStr } }; return(Json(result)); }
public object UserLogin([FromBody] LoginModel model) { string jwtStr = string.Empty; bool suc = false; //这里就是用户登录以后,通过数据库去调取数据,分配权限的操作 string passWordHash = Common.Helper.MD5Helper.GetMD5(model.Password); QueryParams param = new QueryParams(); param.UserName = model.Account; param.PassWord = passWordHash; UserInfoModel user = userService.LogOn(param); if (user != null && !string.IsNullOrEmpty(user.RoleID)) { RoleModel role = roleService.QueryById(user.RoleID); TokenModel tokenModel = new TokenModel(); tokenModel.Uid = DateTime.Now.ToString("yyyyMMddHHssmm"); tokenModel.Roles = UtilConvert.StringToList(role == null ? "Common" : role.RoleName); tokenModel.Users = UtilConvert.StringToList(user.Account); tokenModel.ExpiryDateTime = DateTime.Now.AddMinutes((Convert.ToDouble(ConfigHelper.GetValue("EffectiveMin")))); jwtStr = JwtHelper.IssueJwt(tokenModel); suc = true; } else { jwtStr = "用户名或密码错误!"; } var result = new { data = new { success = suc, token = jwtStr } }; return(Json(result)); }
/// <summary> /// 解析 /// </summary> /// <param name="jwtStr">jwt字符串</param> /// <returns></returns> public static TokenModel SerializeJwt(string jwtStr) { TokenModel result = null; try { var jwtHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr); object role; object user; object time; try { jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role); jwtToken.Payload.TryGetValue(ClaimTypes.UserData, out user); jwtToken.Payload.TryGetValue(JwtRegisteredClaimNames.Exp, out time); } catch (Exception e) { Console.WriteLine(e); throw; } if (role != null && user != null) { result = new TokenModel { Uid = jwtToken.Id, Roles = role != null?UtilConvert.StringToList(role.ToString()) : null, Users = user != null?UtilConvert.StringToList(user.ToString()) : null, }; if (time != null) { result.ExpiryDateTime = Convert.ToDateTime(time.ToString()); } } } catch (Exception) { return(result); } return(result); }