using System.IdentityModel.Tokens.Jwt; using System.Net.Http.Headers; using System.Security.Claims; using System.Text; using HttpClientStudy.Model; using HttpClientStudy.WebApp.Models; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; namespace HttpClientStudy.WebApp.Controllers { /// /// 账号控制器 /// [Route("api/[controller]/[action]")] [ApiController] public class AccountController : ControllerBase { /// /// 构造 /// public AccountController() { } /// /// Ping 测试接口 /// /// /// Ping /// /// [HttpGet] public IActionResult Ping() { return Ok("pong"); } /// /// 获取Token /// /// [AllowAnonymous] [HttpGet] public IActionResult GetToken(string userName, string password) { var account = new Account() { Id = 1, Name = userName, Password = password, Role = "Admin" }; var principal = CreateClaimsPrincipal(account); var token = CreateJwtToken(principal.Claims.ToList()); var data = new { Id = account.Id, Account = account.Name, Role = account.Role, Token = token }; var result = BaseResultUtil.Success(data); return new JsonResult(result); } /// /// 获取Token /// /// [AllowAnonymous] [HttpPost] public IActionResult GetToken(LoginAccount vm) { var account = new Account() { Id = 1, Name = vm.Account, Password = vm.Password, Role = "Admin" }; var principal = CreateClaimsPrincipal(account); var token = CreateJwtToken(principal.Claims.ToList()); var data = new { Id = account.Id, Account = account.Name, Role = account.Role, Token = token }; var result = BaseResultUtil.Success(data); return new JsonResult(result); } /// /// 生成ClaimsPrincipal /// private ClaimsPrincipal CreateClaimsPrincipal(Account account) { List claims = new List { new Claim("ID", account.Id.ToString()), new Claim("Name",account.Name??""), new Claim("Password", account.Password??"123123"), new Claim("Role",account.Role), }; ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal principal = new ClaimsPrincipal(identity); return principal; } /// /// 生成JwtToken /// private string CreateJwtToken(List claims) { //生成Jwt //jwtTokenOptions 是通过配置获取上面配置的参数信息 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("0123456789abcdefghigklmnopqrstdf41sadfweqtdfghsdfgsdfweqr")); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //令牌 var expires = DateTime.Now.AddDays(1); var token = new JwtSecurityToken ( issuer: "WWW.WANGGAOFENG.CN", audience: "WWW.WANGGAOFENG.CN", claims: claims, notBefore: DateTime.Now, expires: expires, signingCredentials: credentials ); string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); return jwtToken; } } }