Search code examples
c#asp.net-core-mvcasp.net-core-identity

How to directly display login screen on welcome/start page in ASP.NET Core 6 MVC app?


I work on my first project, app based on ASP.NET Core 6 MVC with default identity Razor pages. I'm working on .NET 6 and using EF Core 6. The app is a customer management system and it's for internal use only.

I have implemented scaffolded identity, it works properly when accessing by its route: /Identity/Account/Login but the question is: how to display login form on welcome / home page, protecting all other content except login form from unauthorized access? I mean the user who enters: mydomain.com should see only login/register page.

I.e.: when I place [Authorize] attribute on the HomeController, it doesn't redirect me to the login page, I just get a http 404 error. So is it a matter of authorization, routing issue or just HTML layout topic?

I have dug through tons of posts and couldn't find the answer. Maybe I misunderstood the problem?

Regards, Kristo


Solution

  • Add the below code in the startup file this will help you navigates mydomain.com to the Login page.

     app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages(options =>
        {
            options.Conventions.AddPageRoute("/Identity/Account/Login", "");
        });
    });
    

    If you want to protect all other content, you can use the [Authorize] attribute at a global level.

    services.AddAuthorization(options =>
    {
        options.FallbackPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
    });
    

    You have to allow the access to the user for the login or registration page add the [AllowAnonymous] attribute in the PageModel class.

    regarding the 404 error seems like system does not know where to redirect unauthorized users.by using below code it will redirect unauthorized user to the login page.

    services.ConfigureApplicationCookie(options =>
    {
        options.LoginPath = "/Identity/Account/Login";
    });