使用 Microsoft.Owin.Security.OpenIdConnect 和 AzureAD v 2.0 端点的自定义参数

Custom parameter with Microsoft.Owin.Security.OpenIdConnect and AzureAD v 2.0 endpoint

我正在将我的 Azure AD 安全应用程序迁移到 v2.0 端点。

我需要将自定义参数传递给回复 uri。对于以前的 Azure AD 端点,我通过向回复 url 添加一个常用的查询参数来做到这一点。 e.g. https://myserver.com/myredirect_uri?mycustomparamerter=myvalue

不幸的是,对于端点 2.0,我收到一条错误消息,提示回复 uri 与注册的不匹配。当然我的自定义参数值是动态的,我不能硬编码。

我想利用 'state' 参数 described in OAUTH flow. However, I am using Microsoft.Owin.Security.OpenIdConnect and it looks the parameter is already set so I cannot exploit it. I am using an implementation of the flow that is based on MVC that looks like this sample

您能否建议一个解决方法,以便我的服务器在回复中收到自定义参数 url,该参数已在流程开始时设置?

不确定是否有官方方法可以满足您的要求,但从技术上讲,您可以通过身份验证流程注入和提取额外值的一种方法是通过 OWIN 的通知。

在 Startup.Auth.cs 中,当您设置 OpenIdConnectAuthenticationOptions 时,您需要添加以下内容:

app.UseOpenIdConnectAuthentication(
  new OpenIdConnectAuthenticationOptions
  {
    //...
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
      RedirectToIdentityProvider = OnRedirectToIdentityProvider,
      MessageReceived = OnMessageReceived
    },
  });

并使用 RedirectToIdentityProvider 注入您的参数,类似于:

private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
  var stateQueryString = notification.ProtocolMessage.State.Split('=');
  var protectedState = stateQueryString[1];
  var state = notification.Options.StateDataFormat.Unprotect(protectedState);
  state.Dictionary.Add("mycustomparameter", "myvalue");
  notification.ProtocolMessage.State = stateQueryString[0] + "=" + notification.Options.StateDataFormat.Protect(state);
  return Task.FromResult(0);
}

然后使用 MessageReceived 提取它,像这样:

private Task OnMessageReceived(MessageReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
  string mycustomparameter;
  var protectedState = notification.ProtocolMessage.State.Split('=')[1];
  var state = notification.Options.StateDataFormat.Unprotect(protectedState);
  state.Dictionary.TryGetValue("mycustomparameter", out mycustomparameter);
  return Task.FromResult(0);
}

您显然需要 improve/harden 这个,但这应该可以让您前进,除非有更好的整体方法。