Identity Server 4无限循环

时间:2019-06-24 16:18:11

标签: c# asp.net-mvc asp.net-core single-sign-on identityserver4

我正在处理一个ASP.NET Core 2.1项目,该项目中安装了身份服务器4,并且使用实体框架将用户存储在SQL数据库中。成功登录后,该Web项目将具有一个登录页面和一个仪表板。

请在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?}");
        });
    }

下面的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
                },

我已经使用asp.net core 2.1创建了一个客户端项目,并在联系页面(家庭控制器)中授权了属性。 当我们单击联系人页面时,它将重定向到安装了身份服务器以及成功进行用户授权的另一个项目的“登录”页面。页面被重定向到无限循环。

客户端的启动文件:

 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?}");
        });
    }
}

客户端输出日志(无限重定向循环):

  

Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动HTTP / 1.1 POST http://localhost:44330/signin-oidc application / x-www-form-urlencoded 1473   Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:信息:AuthenticationScheme:登录的cookie。   Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求在5.4353ms中完成302   Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动HTTP / 1.1 GET http://localhost:44330/Home/Contact
  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:路由与{action =“ Contact”,controller =“ Home”,page =“”,area =“”}匹配。在控制器IdentityTestClient.Controllers.HomeController(IdentityTestClient)上使用签名Microsoft.AspNetCore.Mvc.IActionResult Contact()执行控制器动作。   Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:授权失败。   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:过滤器“ Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter”上的请求授权失败。   Microsoft.AspNetCore.Mvc.ChallengeResult:信息:使用身份验证方案()执行ChallengeResult。   Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:信息:AuthenticationScheme:oidc受到了质询。   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information:执行的动作IdentityTestClient.Controllers.HomeController.Contact(IdentityTestClient)在8.3527毫秒内   Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求在17.5244ms中完成302

下面是无限循环的网址,

  

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

两个项目都将SSL配置为在本地运行https。

我正在尝试实现一个单一登录解决方案,该解决方案在不同域中具有多个网站,并使用身份服务器进行登录。 任何输入将不胜感激。

2 个答案:

答案 0 :(得分:2)

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

不需要客户端。 除其他事项外,只有您的IdP才有权访问,它会重新配置身份验证方案参数。任何时候您都可以将配置与官方存储库中的minimum working one进行比较。

答案 1 :(得分:0)

就我而言,问题是两个应用程序(IS4和我的api)都使用了http。登录后(并在浏览器中打开该会话),我将两个应用程序都移至了SSL。然后循环开始了。 我的解决方案是删除所有cookie。