5 blazor
我正在定制AuthenticationStateProvider一个 Blazor 应用程序进行测试。我担心新类不会具有与 AuthenticationStateProvider 类相同的功能,因为我不确定 AuthenticationStateProvider 是如何工作的。下面我发布了我的自定义类。你能告诉我这是否是覆盖这个类的可接受的方式吗?
public class ServerAuthenticationStateProvider : AuthenticationStateProvider
{
string UserId;
string Password;
bool IsAuthenticated = false;
public void LoadUser(string _UserId, string _Password)
{
UserId = _UserId;
Password = _Password;
}
public async Task LoadUserData()
{
var securityService = new SharedServiceLogic.Security();
try
{
var passwordCheck = await securityService.ValidatePassword(UserId, Password);
IsAuthenticated = passwordCheck == true ? true : false;
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var userService = new UserService();
var identity = IsAuthenticated
? new ClaimsIdentity(await userService.GetClaims(UserId))
: new ClaimsIdentity();
var result = new AuthenticationState(new ClaimsPrincipal(identity));
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
blazor 如何检测已授权/未授权
public ClaimsIdentity (
System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims,
string authenticationType);
Run Code Online (Sandbox Code Playgroud)
要设置为已验证,只需向 发送一个值authenticationType,引用文档:
IsAuthenticated注意:访问时,IsAuthenticated 属性的值是根据 AuthenticationType 属性的值返回的。
AuthorizeView 组件要求IsAuthenticated.
从CustomAuthStateProvider示例中查看此代码:
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "mrfibuli"),
}, "Fake authentication type");
Run Code Online (Sandbox Code Playgroud)
对于前面的示例,IsAuthenticated将为 true,因为ClaimsIdentity构造函数具有"Fake authentication type"forauthenticationType参数。
总结
如果您创建包含 authenticationType参数的身份,则用户已通过身份验证。如果您创建不带 authenticationType参数的身份,则不会对用户进行身份验证。
var userService = RequestMyUserService(user, password);
var identity = userService.IsValidUser
? new ClaimsIdentity(
new[] {new Claim(ClaimTypes.Name, "mrfibuli"),},
"My Custom User Service") // authenticated
: new ClaimsIdentity(); // not authenticated
...
Run Code Online (Sandbox Code Playgroud)
有关ASP.NET Core 身份验证简介的更多信息,请参阅基于声明的身份验证。
| 归档时间: |
|
| 查看次数: |
1992 次 |
| 最近记录: |