public async Task <OpResult <string> > GetJwtToken(string userId, string userPassword) { var ops = await _iMainServices.VerifyPassword(userId, userPassword); var op = ops.Item1; if (!op.Successed) { return(op); } var user = op.Message; var userName = ops.Item2.UserName; var userDto = ops.Item2.MapTo(new UserInfo()); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, userName), //用户名称 new Claim(ClaimTypes.MobilePhone, ops.Item2.Telphone), //用户手机号 new Claim(ClaimTypes.UserData, JsonHelper.ModelToStr(userDto)), //用户手机号 new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(user.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));//数据库中查出来的当前用户的所有角色,号分开,拼接到list里。后面拦截器会根据这个值来筛选他有误权限来访问url。每个接口上有特性标识。 //用户标识 //用户标识 //var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); //identity.AddClaims(claims); //_permissionRequirement这是个配置,启动的时候注入进来的 //_permissionRequirement.Audience = userName;//这个不能加,加了会报错 return(JwtToken.BuildJwtToken(claims.ToArray(), _permissionRequirement)); }
public OpResult <string> GetJwtToken(string userId, string userPassword) { SysUser sysUser; var op = _authorDomainSvc.VerifyUserInfo(userId, userPassword, out sysUser); if (!op.Successed) { return(op); } var user = op.Message; var userName = sysUser.UserId; //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(user.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));//数据库中查出来的当前用户的所有角色,号分开,拼接到list里。后面拦截器会根据这个值来筛选他有误权限来访问url。每个接口上有特性标识。 //用户标识 //用户标识 //var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); //identity.AddClaims(claims); //_permissionRequirement这是个配置,启动的时候注入进来的 //_permissionRequirement.Audience = userName;//这个不能加,加了会报错 return(JwtToken.BuildJwtToken(claims.ToArray(), _permissionRequirement)); }
public async Task <ApiResult <LoginSysUserDto> > Post() { ApiResult <LoginSysUserDto> res = new ApiResult <LoginSysUserDto>(); res.data = new LoginSysUserDto(); try { TokenModelBeta token = JwtToken.ParsingJwtToken(HttpContext); //获取用户信息 string ExpirationTime = DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString(); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Jti, token.Id), new Claim(ClaimTypes.Name, token.Name), new Claim(ClaimTypes.Gender, "Web"), new Claim(ClaimTypes.GroupSid, token.Organize), new Claim(ClaimTypes.Authentication, token.IsAdmin == true ? "1" : "0"), new Claim(ClaimTypes.Expiration, ExpirationTime) }; claims.Add(new Claim(ClaimTypes.Role, token.Role)); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); res.data.token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement).token; res.data.expires = ExpirationTime; } catch (Exception ex) { res.code = (int)ApiEnum.Failure; res.message = "刷新Token失败"; } return(res); }
public async Task <object> GetJWTToken3(string name, string pass) { string jwtStr = string.Empty; bool suc = false; var user = await sysUserInfoServices.GetUserRoleNameStr(name, pass); if (user != null) { //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, name), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(user.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(new JsonResult(token)); } else { return(new JsonResult(new { Status = false, Message = "认证失败" })); } }
public IActionResult Login(string username, string password, string role) { var isValidated = username == "gsw" && password == "111111"; if (!isValidated) { return new JsonResult(new { Status = false, Message = "认证失败" }); } else { //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new Claim[] { new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Role, role), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; var token = JwtToken.BuildJwtToken(claims, _requirement); return new JsonResult(token); } }
public async Task <object> GetJWTToken3(string name = "", string pass = "") { string jwtStr = string.Empty; bool suc = false; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass)) { return(new JsonResult(new { Status = false, message = "用户名或密码不能为空" })); } var userRoles = "Admin"; //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, name), new Claim(JwtRegisteredClaimNames.Jti, "1"), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(new JsonResult(token)); }
public async Task <MessageModel <dynamic> > RefrenshToken(string token = "") { var data = new MessageModel <dynamic>(); if (token.IsNullOrEmpty()) { data.msg = "令牌无效,重新登录"; return(data); } var jwt = JwtHelper.SerializeJwt(token); var Info = await _userserver.GetSysUser(jwt.Uid); if (jwt.Uid != Guid.Empty && Info != null) { var RoleName = await _userserver.GetUserRoleByUserId(Info.Id); var claims = new List <Claim> { new Claim(ClaimTypes.Name, Info.Name), //设置用户名称 new Claim(JwtRegisteredClaimNames.Jti, Info.Id.ToString()), //设置用户ID new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()), //设置过期时间 new Claim("Id", Info.Id.ToString()), new Claim("userName", Info.Name) }; claims.AddRange(RoleName.Split(',').Select(x => new Claim(ClaimTypes.Role, x))); //将用户角色填充到claims中 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); //用户标识 identity.AddClaims(claims); var tokenkey = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); data.response = tokenkey; data.msg = "refrenshToken success! loading data..."; data.success = true; return(data); } return(data); }
public IActionResult Login(string username, string password) { var isValidated = (username == "gsw" && password == "111111") || (username == "ggg" && password == "222222"); var role = username == "gsw" ? "admin" : "system"; if (!isValidated) { return(new JsonResult(new { Status = false, Message = "认证失败" })); } else { //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new Claim[] { new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Role, role), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims, _requirement); return(new JsonResult(token)); } }
public async Task <object> Login([FromBody] Login login) { string jwtStr = string.Empty; if (string.IsNullOrEmpty(login.UserName) || string.IsNullOrEmpty(login.UserPwd)) { return(new JsonResult(new { Status = false, message = "用户名或密码不能为空" })); } login.UserPwd = MD5Helper.MD5Encrypt32(login.UserPwd); Console.WriteLine(login.UserPwd); var user = _context.Users.Where(x => x.UserName == login.UserName && x.UserPwd == login.UserPwd && x.IsDelete == false).FirstOrDefault(); string roleName = ""; var roleList = await _context.Roles.Where(x => x.IsDelete == false).ToListAsync(); if (user != null) { var userRoles = await _context.UserRoles.Where(a => a.IsDelete == false && a.Uid == user.Id).ToListAsync(); if (userRoles.Count > 0) { var arr = userRoles.Select(ur => ur.Rid.ObjToString()).ToList(); var roles = roleList.Where(d => arr.Contains(d.Id.ObjToString())); roleName = string.Join(',', roles.Select(r => r.RoleName).ToArray()); } //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()), new Claim("GID", "-9999"), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(roleName.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(new JsonResult(new { accessToken = token, username = user.UserName })); } else { return(new JsonResult(new { success = false, message = "认证失败" })); } }
public IActionResult Login([FromBody] LoginModel login) { var isValidate = (login.UserName == "ryan" && login.Password == "12345678") || (login.UserName == "paul" && login.Password == "111111"); var role = login.UserName == "ryan" ? "admin" : "system"; if (!isValidate) { return(new JsonResult(new { Status = false, Message = "认证失败" })); } else { var claims = new Claim[] { new Claim(ClaimTypes.Name, login.UserName), new Claim(ClaimTypes.Role, role), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims, _requirement); return(new JsonResult(token)); } }
public async Task <object> GetJwtToken3(string name = "", string pass = "") { string jwtStr = string.Empty; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass)) { return(new JsonResult(new { Status = false, message = "用户名或密码不能为空" })); } pass = MD5Helper.MD5Encrypt32(pass); var user = await _sysUserInfoServices.Query(d => d.uLoginName == name && d.uLoginPWD == pass); if (user.Count > 0) { var userRoles = await _sysUserInfoServices.GetUserRoleNameStr(name, pass); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, name), new Claim(JwtRegisteredClaimNames.Jti, user.FirstOrDefault().uID.ToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); var data = await _roleModulePermissionServices.RoleModuleMaps(); var list = (from item in data where item.IsDeleted == false orderby item.Id select new PermissionItem { Url = item.Module?.LinkUrl, Role = item.Role?.Name, }).ToList(); _requirement.Permissions = list; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(new JsonResult(token)); } else { return(new JsonResult(new { success = false, message = "认证失败" })); } }
public async Task <ApiResult <TokenInfoViewModel> > RefreshToken(string token) { var r = new ApiResult <TokenInfoViewModel>(); try { if (string.IsNullOrEmpty(token)) { r.status = 400; r.msg = "token无效,请重新登录!"; return(r); } var tokenModel = JwtHelper.SerializeToken(token); if (tokenModel != null && JwtHelper.CustomSafeVerify(token) && tokenModel.Uid > 0) { var user = await _userServices.GetById(tokenModel.Uid); if (user != null) { var userRole = await _roleServices.GetList(_ => _.UserID == user.Id); var role = string.Empty; if (userRole != null && userRole.Any()) { role = string.Join(",", userRole.Select(_ => _.RoleID).Distinct()); } //创建声明数组 var claims = new Claim[] { new Claim("uid", user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, role), new Claim(JwtRegisteredClaimNames.Email, user.Email) }; var responseJson = JwtToken.BuildJwtToken(claims); if (responseJson != null) { r.status = 200; r.msg = "刷新Token成功!"; r.data = responseJson; new AuthHelper(_accessor, _redis).SaveCurrSessionAndUserRole(responseJson, new AuthModel() { UserID = user.Id, UserName = user.UserName, RoleIDs = userRole?.Select(_ => _.Id).Distinct().ToList() ?? new List <int>() }); return(r); } } } r.status = 400; r.msg = "刷新token失败请重新登录!"; return(r); } catch (Exception ex) { r.status = 500; r.msg = ex.Message; } return(r); }
public async Task <MessageModel <dynamic> > TokenAssig([FromBody] LoginViewModel loginViewModel) { var data = new MessageModel <dynamic>(); if (ModelState.IsValid) { loginViewModel.Password = loginViewModel.Password.ToMD5(); SysUser Info = await _userserver.CheckUser(loginViewModel.User, loginViewModel.Password); await _schedulerCenter.AddScheduleJobAsync(new SysSchedule { Name = "test1", JobGroup = "test1group", AssemblyName = "Uwl.QuartzNet.JobCenter", ClassName = "Simple", IntervalSecond = 5, }); //_rabbitMQ.SendData("hello", Info); if (Info == null) { data.msg = "账号或者密码错误"; return(data); } else { try { //_schedulerCenter.AddScheduleJobAsync<SysSchedule>(new SysSchedule()); var RoleName = await _userserver.GetUserRoleByUserId(Info.Id); var claims = new List <Claim> { new Claim(ClaimTypes.Name, Info.Name), //设置用户名称 new Claim(JwtRegisteredClaimNames.Jti, Info.Id.ToString()), //设置用户ID new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()), //设置过期时间 }; claims.AddRange(RoleName.Split(',').Select(x => new Claim(ClaimTypes.Role, x))); //将用户角色填充到claims中 //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); data.response = token; data.msg = "Token获取成功"; data.success = true; return(data); } catch (Exception ex) { data.msg = "获取角色信息失败" + ex.Message; return(data); } } } data.msg = "账号或者密码错误"; return(data); }
public async Task <MessageModel <dynamic> > TokenAssig([FromBody] LoginViewModel loginViewModel) { var FromMailAddres = Appsettings.app(new string[] { "FromMailConfig", "FromMailAddres" }); var FromMailPwd = Appsettings.app(new string[] { "FromMailConfig", "FromMailPwd" }); var ToMail = Appsettings.app(new string[] { "FromMailConfig", "ToMail" }); //await SendEmail.SendMailAvailableAsync(FromMailAddres, FromMailPwd, ToMail, $"{ DateTime.Now.ToString("yyyy-MM-dd")}Redis超出限制错误", "测试发送邮件抄送功能");//new string[] { "*****@*****.**" } var data = new MessageModel <dynamic>(); var cheke = loginViewModel.CheckModel(); if (cheke.Item1) { loginViewModel.Password = loginViewModel.Password.ToMD5(); var Ip = HttpContext.GetClientIP(); //await Console.Out.WriteAsync($"IP为【{Ip}】的客户机访问"); SysUser Info = await _userserver.CheckUser(loginViewModel.User, loginViewModel.Password); if (Info == null) { data.msg = "账号或者密码错误"; return(data); } else { try { var RoleName = await _userserver.GetUserRoleByUserId(Info.Id); var claims = new List <Claim> { new Claim(ClaimTypes.Name, Info.Name), //设置用户名称 new Claim(JwtRegisteredClaimNames.Jti, Info.Id.ToString()), //设置用户ID new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()), //设置过期时间 new Claim("Id", Info.Id.ToString()), new Claim("userName", Info.Name) }; claims.AddRange(RoleName.Split(',').Select(x => new Claim(ClaimTypes.Role, x))); //将用户角色填充到claims中 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); //用户标识 identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); data.response = token; data.msg = "Token获取成功"; data.success = true; return(data); } catch (Exception ex) { data.msg = "获取角色信息失败" + ex.Message; return(data); } } } else { data.msg = cheke.Item2; return(data); } }
public async Task <ApiResult <TokenInfoViewModel> > Login(string name = "", string pwd = "") { var r = new ApiResult <TokenInfoViewModel>(); try { if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pwd)) { r.status = 400; r.msg = "账号或密码不能为空!"; return(r); } var user = await _userServices.GetEntity(t => t.UserName.Equals(name) && t.Password.Equals(MD5Helper.MD5Encrypt32(pwd))); if (user != null) { var userRole = await _roleServices.GetList(_ => _.UserID == user.Id); var role = string.Empty; if (userRole != null && userRole.Any()) { role = string.Join(",", userRole.Select(_ => _.RoleID).Distinct()); } //创建声明数组 var claims = new Claim[] { new Claim("uid", user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, role), new Claim(JwtRegisteredClaimNames.Email, user.Email) }; var responseJson = JwtToken.BuildJwtToken(claims); if (responseJson != null) { r.status = 200; r.msg = "登录成功!"; r.data = responseJson; new AuthHelper(_accessor, _redis).SaveCurrSessionAndUserRole(responseJson, new AuthModel() { UserID = user.Id, UserName = user.UserName, RoleIDs = userRole?.Select(_ => _.Id).Distinct().ToList() ?? new List <int>() }); } } else { r.status = 401; r.msg = "账号或密码错误!"; } } catch (Exception ex) { r.status = 500; r.msg = ex.Message; } return(r); }
public async Task <object> RefreshToken(string token = "") { var jm = new AdminUiCallBack(); if (string.IsNullOrEmpty(token)) { jm.code = 1001; jm.msg = "token无效,请重新登录!"; return(new JsonResult(jm)); } var tokenModel = JwtHelper.SerializeJwt(token); if (tokenModel != null && tokenModel.Uid > 0) { var user = await _sysUserServices.QueryByIdAsync(tokenModel.Uid); if (user != null) { var userRoles = await _sysUserServices.GetUserRoleNameStr(user.userName, user.passWord); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.userName), new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ObjectToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var refreshToken = JwtToken.BuildJwtToken(claims.ToArray(), _permissionRequirement); jm.code = 0; jm.msg = "认证成功"; jm.data = refreshToken; //插入登录日志 var log = new SysLoginRecord(); log.username = user.userName; log.ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); log.os = RuntimeInformation.OSDescription; log.browser = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent]; log.operType = (int)GlobalEnumVars.LoginRecordType.刷新Token; log.createTime = DateTime.Now; await _sysLoginRecordRepository.InsertAsync(log); return(new JsonResult(jm)); } } jm.code = 1001; jm.msg = "token无效,请重新登录!"; return(new JsonResult(jm)); }
public async Task <object> RefreshToken(string token = "") { string jwtStr = string.Empty; if (string.IsNullOrEmpty(token)) { return(new JsonResult(new { Status = false, message = "token无效,请重新登录!" })); } var tokenModel = JwtToken.SerializeJwt(token); if (tokenModel != null && tokenModel.Uid > 0) { string roleName = ""; var roleList = await _context.Roles.Where(x => x.IsDelete == false).ToListAsync(); var user = await _context.Users.FindAsync(tokenModel.Uid); if (user != null) { var userRoles = await _context.UserRoles.Where(a => a.IsDelete == false && a.Uid == user.Id).ToListAsync(); if (userRoles.Count > 0) { var arr = userRoles.Select(ur => ur.Rid.ObjToString()).ToList(); var roles = roleList.Where(d => arr.Contains(d.Id.ObjToString())); roleName = string.Join(',', roles.Select(r => r.RoleName).ToArray()); } //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ObjToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(roleName.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var refreshToken = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(new JsonResult(refreshToken)); } } return(new JsonResult(new { success = false, message = "认证失败" })); }
/// <summary> /// 用户登陆 /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <LoginOutput> LoginAsync(LoginInput input) { // 用户验证 var userInfo = await _dbContext.Queryable <UserInfo>().Where(it => it.UserName == input.UserName).FirstAsync(); if (userInfo == null) { throw new BucketException("GO_0004007", "账号不存在"); } if (userInfo.State != 1) { throw new BucketException("GO_0004008", "账号状态异常"); } if (userInfo.Password != Encrypt.SHA256(input.Password + userInfo.Salt)) { throw new BucketException("GO_4009", "账号或密码错误"); } // 用户角色 var roleList = await _dbContext.Queryable <RoleInfo, UserRoleInfo>((role, urole) => new object[] { JoinType.Inner, role.Id == urole.RoleId }) .Where((role, urole) => urole.Uid == userInfo.Id) .Where((role, urole) => role.IsDel == false) .Select((role, urole) => new { Id = role.Id, Key = role.Key }) .ToListAsync(); // 用户基本信息 var claims = new List <Claim> { new Claim("Uid", userInfo.Id.ToString()), new Claim("Name", userInfo.RealName.SafeString()), new Claim("MobilePhone", userInfo.Mobile.SafeString()), new Claim("Email", userInfo.Email.SafeString()) }; // 角色数据 foreach (var info in roleList) { claims.Add(new Claim(ClaimTypes.Role, info.Key)); claims.Add(new Claim("scope", info.Key)); } // 用户身份标识 var identity = new ClaimsIdentity(); identity.AddClaims(claims); // accessToken var token = JwtToken.BuildJwtToken(claims, _requirement); token.Add("RealName", userInfo.RealName.SafeString()); token.Add("Mobile", userInfo.Mobile.SafeString()); token.Add("Id", userInfo.Id); return(new LoginOutput { Data = token }); }
public async Task <MessageModel <dynamic> > Login(string name = "", string pwd = "") { string jwtStr = string.Empty; MessageModel <dynamic> rt = new MessageModel <dynamic>(); if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pwd)) { rt.msg = "用户名或密码不能为空"; return(rt); } pwd = MD5Helper.MD5Encrypt32(pwd); var user = await _userRepository.Query(d => d.Name == name && d.Pwd == pwd); if (user.Count == 1) { var loginUser = user.FirstOrDefault(); var userRoles = loginUser.Roles; //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, name), new Claim(JwtRegisteredClaimNames.Jti, loginUser.Id.ToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); if (token != null) { rt.msg = "登录成功"; rt.response = token; rt.success = true; return(rt); } else { rt.msg = "认证失败,请核对用户名和密码是否正确"; return(rt); } } else { rt.msg = "认证失败,请核对用户名和密码是否正确"; return(rt); } }
public async Task <object> GetJwtToken(string username = "", string password = "") { string jwtStr = string.Empty; var data = new MessageModel <object>(); if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { data.Success = false; data.Msg = "用户名或密码不能为空"; return(data); } password = Md5Helper.Md5Encrypt32(password); var user = await _userService.Query(d => d.LoginName == username && d.Pwd == password).ConfigureAwait(false); if (user.Count > 0) { var userRoles = await _userService.GetUserRoleNameStr(username, password).ConfigureAwait(false); // 如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, username), // 这里可以保存用户登录的信息,比如用户名,用户id,所属公司id,所属公司名等 new Claim(ClaimTypes.NameIdentifier, user.FirstOrDefault().Id.ToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddMinutes(_requirement.Expiration.TotalMinutes).ToString()) }; claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); // 用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); #region 将登录用户信息保存到缓存中 // 这是测试 _cacheRedis.Add("a", "1"); _cacheMemory.Add("a", "1"); #endregion var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); data.Success = true; data.Response = token; data.Msg = "登录成功!"; return(data); } data.Success = false; data.Msg = "登录失败!"; return(data); }
public async Task <MessageModel <TokenInfoViewModel> > GetJwtToken3(string name = "", string pass = "") { string jwtStr = string.Empty; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass)) { return(Failed <TokenInfoViewModel>("用户名或密码不能为空")); } pass = MD5Helper.MD5Encrypt32(pass); var user = await _sysUserInfoServices.Query(d => d.uLoginName == name && d.uLoginPWD == pass && d.tdIsDelete == false); if (user.Count > 0) { var userRoles = await _sysUserInfoServices.GetUserRoleNameStr(name, pass); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, name), new Claim(JwtRegisteredClaimNames.Jti, user.FirstOrDefault().uID.ToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); // ids4和jwt切换 // jwt if (!Permissions.IsUseIds4) { var data = await _roleModulePermissionServices.RoleModuleMaps(); var list = (from item in data where item.IsDeleted == false orderby item.Id select new PermissionItem { Url = item.Module?.LinkUrl, Role = item.Role?.Name.ObjToString(), }).ToList(); _requirement.Permissions = list; } var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(Success(token, "获取成功")); } else { return(Failed <TokenInfoViewModel>("认证失败")); } }
public async Task <MessageModel <TokenInfoViewModel> > RefreshToken(string token = "") { string jwtStr = string.Empty; if (string.IsNullOrEmpty(token)) { return(new MessageModel <TokenInfoViewModel>() { success = false, msg = "token无效,请重新登录!", }); } var tokenModel = JwtHelper.SerializeJwt(token); if (tokenModel != null && tokenModel.Uid > 0) { var user = await _sysUserInfoServices.QueryById(tokenModel.Uid); if (user != null) { var userRoles = await _sysUserInfoServices.GetUserRoleNameStr(user.uLoginName, user.uLoginPWD); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.uLoginName), new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ObjToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var refreshToken = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(new MessageModel <TokenInfoViewModel>() { success = true, msg = "获取成功", response = refreshToken }); } } return(new MessageModel <TokenInfoViewModel>() { success = false, msg = "认证失败!", }); }
public async Task <IActionResult> Login(string username, string password) { //var isValidated = (username == "gsw" && password == "111111")|| (username == "ggg" && password == "222222"); //var role=username=="gsw"?"admin" :"system"; //if (!isValidated) //{ // return new JsonResult(new // { // Status = false, // Message = "认证失败" // }); //} //else //{ // //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 // var claims = new Claim[] { new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Role, role), new Claim(ClaimTypes.Expiration ,DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString())}; // //用户标识 // var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); // identity.AddClaims(claims); // var token = JwtToken.BuildJwtToken(claims, _requirement); // return new JsonResult(token); //} var user = await _loginService.FindByUsername(username); if (await _loginService.ValidateCredentials(user, password)) { await _loginService.SignIn(user); // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint var role = "admin"; var claims = new Claim[] { new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Role, role), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims, _requirement); return(new JsonResult(token)); } else { return(new JsonResult(new { Status = false, Message = "认证失败" })); } }
public IActionResult Login() { var claims = new List <Claim> { new Claim(ClaimTypes.Name, "Chuang"), new Claim(ClaimTypes.NameIdentifier, "1000"), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(new JsonResult(token)); }
public IActionResult Post([FromBody] LoginPostModel loginPostModel) { if (loginPostModel.UserName == "xbh" && loginPostModel.Password == "123456") { var claims = new[] { new Claim(ClaimTypes.Name, loginPostModel.UserName), new Claim(ClaimTypes.Expiration, DateTime.Now.AddDays(7).ToString()) }; return(Ok(JwtToken.BuildJwtToken(claims, _requirement))); } return(BadRequest("用户名密码错误")); }
/// <summary> /// 获取用户类型名称 /// </summary> /// <param name="dto"></param> /// <returns></returns> public dynamic RefreshToken(Crm_CustomerDto dto) { try { string jwtStr = string.Empty; bool suc = false; if (string.IsNullOrEmpty(dto.Token)) { throw new Exception("token无效,请重新登录!"); } var tokenModel = JwtHelper.SerializeJwt(dto.Token); if (tokenModel != null && !tokenModel.Uid.IsNullOrEmpty()) { throw new Exception("token无效,请重新登录!"); } var customer = _crm_CustomerService.GetIQueryable().Where(f => f.Name == dto.Name && f.Password == dto.Password).FirstOrDefault().MapTo <Crm_CustomerDto>(); if (customer.IsNullOrEmpty()) { throw new Exception("登录失败!"); } customer.UserTypeValue = EnumExtension.GetEnumDescription(((EnumCustomerType)Enum.ToObject(typeof(EnumCustomerType), customer.UserType))); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, customer.Name), new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ObjToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(customer.UserTypeValue.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var refreshToken = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(refreshToken); } catch (Exception) { throw new Exception("认证失败!"); } }
public ActionResult <ApiResult> login([FromBody] LoginRequest obj) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var _requirement = new PermissionRequirement("Vim", "everyone", creds, true) { }; string username = obj.UserName; string userid = obj.UserId.ToString(); string IsAdmin = obj.IsAdmin.ToString(); string ClientType = obj.ClientType.ToString(); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new Claim[] { new Claim("userName", username), new Claim("clientType", ClientType.ToString()), new Claim("userid", userid), new Claim("jti", Guid.NewGuid().ToString()), new Claim("isAdmin", IsAdmin), new Claim(ClaimTypes.NameIdentifier, username), new Claim(ClaimTypes.Role, ""), new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"), new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"), }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims, _requirement, (AuthClientType)(Convert.ToInt32(ClientType))); return(new ApiResult { code = 200, msg = "ok", data = new { Token = token, UserId = Convert.ToInt32(userid), UserName = username, IsAdmin = Convert.ToBoolean(IsAdmin), ClientType = Convert.ToInt32(ClientType) } }); }
public async Task <ResponseMessage <TokenInfoViewModel> > Login([FromBody] LoginUser model) { if (ModelState.IsValid) { var user = await _usersService.Query(x => x.UserName.Equals(model.UserName) && x.Password.Equals(model.Password) && !x.IsRemove); if (user != null) { var userRole = await _userRoleService.Query(x => x.UserId == user.Id); var roles = await _rolesService.Query(x => x.Id == userRole.RoleId); string issuer = Appsettings.app(new[] { "PermissionRequirement", "Issuer" }); string audience = Appsettings.app(new[] { "PermissionRequirement", "Audience" }); string signingKey = Appsettings.app(new[] { "PermissionRequirement", "SigningCredentials" }); var keyByteArray = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(signingKey)); var signingCredentials = new SigningCredentials(keyByteArray, SecurityAlgorithms.HmacSha256); Claim[] claims = new List <Claim>() { new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, roles.RoleName) }.ToArray(); PermissionRequirement requirement = new PermissionRequirement(roles.RoleName, issuer, audience, ClaimTypes.Role, signingCredentials, TimeSpan.FromMinutes(60)); TokenInfoViewModel token = JwtToken.BuildJwtToken(claims, requirement); return(new ResponseMessage <TokenInfoViewModel>() { Msg = "请求成功", Status = 200, Success = true, ResponseInfo = token }); } return(new ResponseMessage <TokenInfoViewModel>() { Msg = "没有该用户", Success = false, }); } return(new ResponseMessage <TokenInfoViewModel>() { Msg = "请求失败", Success = false, }); }
public async Task <ApiResult <LoginSysUserDto> > Get(string username, string password) { ApiResult <LoginSysUserDto> res = new ApiResult <LoginSysUserDto>(); res.data = new LoginSysUserDto(); //获取用户信息 ApiResult <SysUser> apiResult = await _userService.UserNameAndPassQueryAsync(username, password); if (apiResult.code != (int)ApiEnum.Status) { res.code = apiResult.code; res.message = apiResult.message; return(await Task.Run(() => res)); } //修改登录信息 var userLogonUp = await _userLogonService.UpdateAsync(c => new SysUserLogon { LogOnCount = c.LogOnCount + 1 }, s => s.UserId == apiResult.data.Id); if (userLogonUp) { string ExpirationTime = DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString(); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Jti, apiResult.data.Id), new Claim(ClaimTypes.Name, apiResult.data.RealName), new Claim(ClaimTypes.Gender, "Web"), new Claim(ClaimTypes.GroupSid, apiResult.data.OrganizeId), new Claim(ClaimTypes.Authentication, apiResult.data.IsAdministrator == true ? "1" : "0"), new Claim(ClaimTypes.Expiration, ExpirationTime) }; claims.Add(new Claim(ClaimTypes.Role, apiResult.data.RoleId)); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); res.data.token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement).token; res.data.expires = ExpirationTime; //返回过期时间 } return(await Task.Run(() => res)); }
public async Task <object> GetJwtToken3(string name = "", string pass = "") { string jwtStr = string.Empty; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass)) { return(new JsonResult(new { Status = false, message = "用户名或密码不能为空" })); } //pass = MD5Helper.MD5Encrypt32(pass); var user = await _sysUserInfoServices.Query(d => d.UserName == name && d.UserPWD == pass); if (user.Count > 0) { var userRoles = await _sysUserInfoServices.GetUserRoleNameStr(name, pass); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, name), new Claim(JwtRegisteredClaimNames.Jti, user.FirstOrDefault().Id.ToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(new JsonResult(token)); } else { return(new JsonResult(new { success = false, message = "认证失败" })); } }