IdentityServer-如何绕过授权以进行简单调试

我有几个.NET核心API,我将IdentityServer 4用作单独的身份验证服务。

问题在于,在“调试”中,我还希望在不进行身份验证的情况下运行我的API(无需启动IdentityServer)。

因此,我尝试绕过它...我尝试了几种解决方案,但没有任何效果:  -使用AuthorizationHandler:Bypass Authorize Attribute in .Net Core for Release Version  -使用中间件:Simple token based authentication/authorization in asp.net core for Mongodb datastore  -使用过滤器:ASP.NET Core with optional authentication/authorization  -使用AllowAnonymousFilter:Bypass Authorize Attribute in .Net Core for Release Version

但是没有办法,这些解决方案都不起作用,我仍然收到“ 401 Undocumented Error:Unauthorized”!

这是我的代码的某些部分:

public void ConfigureServices(IServiceCollection services)
{
    // JSON - setup serialization
    services.AddControllers().
        AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(new TargetSpot.Core.Json.snakeCaseNamingStrategy()));
            options.JsonSerializerOptions.IgnoreNullValues = true;
        });

    // Force lowercase naming
    services.AddRouting(options => options.LowercaseUrls = true);

    services.AddSingleton<IHttpContextaccessor,HttpContextaccessor>();

    // Setup the connection to the IdentityServer to request a token to access our API
    services.AddAuthentication(IdentityServer4.accessTokenValidation.IdentityServerauthenticationDefaults.AuthenticationScheme)
    .AddIdentityServerauthentication(options =>
    {
        options.Authority = Configuration.GetSection("APISettings")["AuthorityURL"];
        options.RequireHttpsMetadata = false;
        options.ApiName = Configuration.GetSection("APISettings")["APIName"];
    });

    // Add swagger
    services.AddSwaggerGen(options =>
    {
        //options.DescribeAllEnumsAsStrings();
        options.SwaggerDoc("v1",new microsoft.OpenApi.Models.OpenApiInfo
        {
            Title = "HTTP API",Version = "v1",Description = "The Service HTTP API",TermsOfService = new Uri("http://www.myurl.com/tos")
        });

        // XML Documentation
        var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory,xmlFile);
        options.IncludeXmlComments(xmlPath);
    });
}

public void Configure(IApplicationBuilder app,IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseRouting();

    app.UseAuthorization();            
    app.UseAuthentication();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    app.UseSwagger().UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json","Winamp API v1");
    });
}
woshiaitade12 回答:IdentityServer-如何绕过授权以进行简单调试

我有类似的问题。 AllowAnonymousFilter在ASP.NET Core 2.2中有效,但在ASP.NET Core 3.x中无效。 经过一天的调查,我发现从UseEndpoints切换到UseMvc可以解决此问题,并且现在可以禁用身份验证而无需注释掉[Authorize]属性。

似乎UseEndpoints在由AddMvc注册时未使用过滤器,但在使用UseEndpoints时如何正确注册它。

我的解决方案 Startup.ConfigureServices

services.AddMvc(o =>
{
    o.EnableEndpointRouting = false;
    o.Filters.Add(new AllowAnonymousFilter());
});

Startup.Configure

// anonymous filter works with UseMvc but not with UseEndpoints
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",template: "{controller}/{action=Index}/{id?}");
});

//app.UseEndpoints(endpoints =>
//{
//    endpoints.MapControllerRoute(
//        name: "default",//        pattern: "{controller=Home}/{action=Index}/{id?}");
//});
,

我在以下链接中找到了解决方案:https://docs.identityserver.io/_/downloads/en/latest/pdf/。显然,我必须删除在控制器中手动添加的Authorize属性。

app.UseEndpoints(endpoints =>
{
    // Allowing Anonymous access to all controllers but only in Local environment
    if (env.IsEnvironment(Constants.ApplicationConstants.LocalEnvironment))
        endpoints.MapControllers();
    else
        endpoints.MapControllers().RequireAuthorization();
});
本文链接:https://www.f2er.com/3165571.html

大家都在问