gpt4 book ai didi

.net - Blazor WebAssembly。在布局级别添加授权属性

转载 作者:行者123 更新时间:2023-12-05 08:15:18 24 4
gpt4 key购买 nike

我从一个 visual studio 模板开始,这是一个新的 Blazor WebAssembly,具有身份验证和 Web API 作为服务器端。

我的问题是保护所有页面,而不仅仅是某些页面。我试图添加:

@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]

到 MainLayout 而不是所有页面,但没有任何运气。我想这样做是因为我正在写一个管理员,如果没有连接,我根本不希望人们看到布局

最佳答案

I wanted to do that because I'm writing an admin and I don't wantpeople to see the layout at all if there are not connected

可以这么理解,当用户没有登录的时候,是不能进入任何页面的,那么这时候我们可以跳转到登录页面对不对

如果是这样,您可以通过以下步骤实现:

  • 首先在当前blazor中创建一个RedirectToLogin.razor页面项目。

    在本页面的OnInitializedAsync方法中,通过判断是否当前有用户登录,如果没有,重定向到登录页面。

    RedirectToLogin.razor:

    @inject NavigationManager Navigation
    @code {
    [CascadingParameter]
    private Task<AuthenticationState> AuthenticationStateTask { get; set; }

    protected override async Task OnInitializedAsync()
    {
    var authenticationState = await AuthenticationStateTask;

    if (authenticationState?.User?.Identity is null || !authenticationState.User.Identity.IsAuthenticated)
    {
    Navigation.NavigateTo("Identity/Account/Login", true);
    }
    }
    }
  • 然后在App.razor中添加如下代码,确保NotAuthorized 会进入RedirectToLogin.razor 页面:

    <CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
    <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
    <NotAuthorized>
    <RedirectToLogin />
    </NotAuthorized>
    </AuthorizeRouteView>
    </Found>
    <NotFound>
    <LayoutView Layout="@typeof(MainLayout)">
    <p>Sorry, there's nothing at this address.</p>
    </LayoutView>
    </NotFound>
    </Router>
    </CascadingAuthenticationState>
  • 最后在MainLayout.razor页面中,做了区分Authorized和NotAuthorized之间:

    @inherits LayoutComponentBase
    <AuthorizeView>
    <Authorized>
    <div class="sidebar">
    <NavMenu />
    </div>

    <div class="main">
    <div class="top-row px-4 auth">
    <LoginDisplay />
    <a href="https://learn.microsoft.com/aspnet/" target="_blank">About</a>
    </div>

    <div class="content px-4">
    @Body
    </div>
    </div>
    </Authorized>
    <NotAuthorized>
    <RedirectToLogin />
    </NotAuthorized>
    </AuthorizeView>

测试结果如下:

enter image description here

关于.net - Blazor WebAssembly。在布局级别添加授权属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63378376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com