Redirect to login in Blazor Server Azure B2C Authentication

You can force the user to login with the below changes

Approach 1:

_Host.Cshtml Add the below code

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

App.razor

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <h4>Not authorized.</h4>
                </NotAuthorized>
                <Authorizing>
                    <h4>Authentication in progress...</h4>
                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

MainLayout.razor

@inherits LayoutComponentBase

<div class="sidebar">
    <NavMenu />
</div>

<div class="main">
    <AuthorizeView>
        <NotAuthorized></NotAuthorized>            
        <Authorized>
            <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>
        </Authorized>
    </AuthorizeView>
</div>

Approach 2:

Another way For redirecting the user to login page Please make the below changes

_Host.Cshtml

<environment include="Staging,Production">            
            <component render-mode="ServerPrerendered" type="typeof(App)" />
        </environment>
        <environment include="Development">
            <component render-mode="Server" type="typeof(App)" />
        </environment>

Create RedirectToLogin.razor

@inject NavigationManager Navigation


@code {  

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        Navigation.NavigateTo("/AzureADB2C/Account/SignIn");
        return base.OnAfterRenderAsync(firstRender);
    }
}

MainLayout.razor

<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">
        <AuthorizeView>
            <Authorized>
                @Body
            </Authorized>
            <NotAuthorized>
                <Blazor_B2C.Pages.RedirectToLogin></Blazor_B2C.Pages.RedirectToLogin>
            </NotAuthorized>
        </AuthorizeView>
    </div>
</div>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top