问题描述
我正在制作自定义AuthenticationStateProvider
以便在Blazor应用程序中进行测试.我担心新类不会具有与AuthenticationStateProvider类相同的功能,因为我不确定AuthenticationStateProvider的工作方式.在下面,我发布了我的自定义课程.您能告诉我这是否是覆盖此类的公认方法吗?
I am making a custom AuthenticationStateProvider
to test in a Blazor app. I am worried that the new class won't have the same functionality as the AuthenticationStateProvider class because I'm not sure how AuthenticationStateProvider works. Below I posted my custom class. Could you please tell me if this is the accepted way of overrideing this class?
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;
}
}
推荐答案
问题:
答案:
public ClaimsIdentity (
System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims,
string authenticationType);
要设置为已验证,只需将值发送到authenticationType
,并引用文档:
To set as authenticated, just send a value to authenticationType
, quoting docs:
AuthorizeView组件要求提供IsAuthenticated
.
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "mrfibuli"),
}, "Fake authentication type");
对于前面的示例, IsAuthenticated
将为真,因为ClaimsIdentity
构造函数的authenticationType
参数具有"Fake authentication type"
.
For previous example, IsAuthenticated
will be true because ClaimsIdentity
constructor has "Fake authentication type"
for authenticationType
parameter.
总结
如果您创建的身份包括 authenticationType
参数,则表明用户已通过身份验证.如果您在没有 authenticationType
参数的情况下创建身份,则不会对用户进行身份验证.
If you create your identity including authenticationType
parameter the user is authenticated. If you create your identity without authenticationType
parameter, the user is not authenticated.
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
...
更多信息,请参见基于索赔身份验证,有关使用ASP.NET Core进行身份验证的介绍.
More info at Claims-based authentication on Introduction to Authentication with ASP.NET Core.
这篇关于blazor如何检测授权/公证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!