JWT Token認證
今天來測試一下JWT Token認證方式:
先建立API專案,首先model部分:
用於接收登入請求的資料,LoginModel:
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
用於存儲使用者資訊,UserModel:
public class UserModel
{
public string Username { get; set; }
public string Role { get; set; }
}
再來是controller部分:
處理身份驗證,
Login方法:處理登入請求,驗證成功後產生JWT
GenerateJwtToken方法:產生JWT令牌
- 設定令牌內容(Claims)
- 設定過期時間
- 使用密鑰進行簽名
AuthController:
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
if (model.Username == "admin" && model.Password == "password")
{
var token = GenerateJwtToken(model.Username);
return Ok(new { token });
}
return Unauthorized();
}
private string GenerateJwtToken(string username)
{
var securityKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("YourSecretKey12345678901234567890"));
var credentials = new SigningCredentials(
securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "Admin"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: "YourIssuer",
audience: "YourAudience",
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
- 使用[Authorize]特性要求認證
- 只有提供有效的JWT才能訪問這些方法
- 客戶端發送登入請求(用戶名/密碼)
- 服務器驗證後產生JWT並返回
- 客戶端在後續請求中使用Bearer Token方式傳送JWT
- 服務器驗證JWT的有效性
- 驗證通過後允許訪問受保護的資源
留言
張貼留言