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

swaggerui集成oauth implicit的更多相关文章

  1. ABP官方文档翻译 5.4 SwaggerUI集成

    SwaggerUI集成 介绍 ASP.NET Core 安装Nuget包 配置 测试 ASP.NET 5.x 安装Nuget包 配置 测试 介绍 在它的网站上:“...使用Swagger可用的API, ...

  2. 集成基于OAuth协议的单点登陆

    在之前的一篇文章中,我们已经介绍了如何为一个应用添加对CAS协议的支持,进而使得我们的应用可以与所有基于CAS协议的单点登陆服务通讯.但是现在的单点登陆服务实际上并不全是通过实现CAS协议来完成的.例 ...

  3. iOS集成丁香园DXY OAuth 登陆 swift代码示例

    问:iOS集成OAuth登陆分几步? 答:和把大象放冰箱里一样. 第一步:打开webview,跳转到登陆页面: let url = "https://auth.dxy.cn/conn/oau ...

  4. OpenID Connect:OAuth 2.0协议之上的简单身份层

    OpenID Connect是什么?OpenID Connect(目前版本是1.0)是OAuth 2.0协议(可参考本人此篇:OAuth 2.0 / RCF6749 协议解读)之上的简单身份层,用 A ...

  5. OAuth 2.0、OIDC 原理

    OAuth 目录 OAuth 什么是 OAuth? 为什么是 OAuth? SAML OAuth 和 API OAuth 主要组件 OAuth 作用域 OAuth 参与者 OAuth 令牌 OAuth ...

  6. ASP.NET WebApi OWIN 实现 OAuth 2.0

    OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用. OAuth 允许用户提供一个令牌, ...

  7. NET WebApi OWIN 实现 OAuth 2.0

    NET WebApi OWIN 实现 OAuth 2.0 OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和 ...

  8. 在Web API中使用Swagger-UI开源组件(一个深坑的解决)

    介绍: Swagger-Ui是一个非常棒的Web API说明帮助页,具体详情可自行Google和百度. 官网:http://swagger.io/    GitHub地址:https://github ...

  9. 学习Spring Boot:(六) 集成Swagger2

    前言 Swagger是用来描述和文档化RESTful API的一个项目.Swagger Spec是一套规范,定义了该如何去描述一个RESTful API.类似的项目还有RAML.API Bluepri ...

随机推荐

  1. Easyui datagrid 绑定本地Json数据

    var jsonstr = '{"total":1,"rows":[{"id":"M000005","name ...

  2. 整合Spring框架和MyBatis框架

    ------------------------siwuxie095                                 整合 Spring 框架和 MyBatis 框架         ...

  3. ggplot2 梯度作图

    ggplot2是R语言的绘图包 library('ggplot2') df <- data.frame(var=c("a","b","c&quo ...

  4. echart.js在vue中使用

    以前可能写过,懒得去翻了,再写一次 1,安装echarts   导入到页面 import echarts from 'echarts'; 2.在生命周期里面做初始化 data(){ return{ t ...

  5. centos 7 安装pip

    1.首先检查centos 有没有安装python-pip 包, >>yum install python-pipnotice:NO package python-pip available ...

  6. Powershell 脚本判断制定路径下文件是否存在(来源于网络-转载)

    $filelist=gc "file.txt" #获取要检查的文件列表 $csvs= new-object collections.arraylist #创建一个arraylist ...

  7. RNA测序的质量控制

    RNA测序的质量控制 发表评论 3,112 A+ 所属分类:Transcriptomics   收  藏 ENCODE项目向我们揭示,人类基因组中超过70%能得到转录,只不过不会发生在同一个细胞里.为 ...

  8. SQLite 安装

    Windows 平台安装 下载地址:https://www.sqlite.org/download.html 下载预编译的安装包 将下载的安装包=解压到一个文件夹,有三个重要文件: sqlite3.e ...

  9. python 用文本来提供输入信息的模板,不用每次都手动粘贴了

    #下面这一段用一个txt来保存input的信息来模拟input.最后提交代码时候删除这一段即可. a9999=open('1.txt','r') def input(): return a9999.r ...

  10. AX_InventCounting

    static void Job649(Args _args)  {      ItemId                  ItemId          = "000XA00612R1& ...