Search code examples
c#asp.net-identitygoogle-oauthasp.net-core-3.0asp.net-authorization

Infinite login redirect loop with Google and ASP.NET Core Identity


I've hit a redirect loop when trying to access a page behind an Authorize attribute in Net Core 3 no matter whether I am signed in or if the user has permissions. I've followed the MSDN tutorials and done some searching but have yet to find a solution to my issue. I suspect that it isn't recognizing my identity cookie or somehow it isn't redirecting to the right page but I need some guidance on what to look for.

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<GuitarCatalogMVCContext>(options =>
                options.UseSqlite( Configuration.GetConnectionString("DefaultConnection")));


            services.AddIdentity<GuitarCatalogAuthUser, IdentityRole>().AddEntityFrameworkStores<GuitarCatalogMVCContext>().AddDefaultTokenProviders();

            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddGoogle(options =>
            {
                IConfigurationSection googleAuthNSection = Configuration.GetSection("Authentication:Google");

                options.ClientId = googleAuthNSection["ClientId"];
                options.ClientSecret = googleAuthNSection["ClientSecret"];
                options.CallbackPath = new PathString("/signin-google");
            });

            services.AddAuthorization();
        }

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            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();
            });
        }

Using the Google login at /Identity/Account/Login, I get the proper prompt, I can successfully login, and the url is:

https://accounts.google.com/signin/oauth/oauthchooseaccount? 
response_type=code &client_id= ______ 
&redirect_uri=https%3A%2F%2Flocalhost%3A44346%2Fsignin-google 
&scope=openid%20profile%20email &state= _______ &flowName=GeneralOAuthFlow

When I open a controller method behind an [Authorize] attribute, via <a href="@Url.Action("Create", "Listings")" target="_blank"><h1>TEST CREATE LISTING</h1></a>, it signs me in and then brings me immediately back to the same page

I opened the Network tab in Dev Tools and here I can see where my sign in was processed, it took me to the Create page, and then I ended up back at the sign in page. I don't see anything that shows that my sign in failed (or why it is prompting me again to sign in when I am signed in).

enter image description here


Solution

  • It seems that the issue is in the middleware execution order.

    app.UseAuthorization() should be executed after app.UseAuthentication()

    In your current implementation since the authorization middleware is executed first, the User object is never set and therefore all requests appear to be unauthorized.