Home > Blockchain >  Redirect to different part of application in Blazor if user is not authenticated
Redirect to different part of application in Blazor if user is not authenticated

Time:06-17

I'm trying to define a Blazor website that has complete navigation to present the application for non-authenticated users and another completely different navigation for authenticated users.

The idea is that non-authenticated users get to a part of the website that allows anonymous users, with a complete set of pages and navigation. Once they log in, they get to another part of the website which is only for authenticated users with its own navigation.

In addition, I might have two different sets of navigation based on the roles of the users.

For example, an admin might have other views and menus than a standard user.

I have looked at the Routing and navigation documentation, but can't find anything that would allow me to redirect the user based on its authentication state or role to another sub-route with its own MainLayout, etc.

CodePudding user response:

  • App.razor:

      <CascadingAuthenticationState>
        <Router AppAssembly="@typeof(Program).Assembly">
          <Found Context="routeData">
              <AuthorizeRouteView RouteData="@routeData" 
                  DefaultLayout="@typeof(MainLayout)" />
          </Found>
          <NotFound>
              <LayoutView Layout="@typeof(MainLayout)">
                  <p>Sorry, there's nothing at this address.</p>
              </LayoutView>
          </NotFound>
       </Router>
    </CascadingAuthenticationState>
    
  • NavMenu.razor

    <AuthorizeView>
       <Authorized>
          @* For authorized users *@
          <nav>...</nav>
       </Authorized>
       <NotAuthorized>
          @* For unauthorized users *@
          <nav>...</nav>
       </NotAuthorized>
    </AuthorizeView>
    
  • Don't forget to add in Startup or program file this two lines.

    app.UseAuthentication();
    app.UseAuthorization();
    

Microsoft doc

CodePudding user response:

Take a look at this code:

    [Inject]
    public NavigationManager Navigator { get; set; }

    [Inject]
    private IHttpContextAccessor HttpContextAccessor { get; set; }

    public void DoSomething()
    {
        if (HttpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
        {
            Navigator.NavigateTo("/SecretPage");
        }
        else
        {
            Navigator.NavigateTo("/PublicPage");
        }
    }

Don't forget to add this to your startup file: services.AddHttpContextAccessor(); That will make sure IHttpContextAccessor can be injected.

NaviationManager does not need to be manually injected.

  • Related