Blazor Server: redirect to login and facilitate register page

Viewed 1569

I've got a Blazor Server web application where all the pages require to be authenticated except the login page. Whenever you're not authenticated you should be redirected to the login page.

I've achieved this with my App.razor:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeView>
                <Authorized>
                    <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
                </Authorized>
                <NotAuthorized>
                    <LoginPage />
                </NotAuthorized>
            </AuthorizeView>
        </Found>
        <NotFound>
            <h1> 404 - Not Found</h1>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

This does exactly what I want, whenever you're not authenticated and you navigate to a random page, it redirects to the LoginPage.

The problem I'm facing is that I want to facilitate a Register page where someone can create an account. However, with the current App.Razor, if you navigate to localhost/register, you're redirected to the Login page (of course).

Is there a way to solve this (elegantly) within App.Razor? I'd like to prevent having to add the same logic to each page to redirect to the login page in case you're not authenticated.

1 Answers

You should do it like this

<AuthorizeRouteView RouteData="@routeData" 
               DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    @if (!context.User.Identity.IsAuthenticated)
                    {
                        <RedirectToLogin /> 
                    }
                   else
                   {
                        <p>You are not authorized to access this resource.</p>
                    }
                </NotAuthorized>
        </AuthorizeRouteView>

This is yours:

<NotAuthorized>
        <LoginPage />
   </NotAuthorized>

Pseudocode: If user is not authorized, redirect him to the login page.

This is of course wrong. The user may be already logged in, and yet not authorized. Got it ?

You can put the authorize attribute in the _Host.cshtml file, in which case the user is redirected to the login page, even before your Blazor App is rendered. You may place the authorize attribute at the App.razor component if you like, or in the _Imports.Razor file, etc. In order to allow anonymous access to your Register page and or others, just annotate the top of the page with: @attribute [AllowAnonymous]

Related