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 ...
随机推荐
- python驱动SAP完成数据导出(二)
在上一篇 python驱动SAP完成数据导出(一)中,我们提到了数据导出前,SAP布局的重要性,如何识别当前布局模式,以及如何切换到想要的布局.本篇小爬将着重讲讲数据导出的注意事项. 我们可以通过如下 ...
- vant引入及配置
1. vant 官网 https://youzan.github.io/vant/#/zh-CN/quickstart 2. 通 npm 安装 npm i vant -S 3.安装 babel-plu ...
- 如何使用 GitHub Pages 维护自己的博客
目录 前置知识 实际操作 声明 本文地址:如何使用 GitHub Pages 维护自己的博客 前置知识 首先,你应该知道如何用 Hexo 在本地搭建一个博客系统,具体见 Hexo. 其次,我们如果想使 ...
- day 18 C语言顺序结构基础定义1
(1).有以下程序: 程序运行后的输出结果是[B] (A).3,5,5,3 (B).3,5,3,5 (C).5,3,3,5 (D).5,3,5,3 这个题其实也可以弄成改错题,传到函数里面要对其值操作 ...
- java基础01-03-注释、标识符、数据类型讲解
java基础01-注释 java中的注释有三种: 单行注释 多行注释 文件注释 public class helloworld { public static void main(String[] a ...
- 【刷题-LeetCode】188 Best Time to Buy and Sell Stock IV
Best Time to Buy and Sell Stock IV Say you have an array for which the i-th element is the price of ...
- ajax的核心
<script> // ajax 简称(a 代表异步 j 代表javascript a 代表 and x 代表xml--是一种带有标签的数据格式,被json取代了) //ajax 是异步对 ...
- golang中的配置管理库viper
viper简介 Viper是适用于Go应用程序的完整配置解决方案.它旨在在应用程序中工作,并且可以处理所有类型的配置需求和格式.它支持: 设置默认值 从JSON,TOML,YAML,HCL,envfi ...
- java-异常-原理异常对象的抛出throw
1 class Demo { 2 public static int method(int[] arr,int index) { 3 4 // System.out.println(arr[index ...
- python函数位置实参传参
#!/usr/bin/python #coding=utf-8 #好好学习,天天向上 def describe_pet(type,name): print(f"i have a {type} ...