IdentityServer-如何绕过简单调试的授权

问题描述 投票:0回答:1

我有几个.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");
    });
}
asp.net-core authorization asp.net-core-2.0 identityserver4
1个回答
0
投票

出于测试或调试的目的,我不会删除授权。该代码可能取决于某些声明。

由于要删除IdentityServer作为依赖项,因此可以很容易地替换身份验证。在Startup.Configure中:

if (env.IsDevelopment())
{
    app.Use(async (context, next) =>
    {
        // Set claims for the test user.
        var claims = new[] { new Claim("role", "admin"), new Claim("sub", "some guid") };
        var id = new ClaimsIdentity(claims, "DebugAuthorizationMiddleware", "name", "role");
        // Add the test user as Identity.
        context.User.AddIdentity(id);
        // User is now authenticated.
        await next.Invoke();
    });
}
else
{
    app.UseAuthentication();
}
app.UseAuthorization();

由于不需要IdentityServer来认证用户,因此调试时不必运行IdentityServer。

[请注意顺序,如documented:首先UseAuthentication,然后是UseAuthorization。由于对匿名用户进行授权是没有意义的:只有经过身份验证的用户才能被识别。这就解释了为什么在所有情况下都会收到“ 401未经授权”错误的原因。

© www.soinside.com 2019 - 2024. All rights reserved.