迁移Asp.Net WebAPI至.Net Core 2.0后Swagger测试遇认证方案错误
解决Swagger测试时的"No authenticationScheme was specified"错误
你在迁移WebAPI到.NET Core 2.0时遇到的这个错误,核心原因是系统找不到默认的认证挑战方案,同时Swagger的认证配置也没和后端正确衔接。我给你一步步拆解解决方案:
1. 补全后端认证配置
首先要确保ConfigureServices里的认证服务配置完整,明确指定默认的认证和挑战方案。比如你用JWT认证的话,代码应该这么写:
public void ConfigureServices(IServiceCollection services) { services.AddCors(); // 配置JWT认证,指定默认方案 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "你的Issuer", ValidAudience = "你的Audience", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("你的密钥")) }; }); services.AddSwaggerDocumentation(); services.AddMvc(); }
如果是Cookie等其他认证方式,也要明确设置默认挑战方案:
services.AddAuthentication(options => { options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie();
2. 给Swagger添加认证支持
你的AddSwaggerDocumentation扩展方法里,需要配置Swagger的安全定义和要求,这样Swagger UI才能让你输入令牌并传递到请求头:
public static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "你的API名称", Version = "v1" }); // 定义Bearer认证规则 c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "请在请求头中输入格式为「Bearer {token}」的令牌", Name = "Authorization", In = "header", Type = "apiKey" }); // 给所有API接口添加认证要求 c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } } }); }); return services; }
3. 调整中间件顺序
在Configure方法里,UseAuthentication必须放在UseMvc之前,否则认证中间件无法生效:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); // 先启用认证中间件 app.UseAuthentication(); // 启用Swagger及UI app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "你的API V1"); }); // 最后启用MVC app.UseMvc(); }
4. 无认证需求的特殊处理
如果你的API其实不需要认证,但误加了认证中间件,可以要么移除AddAuthentication相关代码,要么添加一个空的认证处理器绕过检查:
// 在ConfigureServices里配置 services.AddAuthentication(options => { options.DefaultChallengeScheme = "DummyScheme"; }) .AddScheme<AuthenticationSchemeOptions, DummyAuthenticationHandler>("DummyScheme", options => { }); // 自定义空认证处理器 public class DummyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions> { public DummyAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } protected override Task<AuthenticateResult> HandleAuthenticateAsync() { return Task.FromResult(AuthenticateResult.NoResult()); } }
内容的提问来源于stack exchange,提问作者Craig
相关产品推荐
相关产品推荐

