当前位置: 首页 > 知识库问答 >
问题:

Identity server在成功登录后不重定向

鲁德佑
2023-03-14

我正在尝试使用MVC客户端设置IdentityServer4。

一切正常,直到我想添加ASP身份。当我添加代码以使用SQL server和Identity时,成功登录后,Identity server不会将我重定向回客户端,但它只是“刷新”页面。

IdentityServer应用程序启动:

 public class Startup
    {
        public IWebHostEnvironment Environment { get; }

        public IConfiguration Configuration { get; }

        public Startup(IWebHostEnvironment environment, IConfiguration configuration)
        {
            Environment = environment;
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            // uncomment, if you want to add an MVC-based UI
            services.AddControllersWithViews();

            services.AddDbContext<NebankaDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<NebankaUser, IdentityRole>()
               .AddEntityFrameworkStores<NebankaDbContext>()
               .AddDefaultTokenProviders();

            services.AddAuthentication()
                .AddGoogle("Google", options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                    options.ClientId = "695872592852-tc9u84trcicjuhrrei1ikdmriarl3gmf.apps.googleusercontent.com";
                    options.ClientSecret = "sVDWez0nZHEzLiSyx165YToF";
                });

            var builder = services.AddIdentityServer()
                .AddInMemoryIdentityResources(Config.Ids)
                .AddInMemoryApiResources(Config.Apis)
                .AddInMemoryClients(Config.Clients)
                .AddTestUsers(TestUsers.Users);

            if (Environment.IsDevelopment())
            {
                // not recommended for production - you need to store your key material somewhere secure
                builder.AddDeveloperSigningCredential();
            }
        }

        public void Configure(IApplicationBuilder app)
        {
            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // uncomment if you want to add MVC
            app.UseStaticFiles();
            app.UseRouting();

            app.UseIdentityServer();

            // uncomment, if you want to add MVC
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }

在IdentityServer中配置

   public static class Config
    {
        public static IEnumerable<IdentityResource> Ids =>
           new List<IdentityResource>
           {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
           };

        public static IEnumerable<ApiResource> Apis =>
            new List<ApiResource>
            {
                new ApiResource("nebankaApi", "Nebanka API")
            };

        public static IEnumerable<Client> Clients =>
            new List<Client>
            {
                new Client
                {
                    ClientId = "client",

                    // no interactive user, use the clientid/secret for authentication
                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    // secret for authentication
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    // scopes that client has access to
                    AllowedScopes = { "nebankaApi" }
                },
                 // interactive ASP.NET Core MVC client
              new Client
                {
                    ClientId = "mvc",
                    ClientSecrets = { new Secret("secret".Sha256()) },

                    AllowedGrantTypes = GrantTypes.Code,
                    RequireConsent = false,
                    RequirePkce = true,

                    // where to redirect to after login
                    RedirectUris = { "http://localhost:5002/signin-oidc" },

                    // where to redirect to after logout
                    PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

                    AllowedScopes = new List<string>
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "nebankaApi"
                    },

                    AllowOfflineAccess = true
                },
                // JavaScript Client
                new Client
                {
                    ClientId = "js",
                    ClientName = "JavaScript Client",
                    AllowedGrantTypes = GrantTypes.Code,
                    RequirePkce = true,
                    RequireClientSecret = false,

                    RedirectUris =           { "http://localhost:5003/callback.html" },
                    PostLogoutRedirectUris = { "http://localhost:5003/index.html" },
                    AllowedCorsOrigins =     { "http://localhost:5003" },

                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "nebankaApi"
                    }
                }
            };

    }

在MVC客户端中启动:

 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)
        {
            services.AddControllersWithViews();

            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
             .AddCookie("Cookies")
             .AddOpenIdConnect("oidc", options =>
             {
                 options.Authority = "http://localhost:5000";
                 options.RequireHttpsMetadata = false;

                 options.ClientId = "mvc";
                 options.ClientSecret = "secret";
                 options.ResponseType = "code";

                 options.SaveTokens = true;

                 options.Scope.Add("nebankaApi");
                 options.Scope.Add("offline_access");
             });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute()
                    .RequireAuthorization();
            });
        }
    }

来自IdentityServer的日志:

[20:08:35 Information] IdentityServer4.Startup
Using the default authentication scheme Identity.Application for IdentityServer

[20:08:35 Debug] IdentityServer4.Startup
Using Identity.Application as default ASP.NET Core scheme for authentication

[20:08:35 Debug] IdentityServer4.Startup
Using Identity.External as default ASP.NET Core scheme for sign-in

[20:08:35 Debug] IdentityServer4.Startup
Using Identity.External as default ASP.NET Core scheme for sign-out

[20:08:35 Debug] IdentityServer4.Startup
Using Identity.Application as default ASP.NET Core scheme for challenge

