swaggerui集成oauth implicit

355798-20190328201727695-1291567384.png

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";
}

效果图

355798-20190328201659664-2011551721.png

//新增的两种返回状态
operation.Responses.Add("401", new Response { Description = "Unauthorized" });
operation.Responses.Add("403", new Response { Description = "Forbidden" });

355798-20190328201754925-467821670.png

355798-20190328201741215-1627087378.png

登录完后请求会带上authorization: Bearer

355798-20190328201810345-196443032.png

示例代码
Swashbuckle.AspNetCore

转载于:https://www.cnblogs.com/ddrsql/p/10617370.html

若依集成OAuth2是一个开源的身份验证和授权框架,用于保护Web应用程序的API。OAuth2通过允许用户提供凭据来访问资源,而无需在每个请求中都提供用户名和密码,提高了用户体验和安全性。 首先,若依集成OAuth2可以帮助开发人员轻松地实现身份验证和授权功能。它提供了几种常用的身份验证方式,如密码授权模式、授权码模式和隐式授权模式等,开发人员可以根据应用的需求选择合适的方式。同时,若依集成OAuth2还支持对接第三方身份验证服务,如微信、QQ等。 其次,若依集成OAuth2具有良好的可扩展性和灵活性。它允许开发人员自定义身份验证和授权流程,以满足特定应用的需求。开发人员可以根据自己的业务逻辑定义不同的权限范围和访问令牌有效期等,提高了应用的安全性和控制能力。 最后,若依集成OAuth2还提供了一套完整的管理和监控功能。它包括对用户、角色和权限的管理,以及对令牌的生成、刷新和销毁等操作。开发人员可以通过该框架实现对用户和资源的精细控制,提高了应用的管理和运维效率。 总而言之,若依集成OAuth2是一个功能强大、易于使用和高度可定制的身份验证和授权框架。它可以帮助开发人员快速实现安全的API访问机制,并提供了丰富的管理和监控功能,是构建可靠和安全的Web应用程序的理想选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值