14

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

Kevin Hoang
  • 922
  • 1
  • 10
  • 25

7 Answers7

22

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...

lordasgart
  • 331
  • 2
  • 4
6

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>();
Khalil
  • 1,047
  • 4
  • 17
  • 34
  • Thank you for this! Put an end to days of beating my head against a wall! Do you have any info on *why* this change works? Or somewhere I could go to find it? Again, thanks! – TwainJ Jan 27 '21 at 23:52
  • AddDefaultIdentity Adds a set of common identity services to the application, including a default UI, token providers, and configures authentication to use identity cookies. It basically redirects to the authentication server if you visit a protected route but you are already authenticated so the authentication server redirects backs. Due to this end less loop occurs. – Khalil Jan 28 '21 at 15:55
4

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.

dewebeloper
  • 43
  • 1
  • 9
  • What if this is needed? I have a "manage authentication application" which has needs to be authenticated using sso. – jwize May 22 '19 at 03:50
  • 1
    This fixed my issue, i was migrating from identity framework to identity server and left the defaultIdentityUI lines. – Abhishek Siddhu Jul 01 '19 at 16:11
2

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" );
        }
yibe
  • 338
  • 3
  • 7
0

Well, you do have a very long request shown there in your Identity Server log - and the error says "Bad Request - request too long". I'd guess that the problem is that your request is too big :) maximum length of HTTP GET request?

Have you tried posting rather than using a GET?

Mashton
  • 6,037
  • 2
  • 25
  • 35
0

This issue was solved after I updated the latest nuget package of IdentityServer4 and .NET Core.

Kevin Hoang
  • 922
  • 1
  • 10
  • 25
0

It happend to me in Azure Portal and IdentityServer4 at the same time. Cause: I changed the local DATE in my PC in order to test a recurring billing and I forgot it. When I tried to login into Azure portal or into my Identity Server, it entered in a Infinite authentication loop.

Solution: Local PC -> Control Panel -> Date & time settings -> Set time automatically on

I hope it helps