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

Dra*_*ouf 1 .net asp.net-core blazor-client-side blazor-webassembly

我从一个 Visual Studio 模板开始,一个新的 Blazor WebAssembly,以身份验证和 Web API 作为服务器端。

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

@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
Run Code Online (Sandbox Code Playgroud)

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

Lou*_*raQ 8

我想这样做是因为我正在写一个管理员,如果没有连接,我根本不希望人们看到布局

可以理解为,用户未登录时,无法进入任何页面,jump to the login page此时我们可以,对吗?

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

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

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

    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);
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 然后在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>
    
    Run Code Online (Sandbox Code Playgroud)
  • 最后,在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://docs.microsoft.com/aspnet/" target="_blank">About</a>
                </div>
    
                <div class="content px-4">
                    @Body
                </div>
            </div>
        </Authorized>
        <NotAuthorized>
            <RedirectToLogin />
        </NotAuthorized>
    </AuthorizeView>
    
    Run Code Online (Sandbox Code Playgroud)

这是测试结果:

在此处输入图片说明


syn*_*tic 5

将 @attribute [Authorize] 放入 _Imports.razor 似乎有效。看到这个答案。如果找不到路线,接受的答案可能无法正常工作。不过,您可以使用不同的公共布局(不是 MainLayout)。