.net-core - 从 Blazor 应用程序中的中间件类获取经过身份验证的用户

标签 .net-core asp.net-identity blazor blazor-server-side .net-core-3.1

我有一个服务器端 Blazor 应用程序。每个用户在访问页面时都必须经过身份验证。为此,用户被重定向到“身份服务器”登录页面。当用户使用正确的凭据登录时,他将被重定向回 Blazor 应用。

我已经使用 CascadingAuthenticationState 设置了我的 Blazor 应用,这样我就可以在我的 Blazor 页面中访问 User 对象及其声明。

这在组件内部是这样的:

[CascadingParameter]
private Task<AuthenticationState> AuthenticationStateTask { get; set; }
...
... 
var authState = await AuthenticationStateTask;
var claims = authState.User.Claims; // Works fine.

当我这样做时,我可以访问用户声明。

到目前为止一切顺利。

但我还有一个中间件类,我需要在其中访问用户声明。

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);
}

但由于某些原因,User 声明始终为空。

为什么我的 Blazor 组件中的 User.Claims 对象充满了所有声明,但当我通过 HttpContext 对象访问它们时它们是空的?

最佳答案

注册中间件的顺序很关键。这也是我个人最近在自己的项目中经常遇到的问题 - 但是,如果您乱序配置它们,则不会出现警告。

引自微软文档 Middleware order :

The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.

您似乎在 .NET Core 身份验证中间件之前调用您的中间件,因此您的用户对象为空 - 或者缺少声明。

将您的 app.UseMiddleware<T>app.UseAuthentication() 之后和 app.UseAuthorization() .

关于.net-core - 从 Blazor 应用程序中的中间件类获取经过身份验证的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59345078/

相关文章:

c# - 如果变量更改发生在单独的线程上,Blazor 不会检测到变量更改

c# - 使用 Microsoft Graph API 获取 Outlook 中的所有消息

c# - 使用身份提供者在 asp.net mvc 4 应用程序中添加角色

c# - 如何在 ASP.NET Core 中默认使用不记名 token 保护所有 Controller ?

c# - Blazor UI 锁定

asp.net-core - Blazor Wasm PWA 未更新

entity-framework - HasData 的数据播种不适用于 Visual Studio for Mac

c# - 如何使用 EF Core 在 ASP.NET Core 中取消应用迁移

entity-framework - 回滚事务抛出 "There is already an open DataReader associated with this Command..."错误

部署后 ASP.Net Core Identity 登录状态丢失