【问题标题】:Custom `AuthenticationStateProvider` Authentication Failing自定义 `AuthenticationStateProvider` 身份验证失败
【发布时间】:2020-10-29 01:12:53
【问题描述】:

我创建了一个自定义 ApiAuthenticationStateProvider,在返回 AuthenticationState 后仍然声明

info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed.

这是我失败的ApiAuthenticationStateProvider 的简化版本:

public class ApiAuthenticationStateProvider : AuthenticationStateProvider
{
   public override Task<AuthenticationState> GetAuthenticationStateAsync()
   {
       Console.WriteLine("Getting auth state...");
               
       var claims = new[] { new Claim(ClaimTypes.Name, "some.email@somewhere.com") };
       var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims));
       var authState = Task.FromResult(new AuthenticationState(authenticatedUser));

       return Task.FromResult(authState);
   }
}

我可以从 Console.WriteLine 中看出它正在使用我的自定义提供程序,但要提供完整的详细信息,这是我用来在 Program.cs 中添加的代码:

builder.Services.AddScoped&lt;AuthenticationStateProvider, ApiAuthenticationStateProvider&gt;();

【问题讨论】:

    标签: .net-core blazor blazor-webassembly


    【解决方案1】:

    这个问题可以在这个答案中解决。 https://stackoverflow.com/a/20254797/2682662

    基本上在构造ClaimsIdentity时需要为认证类型提供一个字符串值。

    var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "Needs Auth Type Here"));
    

    【讨论】:

    • 这个答案似乎是最正确的,并链接到解释为什么需要字符串'auth type'。
    【解决方案2】:

    要在 Blazor 上运行,您必须添加 authenticationType 参数值和 ClaimsIdentity,这样您的代码将更改为:

    public class ApiAuthenticationStateProvider : AuthenticationStateProvider
    {
       public override Task<AuthenticationState> GetAuthenticationStateAsync()
       {
           Console.WriteLine("Getting auth state...");
                   
           var claims = new[] { new Claim(ClaimTypes.Name, "some.email@somewhere.com") };
           var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationTypes.Password));
           var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
    
           return Task.FromResult(authState);
       }
    }
    

    注意ClaimsIdentityAuthenticationTypes.Password 参数。

    在构造ClaimsIdentity 的所有地方都应该是相同的。

    更新: 根据this comment,身份验证类型的值应该是AuthenticationTypes class 中定义的值之一。 更新了上面的代码以使用此类而不是随机的身份验证类型名称。

    【讨论】:

      【解决方案3】:

      https://docs.microsoft.com/en-us/dotnet/api/system.security.claims.claimsidentity.-ctor?view=netcore-3.1

      您的 ClaimsIdentity() 仅使用您在上面创建的声明数组实例化的对象在文档中似乎是正确的,但提供声明类型的字符串(也在上面的文档中)似乎实际上是需要的

      var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "Needs Auth Type Here"));

      【讨论】:

        猜你喜欢
        • 2022-08-10
        • 1970-01-01
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        • 2018-03-02
        • 2014-07-15
        相关资源
        最近更新 更多