1

I use Asp.Net Core 3.0.1 and I need to force redirect to Identity Login Page, but, the problem after I changed the startup configuration it still redirect me to /Home/Index page, and here is my startup class code:

public class Startup
{
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    //Conection Provider for Identity
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("yourConnection")));

    services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();


    services.AddMemoryCache();


    services.Configure<IdentityOptions>(options =>
    {
        //Password Settings
        options.Password.RequireDigit = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = true;
        options.Password.RequireUppercase = true;
        options.Password.RequiredLength = 8;
        options.Password.RequiredUniqueChars = 1;

        //Lockout Settings
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
        options.Lockout.MaxFailedAccessAttempts = 3;
        options.Lockout.AllowedForNewUsers = true;

        //User settings
        options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+#";
        options.User.RequireUniqueEmail = true;

    });

    //Configure application cookie
    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(1);
        options.LoginPath = "/Login";
        options.LogoutPath = "/Logout";
        options.AccessDeniedPath = "/AccessDenied";
        options.SlidingExpiration = true;
    });


    services.AddMvc(options =>
    {
        options.EnableEndpointRouting = false;
    })
    .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0)
    .AddSessionStateTempDataProvider();


    services.AddDistributedMemoryCache();
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(1);
    });


    services.AddTransient<IEmailSender, EmailSender>(i =>
        new EmailSender(
            Configuration["EmailSender:Host"],
            Configuration.GetValue<int>("EmailSender:Port"),
            Configuration.GetValue<bool>("EmailSender:EnableSSL"),
            Configuration["EmailSender:UserName"],
            Configuration["EmailSender:Password"]
        ));

    services.AddControllersWithViews();
    services.AddRazorPages(options =>
    {
        options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
    });

}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();


    app.UseRouting();

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

    app.UseSession();
    app.UseMvc(routes =>
    {
        //routes.MapRoute(
        //    name: "Identity",
        //    template: "Identity/{controller=Account}/{action=Login}/{id?}");

        routes.MapAreaRoute(
            name: "Identity",
            areaName: "Identity",
            template: "Identity/{controller=Account}/{action=Login}/{id?}");


    });

    app.UseCookiePolicy();

    CreateRoles(serviceProvider).Wait();
    RotativaConfiguration.Setup((Microsoft.AspNetCore.Hosting.IHostingEnvironment) env);

}

How can I force my application to startup with /Account/Login in Identity area?

Here is some link I searched in the same problem:

  1. Redirect to login when unauthorized in ASP.NET Core

  2. https://wakeupandcode.com/authentication-authorization-in-asp-net-core-razor-pages/

  3. https://dotnetcoretutorials.com/2017/09/16/cookie-authentication-asp-net-core-2-0/

3
  • Your code is one mix of legacy and endpoint routing. Good chance that code is ignored because of that. Try to remove the old code (AddMvc, EnableEndpointRouting = false, UseMvc) and migrate to EndpointRouting (UseEndpoints). You already have AddControllersWithViews, combined with AddRazorPages (no need for AddMvc). Check the documentation.
    – user4864425
    Oct 17, 2019 at 22:52
  • In general, defining template routes do not force the user to the login page. The only thing that does, is when the user hits a secured page. So in order to redirect an anonymous user to the login page, is to add a global filter that requires that. For AddControllersWithViews: options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())), and for RazorPages probably some convention. This will only work for anonymous users, which is I assume the purpose.
    – user4864425
    Oct 17, 2019 at 22:55
  • For an exact order check the documentation.
    – user4864425
    Oct 17, 2019 at 23:08

3 Answers 3

2

I use netcore 3.0 too.

My differences between on you code

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

Mycode is working on when cookie is not valid. I use cookie like this

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.Cookie.Name = "<Your cookiename>";
                    options.LoginPath = "auth/login";//This should login page path
                    options.LogoutPath = "auth/logout";//This should logout page path
                    options.ExpireTimeSpan = TimeSpan.FromDays(1);
                    options.SlidingExpiration = false;
                });

I Hope it's help :)

4
  • I tried to apply but, I phased one problem, this code gives me error configuration.Cookie.CoookieName; configuration.Cookie.LoginPath;
    – ali
    Oct 15, 2019 at 13:00
  • Ohh no, configuration.Cookie just my code peace ali, sorry about that. You have to edit your configuration. Ex: options.LoginPath = "auth/login" options.LogoutPath="auth/logout" I am editing my answer to more clear
    – cancmrt
    Oct 15, 2019 at 13:36
  • In migration guide we don't use UseMvc anymore, we use UseEndpoints instead, you can look in learn.microsoft.com/tr-tr/aspnet/core/migration/…
    – cancmrt
    Oct 15, 2019 at 14:08
  • Thank you for your answer, but, until now The problem still there.
    – ali
    Oct 16, 2019 at 4:51
1

I have similar issue, after wasting hours, I solved this by putting [Authorized] attribute on top of the class. I hope I've helped someone on this. :)

[Authorize]
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {

    }
}
0

I have had that problem before, in the .net core 2.2 and I fixed it in the launchSettings.json file as you can see in Microsoft Docs

It seems to work for version 3 as well, as you can see in the example below for multiple environments:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:54339/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_My_Environment": "1",
        "ASPNETCORE_DETAILEDERRORS": "1",
        "ASPNETCORE_ENVIRONMENT": "Staging"
      }
    },
    "EnvironmentsSample": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Staging"
      },
      "applicationUrl": "http://localhost:54340/"
    },
    "Kestrel Staging": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_My_Environment": "1",
        "ASPNETCORE_DETAILEDERRORS": "1",
        "ASPNETCORE_ENVIRONMENT": "Staging"
      },
      "applicationUrl": "http://localhost:51997/"
    }
  }
}

In my case I had to add "launchUrl": "my url"

Like the following snippet:

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true,
    "iisExpress": {
      "launchUrl": "[your url here]"
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "[your url here]",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.