1. [Route("api/[controller]")]
    2. public class AuthenticateController : Controller
    3. {
    4. [HttpPost]
    5. [Route("login")]
    6. public IActionResult Login([FromBody]LoginInput input)
    7. {
    8. //从数据库验证用户名,密码
    9. //验证通过 否则 返回Unauthorized
    10. //创建claim
    11. var authClaims = new[] {
    12. new Claim(JwtRegisteredClaimNames.Sub,input.Username),
    13. new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
    14. };
    15. IdentityModelEventSource.ShowPII = true;
    16. //签名秘钥 可以放到json文件中
    17. var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecureKeySecureKeySecureKeySecureKeySecureKeySecureKey"));
    18. var token = new JwtSecurityToken(
    19. issuer: "https://www.cnblogs.com/chengtian",
    20. audience: "https://www.cnblogs.com/chengtian",
    21. expires: DateTime.Now.AddHours(2),
    22. claims: authClaims,
    23. signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
    24. );
    25. //返回token和过期时间
    26. return Ok(new
    27. {
    28. token = new JwtSecurityTokenHandler().WriteToken(token),
    29. expiration = token.ValidTo
    30. });
    31. }
    32. }