blazor - Blazor 自定义身份验证状态提供程序
问题描述
我创建了一个自定义身份验证状态提供程序,它检查我们内部 LDAP 服务上的用户名和密码。我的以下代码在初始登录期间工作正常。但是登录后,如果我按 F5 或刷新页面,它会自动进入登录页面。有人可以帮忙吗?
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly ILdapAuthenticationService _ldapAuthenticationService;
private ClaimsPrincipal _cachedClaimsPrincipal;
public CustomAuthenticationStateProvider(ILdapAuthenticationService
ldapAuthenticationService)
{
_ldapAuthenticationService = ldapAuthenticationService;
}
public override async
Task<Microsoft.AspNetCore.Components.Authorization.AuthenticationState>
GetAuthenticationStateAsync()
{
if (_cachedClaimsPrincipal != null)
return await Task.FromResult(
new
Microsoft.AspNetCore.Components.Authorization.AuthenticationState(_cachedClaimsPrincipal));
return await Task.FromResult(new
Microsoft.AspNetCore.Components.Authorization.AuthenticationState(new ClaimsPrincipal(new
ClaimsIdentity())));
}
public void ValidateLogin(string username, string password)
{
if (string.IsNullOrEmpty(username)) throw new Exception("Enter username");
if (string.IsNullOrEmpty(password)) throw new Exception("Enter password");
if (_ldapAuthenticationService.AuthenticateUser(username, password))
{
_cachedClaimsPrincipal = _ldapAuthenticationService.CurrentUser.ClaimsPrincipal;
}
NotifyAuthenticationStateChanged(
Task.FromResult(new
AuthenticationState(_ldapAuthenticationService.CurrentUser.ClaimsPrincipal)));
}
}
public class RedirectToLogin : ComponentBase
{
[Inject]
protected NavigationManager NavigationManager { get; set; }
[CascadingParameter]
private Task<Microsoft.AspNetCore.Components.Authorization.AuthenticationState>
authenticationStateTask { get; set; }
protected override void OnInitialized()
{
NavigationManager.NavigateTo("/");
}
}
创建 RedirectToLogin 以便用户在浏览任何页面之前必须进行身份验证
解决方案
您的 CustomAuthenticationStateProvider 将具有在请求后终止的范围,因此将 ClaimsPrincipal 缓存在此类的本地成员中将不起作用:
private ClaimsPrincipal _cachedClaimsPrincipal;
在构造函数上添加调试日志,您将看到它为每个请求创建(因此 _cachedClaimsPrincipal 中的任何存储值都将丢失)。
public CustomAuthenticationStateProvider(ILdapAuthenticationService
ldapAuthenticationService)
{
System.Diagnostics.Debug.WriteLine("Constructor");
_ldapAuthenticationService = ldapAuthenticationService;
}
您需要将其缓存在持久位置(例如,用于服务器端的会话对象或用于客户端的本地存储)。
推荐阅读
- laravel - 按与其他模型的关系分组的模型记录
- raspberry-pi4 - 在 arm64(树莓派 4)上安装 azerothcore 时出错
- python - ModelMultipleChoiceField 返回查询集而不是对象实例
- c# - 有没有办法声明一个具有固定 int 大小的浮点数组?
- javascript - 为什么这两个字符串对于 bcrypt 是相同的?
- qt - 为什么在 QQuickWidget 上给出 id 时 QML 菜单不会在外部按下时关闭?
- javascript - 为什么我的动作在传递给事件处理程序时没有调度
- r - 使用重叠阈值逐行选择跨列组合
- javascript - Redux action 和 async/await 函数在类组件和函数中具有不同的行为
- heroku - 此响应无法在 Heroku 中设置 Cookie