Search code examples
authorizationblazorblazor-webassembly

Blazor redirect on policy failed


I need to react differently based on which authorization policy failed. So, if PolicyA failed when user tried to navigate to pageA (which requires PolicyA), I would like to redirect to pageB.

Is this possible in Blazor WASM?


Solution

  • One option is to use IAuthorizationService and the cascaded parameter of type Task<AuthenticationState> like this:

    @using Microsoft.AspNetCore.Authorization
    @inject IAuthorizationService AuthorizationService
    @inject NavigationManager NavigationManager
    
    ...
    
    @code {
        [CascadingParameter]
        private Task<AuthenticationState> authenticationStateTask { get; set; }
    
        protected async override Task OnInitializedAsync()
        {
            var user = (await authenticationStateTask).User;
    
            if ((await AuthorizationService.AuthorizeAsync(user, "PolicyA"))
                .Succeeded)
            {
                NavigationManager.NavigateTo("pageB");
            }
    
            // rest of the code
        }
    }
    

    Another option is to use AuthorizeView component like this:

    @inject NavigationManager NavigationManager
    
    <AuthorizeView Policy="PolicyA">
        <Authorized>
            @* Page content *@
        </Authorized>
        <NotAuthorized>
            @{ Navigation.NavigateTo("pageB"); }
        </NotAuthorized>
    </AuthorizeView>
    
    @code {
    
    }