从身份服务器注销后如何将用户重定向到客户端应用程序?

时间:2019-06-06 11:57:51

标签: c# asp.net-core identityserver4

我要在用户从该客户端注销后将其重定向到同一客户端。因此,如果我假设一台身份服务器上有5个客户端,那么我希望用户能够从一个客户端注销并在同一客户端上却注销。

我尝试过的一件事是在快速入门中在AccountController中使用PostLogoutRedirectUri,但该值始终为null。我发现的解决方法是手动设置PostLogoutRedirectUri,如果服务器上只有一个客户端,则效果很好,但是如果我有多个客户端,则效果不佳。有什么办法知道哪个客户端已经“注销”?

$('[href]')

我的客户

  public async Task<IActionResult> Logout(LogoutInputModel model)
    {
        // build a model so the logged out page knows what to display
        var vm = await BuildLoggedOutViewModelAsync(model.LogoutId);

        if (User?.Identity.IsAuthenticated == true)
        {
            // delete local authentication cookie
            await HttpContext.SignOutAsync();

            // raise the logout event
            await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()));
        }

        // check if we need to trigger sign-out at an upstream identity provider
        if (vm.TriggerExternalSignout)
        {
            // build a return URL so the upstream provider will redirect back
            // to us after the user has logged out. this allows us to then
            // complete our single sign-out processing.
            string url = Url.Action("Logout", new { logoutId = vm.LogoutId });

            // this triggers a redirect to the external provider for sign-out
            return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
        }


        vm.PostLogoutRedirectUri = "http://localhost:56582";
        return Redirect(vm.PostLogoutRedirectUri);
    }

1 个答案:

答案 0 :(得分:1)

您不应该手动设置uri。实际上,IdentityServer示例中的默认注销方法可以正常工作。

尝试3_ImplicitFlowAuthentication示例项目时,您会看到PostLogoutRedirectUri不为null,并且重定向有效(但不是自动)。

在您的情况下,PostLogoutRedirectUrinull的原因可能是因为未保留 id_token 。确保在MvcClient.Startup中添加以下行:

options.SaveTokens = true;

这会将令牌保留在cookie中。

为了自动重定向回客户端,请对示例代码进行一些调整。在IdentityServer AccountOptions中设置

AutomaticRedirectAfterSignOut = true;

AccountController.Logout方法中,添加以下行:

if (vm.AutomaticRedirectAfterSignOut && 
               !string.IsNullOrWhiteSpace(vm.PostLogoutRedirectUri))
    return Redirect(vm.PostLogoutRedirectUri);

就在最后一行之前:

return View("LoggedOut", vm);

再次运行该示例时,您应该看到注销后用户现在自动返回到客户端。