我可以强制 AuthenticationState 刷新(当声明发生更改时)吗?

问题描述 投票:0回答:1

有什么方法可以在声明更改时强制 AuthenticationState 重新读取数据库吗?

我已经实现了

ServerAuthenticationStateProvider
,它非常适合我添加
IdentityUser.Enabled
。但是,当我将其设置为在调用
ExAuthenticationStateProvider.GetAuthenticationStateAsync()
时重新读取声明时,虽然确实返回并更新了声明列表,但该列表不会传播到
AuthenticationState 

除了让用户注销并重新登录之外,还有其他方法可以传播它吗?

我的 Routes.razor 是:

<Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                <div class="message--401">
                    <h1 role="alert">Sorry, you're not authorized to view this page.</h1>
                    <p>You must have an Admin claim and be set to use 2FA when logging in.</p>
                </div>
            </NotAuthorized>
        </AuthorizeRouteView>
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <div class="message--404">
                <h1 role="alert">Sorry, there's nothing at this address.</h1>
            </div>
        </LayoutView>
    </NotFound>
asp.net-identity blazor-server-side
1个回答
0
投票

您可以重写

GetAuthenticationStateAsync()
类中的
CustomServerAuthenticationStateProvider
方法,以从您需要的源返回新的身份信息。 (如db)
例如,我们可以使用
userManager.GetUserAsync
从数据库中获取用户信息并返回。

    public class CustomServerAuthenticationStateProvider : ServerAuthenticationStateProvider
    {
        private readonly UserManager<ApplicationUser> userManager;
        private readonly SignInManager<ApplicationUser> signInManager;
        public CustomServerAuthenticationStateProvider(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }
        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var authenticationState =await base.GetAuthenticationStateAsync(); //use method from base to get current state.
            var user = await userManager.GetUserAsync(authenticationState.User);
            var claimsPrincipal =await signInManager.CreateUserPrincipalAsync(user);
            return new AuthenticationState(claimsPrincipal);
        }
    }

然后

GetAuthenticationStateAsync
将始终向您返回更新后的索赔。并且不要忘记为此示例注册 UserManager 和 SignInManger。

builder.Services.AddIdentityCore<ApplicationUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddSignInManager()
    .AddUserManager<UserManager<ApplicationUser>>()
    .AddDefaultTokenProviders();
© www.soinside.com 2019 - 2024. All rights reserved.