如何为ASP.NET Core 6.0应用实现ApiKey验证机制?

2026-05-25 16:552阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计735个文字,预计阅读时间需要3分钟。

如何为ASP.NET Core 6.0应用实现ApiKey验证机制?

这个代码段演示了如何在ASP.NET Core项目中添加API密钥验证支持。首先,使用以下命令创建一个新的Web API项目:

bashdotnet new webapi -minimal -o yourwebapi

然后,修改生成的项目中的`Startup.cs`文件,找到并替换`builder.Services.AddSwaggerGen`这一行:

csharp// 修改前builder.Services.AddSwaggerGen();

// 修改后builder.Services.AddSwaggerGen(options=>{ options.AddSecurityDefinition(Bearer, new OpenApiSecurityScheme { Description=JWT Authorization header using the Bearer scheme. Enter 'Bearer' followed by space and then your token in the text input below., Name=Authorization, In=ParameterLocation.Header, Type=SecuritySchemeType.ApiKey, Scheme=Bearer });

options.OperationFilter();});

这里,我们添加了一个自定义的API密钥验证方案,并配置了Swagger以使用这个方案。同时,我们引入了一个名为`SwaggerAuthorizationFilter`的自定义操作过滤器,它将在Swagger文档中添加授权信息。

这个代码段演示了如何为一个ASP.NET Core项目中添加Apikey验证支持。

首先,通过下面的代码创建项目

dotnet new webapi -minimal -o yourwebapi

如何为ASP.NET Core 6.0应用实现ApiKey验证机制?

然后修改已经生成的 builder.Services.AddSwaggerGen 这个方法,以便在Swagger 的页面可以输入ApiKey进行调试。

builder.Services.AddSwaggerGen((options) => { options.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme { Type = SecuritySchemeType.ApiKey, In = ParameterLocation.Header, Name = "ApiKey" }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" } }, new string[] {} } }); });

var app = builder.Build(); 这一行下方添加一个中间件,用来验证ApiKey。请注意,这里特意跳过了swagger目录。另外,这里的密钥校验是硬编码的,你可以修改成自己需要的方式。

app.Use(async (context, next) => { var found = context.Request.Headers.TryGetValue("ApiKey", out var key); if (context.Request.Path.StartsWithSegments("/swagger") || (found && key == "abc")) { await next(context); } else { context.Response.StatusCode = 401; await context.Response.WriteAsync("没有合法授权"); return; } });

通过 dotnet watch run 将应用运行起来,并且访问 /swagger/index.html 这个网页,可以看到当前API项目的所有方法,并且可以输入ApiKey

然后你就可以在swagger 中进行API 调用测试了,当然你也可以通过 postman 等工具来测试。这里就不展开了。

完整代码如下,请参考

using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen((options) => { options.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme { Type = SecuritySchemeType.ApiKey, In = ParameterLocation.Header, Name = "ApiKey" }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" } }, new string[] {} } }); }); var app = builder.Build(); app.Use(async (context, next) => { var found = context.Request.Headers.TryGetValue("ApiKey", out var key); if (context.Request.Path.StartsWithSegments("/swagger") || (found && key == "abc")) { await next(context); } else { context.Response.StatusCode = 401; await context.Response.WriteAsync("没有合法授权"); return; } }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; app.MapGet("/weatherforecast", () => { var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast ( DateTime.Now.AddDays(index), Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); return forecast; }) .WithName("GetWeatherForecast"); app.Run(); record WeatherForecast(DateTime Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); }

本文共计735个文字,预计阅读时间需要3分钟。

如何为ASP.NET Core 6.0应用实现ApiKey验证机制?

这个代码段演示了如何在ASP.NET Core项目中添加API密钥验证支持。首先,使用以下命令创建一个新的Web API项目:

bashdotnet new webapi -minimal -o yourwebapi

然后,修改生成的项目中的`Startup.cs`文件,找到并替换`builder.Services.AddSwaggerGen`这一行:

csharp// 修改前builder.Services.AddSwaggerGen();

// 修改后builder.Services.AddSwaggerGen(options=>{ options.AddSecurityDefinition(Bearer, new OpenApiSecurityScheme { Description=JWT Authorization header using the Bearer scheme. Enter 'Bearer' followed by space and then your token in the text input below., Name=Authorization, In=ParameterLocation.Header, Type=SecuritySchemeType.ApiKey, Scheme=Bearer });

options.OperationFilter();});

这里,我们添加了一个自定义的API密钥验证方案,并配置了Swagger以使用这个方案。同时,我们引入了一个名为`SwaggerAuthorizationFilter`的自定义操作过滤器,它将在Swagger文档中添加授权信息。

这个代码段演示了如何为一个ASP.NET Core项目中添加Apikey验证支持。

首先,通过下面的代码创建项目

dotnet new webapi -minimal -o yourwebapi

如何为ASP.NET Core 6.0应用实现ApiKey验证机制?

然后修改已经生成的 builder.Services.AddSwaggerGen 这个方法,以便在Swagger 的页面可以输入ApiKey进行调试。

builder.Services.AddSwaggerGen((options) => { options.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme { Type = SecuritySchemeType.ApiKey, In = ParameterLocation.Header, Name = "ApiKey" }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" } }, new string[] {} } }); });

var app = builder.Build(); 这一行下方添加一个中间件,用来验证ApiKey。请注意,这里特意跳过了swagger目录。另外,这里的密钥校验是硬编码的,你可以修改成自己需要的方式。

app.Use(async (context, next) => { var found = context.Request.Headers.TryGetValue("ApiKey", out var key); if (context.Request.Path.StartsWithSegments("/swagger") || (found && key == "abc")) { await next(context); } else { context.Response.StatusCode = 401; await context.Response.WriteAsync("没有合法授权"); return; } });

通过 dotnet watch run 将应用运行起来,并且访问 /swagger/index.html 这个网页,可以看到当前API项目的所有方法,并且可以输入ApiKey

然后你就可以在swagger 中进行API 调用测试了,当然你也可以通过 postman 等工具来测试。这里就不展开了。

完整代码如下,请参考

using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen((options) => { options.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme { Type = SecuritySchemeType.ApiKey, In = ParameterLocation.Header, Name = "ApiKey" }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" } }, new string[] {} } }); }); var app = builder.Build(); app.Use(async (context, next) => { var found = context.Request.Headers.TryGetValue("ApiKey", out var key); if (context.Request.Path.StartsWithSegments("/swagger") || (found && key == "abc")) { await next(context); } else { context.Response.StatusCode = 401; await context.Response.WriteAsync("没有合法授权"); return; } }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; app.MapGet("/weatherforecast", () => { var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast ( DateTime.Now.AddDays(index), Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); return forecast; }) .WithName("GetWeatherForecast"); app.Run(); record WeatherForecast(DateTime Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); }