我正在致力于将 Identity 集成到我的 .NET Core 8.0 应用程序中并实现 JWT Bearer 身份验证。但是,我遇到了错误
System.InvalidOperationException:方案已存在:Bearer
运行应用程序时。
我的
Program.cs
代码是:
using Solv.Identity.Api.Common;
using Solv.Identity.Api.Configurations;
using Solv.Identity.Api.Endpoints;
using Solv.Identity.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Solv.Identity.Application.Auth;
using Solv.Identity.Application.Features.Configuration;
using System.Text;
using Solv.Identity.Application.Features.Users;
using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
var builder = WebApplication.CreateBuilder(args);
// Register AuthService
builder.Services.AddTransient<AuthService>();
// Add authentication and authorization
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.PrivateKey)),
ValidateIssuer = false,
ValidateAudience = false
};
});
builder.Services.AddAuthorization(x =>
{
x.AddPolicy("tech", p => p.RequireRole("developer"));
});
// Controllers
builder.AddValidationSetup();
// Swagger
builder.Services.AddSwaggerSetup();
// Persistence
builder.Services.AddPersistenceSetup(builder.Configuration);
// Application layer setup
builder.Services.AddApplicationSetup();
// Request response compression
builder.Services.AddCompressionSetup();
//// HttpContextAcessor
builder.Services.AddHttpContextAccessor();
//// Mediator
builder.Services.AddMediatRSetup();
//// Exception handler
builder.Services.AddExceptionHandler<ExceptionHandler>();
builder.Logging.ClearProviders();
// Add serilog
if (builder.Environment.EnvironmentName != "Testing")
{
//builder.Host.UseLoggingSetup(builder.Configuration);
// Add opentelemetry
builder.AddOpenTemeletrySetup();
}
builder.Services.AddHttpClient();
#region Keycloak
builder.Services.AddKeycloakServices();
builder.AddKeycloakSettings();
builder.AddKeycloakAuthorization();
#endregion
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseResponseCompression();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseSwaggerSetup();
app.UseHsts();
app.UseResponseCompression();
app.UseHttpsRedirection();
// Configure middleware
app.UseAuthentication();
app.UseAuthorization();
// Define endpoints
app.MapGet("/login", (AuthService service) =>
{
var user = new User(
1,
"M.Sohail",
"M.Sohail",
"[email protected]",
"abcd123",
new[] { "developer" });
return service.Create(user);
});
app.MapGet("/test", () => "OK!")
.RequireAuthorization();
app.MapGet("/test/tech", () => "tech OK!")
.RequireAuthorization("tech");
app.UseMiddleware<LoggingMiddleware>();
await app.Migrate();
await app.RunAsync();
我尝试重新排列
Program.cs
中中间件和身份验证设置的顺序,但错误仍然存在。
我已经检查了对
AddAuthentication
和 AddJwtBearer
方法的重复调用。
如果需要,我可以提供代码的简化版本,重点关注导致错误的身份验证设置。
环境
我并不是说这是绝对的解决方案,但它可以解决问题:
.AddJwtBearer("GiveSomeUniqueNameHere", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.PrivateKey)),
ValidateIssuer = false,
ValidateAudience = false
};
});
这就是您为身份验证方案指定名称的方式,从而避免与默认命名方案发生冲突。但是,您可能应该查看其他方案的来源,并在不需要时将其注释掉。
我看到您正在添加一些与 KeyCloak 相关的内容,也许可以尝试将它们注释掉,看看问题是否消失。这些方法可能会添加一些身份验证方案。
附注
builder.Services.AddExceptionHandler<ExceptionHandler>();
是做什么用的?您可以使用内置的 UseExceptionHandler
进行全局异常处理,除非您确实需要自定义的东西。