【问题标题】:Blazor: Custom AuthenticationStateProvider never returns authorised stateBlazor:自定义 AuthenticationStateProvider 永远不会返回授权状态
【发布时间】:2023-03-25 23:22:02
【问题描述】:

我有一个非常基本的 blazor 项目设置,通过实现 AuthenticationStateProvider 来通过自定义身份验证机制测试授权。

我伪造了授权状态以始终返回伪造的登录用户并将@attribute [Authorized] 添加到我的可路由页面组件,但导航到时它始终显示“未授权”消息。

首先在 Startup.cs 中添加必要的初始化

 app.UseAuthentication();
 app.UseAuthorization();

我已经实现了一个自定义的 AuthenticationStateProvider,它总是返回一个登录的用户:

public class LocalStorageAuthenticationStateProvider : AuthenticationStateProvider
{

        public override Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var identity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Email, "user@fake.com","apiauth_type_email")
            });
    
            var user = new ClaimsPrincipal(identity);

            return Task.FromResult(new AuthenticationState(user));
        }
 }

..我已经注册了我的自定义提供程序:

    services.AddScoped<AuthenticationStateProvider, LocalStorageAuthenticationStateProvider>();

..我已将 AuthorizeRouteView 添加到 App.razor

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

最后,我将授权属性添加到我的可路由页面:

@page "/personal/dashboard"
@attribute [Authorize]

但是当我导航到那里时,我总是会收到“未授权”的消息。我在这里错过了什么?

【问题讨论】:

    标签: authentication authorization blazor blazor-server-side blazor-webassembly


    【解决方案1】:

    你的问题在这里:

    var identity = new ClaimsIdentity(new[]
    {
          new Claim(ClaimTypes.Email, "user@fake.com","apiauth_type_email")
    });
    

    您有拼写错误,没有为ClaimsIdentity 提供authenticationType。您的代码应如下所示:

    var identity = new ClaimsIdentity(new[]
      {
         new Claim(ClaimTypes.Email, "user@fake.com")
      }, "apiauth_type_email");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2019-11-15
      • 2011-07-25
      • 1970-01-01
      相关资源
      最近更新 更多