.NET 8 WebAPI引入Microsoft.IdentityModel.JsonWebTokens后OIDC报错
问题:添加Microsoft.IdentityModel.JsonWebTokens后OIDC认证报错“无法重定向到授权端点”
错误信息
无法重定向到授权端点,配置可能缺失或无效。
项目配置(WebApi.csproj)
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <InvariantGlobalization>false</InvariantGlobalization> </PropertyGroup> <ItemGroup> <PackageReference Include="IdentityModel" Version="6.2.0" /> <PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="8.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.3" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.3" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.3" /> <PackageReference Include="Hangfire.AspNetCore" Version="1.8.11" /> <PackageReference Include="Hangfire.Core" Version="1.8.11" /> <PackageReference Include="Hangfire.SqlServer" Version="1.8.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.3" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.3" /> <PackageReference Include="Serilog" Version="3.1.1" /> <PackageReference Include="Serilog.AspNetCore" Version="8.0.1" /> <PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" /> <PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" /> <PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" /> <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> <PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" /> <PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="7.5.0" /> </ItemGroup> </Project>
认证配置代码
services.AddAuthentication(sharedOptions => { //sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; //sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme) .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options => { var oidc = new OidcOptions(); configuration.GetSection(OidcOptions.Key).Bind(oidc); options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.Scope.Clear(); oidc.Scopes.ForEach(options.Scope.Add); options.Authority = oidc.Authority; options.ClientId = oidc.ClientId; options.ClientSecret = oidc.ClientSecret; options.ResponseType = OpenIdConnectResponseType.Code; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.Events = new OpenIdConnectEvents { OnRedirectToIdentityProvider = async context => { var authEndpoint = context.ProtocolMessage.IssuerAddress; // Debug or log the authEndpoint here to inspect its value await Task.CompletedTask; } }; });
当前排查发现中间件中的issuer url未被设置,且仅在添加Microsoft.IdentityModel.JsonWebTokens包后出现该问题。
解决方法
1. 统一Identity相关包版本
问题核心是版本不兼容:.NET 8对应Microsoft身份认证包版本应为8.x,但添加的Microsoft.IdentityModel.JsonWebTokens是7.5.0(属于.NET 7版本),版本冲突导致OIDC配置解析逻辑异常。
修改csproj中的包版本,与其他Microsoft认证包保持一致:
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.0.3" />
2. 验证OIDC配置绑定有效性
在OnRedirectToIdentityProvider事件中添加日志,确认从配置读取的oidc.Authority值是否正确:
OnRedirectToIdentityProvider = async context => { var authEndpoint = context.ProtocolMessage.IssuerAddress; // 打印配置读取到的Authority Console.WriteLine($"Configured Authority: {oidc.Authority}"); Console.WriteLine($"Issuer Address: {authEndpoint}"); await Task.CompletedTask; }
如果oidc.Authority为空,检查appsettings.json中对应配置节(OidcOptions.Key指定的节点)是否存在且配置正确,例如:
"Oidc": { "Authority": "https://your-identity-server.com", "ClientId": "your-client-id", "ClientSecret": "your-client-secret", "Scopes": ["openid", "profile", "api"] }
3. 显式配置JWTBearer选项
原代码中AddJwtBearer未配置任何参数,版本冲突下默认行为可能变化,建议显式配置JWT验证参数:
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { var jwtSection = configuration.GetSection("Jwt"); options.Authority = jwtSection["Authority"]; // JWT授权服务器地址 options.Audience = jwtSection["Audience"]; // 你的API受众 options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true }; })
4. 明确默认认证方案
取消注释默认方案配置,根据业务需求设置:
services.AddAuthentication(sharedOptions => { // 如果以API为主,JWT作为默认认证方案 sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; // 需要OIDC挑战时使用OpenIdConnect方案 sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; })
或者在需要OIDC认证的接口上明确指定认证方案:
[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)] public IActionResult OidcProtectedEndpoint() { return Ok(); }
内容的提问来源于stack exchange,提问作者Marko
相关产品推荐
相关产品推荐

