【问题标题】:How does blazor detect authorized / notautorizedBlazor 如何检测授权/未授权
【发布时间】:2021-09-13 16:55:58
【问题描述】:

我正在制作自定义 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;
    }
}

【问题讨论】:

  • 别担心...你看到我对你上一个问题的回答了吗?在我看来,你从中得到的唯一东西就是担心......

标签: c# blazor


【解决方案1】:

问题:

blazor 如何检测授权/未授权

答案:

这是constructors for ClaimsIdentity 之一:

public ClaimsIdentity (
 System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, 
 string authenticationType);

set as authenticated,只需将值发送至authenticationType,引用文档:

IsAuthenticated注意:访问时,IsAuthenticated 属性的值是根据 AuthenticationType 属性的值返回的。

AuthorizeView component 请求IsAuthenticated

CustomAuthStateProvider sample看这段代码:

    var identity = new ClaimsIdentity(new[]
    {
        new Claim(ClaimTypes.Name, "mrfibuli"),
    }, "Fake authentication type");

对于前面的示例,IsAuthenticated 将为 true,因为 ClaimsIdentity 构造函数有 "Fake authentication type" 用于 authenticationType 参数。

总结

如果您创建自己的身份包括 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

    ...

更多信息请访问Claims-based authentication,了解 ASP.NET Core 身份验证简介。

【讨论】:

  • 你为什么在你的回答中重复这个问题?这是新的 SO 政策吗?
  • 嗨@UweKeim,因为OP要求“你能告诉我这是否是覆盖这个类的公认方式吗?”但我回答了“如何blazor 是否检测到授权/未授权”(涵盖了操作问题)。这解决了你的问题?感谢您的评论。
猜你喜欢
  • 2021-02-08
  • 2023-03-20
  • 2013-11-01
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 2011-04-21
  • 2022-08-24
相关资源
最近更新 更多