ASP.NET Core Web Application different landing page based on role

Jimmy Tsang 20 Reputation points
2023-05-19T19:25:45.6166667+00:00

I have an ASP.NET Core web application, and it is configured to authenticate with Microsoft identity platform. Users are assigned different role. My question is based on the user's role, how do I configure the application to redirect user to different landing page after they are authenticate.

  • Admin users will land on ./admin/index.
  • Non-admin will land on ./index
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Vahid Ghafarpour 23,385 Reputation points Volunteer Moderator
    2023-05-19T19:35:59.4966667+00:00

    You need to configure Authentication middleware in the Startup.cs

    // Inside ConfigureServices method
    services.AddAuthentication()
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
    
    services.AddAuthorization(options =>
    {
        options.AddPolicy("AdminOnly", policy =>
            policy.RequireRole("Admin"));
    });
    

    and next in the authentication callback, redirect to where you prefer (e.g. OnAuthenticated or OnTokenValidated)

    // Inside the authentication callback method
    var user = context.Principal;
    if (user.IsInRole("Admin"))
    {
        context.Response.Redirect("/admin/index");
    }
    else
    {
        context.Response.Redirect("/index");
    }
    
    
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.