Identity Server 4无限循环 [英] Identity Server 4 Infinite Loop

查看:114
本文介绍了Identity Server 4无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

请在Startup.cs中的代码下面找到

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

下面的IDS中的客户详细信息:

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
                },

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

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.

客户端的启动文件:

 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:信息:请求启动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/主页/联系方式
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

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://本地主机:44307/connect/authorize?client_id = SingleSignOnInternalClient& redirect_uri = https%3A%2F%2Flocalhost%3A44330%2Fsignin-oidc& response_type = id_token& scope = openid%20profi乐&安培; response_mode = form_post&安培;随机数= 636969892902312620.YzUzMWRiNTktN2Q5Mi00NzZiLWJhMjQtNzEzMjI5Mzk1MTE2ZjM5NWQ2NTEtOTQ4Yi00MDljLWIyYzQtNWE5OTA3YWZkMDFj&安培;状态= CfDJ8HSRls71XI5DkQoP2L7ypNS9cYyKsLJm7m1dhd3hXQldeb3Esa0g7uZHU6MiqjlsqTk6h7QaqxXsFuMk05KZfdVdN2qJ9j9v5zVg-BeAFNT5rH_Suq8NUl47VUSfTl6zyrBLxYYgeLn8gfdaQpbmwsynpBuMZ9FR8C8eoVNxyPyQ0nGdBryxybey4QFO1xnwiENQtddWxPexgDBNsAGFNd5l6IYhdHaunWz9Ab7NHS68xdfwORdsNFMJRHtUxAGGhQ08U1WP_-TD2xm1rctVfUFZ_GqoNyc_KDanEmp4AVo5eEF0KgQl6mx4kH0PRMPHeDh3KjZTddKEVQglT0J2Kjo&安培; X-客户SKU = ID_NETSTANDARD1_4&安培; X-客户-VER = 5.2.0.0

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

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.

推荐答案

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

不需要客户端. 除其他事项外,只有您的IdP才有权访问,它会重新配置身份验证方案参数.任何时候您都可以将配置与进行比较.官方资料库中的最低工作人数.

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.

这篇关于Identity Server 4无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