在ASP.NET Core 3.0及以下版本中,使用多个身份验证方案很容易实现。但是,在3.1版本中,如果要使用多个身份验证方案,必须启用AuthenticationOptions.DefaultAuthenticateScheme - 这是用于处理未指定身份验证方案的默认身份验证方案。如果没有显式地配置DefaultAuthenticateScheme,它将为某些身份验证方案带来负担。此时,运行应用程序时,会发出此异常:'InvalidOperationException: Multiple authentication schemes cannot be active at the same time unless they have different DefaultSignInScheme.”
解决方法很简单,代码示例如下:
// Startup.cs文件 public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(options => { options.DefaultScheme = "Bearer"; // 设置默认的身份验证方案 options.DefaultAuthenticateScheme = "Bearer"; // 设置默认的身份验证方案 options.DefaultChallengeScheme = "Bearer"; // 设置默认的身份验证方案 }) .AddJwtBearer("Bearer", options => { options.Authority = "https://localhost:5001"; // 验证服务器地址 options.Audience = "api"; // 要保护的API资源名称 }); }
以上代码允许应用程序使用多个身份验证方案,并且以'Bearer”方式进行身份验证。可以根据需要调整参数。