如果用户未通过身份验证,Blazor将重定向到登录名

时间:2020-03-24 23:42:26

标签: blazor blazor-client-side

我正在尝试使用Blazor WebAssembly开发应用程序,我想知道如果用户未通过身份验证如何保护整个应用程序。我要实现的行为是:

  • 如果匿名用户要求提供任何页面,则该用户将被重定向到登录页面

更好

  • 用户必须通过使用该应用的身份验证

此刻,我已经实现了将[Authorize]属性应用于每个页面的行为,但是我想将其集中。

我已经在Blazor服务器端通过在[Authorize]组件内应用_host.razor属性实现了这一目标。

甚至Blazor客户端也有解决方案吗?

4 个答案:

答案 0 :(得分:8)

可能有一些更轻松的方法,但这对我有用:

假设您已根据these instructions

正确配置了身份验证

在MainLayout.razor(默认用于所有组件)中,添加一个code块,如下所示:

@code{ 

    [CascadingParameter] protected Task<AuthenticationState> AuthStat { get; set; }

    protected async override Task OnInitializedAsync()
    {
        base.OnInitialized();
        var user = (await AuthStat).User;
        if(!user.Identity.IsAuthenticated)
        {
            NavigationManager.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}");
        }
    }
}

如果用户未通过身份验证,我们将在“ authentication /”处重定向到内置的RemoteAuthenticatorView组件,并进行“登录”操作。这应该启动身份验证

答案 1 :(得分:4)

基本上要对BlazorApp.Client中的所有页面应用授权,您必须添加:

> date
[1] "2020-05-07"

...到您的_Imports.razor文件。

此外,您可以添加:

@attribute [Microsoft.AspNetCore.Authorization.Authorize]

...在不需要授权的页面上。

此外,如果您想将用户重定向到任何页面,这是我想到的:

@attribute [Microsoft.AspNetCore.Authorization.AllowAnonymous]

...其中navMan是NavigationManager的注入实例。如果他们尝试访问仅授权用户页面,则将用户重定向到我的Login.razor。

答案 2 :(得分:2)

我尝试了@Brett 的解决方案,它奏效了,但是在重定向回用户来自它的页面时,它最终说 Authorizing...Checking login state... 然后最后 Completing login... 并被卡住了那里。然后,用户必须点击链接或手动输入之前的 URL 才能返回。

enter image description here

enter image description here

enter image description here

Microsoft 现在有关于“需要对整个应用进行授权”的文档。

https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/?view=aspnetcore-5.0#require-authorization-for-the-entire-app

根据文档,您可以:

  • _Imports.razor 文件中使用 Authorize 属性指令:
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
  • 为 Pages 文件夹中的每个 Razor 组件添加 Authorize 属性。

我将代码添加到 _Imports.razor,但随后我只收到内容的白屏:

enter image description here

然后我注意到 https://localhost:44123/authentication/login 也给了我一个 Shared\RedirectToLogin.razor 通常指向的白色屏幕。然后我将 @attribute [AllowAnonymous] 添加到 Pages\Authentication.razor,然后一切都按预期工作,我没有卡住。

enter image description here

使用此解决方案,我还可以看到默认的 You are logged out. 消息。

enter image description here

答案 3 :(得分:0)

您可以将<NotAuthorizedContent>组件的<Router>模板用作described here

<CascadingAuthenticationState>
    <Router AppAssembly="typeof(Startup).Assembly">
        <NotFoundContent>
            <p>Sorry, there's nothing at this address.</p>
        </NotFoundContent>
        <NotAuthorizedContent>
            <h1>Sorry</h1>
            <p>You're not authorized to reach this page. You may need to log in as a different user.</p>
        </NotAuthorizedContent>
        <AuthorizingContent>
            <p>Please wait...</p>
        </AuthorizingContent>
    </Router>
</CascadingAuthenticationState>

用名为<NotAuthorizedContent>之类的自定义组件替换RedirectToLogin的内容,该组件的OnInitializedAsync检查用户是否已登录,如果不登录,则进行重定向。