自定义`AuthenticationStateProvider`验证失败

时间:2020-07-08 15:09:52

标签: .net-core blazor blazor-webassembly

我创建了一个自定义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<AuthenticationStateProvider, ApiAuthenticationStateProvider>();

3 个答案:

答案 0 :(得分:2)

此问题可以解决。 https://stackoverflow.com/a/20254797/2682662

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

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

答案 1 :(得分: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的所有地方都应该相同。

更新: 根据{{​​3}},认证类型的值应为this comment中定义的值之一。 更新了上面的代码以使用此类而不是随机的auth类型名称。

答案 2 :(得分:1)

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"));