PostLogoutRedirectUri всегда равен нулю в удостоверении Server 4 с SPA (клиент Angular 7 OIDC) - PullRequest
0 голосов
/ 18 декабря 2018

Использование аутентификации входа в Facebook в приложении angular с сервером идентификации. 4. При выходе из системы PostLogoutRedirectUri, ClientName, LogoutId всегда равен нулю.

private async Task<LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId)
    {
        // get context information (client name, post logout redirect URI and iframe for federated signout)
        var logout = await _interaction.GetLogoutContextAsync(logoutId);

        var vm = new LoggedOutViewModel
        {
            AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut,
            PostLogoutRedirectUri = logout?.PostLogoutRedirectUri,
            ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName,
            SignOutIframeUrl = logout?.SignOutIFrameUrl,
            LogoutId = logoutId
        };

        if (User?.Identity.IsAuthenticated == true)
        {
            var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value;
            if (idp != null && idp != IdentityServer4.IdentityServerConstants.LocalIdentityProvider)
            {
                var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp);
                if (providerSupportsSignout)
                {
                    if (vm.LogoutId == null)
                    {
                        // if there's no current logout context, we need to create one
                        // this captures necessary info from the current logged in user
                        // before we signout and redirect away to the external IdP for signout
                        vm.LogoutId = await _interaction.CreateLogoutContextAsync();
                    }

                    vm.ExternalAuthenticationScheme = idp;
                }
            }
        }

        return vm;
    }

Код ошибки углового идентификатора oidc

logout(): Promise<any> {
        return this._userManager.signoutRedirect();
    }

Настройка клиента

public IEnumerable<Client> GetClients()
        {
            var client = new List<Client>
            {
                new Client
                {
                     ClientId = ConstantValue.ClientId,
                    ClientName = ConstantValue.ClientName,
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowAccessTokensViaBrowser = true,
                    RequireConsent = false,
                    RedirectUris =           { string.Format("{0}/{1}", Configuration["IdentityServerUrls:ClientUrl"], "assets/oidc-login-redirect.html"), string.Format("{0}/{1}", Configuration["IdentityServerUrls:ClientUrl"], "assets/silent-redirect.html") },
                    PostLogoutRedirectUris = { string.Format("{0}?{1}", Configuration["IdentityServerUrls:ClientUrl"] , "postLogout=true") },
                    AllowedCorsOrigins =     { Configuration["IdentityServerUrls: ClientUrl"] },

                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        ConstantValue.ClientDashApi
                    },
                    IdentityTokenLifetime=120,
                    AccessTokenLifetime=120
                },
            };
            return client;
        }

id added

logoutId всегда равен нулю.Я успешно могу войти в Facebook вернуться к методу обратного вызова.Но URI перенаправления всегда нулевой.

Ссылка IdentityServer4 PostLogoutRedirectUri null

1 Ответ

0 голосов
/ 22 января 2019

Возможно, это не ваша проблема, но это была моя проблема, когда я получил ту же ошибку, что и вы, поэтому я публикую здесь свой собственный опыт.

Я следил за видео Pluralsight, которое создавало приложение Angular с использованием IdentityServer4 в качестве сервера STS, и оно указало мне установить post_logout_redirect_uri в конфигурации для моего UserManager в AuthService, который я создавал, вот так:

var config = {
        authority: 'http://localhost:4242/',
        client_id: 'spa-client',
        redirect_uri: `${Constants.clientRoot}assets/oidc-login-redirect.html`,
        scope: 'openid projects-api profile',
        response_type: 'id_token token',
        post_logout_redirect_uri: `${Constants.clientRoot}`,
        userStore: new WebStorageStateStore({ store: window.localStorage })
    }
    this._userManager = new UserManager(config);

Старая проблема в репозитории github https://github.com/IdentityServer/IdentityServer4/issues/396 обсуждала тот факт, что это устанавливается автоматически сейчас и не нужнобыть установленным явно (см. конец потока).После того как я удалил это из конфигурации, у меня больше не было проблемы, когда logoutId был нулевым в методе выхода из AccountController:

/// <summary>
/// Show logout page
/// </summary>
[HttpGet]
public async Task<IActionResult> Logout(string logoutId)

Так что это была правильная настройка для меня:

var config = {
        authority: 'http://localhost:4242/',
        client_id: 'spa-client',
        redirect_uri: `${Constants.clientRoot}assets/oidc-login-redirect.html`,
        scope: 'openid projects-api profile',
        response_type: 'id_token token',
        userStore: new WebStorageStateStore({ store: window.localStorage })
    }
    this._userManager = new UserManager(config);
...