在 ASP.NET Core MVC 中实现 API 请求认证(使用 HMAC)、用户认证与授权以及 Web Token(JWT)认证时,可以按照以下步骤实现:
1. HMAC(Hash-based Message Authentication Code)认证
HMAC 认证用于确保 API 请求的完整性和认证。通过计算请求消息和密钥的 HMAC 值来验证请求的合法性。
后端实现(ASP.NET Core)
首先,创建一个 HMAC 服务类,用于计算和验证 HMAC 签名。
public interface IHmacService
{
string GenerateHmac(string message, string secretKey);
bool VerifyHmac(string message, string receivedHmac, string secretKey);
}
public class HmacService : IHmacService
{
public string GenerateHmac(string message, string secretKey)
{
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey)))
{
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
return Convert.ToBase64String(hash);
}
}
public bool VerifyHmac(string message, string receivedHmac, string secretKey)
{
var computedHmac = GenerateHmac(message, secretKey);
return computedHmac == receivedHmac;
}
}
在 Startup.cs 中注册服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IHmacService, HmacService>();
}
API 控制器中的 HMAC 验证
在 API 控制器中,你可以使用 HmacService 来验证请求中的 HMAC 签名。
[ApiController]
[Route("api/[controller]")]
public class ApiController : ControllerBase
{
private readonly IHmacService _hmacService;
private readonly string _secretKey = "YourSecretKey"; // 可以从配置文件中读取
public ApiController(IHmacService hmacService)
{
_hmacService = hmacService;
}
[HttpPost]
public IActionResult Post([FromBody] string data, [FromHeader(Name = "X-HMAC-Signature")] string receivedHmac)
{
if (_hmacService.VerifyHmac(data, receivedHmac, _secretKey))
{
// HMAC 验证成功
return Ok("Request authenticated.");
}
else
{
// HMAC 验证失败
return Unauthorized("Invalid HMAC.");
}
}
}
前端发送带 HMAC 的请求
在前端,你需要计算消息的 HMAC 并将其添加到请求头中。
function calculateHmac(message, secretKey) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const key = encoder.encode(secretKey);
return crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"])
.then(key => crypto.subtle.sign("HMAC", key, data))
.then(signature => {
return btoa(String.fromCharCode(...new Uint8Array(signature)));
});
}
const message = JSON.stringify({ /* data to send */ });
const secretKey = "YourSecretKey"; // The secret key should match the server's secret key
calculateHmac(message, secretKey).then(hmac => {
fetch("https://yourapi.com/api/endpoint", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-HMAC-Signature": hmac
},
body: message
});
});
2. 用户认证与授权(JWT)
后端实现(ASP.NET Core)
- 安装必要的 NuGet 包:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
- 在
Startup.cs配置 JWT 认证:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourIssuer",
ValidAudience = "yourAudience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey"))
};
});
services.AddControllers();
}
- 创建 JWT 生成器服务:
public class JwtService
{
private readonly string _secretKey = "YourSecretKey";
public string GenerateToken(string username)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "User")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "yourIssuer",
audience: "yourAudience",
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
- 在登录时生成 JWT:
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
if (IsValidUser(model)) // Check username/password from your database
{
var token = _jwtService.GenerateToken(model.Username);
return Ok(new { Token = token });
}
return Unauthorized();
}
- 在 API 控制器中使用
[Authorize]特性来保护路由:
[Authorize]
[HttpGet]
public IActionResult GetProtectedData()
{
return Ok("This is a protected resource.");
}
前端发送带 JWT 的请求
在前端,当用户登录成功后,你会收到一个 JWT。之后需要将它作为 Authorization header 添加到所有 API 请求中。
const token = "YourJWTToken"; // This should be saved securely, e.g., in localStorage or sessionStorage
fetch("https://yourapi.com/api/protected", {
method: "GET",
headers: {
"Authorization": `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
总结
- HMAC认证:通过计算消息的 HMAC 签名来验证请求的完整性。
- 用户认证与授权:使用 JWT 进行认证,并通过授权验证用户身份。
- Web Token认证(JWT):通过生成和验证 JWT 来处理用户认证和授权。
、用户认证与授权以及 Web Token(JWT)认证&spm=1001.2101.3001.5002&articleId=143696776&d=1&t=3&u=cc621f0ba97944d3ad066baafe3209b4)
486

被折叠的 条评论
为什么被折叠?



