3

我创建了一个习惯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>();

4

3 回答 3

3

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

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

var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "Needs Auth Type Here"));
于 2020-07-08T15:16:04.120 回答
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这在所有构造的地方都应该是相同的。

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

于 2020-07-08T15:16:18.337 回答
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"));

于 2020-07-08T15:19:27.273 回答