Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite authentication loop when using identityserver4 in asp.net core 2.0

I have an Identity Server using identityserver4 framework, its url is http://localhost:9000

My web application is asp.net core 2.0, its url is http://localhost:60002. This application will use the login page of Identity Server.

I want after logging in, the Identity Server will redirect to the application page (http://localhost:60002)

Here is the Startup.cs of client application

Startup.cs

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

        public IConfiguration Configuration { get; }

        private string AuthorityUri => Configuration.GetValue<string>("UserManagement-Authority");

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

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect(options =>
            {
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.Authority = AuthorityUri; // "http://localhost:9000"
                options.RequireHttpsMetadata = false;
                options.ClientId = "customer.api";
                options.ClientSecret = "testsecret";
                options.ResponseType = "code id_token";
                options.Scope.Add("customerprivatelinesvn.api");
                options.Scope.Add("offline_access");
                options.GetClaimsFromUserInfoEndpoint = true;
                options.SaveTokens = true;
            });

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();            

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

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
    }

Here is the loggin page on Identity Server

enter image description here

But there is an infinite loop that calls to http://localhost:9000/connect/authorize endpoint, and then it returns to http://localhost:60002/signin-oidc with "Bad Request - Request Too Long" as below.

When I look at the cookies, there ar lots of items ".AspNetCore.Correlation.OpenIdConnect.xxx" enter image description here

Here is the log on Identiy Server. It said that Identiy.Application was successfully authenticated. enter image description here

Does anyone know what this problem is? And how to resolve this? Thank you very much.

Best regards,

Kevin

like image 578
Kevin Hoang Avatar asked Nov 03 '17 16:11

Kevin Hoang


4 Answers

I also had a login loop after copying the startup code from an existing .NET Core 2.2 project and reused it in a new .NET Core 3.1 project.

The problem here was, that the app.UseAuthentication() must be called before the new app.UseAuthorization();

https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#migrate-startupconfigure

Only in case someone is running into this issue too...

like image 150
lordasgart Avatar answered Oct 19 '22 20:10

lordasgart


In my case, I was missing RedirectUri when initiating the Signin from the client. Problem solved by adding the RedirectUri as below.

 public IActionResult SignIn()
        {

            return Challenge(new AuthenticationProperties() { RedirectUri = "/" }, "oidc" );
        }
like image 26
yibe Avatar answered Oct 19 '22 20:10

yibe


In your client app, in Startup check if you have something like

services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

Remove that part and try again.

like image 4
dewebeloper Avatar answered Oct 19 '22 20:10

dewebeloper


Adding default Identity in the client app would cause an infinite redirect loop.

In the client app, if you need to use UserManager, RoleManager.

Then use the below code.

services.AddIdentityCore<IdentityUser>()
                .AddRoles<IdentityRole>()
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddSignInManager<SignInManager<IdentityUser>>()
                .AddEntityFrameworkStores<ApplicationDbContext>();
like image 4
Khalil Avatar answered Oct 19 '22 20:10

Khalil