[20:08:35 Debug] IdentityServer4.Startup
Using Identity.Application as default ASP.NET Core scheme for forbid

[20:11:52 Debug] IdentityServer4.Startup
Login Url: /Account/Login

[20:11:52 Debug] IdentityServer4.Startup
Login Return Url Parameter: ReturnUrl

[20:11:52 Debug] IdentityServer4.Startup
Logout Url: /Account/Logout

[20:11:52 Debug] IdentityServer4.Startup
ConsentUrl Url: /consent

[20:11:52 Debug] IdentityServer4.Startup
Consent Return Url Parameter: returnUrl

[20:11:52 Debug] IdentityServer4.Startup
Error Url: /home/error

[20:11:52 Debug] IdentityServer4.Startup
Error Id Parameter: errorId

[20:11:52 Debug] IdentityServer4.Hosting.EndpointRouter
Request path /.well-known/openid-configuration matched to endpoint type Discovery

[20:11:52 Debug] IdentityServer4.Hosting.EndpointRouter
Endpoint enabled: Discovery, successfully created handler: IdentityServer4.Endpoints.DiscoveryEndpoint

[20:11:52 Information] IdentityServer4.Hosting.IdentityServerMiddleware
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryEndpoint for /.well-known/openid-configuration

[20:11:52 Debug] IdentityServer4.Endpoints.DiscoveryEndpoint
Start discovery request

[20:11:54 Debug] IdentityServer4.Hosting.EndpointRouter
Request path /.well-known/openid-configuration/jwks matched to endpoint type Discovery

[20:11:54 Debug] IdentityServer4.Hosting.EndpointRouter
Endpoint enabled: Discovery, successfully created handler: IdentityServer4.Endpoints.DiscoveryKeyEndpoint

[20:11:54 Information] IdentityServer4.Hosting.IdentityServerMiddleware
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryKeyEndpoint for /.well-known/openid-configuration/jwks

[20:11:54 Debug] IdentityServer4.Endpoints.DiscoveryKeyEndpoint
Start key discovery request

[20:11:55 Debug] IdentityServer4.Hosting.EndpointRouter
Request path /connect/authorize matched to endpoint type Authorize

[20:11:55 Debug] IdentityServer4.Hosting.EndpointRouter
Endpoint enabled: Authorize, successfully created handler: IdentityServer4.Endpoints.AuthorizeEndpoint

[20:11:55 Information] IdentityServer4.Hosting.IdentityServerMiddleware
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize

[20:11:55 Debug] IdentityServer4.Endpoints.AuthorizeEndpoint
Start authorize request

[20:11:55 Debug] IdentityServer4.Endpoints.AuthorizeEndpoint
No user present in authorize request

[20:11:55 Debug] IdentityServer4.Validation.AuthorizeRequestValidator
Start authorize request protocol validation

[20:11:55 Debug] IdentityServer4.Stores.ValidatingClientStore
client configuration validation for client mvc succeeded.

[20:11:55 Debug] IdentityServer4.Validation.AuthorizeRequestValidator
Checking for PKCE parameters

[20:11:55 Debug] IdentityServer4.Validation.AuthorizeRequestValidator
Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator

