Идентификационный сервер не перенаправляет после успешного входа в систему - PullRequest
0 голосов
/ 31 октября 2019

Я пытаюсь настроить IdentityServer4 с клиентом MVC.

Все работает, пока я не хочу добавить ASP Identity. Когда я добавил код для использования SQL-сервера и 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?

Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...