
如何快速實現(xiàn)REST API集成以優(yōu)化業(yè)務(wù)流程
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
此控制器提供用于獲取天氣預(yù)報的基本終端節(jié)點。現(xiàn)在,讓我們添加身份驗證以使用 API 密鑰保護(hù)此終端節(jié)點。
要添加 API 密鑰身份驗證,我們需要創(chuàng)建自定義中間件,它將:
創(chuàng)建一個名為 的新文件夾,并添加一個名為 的類 :MiddlewareApiKeyMiddleware
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string ApiKeyHeaderName = "X-API-KEY";
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key was not provided.");
return;
}
var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();
var apiKey = appSettings.GetValue<string>("ApiKey");
if (!apiKey.Equals(extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized client.");
return;
}
await _next(context);
}
}
此中間件檢查請求標(biāo)頭 () 中的 API 密鑰,并將其與配置中存儲的值進(jìn)行比較。如果密鑰缺失或無效,則返回狀態(tài)。X-API-KEY401 Unauthorized
在 中,將中間件添加到請求管道的行之前:Program.csapp.MapControllers()
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseMiddleware<ApiKeyMiddleware>();
app.MapControllers();
app.Run();
您需要一種方法來安全地存儲 API 密鑰。為簡單起見,我們將在此示例中使用 App settings。在文件中,為 API 密鑰添加一個條目:appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ApiKey": "my-super-secret-api-key"
}
在實際應(yīng)用程序中,您可以將 API 密鑰存儲在更安全的位置,例如 Azure Key Vault、AWS Secrets Manager 或環(huán)境變量。
嘗試在沒有 API 密鑰的情況下調(diào)用終端節(jié)點:WeatherForecast
curl -X GET "https://localhost:5001/WeatherForecast"
您應(yīng)該會收到一條消息“未提供 API 密鑰”的響應(yīng)。401 Unauthorized
現(xiàn)在,再次嘗試該請求,但這次包括 API 密鑰:
curl -X GET "https://localhost:5001/WeatherForecast" -H "X-API-KEY: my-super-secret-api-key"
您應(yīng)該會得到一個包含天氣預(yù)報數(shù)據(jù)的成功響應(yīng)。
假設(shè)您的應(yīng)用程序需要對各種 API 密鑰具有不同級別的訪問權(quán)限。您可以擴(kuò)展中間件以支持基于 API 密鑰的基于角色的授權(quán)。
為 API 密鑰添加角色檢查:
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string ApiKeyHeaderName = "X-API-KEY";
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key was not provided.");
return;
}
var configuration = context.RequestServices.GetRequiredService<IConfiguration>();
var apiKeys = configuration.GetSection("ApiKeys").Get<Dictionary<string, string>>();
if (!apiKeys.TryGetValue(extractedApiKey, out var role))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized client.");
return;
}
// Store the role for further processing
context.Items["UserRole"] = role;
await _next(context);
}
}
在appsettings.json
{
"ApiKeys": {
"my-admin-api-key": "Admin",
"my-user-api-key": "User"
}
}
在 Controller 中使用 User 角色
[ApiController]
[Route("[controller]")]
public class SecureController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
var userRole = HttpContext.Items["UserRole"] as string;
if (userRole == "Admin")
{
return Ok("Welcome, Admin!");
}
return Forbid("You do not have permission to access this resource.");
}
}
只需幾個步驟,我們就為 ASP.NET Core 應(yīng)用程序添加了強(qiáng)大的 API 密鑰身份驗證。我們還對其進(jìn)行了擴(kuò)展以支持基于角色的授權(quán),從而增加了對訪問的更多控制。API 密鑰身份驗證是保護(hù) API 以簡化用例的好方法,使用 .NET 8,實現(xiàn)此模式比以往任何時候都更容易。
文章轉(zhuǎn)自微信公眾號@架構(gòu)師老盧