public ResponseResult MainLogin() { ResponseResult result = new (); var list = new List <dynamic> { new { Id = "12", UserName = "******", Pwd = "123456", Role = "admin" }, new { Id = "45", UserName = "******", Pwd = "456789", Role = "system" }, }; var user = list.SingleOrDefault(q => q.UserName == "aaa" && q.Pwd == "123456"); if (user == null) { result.errno = 1; result.errmsg = "用户名或密码错误"; return(result); } else { var userRoles = list.Select(q => q.Role).ToList(); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, user.Id), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(TimeSpan.FromSeconds(60 * 60).TotalSeconds).ToString()) }; claims.AddRange(userRoles.Select(s => new Claim(ClaimTypes.Role, s))); var token = JwtHelper.BuildJwtToken(claims.ToArray(), _requirement); result.data = token; } return(result); }
public IActionResult Token(string email, string password, string url) { var result = new TResultModel <TokenVO>(1); return(Wrapper(ref result, () => { password = MD5Util.GenerateMD5(password); var vip = _vipRepository.GetVip(email, password); if (vip != null) { var jwtStr = JwtHelper.BuildJwtToken(new Claim[3] { new Claim(ClaimTypes.Role, "Admin"), new Claim("Name", vip.NickName), new Claim("Id", vip.Id.ToString()) }, _permissionRequirement); result.TModel = new TokenVO() { Token = jwtStr }; } else { result.ResultNo = -1; } }, false)); }
public async Task <ApiResponseModel <JwtTokenDto> > RefreshToken(string token) { if (token.IsNullOrEmpty()) { return(ApiResponse.Error <JwtTokenDto>("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.GetUserRoleByUserId(user.uID); 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.Select(s => new Claim(ClaimTypes.Role, s.Name))); var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var refreshToken = JwtHelper.BuildJwtToken(claims, _requirement); return(ApiResponse.Success <JwtTokenDto>(refreshToken)); } } return(ApiResponse.Error <JwtTokenDto>("token无效,请重新登录")); }
public async Task <LoginViewModel> RefreshToken([FromForm] string token) { if (string.IsNullOrEmpty(token)) { throw new NoAuthorizeException("token无效,请重新登录!"); } var tokenModel = JwtHelper.SerializeJwt(token); T_UserInfo userInfo = await _userService.FindAsync(tokenModel.UserId); if (userInfo == null) { throw new NoAuthorizeException("token无效,请重新登录!"); } JwtModel jwtModel = new JwtModel { IsAdmin = userInfo.IsAdmin, UserId = userInfo.Id, NickName = userInfo.NickName, UserName = userInfo.UserName, Expiration = TimeSpan.FromSeconds(60 * 60), Role = userInfo.IsAdmin ? string.Join(",", ConstInfo.ClientPolicy, ConstInfo.AdminPolicy) : ConstInfo.ClientPolicy }; var result = JwtHelper.BuildJwtToken(jwtModel); result.NickName = userInfo.NickName; result.AvatarUrl = userInfo.AvatarUrl; result.UseMdEdit = userInfo.UseMdEdit; return(result); }
public IActionResult GitHubCallBcak(string code) { var result = new TResultModel <TokenVO>(1); return(Wrapper(ref result, () => { var clientId = "f1f3420ef57e2d2a089d"; var clientSecret = "4c25c6af2c4ac119b606ea18445f5745506d87cb"; var url = $@"https://github.com/login/oauth/access_token?client_id={clientId}&client_secret={clientSecret}&code={code}"; var tokenResponse = HeyTom.Infra.Util.Http.HttpClient.Post(url, "", header: new Dictionary <string, string>() { { "accept", "application/json" } }); var tokenData = JsonConvert.DeserializeObject <TokenData>(tokenResponse); var accessToken = $"token {tokenData.access_token}"; var userUrl = "https://api.github.com/user"; var UserResult = HeyTom.Infra.Util.Http.HttpClient.Get(userUrl, accessToken); var gitInfo = JsonConvert.DeserializeObject <GitHubUserInfo>(UserResult); var jwtStr = JwtHelper.BuildJwtToken(new Claim[2] { new Claim(ClaimTypes.Role, "Admin"), new Claim("Name", gitInfo.login), }, _permissionRequirement); result.TModel = new TokenVO() { Token = jwtStr }; }, false)); }
public async Task <LoginViewModel> Login([FromBody] LoginParam param) { string md5pwd = SafeHelper.MD5TwoEncrypt(param.PassWord); T_UserInfo userInfo = await _userService.FindAsync(u => u.UserName == param.UserName && u.PassWord == md5pwd); if (userInfo == null) { throw new UserFriendlyException("用户名或密码错误"); } JwtModel jwtModel = new JwtModel { IsAdmin = userInfo.IsAdmin, UserId = userInfo.Id, NickName = userInfo.NickName, UserName = userInfo.UserName, Expiration = TimeSpan.FromSeconds(60 * 60), Role = userInfo.IsAdmin ? string.Join(",", ConstInfo.ClientPolicy, ConstInfo.AdminPolicy) : ConstInfo.ClientPolicy }; var result = JwtHelper.BuildJwtToken(jwtModel); result.NickName = userInfo.NickName; result.AvatarUrl = userInfo.AvatarUrl; result.UseMdEdit = userInfo.UseMdEdit; return(result); }
/// <summary> /// 邮箱登录获取token /// </summary> /// <param name="emailLoginDTO"></param> /// <returns></returns> public TResultModel <TokenDTO> Login(EmailLoginDTO emailLoginDTO) { var md5Password = Md5Helper.GenerateMD5(emailLoginDTO.Password); var member = _memberRepository.GetByEmail(emailLoginDTO.Email); if (member == null || md5Password != member.Password) { return(new TResultModel <TokenDTO>(-1, "用户名或密码错误")); } else { var jwtStr = JwtHelper.BuildJwtToken(new Claim[3] { new Claim(ClaimTypes.Role, "Admin"), new Claim("Name", member.NickName), new Claim("Id", member.Id.ToString()) }, _permissionRequirement); return(new TResultModel <TokenDTO>(1, "success") { TModel = new TokenDTO() { Token = jwtStr } }); } }
public IActionResult Get(string email, string password) { var result = new TResultModel <TokenVModel>(1); return(this.Wrapper(ref result, () => { var md5Password = Md5Helper.GenerateMD5(password); var user = _userRepository.GetByEmail(email); if (user == null || md5Password != user.Pwd) { result.ResultNo = -1; result.Message = "用户名或密码错误"; return; } else { var jwtstr = JwtHelper.BuildJwtToken(new Claim[3] { // new Claim(ClaimTypes.Role,"admin"), new Claim("userName", user.Name), new Claim("userId", user.Id.ToString()), new Claim("email", user.Email), }, _permissionRequirement); result.TModel = new TokenVModel() { token = jwtstr }; } }, false)); }
public async Task <IActionResult> Login(LoginInput input) { if (string.IsNullOrWhiteSpace(input.UserName)) { throw new UserOperationException("请输入用户名!"); } if (string.IsNullOrWhiteSpace(input.Password)) { throw new UserOperationException("请输入密码!"); } var user = (await _userServices.Query(u => u.UserName == input.UserName && u.Password == MD5Helper.MD5Encrypt32(input.Password))).SingleOrDefault(); if (user == null) { throw new UserOperationException("用户不存在或密码错误!"); } if (user.Status == 0) { throw new UserOperationException("您的账号已被禁用!"); } var tokenModel = new TokenModelJwt { UserId = user.Id }; var userRoles = await _userRoleServices.Query(ur => ur.UserId == user.Id); if (userRoles.Any()) { var roleIds = userRoles.Select(ur => ur.RoleId).ToList(); var roles = await _roleServices.Query(r => roleIds.Contains(r.Id)); tokenModel.Roles = roles.Select(r => r.Name).ToList(); } var userPermissions = await _permissionServices.GetUserPermissions(user.Id); _requirement.Permissions = userPermissions.Select(p => new Permission { Role = p.RoleName, Url = p.LinkUrl }).ToList(); var token = _jwtHelper.BuildJwtToken(tokenModel); return(Ok(token)); }
public ResponseResult RefreshToken(string token = "") { ResponseResult result = new ResponseResult(); if (string.IsNullOrEmpty(token)) { result.errno = 1; result.errmsg = "token无效,请重新登录"; return(result); } var tokenModel = JwtHelper.SerializeJwt(token); if (tokenModel == null || JwtHelper.customSafeVerify(token) && tokenModel.Uid < 0) { result.errno = 4; result.errmsg = "认证失败"; return(result); } else { var userList = new List <dynamic> { new { Id = "12", UserName = "******", Pwd = "123456", Role = "admin" }, new { Id = "45", UserName = "******", Pwd = "456789", Role = "invoice" }, }; var user = userList.SingleOrDefault(q => q.UserName == "aaa" && q.Pwd == "123456"); if (user == null) { result.errno = 1; result.errmsg = "用户名或密码错误"; return(result); } else { var userRoles = userList.Select(q => q.Role).ToList(); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; //claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); claims.AddRange(userRoles.Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var refreshToken = JwtHelper.BuildJwtToken(claims.ToArray(), _requirement); result.data = refreshToken; return(result); } } }
private string GetJwtToken(LoginOutput loginOutput) { //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, loginOutput.LoginName), new Claim(JwtRegisteredClaimNames.Sid, loginOutput.Id.ToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_jwtSetting.Value.ExpireSeconds).ToString(CultureInfo.InvariantCulture)), new Claim(ClaimTypes.Role, "Type"), new Claim("mobile", loginOutput.Mobile) }; var token = JwtHelper.BuildJwtToken(claims.ToArray(), _jwtSetting); return(token); }
public async Task <object> GetJwtToken(string name = "", string pass = "") { string jwtStr = string.Empty; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass)) { return(new JsonResult(new { status = false, message = "用户名或密码不能为空!" })); } if (!await _loginRepository.UserExistsAsync(name, pass)) { return(new JsonResult(new { status = false, message = "用户名或密码不正确" })); } var user = await _loginRepository.GetUserAsync(name, pass); int userId = user.Id; TokenModel userModel = await _loginRepository.GetTokenModelAsync(userId); Role userRole = userModel.Role; Claim[] claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim("UserId", userId.ToString()), new Claim(ClaimTypes.Role, userRole.ToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString()) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtHelper.BuildJwtToken(claims, _permissionRequirement); return(new JsonResult(token)); }
public async Task <ApiResponseModel <JwtTokenDto> > GetJwtStr(string name, string pass) { string jwtStr = string.Empty; LogServer.WriteLog("用户登录:" + name); if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass)) { return(ApiResponse.Error <JwtTokenDto>("用户名或密码不能为空")); } pass = MD5Helper.MD5Encrypt32(pass); var userInfo = await _sysUserInfoServices.GetUserByLogin(name, pass); if (userInfo == null) { return(ApiResponse.Error <JwtTokenDto>("用户名不存在")); } var roleList = await _sysUserInfoServices.GetUserRoleByUserId(userInfo.uID); var claims = new List <Claim> { new Claim(ClaimTypes.Name, name), new Claim(JwtRegisteredClaimNames.Jti, userInfo.uID.ObjToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(roleList.Select(s => new Claim(ClaimTypes.Role, s.Name))); var data = await _roleModulePermissionServices.RoleModuleMaps(); var list = data.OrderBy(m => m.Id).Select(m => new PermissionItem { Url = m.Module?.LinkUrl, Role = m.Role?.Name, }).ToList(); _requirement.Permissions = list; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtHelper.BuildJwtToken(claims, _requirement); return(ApiResponse.Success(token)); }
public IActionResult Get() { var tokenmodel = new TokenModel { Uid = Guid.NewGuid().ToString(), Project = "Horizon.Sample.WebApi", Role = "admin", TokenType = TokenType.Web, UserName = "******", GrandType = "AccessToken" }; return(Ok(JwtHelper.BuildJwtToken(tokenmodel))); //var rng = new Random(); //return Enumerable.Range(1, 5).Select(index => new WeatherForecast //{ // Date = DateTime.Now.AddDays(index), // TemperatureC = rng.Next(-20, 55), // Summary = Summaries[rng.Next(Summaries.Length)] //}) //.ToArray(); }
public ResponseResult GetJWTToken() { ResponseResult result = new ResponseResult(); var userList = new List <dynamic> { new { Id = "12", UserName = "******", Pwd = "123456", Role = "admin" }, new { Id = "45", UserName = "******", Pwd = "456789", Role = "invoice" }, }; var user = userList.SingleOrDefault(q => q.UserName == "aaa" && q.Pwd == "123456"); if (user == null) { result.errno = 1; result.errmsg = "用户名或密码错误"; return(result); } else { var userRoles = userList.Select(q => q.Role).ToList(); //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; //claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); claims.AddRange(userRoles.Select(s => new Claim(ClaimTypes.Role, s))); if (!Permissions.IsUseIds4) { //jwt //var data = await _roleModulePermissionServices.RoleModuleMaps(); var data = new List <PermissionData>() { new PermissionData { Id = 1, LinkUrl = "/api/Oauth2/GetProduct1", Name = "invoice" }, new PermissionData { Id = 2, LinkUrl = "/api/values", Name = "admin" }, new PermissionData { Id = 3, LinkUrl = "/api/Oauth2/GetProduct2", Name = "system" }, new PermissionData { Id = 4, LinkUrl = "/api/values1", Name = "system" } }; var list = (from item in data where item.IsDeleted == false orderby item.Id select new PermissionItem { Url = item.LinkUrl, Name = item.Name.ToStringDefault(), }).ToList(); //DMS.Extensions.Authorizations.AppConfig.Audience = user.UserName + DateTime.Now.ToString(); //_requirement.Audience = DMS.Extensions.Authorizations.AppConfig.Audience; _requirement.Permissions = list; } var token = JwtHelper.BuildJwtToken(claims.ToArray(), _requirement); result.data = token; } return(result); }