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

推荐订阅源

N
News and Events Feed by Topic
V
V2EX
博客园 - 【当耐特】
Vercel News
Vercel News
雷峰网
雷峰网
爱范儿
爱范儿
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Microsoft Azure Blog
Microsoft Azure Blog
F
Full Disclosure
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
NISL@THU
NISL@THU
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Attack and Defense Labs
Attack and Defense Labs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC
P
Proofpoint News Feed
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
K
Kaspersky official blog
I
InfoQ
Google Online Security Blog
Google Online Security Blog
L
LINUX DO - 最新话题
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
V
Visual Studio Blog
AI
AI
Schneier on Security
Schneier on Security
B
Blog RSS Feed
T
Tor Project blog
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
T
Threat Research - Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
Cyber Attacks, Cyber Crime and Cyber Security
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
V2EX - 技术
V2EX - 技术
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
A
Arctic Wolf
Webroot Blog
Webroot Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main

博客园 - ddrsql

从“黑盒”到“全景”:在.NET中拥抱OpenTelemetry与SigNoz的可观测工具 关于git分支堆叠 记录团队使用git合并代码丢失 记一次对老服务改造 国产麒麟(Kylin-Server-10)系统无外网环境安装docker vue3学习之axios、mockjs、nswag vue3学习之tabler组件Layout布局 vue3学习之BootstrapVueNext Framework升级到Core以及Dapper支持达梦数据库 Avalonia集成Prism与Abp Avalonia中使用EF增删改查DM数据库 Linux中使用原生Wpf之Avalonia WPF通过wine适配统信uos系统 单体仓库下通过helm优雅的将微服务部署到k8s DevOps 前端项目(angular、vue、react)打包静态资源生成一份Docker镜像支持部署不同环境 VS使用IIS调试(非附加进程).net core、.net framework程序 k8s集群通过nginx-ingress做tcp、udp 4层网络转发 DevOps .net core Jenkins持续集成Linux、Docker、K8S redis cluster集群web管理工具 relumin
swaggerui集成oauth implicit
ddrsql · 2019-03-28 · via 博客园 - ddrsql

swaggerui集成oauth implicit

添加引用
Swashbuckle.AspNetCore
IdentityServer4.AccessTokenValidation

预先准备好IdentityServer4配置client与Api Resources
Startup 配置 Authentication Api Resources 和SwaggerUI Client配置

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(option =>
    {
        option.Filters.Add(typeof(ActionFilter));
        option.Filters.Add(typeof(ExceptionFilter));
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    string youAuthority = "http://127.0.0.1";
    services.AddAuthentication("Bearer")
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = youAuthority;
            options.ApiName = "Api";
            options.RequireHttpsMetadata = false;
        });

    services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new Info { Title = "Test Service API", Version = "v1" });
        options.DocInclusionPredicate((docName, description) => true);
        options.CustomSchemaIds(type => type.FullName);

        options.AddSecurityDefinition("oauth2", new OAuth2Scheme
        {
            Type = "oauth2",
            Flow = "implicit",
            AuthorizationUrl = $"{youAuthority}/connect/authorize",
            TokenUrl = $"{youAuthority}/connect/token",
            Scopes = new Dictionary<string, string>()
            {
                { "scope", "定义的scope" }  //Api Resources 中的 scope
            }
        });

        options.OperationFilter<AuthResponsesOperationFilter>();
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseAuthentication();
    app.UseMiddleware<FirstMiddleware>();

    app.UseMvc();
    
    app.UseSwagger().
        UseSwaggerUI(options =>![](https://img2018.cnblogs.com/blog/355798/201903/355798-20190328201652364-1689226610.png)

        {
            options.SwaggerEndpoint("/swagger/v1/swagger.json", "Test Service API");
            //支持 implicit 的 Client
            options.OAuthClientId("swaggerui");
            options.OAuthAppName("Test Service Swagger Ui");
        });
}

对有鉴权属性的方法添加请求时传递token和添加预设返回状态

public class AuthResponsesOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        // 反射Controller 包含 AuthorizeAttribute 时在请求头添加authorization: Bearer 
        var controllerScopes = context.ApiDescription.ControllerAttributes()
            .OfType<AuthorizeAttribute>()
            .Select(attr => attr.Policy);

        var actionScopes = context.MethodInfo
            .GetCustomAttributes(true)
            .OfType<AuthorizeAttribute>()
            .Select(attr => attr.Policy)
            .Distinct();

        var requiredScopes = controllerScopes.Union(actionScopes).Distinct();

        if (requiredScopes.Any())
        {
            operation.Responses.Add("401", new Response { Description = "Unauthorized" });
            operation.Responses.Add("403", new Response { Description = "Forbidden" });

            operation.Security = new List<IDictionary<string, IEnumerable<string>>>();
            operation.Security.Add(new Dictionary<string, IEnumerable<string>>
            {
                { "oauth2", requiredScopes }
            });
        }
    }
}

在 Action 上添加 Authorize

[HttpGet("{id}")]
[Authorize]
public ActionResult<string> Get(int id)
{
    return "value";
}

效果图

//新增的两种返回状态
operation.Responses.Add("401", new Response { Description = "Unauthorized" });
operation.Responses.Add("403", new Response { Description = "Forbidden" });

登录完后请求会带上authorization: Bearer

示例代码
Swashbuckle.AspNetCore