且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将参数传递给Azure Active Directory身份验证

更新时间:2023-12-05 20:00:34

类似于Gaurav的建议,但增加了一些特殊注意事项.基本上,状态是由Owin中间件使用的,因此,尽管您可以注入自己的东西,但需要确保在Owin中间件尝试使用它之前先将其还原,否则会出现身份验证错误.

Similar to what Gaurav is suggesting, but adding a few special considerations. Basically, the state is used by the Owin middleware, so while you can inject your own stuff, you need to make sure you revert it back before the Owin middleware tries to use it otherwise you'll get auth errors.

这实际上是我回答的一个非常类似的问题:

This is effectively what I replied to a very similar question:

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

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

In Startup.Auth.cs, when you setup the OpenIdConnectAuthenticationOptions you'd add the following:

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

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

And use RedirectToIdentityProvider to inject your parameter, something along the lines of:

private static 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提取它,如下所示:

And then use MessageReceived to extract it, like so:

private static 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);
}

您显然需要对此进行改进/强化,但这应该可以助您一臂之力.

You'd obviously need to improve/harden this but this should get you going.