ASP.NET Core 3.1 [Authorize] attribute redirects to login even for logged in user

8.5k views Asked by At

Ihave an ASP.NET Core sandbox project. I have added IdentityDbContext. Registration page works correct. Login/Logout pages work correct. (It can be seen by html that is shown for SignInManager.IsSignedIn(User) users)

I have a controller marked with [Authorize]:

[Authorize]
public class MyTestController : Controller
{
    ...
}

When I try to navigate to it for the first time - it works correct (redirects to login page)

But after successful login it redirect again back to login with the same link: https://localhost:44359/Identity/Account/Login?ReturnUrl=%2FMyTest

Here is my code from Startup.cs:

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
            services.AddRazorPages().AddRazorRuntimeCompilation();
            services.AddControllers().AddNewtonsoftJson(options =>
            {
                // Use the default property (Pascal) casing
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.AddDbContext<MyAppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
            services.AddDefaultIdentity<IdentityUser>(options =>
                {
                    options.Password.RequireDigit = false;
                    options.Password.RequireLowercase = false;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase = false;
                })
                .AddEntityFrameworkStores<MyAppContext>();

            services.AddAuthorization();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

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

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

Previously I have added scaffolded identity items for Login, Logout, Register. Controller without [Authorize] works good.

1

There are 1 answers

5
Kia Kaha On BEST ANSWER

It seems to me that the order of your middlewares is incorrect. ASP.NET needs to know if a user is first authenticated in order to decide if it is authorized for the request. Try to swap these two:

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

Microsoft's documentation on the subject: Configure Identity