在 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

最低0.47元/天 解锁文章
547

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



