Swagger不用多说,可以自动生成Web Api的接口文档和客户端调用代码,方便开发人员进行测试。通常我们只需要几行代码就可以实现这个功能:

...
builder.Services.AddSwaggerGen();
...
app.UseSwagger();
app.UseSwaggerUI();
...

可如果使用Identity Server 4等认证服务对Web Api进行保护后,使用上面代码生成的Web Api文档就无法工作了,在进行测试时会提示401错误。



本文介绍如何使Swagger在Identity Server 4认证服务保护下工作。

配置Identity Server 4

首先,使用开源的Identity Server 4 Admin搭建认证服务,这部分工作在系列文章《Identity Server 4 从入门到落地》中有详细的介绍,这里不再重复。

准备测试用Web Api

接下来,使用Visual Studio 2022创建一个Asp.Net Core Web Api项目,我们使用项目中缺省的Web Api进行测试。在项目中增加Identity Server 4对Web Api的保护,这部分的详细介绍参见《Identity Server 4 从入门到落地(十)—— 编写可配置的客户端和Web Api》,这里只列出必要的步骤。

1、使用Nuget包管理器安装ZL.IdentityServer4ClientConfig和ZL.SameSiteCookiesService

2、修改Program.cs,增加如下代码:

...
builder.Services.AddIdentityServer4Api(builder.Configuration);//增加代码
builder.Services.AddSameSiteSupport();;//增加代码
...
app.UseCors("cors");//增加代码
app.UseAuthentication(); //增加代码
app.UseAuthorization();

3、在appSettings.json中增加相应的配置:

"IdentityServer4Api": {

"Authority": "http://host.docker.internal:4010",

"CorsOrgins": [

"http://host.docker.internal:5291"

],

"Policies": [

{

"Name": "ApiScope",

"RequireAuthenticatedUser": "true",

"Claims": [

{

"ClaimType": "scope",

"AllowValues": [ "testapi" ]

}

]

}

],

这里定义的认证服务器地址需要根据实际情况进行修改,CorsOrgins中设置的是允许访问的客户端的Uri。这里定义的允许访问的scope是testapi,需要根据实际进行修改。

4、为Web Api的Action增加[Authorize]标签:

        [Authorize]
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}

在认证中心增加Web Api Scope和Swagger Client

现在我们在认证中心增加Web Api Scope和Swagger Client。

首先,增加Web Api Scope,在配置文件中定义的允许访问的scope是testapi,所以在这里增加的Scope名称必须为testapi。



然后,还需要为Swagger 增加一个客户端,名称为demo_api_swagger:



客户端定义中有几个地方需要注意,首先是允许作用域必须与前面定义的相同,这里是testapi:



需要客户端密钥设置为false:



还有重定向的Url,Swagger针对oauth 2.0的重定向地址是swagger/oauth2-redirect.html



最后,不要忘记在令牌分页中设置CORS:

修改Swagger相关代码

在认证中心设置完成后,还需要修改Web Api项目中Swagger相关的代码,使Swagger支持认证。

首先需要增加一个类,实现IOperationFilter接口:

using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen; namespace WebApiIDS4Demo
{
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var hasAuthorize =
context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any()
|| context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any(); if (hasAuthorize)
{
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" }); operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
[
new OpenApiSecurityScheme {Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "oauth2"}
}
] = new[] {"api1"}
}
}; }
}
}
}

然后,在Program.cs中修改Swagger相关的代码:

...
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "Protected API", Version = "v1" });
var strurl = builder.Configuration["IdentityServer4Api:Authority"];
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri( strurl +"/connect/authorize"),
TokenUrl = new Uri(strurl + "/connect/token"),
Scopes = new Dictionary<string, string>
{
{"testapi", "Demo API - full access"}
}
}
}
});
options.OperationFilter<AuthorizeCheckOperationFilter>();
});
...
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
options.OAuthClientId("demo_api_swagger");
options.OAuthAppName("Demo API - Swagger");
options.OAuthUsePkce();
});
}

改造完成,可以进行测试了,运行Web Api项目,缺省进入Swagger文档页面,我们会发现多了一个Authorize按钮,并且Web Api方法旁边会有一个加锁的图标:



这时,如果访问Web Api,会出现401错误,我们需要先进行认证再访问,点击加锁的图标,弹出认证界面:



点击认证按钮,如果顺利的话,会出现认证完成的界面:



点击Close关闭窗口,会发现加锁图标发生了变化:



这时,再次访问Web Api就可以正常返回数据了:

