Asp.Net Core: Swagger 与 Identity Server 4
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的更多相关文章
- Asp.net core 学习笔记 ( identity server 4 JWT Part )
更新 : id4 使用这个 DbContext 哦 dotnet ef migrations add identity-server-init --context PersistedGrantDbCo ...
- asp.net core系列 46 Identity介绍
一. Identity 介绍 ASP.NET Core Identity是一个会员系统,可为ASP.NET Core应用程序添加登录功能.可以使用SQL Server数据库配置身份以存储用户名,密码和 ...
- 发布到ASP.NET CORE项目到 Windows server 2012
原文: https://github.com/zeusro/MarkdownBlog/blob/master/2018/2018-01-17-01.md 发布到ASP.NET CORE项目到 Wind ...
- .net core使用Ocelot+Identity Server统一网关验证
源码下载地址:下载 项目结构如下图: 在Identity Server授权中,实现IResourceOwnerPasswordValidator接口: public class IdentityVal ...
- asp.net core系列 52 Identity 其它关注点
一.登录分析 在使用identity身份验证登录时,在login中调用的方法是: var result = await _signInManager.PasswordSignInAsync(Input ...
- ASP.NET Core 身份认证 (Identity、Authentication)
Authentication和Authorization 每每说到身份验证.认证的时候,总不免说提及一下这2个词.他们的看起来非常的相似,但实际上他们是不一样的. Authentication想要说明 ...
- 坎坷路:ASP.NET Core 1.0 Identity 身份验证(中集)
上一篇:<坎坷路:ASP.NET 5 Identity 身份验证(上集)> ASP.NET Core 1.0 什么鬼?它是 ASP.NET vNext,也是 ASP.NET 5,以后也可能 ...
- 用VSCode开发一个基于asp.net core 2.0/sql server linux(docker)/ng5/bs4的项目(2)
第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 为Domain Model添加约束 前一部分, 我们已经把数据库创建出来了. 那么我们先看看这个数据库 ...
- 用VSCode开发一个基于asp.net core 2.0/sql server linux(docker)/ng5/bs4的项目(1)
最近使用vscode比较多. 学习了一下如何在mac上使用vscode开发asp.netcore项目. 这里是我写的关于vscode的一篇文章: https://www.cnblogs.com/cgz ...
随机推荐
- 阿里云服务器ECS Ubuntu16.04 + Seafile 搭建私人网盘 (Seafile Pro)
原文链接:? 传送门 本文主要讲述 使用 Ubuntu 16.04 云服务器 通过脚本实现对 Seafile Pro 的安装,完成私人网盘的搭建 首先给出 Seafile 专业版的下载地址(Linux ...
- elasticsearch在linux上的安装,Centos7.X elasticsearch 7.6.2安装
本文环境:Elasticsearch7.6.2目前最先版本 centos7.X JDK1.8 elasticsearch介绍 官网:https://www.elastic.co/cn/pr ...
- 【C】C语言大作业——学生学籍管理系统
文章目录 学生管理系统 界面 主界面 登陆界面 注册界面 管理界面 学生界面 退出界面 链接 注意 学生管理系统 学C语言时写的一个大作业,弄了一个带图形界面的,使用的是VS配合EasyX图形库进行实 ...
- 【Java】main方法的理解
main方法的理解 main()方法作为程序的入口 main()方法也是一个普通的静态方法 main()方法可以作为我们与控制台交互的方式.(之前:使用Scanner) main方法中的参数args就 ...
- day 11 算法的时间空间复杂度
(1).有以下程序: 求输入的n值(除1和n)之外的所有因子之和. 分析:这里函数内的循环体i初值不能为零.%是表示"取余",0除以任何数都不会存在余数的,所有是余数为0. (2) ...
- 安卓无法访问Azure服务器和微软API
Azure服务器保护机制限制移动端访问 必须使用移动app服务来转接api,才可以访问.
- dp问题解题思路
[基本问题单元的定义]这取决于你所查看问题的角度,找到一个划分,推进问题的角度十分重要.作者找到的方式是dp[ i ][ j ],用来表示 substring( i , j),然后站在这个角度,假设s ...
- golang中time包日期时间常用用法
package main import ( "fmt" "reflect" "time" ) var week time.Duration ...
- Ubuntu 14.04更换内核
1:查看当前安装的内核 dpkg -l|grep linux-image 2:查看可以更新的内核版本: sudo apt-cache search linux-image 3:安装新内核 sudo a ...
- JavaScript之详述闭包导致的内存泄露
一.内存泄露 1. 定义:一块被分配的内存既不能使用,也不能回收.从而影响性能,甚至导致程序崩溃. 2. 起因:JavaScript的垃圾自动回收机制会按一定的策略找出那些不再继续使用的变量,释放其占 ...