我有几个.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");
});
}