Blazor WASM登录后路径被添加/authentication的异常问题
问题概述
登录后页面路径自动添加/authentication前缀,导致无法加载_framework/blazor.webassembly.js。正确回调路径应为:
https://localhost:7293/login-callback?code=764B947CAE732C640B3D01E7C3E9C0DE3C13F0E8F6578975DA13079053CD9376-1&scope=ProtegiaWasm.ServerAPI%20openid%20profile&state=28d572d1a9074ae28f184d8820262bb9&session_state=qOB10fFgJDRubXqkIcc6lvlizTa5xMmIAhRLuTw3d4c.D640C48FAD733ADDECB15032D1F52F06&iss=https%3A%2F%2Flocalhost%3A7293
实际生成的错误路径则包含/authentication前缀:
https://localhost:7293/authentication/login-callback?code=764B947CAE732C640B3D01E7C3E9C0DE3C13F0E8F6578975DA13079053CD9376-1&scope=ProtegiaWasm.ServerAPI%20openid%20profile&state=28d572d1a9074ae28f184d8820262bb9&session_state=qOB10fFgJDRubXqkIcc6lvlizTa5xMmIAhRLuTw3d4c.D640C48FAD733ADDECB15032D1F52F06&iss=https%3A%2F%2Flocalhost%3A7293
不建议直接修改AuthenticationService.js
不推荐修改/_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js,原因如下:
- 该文件是官方NuGet包的内置资源,更新包后所有修改会被覆盖
- 手动修改库文件可能引发未预见的认证逻辑异常,增加维护成本
正确解决方法
1. 调整认证配置中的路径前缀
在项目的Program.cs中,配置AddOidcAuthentication时显式指定认证路径,移除默认的/authentication前缀:
builder.Services.AddOidcAuthentication(options => { // 绑定你的身份提供商配置(如Identity Server、Auth0等) builder.Configuration.Bind("YourAuthProvider", options.ProviderOptions); options.ProviderOptions.ResponseType = "code"; // 自定义认证路径,去掉/authentication前缀 options.AuthenticationPaths.LogInCallbackPath = "/login-callback"; options.AuthenticationPaths.LogInPath = "/login"; options.AuthenticationPaths.LogOutCallbackPath = "/logout-callback"; options.AuthenticationPaths.LogOutPath = "/logout"; });
2. 同步身份提供商的回调地址配置
确保你的身份提供商(如Identity Server、Azure AD等)后台配置的回调URL、注销回调URL与上述自定义路径完全一致,不包含/authentication前缀。
3. 检查项目路由配置
确认App.razor中的路由组件没有额外添加/authentication前缀,避免路由冲突导致路径错误。
4. 自定义认证逻辑(可选)
如果需要更复杂的路径处理逻辑,建议通过以下方式扩展:
- 继承
RemoteAuthenticationService实现自定义认证服务 - 自定义
AuthenticationStateProvider来覆盖默认路径生成逻辑
内容的提问来源于stack exchange,提问作者jorge

