惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - 司徒正美
N
News and Events Feed by Topic
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
Help Net Security
Help Net Security
N
News and Events Feed by Topic
O
OpenAI News
L
LangChain Blog
F
Full Disclosure
A
About on SuperTechFans
The GitHub Blog
The GitHub Blog
GbyAI
GbyAI
Cloudbric
Cloudbric
W
WeLiveSecurity
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
Attack and Defense Labs
Attack and Defense Labs
PCI Perspectives
PCI Perspectives
TaoSecurity Blog
TaoSecurity Blog
AI
AI
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Apple Machine Learning Research
Apple Machine Learning Research
C
CERT Recently Published Vulnerability Notes
T
The Exploit Database - CXSecurity.com
T
Threatpost
P
Palo Alto Networks Blog
G
GRAHAM CLULEY
Last Week in AI
Last Week in AI
雷峰网
雷峰网
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 聂微东
P
Proofpoint News Feed
Latest news
Latest news
S
SegmentFault 最新的问题
J
Java Code Geeks
T
Threat Research - Cisco Blogs
H
Help Net Security
P
Privacy International News Feed

博客园 - 陈希章

在本地运行Kusto服务器 请大家支持博客园,购买VIP会员,https://cnblogs.vip PowerAutomate 流程中如何使用环境变量 在PowerShell进行输入预测,提高工作效率 可能是最简单的本地GPT3 对话机器人,支持OpenAI 和 Azure OpenAI Install Docker in WSL 2 (ubuntu) 设置必应搜索默认使用国际版 大数据分析新玩法之Kusto宝典 - 新书发布,免费发行 Kusto 2023 快速入门 开篇 —— 启发式和探索式的大数据分析工具 低代码和人工智能助力疫情期间抗原自测信息自动化收集和处理 批量执行失败的Power Automate 流程 一文讲透为Power Automate for Desktop (PAD) 实现自定义模块 - 附完整代码 是时候使用 YAML 来做配置或数据文件了 在博客文章中使用mermaid 定义流程图,序列图,甘特图 使用本地自签名证书为 React 项目启用 https 支持 博客园最新的在线编辑器,快捷键一览 用浏览器快速开启Docker的体验之旅 云原生开启.NET 跨平台之路 Azure Service Fabric 踩坑日志
为 ASP.NET Core (6.0)服务应用添加ApiKey验证支持
陈希章 · 2022-05-06 · via 博客园 - 陈希章

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

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

dotnet new webapi -minimal -o yourwebapi

然后修改已经生成的 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 https://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);
}