Asp.Net Core: Swagger 与 Identity Server 4的更多相关文章

  1. Asp.net core 学习笔记 ( identity server 4 JWT Part )

    更新 : id4 使用这个 DbContext 哦 dotnet ef migrations add identity-server-init --context PersistedGrantDbCo ...

  2. asp.net core系列 46 Identity介绍

    一. Identity 介绍 ASP.NET Core Identity是一个会员系统,可为ASP.NET Core应用程序添加登录功能.可以使用SQL Server数据库配置身份以存储用户名,密码和 ...

  3. 发布到ASP.NET CORE项目到 Windows server 2012

    原文: https://github.com/zeusro/MarkdownBlog/blob/master/2018/2018-01-17-01.md 发布到ASP.NET CORE项目到 Wind ...

  4. .net core使用Ocelot+Identity Server统一网关验证

    源码下载地址:下载 项目结构如下图: 在Identity Server授权中,实现IResourceOwnerPasswordValidator接口: public class IdentityVal ...

  5. asp.net core系列 52 Identity 其它关注点

    一.登录分析 在使用identity身份验证登录时,在login中调用的方法是: var result = await _signInManager.PasswordSignInAsync(Input ...

  6. ASP.NET Core 身份认证 (Identity、Authentication)

    Authentication和Authorization 每每说到身份验证.认证的时候,总不免说提及一下这2个词.他们的看起来非常的相似,但实际上他们是不一样的. Authentication想要说明 ...

  7. 坎坷路:ASP.NET Core 1.0 Identity 身份验证(中集)

    上一篇:<坎坷路:ASP.NET 5 Identity 身份验证(上集)> ASP.NET Core 1.0 什么鬼?它是 ASP.NET vNext,也是 ASP.NET 5,以后也可能 ...

  8. 用VSCode开发一个基于asp.net core 2.0/sql server linux(docker)/ng5/bs4的项目(2)

    第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 为Domain Model添加约束 前一部分, 我们已经把数据库创建出来了. 那么我们先看看这个数据库 ...

  9. 用VSCode开发一个基于asp.net core 2.0/sql server linux(docker)/ng5/bs4的项目(1)

    最近使用vscode比较多. 学习了一下如何在mac上使用vscode开发asp.netcore项目. 这里是我写的关于vscode的一篇文章: https://www.cnblogs.com/cgz ...

随机推荐

  1. uni-app、小程序之swiper-item内容过多显示不全的解决方案

    原文 最近在项目遇到swiper高度不能自适应,导致swiper-item 里面的内容过多时只能显示一部分,最终解决方案: <swiper> <swiper-item> < ...

  2. 面试官问,Redis 是单线程还是多线程?我懵了

    我们平时看到介绍 Redis 的文章,都会说 Redis 是单线程的.但是我们学习的时候,比如 Redis 的 bgsave 命令,它的作用是在后台异步保存当前数据库的数据到磁盘,那既然是异步了,肯定 ...

  3. ELF文件格式学习总结

    ELF文件格式学习总结 ELF文件格式学习总结1. 概述2. 目标文件结构3. ELF文件头3.1 魔数3.2 文件类型3.3 机器类型4. ELF文件内容4.1段表4.2字符串表(.**strtab ...

  4. fastjson字符串转JSON的$ref问题

    先说结论: fastjson在把对象转换成字符串的时候,如果遇到相同的对象的时候,默认开启引用检测将相同的对象写成引用的形式. 官网文档:https://github.com/alibaba/fast ...

  5. Java包装类和处理对象

    Java中基本类型变量和字符串之间的转换 public class Primitive2String { public static void main(String args[]) { String ...

  6. MATLAB绘图入门

    %%%1.运算符:(1).% mean() -->平均值 1.对于一个数组,mean(数组名)则返回均值2.对于一个矩阵,mean(数组名,1或2) 1代表返回矩阵每列的平均值 2代表返回矩阵每 ...

  7. 【刷题-LeetCode】238. Product of Array Except Self

    Product of Array Except Self Given an array nums of n integers where n > 1, return an array outpu ...

  8. Cesium入门3 - Cesium目录框架结构

    Cesium入门3 - Cesium目录框架结构 Cesium中文网:http://cesiumcn.org/ | 国内快速访问:http://cesium.coinidea.com/ app目录 下 ...

  9. JDK原子操作类

    在Atomic包里一共提供了13个类,属于4种类型的原子更新方式,分别是原子更新基本类型.原子更新数组.原子更新引用和原子更新属性(字段).Atomic包里的类基本都是使用Unsafe实现的包装类. ...

  10. 前端基础之javaScript(基本类型-布尔值数组-if-while)

    目录 一:javaScript基本数据类型 1.字符串类型常用方法 2.返回长度 3.移出空白 4.移除左边的空白 5.移出右边的空格 6.返回第n个字符 7.子序列位置 8.根据索引获取子序列 9. ...