Identity Server 4 Infinite Loop

柔情痞子 提交于 2020-01-24 18:00:50

问题


I'm working on a asp.net core 2.1 project with identity server 4 installed in it and the users stored in SQL database using entity framework. The Web project has a login page and a dashboard once login is successful.

Please find below the code in Startup.cs,

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

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        services.AddMvc();

        services.AddDbContext<ApplicationDbContext>(builder =>
            builder.UseSqlServer(connectionString, sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly)));

        services.AddDbContext<SingleSignOn_dbContext>(builder =>
            builder.UseSqlServer(connectionString));

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

        services.AddIdentityServer(options =>
        {
            options.UserInteraction.LoginUrl = "/Master/Login"; // Set the default login page for Identity server.
        }).AddOperationalStore(options =>
                options.ConfigureDbContext = builder =>
                   builder.UseSqlServer(connectionString, sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly)))

            .AddConfigurationStore(options =>
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connectionString, sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly)))
            .AddAspNetIdentity<IdentityUser>()
            .AddDeveloperSigningCredential();

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // 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();
        }
        else
        {
            app.UseExceptionHandler("/Master/Error");
            app.UseHsts();
        }

        // Only need to run this once.
        InitializeDbTestData(app);

        app.UseIdentityServer();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

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

Client Details below in IDS:

 new Client {
                    ClientId = "SingleSignOnInternalClient",
                    ClientName = "Example Implicit Client Application",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowAccessTokensViaBrowser = true,
                    AllowedScopes = new List<string>
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Email,
                        "role",
                        "customAPI.write"
                    },
                    AllowedCorsOrigins = new List<string> {"192.168.6.112"},
                    RedirectUris = new List<string> {"https://localhost:44330/signin-oidc"},  // Configuration.GetSection("TestClient").GetSection("RedirectURL").Value
                    PostLogoutRedirectUris = new List<string> {"https://localhost:44330"},
                    RequireConsent = false,
                    AllowRememberConsent = false,
                    AccessTokenType = AccessTokenType.Jwt
                },

I've created a client project using asp.net core 2.1 and authorize attribute in the contact page (Home controller). When we clicked on the contact page, it redirects to the Login page of the other project where identity server is installed and when successful user authorization is made. The page is redirected to an infinite loop.

Startup file of client:

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

    public IConfiguration Configuration { get; }

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

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

        // Use cooking authentication for signing in users.
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "cookie";
            options.DefaultChallengeScheme = "oidc";
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;

        })
        .AddCookie("cookie")
        .AddOpenIdConnect("oidc", options =>
        {
            options.Authority = Configuration.GetValue<string>("Authority:EndPoint");    //services.Configure<"Authority">(Configuration.GetSection("EndPoint"));
            options.ClientId = "SingleSignOnInternalClient";
            options.SignInScheme = "cookie";
            options.SaveTokens = true;
            //options.GetClaimsFromUserInfoEndpoint = true;    
            options.RequireHttpsMetadata = false;
        });

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddMvc(options =>
        {
            ///options.Filters.Add

        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // 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.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

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

Output Log in Client(infinite redirect Loop):

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:44330/signin-oidc application/x-www-form-urlencoded 1473 Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: cookie signed in. Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 5.4353ms 302 Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44330/Home/Contact
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Contact", controller = "Home", page = "", area = ""}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Contact() on controller IdentityTestClient.Controllers.HomeController (IdentityTestClient). Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'. Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes (). Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:Information: AuthenticationScheme: oidc was challenged. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action IdentityTestClient.Controllers.HomeController.Contact (IdentityTestClient) in 8.3527ms Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 17.5244ms 302

The Url of the infinite loop is below,

https://localhost:44307/connect/authorize?client_id=SingleSignOnInternalClient&redirect_uri=https%3A%2F%2Flocalhost%3A44330%2Fsignin-oidc&response_type=id_token&scope=openid%20profile&response_mode=form_post&nonce=636969892902312620.YzUzMWRiNTktN2Q5Mi00NzZiLWJhMjQtNzEzMjI5Mzk1MTE2ZjM5NWQ2NTEtOTQ4Yi00MDljLWIyYzQtNWE5OTA3YWZkMDFj&state=CfDJ8HSRls71XI5DkQoP2L7ypNS9cYyKsLJm7m1dhd3hXQldeb3Esa0g7uZHU6MiqjlsqTk6h7QaqxXsFuMk05KZfdVdN2qJ9j9v5zVg-BeAFNT5rH_Suq8NUl47VUSfTl6zyrBLxYYgeLn8gfdaQpbmwsynpBuMZ9FR8C8eoVNxyPyQ0nGdBryxybey4QFO1xnwiENQtddWxPexgDBNsAGFNd5l6IYhdHaunWz9Ab7NHS68xdfwORdsNFMJRHtUxAGGhQ08U1WP_-TD2xm1rctVfUFZ_GqoNyc_KDanEmp4AVo5eEF0KgQl6mx4kH0PRMPHeDh3KjZTddKEVQglT0J2Kjo&x-client-SKU=ID_NETSTANDARD1_4&x-client-ver=5.2.0.0

Both the projects have SSL configured to run https locally.

I'm trying to achieve a single sign on solution which has multiple websites in different domain and using the Identity server for login. Any inputs will be much appreciated.


回答1:


services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>();

is not needed client side. Beyond the other things, only your IdP should have access to, it re-configures your auth scheme parameters. Anytime you can compare your configuration with the minimum working one from the official repository.



来源:https://stackoverflow.com/questions/56740490/identity-server-4-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!