blazor Web 应用程序 .net8 - 协商身份验证 - 刷新页面时出现 http 403

问题描述 投票:0回答:1

我在 Windows 身份验证和 blazor web 应用程序 .net8 方面遇到问题,除了一个细节外,一切正常: 当我在具有授权属性的路线上时,如果我在此页面上按 F5,我会收到 http 403。

为了重现我的问题,我从一个空白的 blazor Web 应用程序项目开始。以下是我遵循的步骤:

  • 添加 Microsoft.AspNetCore.Authentication.Negotiate 包
  • 将其包裹在 Routes.razor 中的 a 中
  • 将 Routes.razor 中的 更改为 an
  • 添加到Program.cs
    builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate(); builder.Services.AddAuthorization(options => options.FallbackPolicy = options.DefaultPolicy);

然后我创建了一个简单的权限来重现问题:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("view", policy => policy.RequireClaim("Permission", "view"));
});

我创建了一个 CustomAuthenticationStateProvider 来系统地添加此授权

并将以下属性添加到计数器示例页面:

@attribute [Authorize(Policy = "view")]

当我通过菜单导航到此页面时,我可以正确访问该页面,一切都很好。

如果按 F5,我会收到 http 403 错误。有人可以解释一下出了什么问题吗?

提前致谢

编辑1: 对于我的测试来说,这是一个非常基本的 CustomAuthenticationStateProvider 类:

public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
    public IHttpContextAccessor HttpContextAccessor { get; set; }

    public CustomAuthenticationStateProvider(IConfiguration conf, IHttpContextAccessor httpContextAccessor)
    {
        HttpContextAccessor = httpContextAccessor;
    }

    public async override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        if (HttpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
        {
            var identity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, "username")
            }, "windows auth");

            identity.AddClaim(new Claim("Permission", "view"));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "username"));
            identity.AddClaim(new Claim(ClaimTypes.GivenName, "username"));
            identity.AddClaim(new Claim(ClaimTypes.Name, "username"));
            var user = new ClaimsPrincipal(identity);
            return new AuthenticationState(user);
        }
        return new AuthenticationState(new ClaimsPrincipal());
    }
}
asp.net-core authentication blazor blazor-server-side http-status-code-403
1个回答
0
投票

@attribute [Authorize(Policy = "view")]
在这里不起作用。它独立于
CustomAuthenticationStateProvider
工作。因此,当通过授权管道时,不会添加“权限”声明。
您可以使用
AuthorizeView
代替。它将在
CustomAuthenticationStateProvider
之后起作用。尝试修改计数器页面如下:

@page "/counter"
@inject NavigationManager NavigationManager
<PageTitle>Counter</PageTitle>

//apply view policy
<AuthorizeView Policy="view">
   //only display when pass
    <Authorized>
        <h1>Counter</h1>

        <p role="status">Current count: @currentCount</p>

        <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    </Authorized>
    <NotAuthorized>
        @{
            //if not authorize redirect to somewhere
            NavigationManager.NavigateTo($"https://www.google.com");
        }
    </NotAuthorized>
</AuthorizeView>
© www.soinside.com 2019 - 2024. All rights reserved.