Viv*_*ndi 4 asp.net-identity .net-core blazor blazor-server-side .net-core-3.1
我有一个服务器端 Blazor 应用程序。每个用户想要访问某个页面时都必须经过身份验证。为此,用户被重定向到“身份服务器”登录页面。当用户使用正确的凭据登录时,他会被重定向回 Blazor 应用程序。
我已使用 设置我的 Blazor 应用程序CascadingAuthenticationState
,以便我可以User
在 Blazor 页面内访问该对象及其声明。
组件内部是这样的:
[CascadingParameter]
private Task<AuthenticationState> AuthenticationStateTask { get; set; }
...
...
var authState = await AuthenticationStateTask;
var claims = authState.User.Claims; // Works fine.
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我可以访问用户的声明。
到目前为止,一切都很好。
但我还有一个中间件类,我需要在其中访问用户声明。
public async Task InvokeAsync(HttpContext context)
{
if (context?.User?.Claims != null && context.User.Claims.Any())
{
Console.WriteLine("aaa");
}
// Call the next delegate/middleware in the pipeline
await _next(context);
}
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,这些User
主张总是空洞的。
为什么User.Claims
Blazor 组件内部的对象填充了所有声明,但当我通过对象访问它们时它们是空的HttpContext
?
注册中间件的顺序至关重要。这也是我个人最近在自己的项目中经常遇到的问题 - 然而,如果您乱序配置它们,则不会出现任何警告。
引用 Microsoft 文档中有关中间件订单的内容:
在 Startup.Configure 方法中添加中间件组件的顺序定义了请求时调用中间件组件的顺序以及响应的相反顺序。该顺序对于安全性、性能和功能至关重要。
看来您是在 .NET Core 身份验证中间件之前调用中间件,因此您的 User 对象为 null - 或缺少声明。
将您的app.UseMiddleware<T>
afterapp.UseAuthentication()
和app.UseAuthorization()
.
归档时间: |
|
查看次数: |
2657 次 |
最近记录: |