[20:11:55 Debug] IdentityServer4.Endpoints.AuthorizeEndpoint
ValidatedAuthorizeRequest
{"ClientId": "mvc", "ClientName": null, "RedirectUri": "http://localhost:5002/signin-oidc", "AllowedRedirectUris": ["http://localhost:5002/signin-oidc"], "SubjectId": "anonymous", "ResponseType": "code", "ResponseMode": "form_post", "GrantType": "authorization_code", "RequestedScopes": "openid profile nebankaApi offline_access", "State": "CfDJ8KeCHJ_-ej5DnjBMTWwd_H8hfePOTfTcHK-UDHHk9nqRCxUMx2jxOiz8v94UCXVmzdJSKXUx6GdUSQxahek27lZnaTjs9NfaF2dEV8hlMMYEhqN35inWKVjJvpv-C07e8XIlvzYTtXcecWr6sPWI6gnmBp2BBq5xKjMzMxV7MfCkdeicQM51SkIayK_JvJQBdecLTjwZYyfOV6TaBeHcqRZlfBQjFKc4VPhj5NcyB3tg5Uz2iUtA7GpB_mwPlw7BuQ1TL7x7e1xePt3IHrqICwwhY01rismagjE2gNF8Rt9L6O1J_rP1gQFzLErd4GYT5lUmoYct126WMUONQpZ5abeDF4XCQvlcSI1wWdlOk3Y3SCPL3hrk358h2QorMtBu2w", "UiLocales": null, "Nonce": "637081459147499481.YjVmODliMWEtMDE5Yy00NDU2LWEwNzgtNjIzZjFiNjZkY2FlOTBhOTRiNzUtYmJmNy00MDQ2LTgyNTItY2RjYjgwYzVmY2Vj", "AuthenticationContextReferenceClasses": null, "DisplayMode": null, "PromptMode": null, "MaxAge": null, "LoginHint": null, "SessionId": null, "Raw": {"client_id": "mvc", "redirect_uri": "http://localhost:5002/signin-oidc", "response_type": "code", "scope": "openid profile nebankaApi offline_access", "code_challenge": "kYtJXHUEOvcgjMxHkSZ37Bli176hsMFhoOqSzgr6-e0", "code_challenge_method": "S256", "response_mode": "form_post", "nonce": "637081459147499481.YjVmODliMWEtMDE5Yy00NDU2LWEwNzgtNjIzZjFiNjZkY2FlOTBhOTRiNzUtYmJmNy00MDQ2LTgyNTItY2RjYjgwYzVmY2Vj", "state": "CfDJ8KeCHJ_-ej5DnjBMTWwd_H8hfePOTfTcHK-UDHHk9nqRCxUMx2jxOiz8v94UCXVmzdJSKXUx6GdUSQxahek27lZnaTjs9NfaF2dEV8hlMMYEhqN35inWKVjJvpv-C07e8XIlvzYTtXcecWr6sPWI6gnmBp2BBq5xKjMzMxV7MfCkdeicQM51SkIayK_JvJQBdecLTjwZYyfOV6TaBeHcqRZlfBQjFKc4VPhj5NcyB3tg5Uz2iUtA7GpB_mwPlw7BuQ1TL7x7e1xePt3IHrqICwwhY01rismagjE2gNF8Rt9L6O1J_rP1gQFzLErd4GYT5lUmoYct126WMUONQpZ5abeDF4XCQvlcSI1wWdlOk3Y3SCPL3hrk358h2QorMtBu2w", "x-client-SKU": "ID_NETSTANDARD2_0", "x-client-ver": "5.5.0.0"}, "$type": "AuthorizeRequestValidationLog"}

[20:11:55 Information] IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator
Showing login: User is not authenticated

[20:11:55 Debug] IdentityServer4.Validation.AuthorizeRequestValidator
Start authorize request protocol validation

我只想被重定向回客户端与记录的用户身份设置。

你能给我推荐一些网站或书籍来进一步学习IdentityServer和openId吗?

谢啦

共有1个答案

景远航
2023-03-14

从客户端配置中的权限url判断:

.AddOpenIdConnect("oidc", options =>
{
    options.Authority = "http://localhost:5000";

为了使IDP服务器在chrome中工作,您必须使用HTTPS,或者将cookie策略选项设置为Lax或Strict:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCookiePolicy(new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.Strict });
}

更新:

自2019年5月起,Chrome为cookies link推出了默认安全模式:

开发者必须使用一个新的cookie设置,SameSite=None,为跨站点访问指定cookie。当SameSite=None属性存在时,必须使用额外的安全属性,以便只能通过HTTPS连接访问跨站点Cookie。

 类似资料:
  • MvcConfig方法如下所示:

  • 我正在我是身份提供者的地方实施SSO,现在我能够成功登录到服务提供者。但它把我带到了主页。我想在发布响应时指定着陆页URL。搜索了很多,但找不到任何令人信服的东西。不太知道SAML响应的哪个元素携带着陆页URL或采用我必须指定的形式。使用java和opensaml库生成响应。

  • 问题内容: 我知道之前曾有人问过这个问题,但是我在这里面临一个特殊的问题。 我使用Spring Security 3.1.3。 我的Web应用程序中有3种可能的登录案例: 通过登录页面登录:确定。 通过受限页面登录:也可以。 通过非受限页面登录:不好,…每个人都可以访问“产品”页面,并且用户可以在登录后发表评论。因此,同一页面中包含一个登录表单,以允许用户进行连接。 情况3)的问题是我无法设法将用

  • 我知道这个问题以前有人问过,但我现在面临一个特殊的问题。 我使用spring security 3.1.3。 我的web应用程序中有3种可能的登录情况: 通过登录页登录:确定。 通过受限页面登录:也可以。 通过非受限页面登录:不确定...每个人都可以访问“产品”页面,如果用户已经登录,他可以发表评论。因此登录表单包含在同一页面中,以便允许用户进行连接。 案例3)的问题是,我无法将用户重定向到“产品

  • 下面是我的app.js代码,Login.js登录页面位于http://localhost:3000/Login,所以如果用户成功登录,我如何将用户重定向到http://localhost:3000/home page,它加载了“homeComponent.jsx”。为了简洁起见,我省略了“homeComponent.jsx”的代码

  • 我在模态窗口中有登录表单。成功登录后,用户被重定向到< code>/页面。我正试图找到一种方法,在登录后留在联系页面或另一个页面。如何做到这一点?我的代码是: