Search code examples
authenticationhttp-redirect.net-coreasp.net-core-mvcasp.net-boilerplate

How to redirect to login page in ABP?


  1. I download the .NET Core sample from ASP.NET Boilerplate website,
  2. change the DB connection string, update DB,
  3. run Web Api, show the Swagger successfully,
  4. add a Home/Index View, change Home/Index action to return the View, not Swagger,
  5. run again, show home page successfully,
  6. then add a Home.Account Controller and Home.Account View, login page.
  7. Add AbpMvcAuthentication attribute on Home/Index, what I want is when access Home, redirect to login page.

When I go to the Home, it shows an empty page, not Home, nor login page. It seems authenticate failed, but did not redirect to login page.

My question is: how to let AbpMvcAuthentication know which page to redirect when authenticate failed?


Solution

  • There is no login page for the *.Web.Host project, where the redirect to Swagger is.

    You should change your Startup Project to *.Web.Mvc instead:

    enter image description here

    If you just want to login, consider using Swagger authentication helpers from the browser console:

    abp.swagger.login();
    

    To answer your question, you can re-enable authentication redirect by reverting commit 92b6270:

    // What it was (and what you want)
    services.AddAuthentication()
        .AddJwtBearer(options =>
    
    // What it is
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = "JwtBearer";
        options.DefaultChallengeScheme = "JwtBearer";
    }).AddJwtBearer("JwtBearer", options =>
    

    Startup.cs:

    app.UseAuthentication();
    
    app.UseJwtTokenMiddleware(); // Add this back
    
    app.UseAbpRequestLocalization();
    

    To be clear, this redirects to a blank page since there is no login page for the *.Web.Host project.

    This is the opposite of the expected behaviour in ABP 401 response from API instead of redirect.

    Also, you can configure login path for redirect:

    You can configure that in Startup.cs:

    IdentityRegistrar.Register(services);
    AuthConfigurer.Configure(services, _appConfiguration);
    
    // Add this line:
    services.ConfigureApplicationCookie(options => options.LoginPath = "/Admin/Login");
    

    Related docs: https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x