Search code examples
asp.net-identityasp.net-core-1.0

ASP.Net Core 1.0.0-preview2 infinite redirect loop


I get infinite redirect loop when I publish application like this:

/Account/Login?ReturnUrl=%2FLPanel3%2FHome%2FError%3FReturnUrl%3D%252FLPanel3%252FHome%252FError%253FReturnUrl%253D%25252FLPanel3%25252FHome%25252FError%25253FReturnUrl%25253D%2525252FLPanel3%2525252FHome%2525252FError%2525253FReturnUrl%2525253D%252525252FLPanel3%252525252FHome%...

But on my Account controller I have [AllowAnonymous] and it doesn't help. My Startup looks like this:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); 

        if (env.IsDevelopment())
        {
            builder.AddUserSecrets();

            builder.AddApplicationInsightsSettings(developerMode: true);
        }
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();

    }

    public IConfigurationRoot Configuration { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddAuthorization(options =>
        {
            options.AddPolicy("AdministratorOnly", policy => policy.RequireRole("Administrator", "Create", "Access", "Manage"));
            options.AddPolicy("Manage", policy => policy.RequireRole("Create", "Access", "Manage"));
            options.AddPolicy("Access", policy => policy.RequireRole("Access"));
        });
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("Connection")));

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            options.Cookies.ApplicationCookie.CookieName = "Cookie";
            options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(1);
            options.Cookies.ApplicationCookie.SlidingExpiration = true;
        })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        }).AddJsonOptions(opt =>
                opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver())
            .AddJsonOptions(opt => opt.SerializerSettings
                .ReferenceLoopHandling = ReferenceLoopHandling.Ignore);


        services.AddLogging();
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
        services.AddScoped<ILPRepository, LPRepository>();
        services.AddTransient<SeedDatabase>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SeedDatabase seeder)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");

            try
            {
                using (var serviceScope =     app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                    .CreateScope())
                {
                    serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                         .Database.Migrate();
                }
            }
            catch { }
        }

        app.UseApplicationInsightsExceptionTelemetry();

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookie",
            LoginPath = new PathString("/Account/Login/"),
            AccessDeniedPath = new PathString("/Account/Forbidden/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true
        });

        app.UseStaticFiles();

        app.UseIdentity();

        app.UseStatusCodePagesWithReExecute("/Home/Errors/{0}");



        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}/{id?}",
                defaults: new { controller = "Home", action = "Index" }
               );
        });

    }

}

I don't have any other libraries that are looking for login, authentication and so on...


Solution

  • I have fixed it with Creating new Web Site in IIS and setting my Anonymous Authentication User to "Application Pool" instead of specific user "IUSR" and also setting https on my app.

    Change Anonymouse user Authentication

    Now it works finally. And Anonymous Authentication must be enabled. This you can configure on launchSettings.json

    "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:60888/",
      "sslPort": 44444
    }},
    

    To enable https you need to confiure it also in startup.cs

     services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                #if !DEBUG
                        config.Filters.Add(new RequireHttpsAttribute());
                #endif
                config.Filters.Add(new AuthorizeFilter(policy));
    
            }).AddJsonOptions(opt =>
                    opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver())
                .AddJsonOptions(opt => opt.SerializerSettings
                    .ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
        }