【发布时间】:2020-04-18 11:36:48
【问题描述】:
有没有办法在 Component 之外访问身份验证状态? 比如我正在尝试,
public class ServersideCurrentUserIdentityProvider : ICurrentUserIdentityProvider, IDisposable
{
private Task<AuthenticationState> currentAuthenticationStateTask;
private readonly AuthenticationStateProvider stateProvider;
public ServersideCurrentUserIdentityProvider(AuthenticationStateProvider stateProvider)
{
this.stateProvider = stateProvider;
stateProvider.AuthenticationStateChanged += OnAuthenticationStateChanged;
currentAuthenticationStateTask = stateProvider.GetAuthenticationStateAsync();
}
private void OnAuthenticationStateChanged(Task<AuthenticationState> task)
{
this.currentAuthenticationStateTask = task;
}
public async Task<ClaimsPrincipal> GetCurrentUserPrincipal()
{
var state = await currentAuthenticationStateTask;
return state.User;
}
public void Dispose()
{
this.stateProvider.AuthenticationStateChanged -= OnAuthenticationStateChanged;
}
}
这个类在 DI 中注册 作为
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
services.AddSingletone<ICurrentUserIdentityProvider,ServersideCurrentUserIdentityProvider>()
我正在尝试使用 CurrentUserProvider 作为 db Context 的参数 作为
public class ExampleDbContext()
{
public ExampleDbContext(DbContextOption opt, ICurrentUserProvider provider){
override Task<int> onSaveChange(){
var principal= await this.userProvider.GetCurrentPrincipal();
foreach ..
entity.CreatedBy=principal.Name;
}
}
当我尝试运行时,我得到 exception 说,GetAuthenticationState 应该在 SetAuthentication 状态之后调用, 我该怎么做???
【问题讨论】:
-
您在启动期间看到异常,因为每次调用数据库上下文时数据库的构造函数都会运行。它甚至会在您的用户有机会登录之前被调用。因此,您不能依赖 DbContext 中的服务,并且您需要处理可能没有用户与请求关联的事实。这意味着跳过 GetCurrentPrincipal 调用。
-
这实际上并不正确。
-
@crypted 你找到解决方案了吗?尝试做类似的事情......
标签: asp.net-identity blazor blazor-server-side cookie-authentication