首页 技术 正文
技术 2022年11月11日
0 收藏 453 点赞 3,556 浏览 2811 个字

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,103
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,579
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,427
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,199
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,834
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,917