Identity Server 4 - 注销 - 传递其他数据

时间:2017-09-25 17:38:47

标签: c# asp.net-mvc authentication openid-connect identityserver4

当用户在某些情况下退出时,我想在已注销的页面上显示一条消息。为了实现这一点,我希望能够在注销时从客户端向Identity Server / Authority站点发送可选参数。

虽然我有标准的注销流程,但是我在处理这种情况时遇到了一个障碍,因为当地的信息似乎很薄,建议的解决方案无效。

从我读过的'state'参数是传递这些信息的正确方法,但目前尚未通过。 AcrValues仅用于以其他方式发送信息。

下面我的简单实现只是将状态查询字符串项添加到结束会话端点。但是,当我检查我的客户端用于转到身份服务器实例的查询字符串时,它将丢失。

重定向(discoveryResponse.EndSessionEndpoint + “&安培;状态= foo” 的)

很高兴收到任何帮助!

MVC客户端的当前流程:

请注意;为简洁起见,删除了一些代码。

使用state = foo:

从客户端控制器启动注销
public class LogoutController : Controller
{
    public ActionResult Index()
    {
        Request.GetOwinContext().Authentication.SignOut();

        var discoveryClient = new DiscoveryClient(clientConfig.Authority) { Policy = {RequireHttps = false} };

        var discoveryResponse = discoveryClient.GetAsync().Result;

        var tokenClaim = ((ClaimsIdentity)User.Identity).FindFirst("id_token");

        return Redirect(discoveryResponse.EndSessionEndpoint+ "?id_token_hint="+ tokenClaim + "&state=foo");
    }
}

为请求调用RedirectToIdentityProvider:

IdTokenHint和PostLogoutRedirectUri已正确设置并传递。

    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
      {
         Notifications = new OpenIdConnectAuthenticationNotifications
         {
            RedirectToIdentityProvider = n =>
            {
              if (n.ProtocolMessage.RequestType != OpenIdConnectRequestType.LogoutRequest)
              return Task.FromResult(0);

              var idTokenHint = n.OwinContext.Authentication.User.FindFirst(OpenIdConnectClaimType.IdToken);

          if (idTokenHint == null) return Task.FromResult(0);

          n.ProtocolMessage.IdTokenHint = idTokenHint.Value;

  n.OwinContext.Response.Cookies.Append("IdentityServerPostLogoutReturnUri", 
  n.ProtocolMessage.PostLogoutRedirectUri);
          n.ProtocolMessage.PostLogoutRedirectUri = 
  n.Options.PostLogoutRedirectUri;


        return Task.FromResult(0);
           }
        }

生成的网址(不是缺少“州”项目):

http://localhost:44362/connect/endsession?post_logout_redirect_uri=http%3a%2f%2flocalhost%3a2577%2fpostloginredirect&id_token_hint=removed&x-client-SKU=ID_NET&x-client-ver=1.0.40306.1554

授权网站上的退出页面:

这是我希望能够访问state参数的地方。

public class LogoutController : Controller
{
  public async Task<ViewResult> Index(string logoutId)
  {
    if (logoutId == null) throw new Exception("Missing logoutId");

    var logoutRequest = await interactionService.GetLogoutContextAsync(logoutId);

    var vm = new LoggedOutViewModel(logoutRequest, logoutId);

    if (!string.IsNullOrWhiteSpace(httpContextService.GetCookieValue(PostLogoutReturnUriCookieKey)))
    {
      vm.PostLogoutRedirectUri = httpContextService.GetCookieValue(PostLogoutReturnUriCookieKey);
      httpContextService.ClearCookie(PostLogoutReturnUriCookieKey);
    }

    await httpContextService.SignOutAsync();
    return View("Index", vm);
  }
}

1 个答案:

答案 0 :(得分:3)

我已经深入挖掘了一下,发现Microsoft.Owin.Security.OpenIdConnect中间件中的以下几行导致了什么问题。

protected override async Task ApplyResponseGrantAsync()
{
    AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);

    if (signout != null)
    {
        // snip
        var notification = new RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
        {
            ProtocolMessage = openIdConnectMessage
        };

        await Options.Notifications.RedirectToIdentityProvider(notification);
        // This was causing the issue
        if (!notification.HandledResponse)
        {
            string redirectUri = notification.ProtocolMessage.CreateLogoutRequestUrl();
            if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
            {
                _logger.WriteWarning("The logout redirect URI is malformed: " + redirectUri);
            }
            Response.Redirect(redirectUri);
        }
    }
}

为了防止中间件在检测到退出消息时覆盖重定向,请参阅&#39; HandleResponse&#39;需要在RedirectToIdentityProvider事件中调用方法。

这允许原始状态&#39;查询要传递给Identity Server的字符串项,并使用交互服务将其拉出。

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    // Snip
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        AuthorizationCodeReceived = async n =>
        {
            // Snip
        },
        RedirectToIdentityProvider = n =>
        {
            // Snip
            n.HandleResponse(); // The magic happens here
        }
}