public IActionResult Token([FromBody] User user) { // 验证身份 if (!(user.username == "admin" && user.password == "123456")) { return(BadRequest(new { error = "验证账号密码失败" })); } user.role = "manager"; // 配置参数 var claims = new[] { new Claim(ClaimTypes.Name, user.username), new Claim(ClaimTypes.Role, user.role) }; // 生成对称秘钥 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey)); // 生成签名证书 var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); // 生成token var token = new JwtSecurityToken( _jwtSettings.Issuer, _jwtSettings.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(30), signingCredentials); return(Ok(new { token = JwtSecurityTokenService.Encode(token) })); }
protected async Task WhenATokenIsIssued() { var securityTokenService = new JwtSecurityTokenService(Options); IssuedToken = await securityTokenService.Issue(Principal, Expiration); ValidateIssuedToken(); }
public IEnumerable <string> Get() { var jwtToken = JwtSecurityTokenService.ReadHeaders(Request.Headers); var name = jwtToken.Claims.FirstOrDefault(t => t.Type == ClaimTypes.Name)?.Value; var role = jwtToken.Claims.FirstOrDefault(t => t.Type == ClaimTypes.Role)?.Value; return(new[] { name, role }); }