[AllowAnonymous]//对获取token得方法加允许匿名标注//不受授权控制,任何人都可访问 public async Task <string> Token([FromBody] LoginViewModel loginViewModel) { if (ModelState.IsValid) { SysUser user = await _userserver.CheckUser(loginViewModel.User, loginViewModel.Password); //判断用户名密码是否正确,如果不正确返回Token !(loginViewModel.User=="avery"&& loginViewModel.Password=="123") if (user == null) { return("账号或者密码错误"); } else { #region MyRegion var Ip = HttpContext.GetClientIP(); //var claim = new Claim[] //{ // new Claim(ClaimTypes.Name,user.Account), // new Claim(ClaimTypes.Role,user.Account), //}; ////设置对称秘钥 //var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey)); ////生成签名证书(秘钥,加密算法) //var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); ////生成token [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包,并引用System.IdentityModel.Tokens.Jwt命名空间 //var token = new JwtSecurityToken(_jwtSettings.Issuer, _jwtSettings.Audience, claim, DateTime.Now, DateTime.Now.AddDays(1), creds); #endregion TokenModelJWT tokenModel = new TokenModelJWT() { Uid = user.Id, Role = "Admin", }; var token = JwtHelper.IssueJWT(tokenModel); try { //var ss= DateTime.Now; //_redisCacheManager.Set("Id", new { Id = 12 },ss.TimeOfDay); //_log.Add("创建TOken", "用户登陆", Ip,EnumTypes.其他分类); return(token); } catch (Exception ex) { throw; } } } return("账号或者密码错误"); }