Identity server does not redirect after sucessfull login

夙愿已清 提交于 2021-01-28 01:46:13

问题


I am trying to set up IdentityServer4 with MVC client.

Everything works fine until I want to add ASP Identity. When I added code to use SQL server and Identity, after sucessfull login Identity server does not redirects me back to my client, but it just "refreshes" the page.

IdentityServer app startup:

 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();
            });
        }
    }

Config in 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"
                    }
                }
            };

    }

Startup in MVC 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)
        {
            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();
            });
        }
    }

Logs from 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

I just want to be redirected back to client with logged user identity set up.

Can you please recomend me some websites or books for further study of IdentityServer and openId?

Thanks


回答1:


Judging from your authority url inside the client configuration:

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

In order for the IDP server to work in chrome you must use HTTPS, Or set the cookie policy option to Lax or Strict:

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

Update:

As of 05/2019 Chrome introduced a secure-by-default model for cookies link:

Developers must use a new cookie setting, SameSite=None, to designate cookies for cross-site access. When the SameSite=None attribute is present, an additional Secure attribute must be used so cross-site cookies can only be accessed over HTTPS connections.



来源:https://stackoverflow.com/questions/58650159/identity-server-does-not-redirect-after-sucessfull-login

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