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

Passing parameters to Azure Active Directory authentication

我有一个 ASP.Net MVC 应用程序,Owin,我也在使用 Azure Active Directory 身份验证。

我想在用户重定向到 Azure AD 身份验证页面时传递一个参数。因此,当用户登录或注册时,我想将 ProjectId (int) 作为参数传递。

在用户签名 in/up 并重定向到我的应用程序后,我想接收作为参数传递的 ProjectId

我怎样才能做到这一点?

编辑:添加代码

// The ACR claim is used to indicate which policy was executed
public const string AcrClaimType = "http://schemas.microsoft.com/claims/authnclassreference";
public const string PolicyKey = "b2cpolicy";
private const string OidcMetadataSuffix = "/.well-known/openid-configuration";

public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions
    {
        // These are standard OpenID Connect parameters, with values pulled from web.config
        ClientId = ClientId,
        RedirectUri = RedirectUri,
        PostLogoutRedirectUri = RedirectUri,
        UseTokenLifetime = false,
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthenticationFailed = AuthenticationFailed,
            RedirectToIdentityProvider = OnRedirectToIdentityProvider,
            SecurityTokenValidated = OnSecurityTokenValidated
        },
        Scope = "openid",
        ResponseType = "id_token",

        // The PolicyConfigurationManager takes care of getting the correct Azure AD authentication
        // endpoints from the OpenID Connect metadata endpoint.  It is included in the PolicyAuthHelpers folder.
        ConfigurationManager = new PolicyConfigurationManager(
            string.Format(CultureInfo.InvariantCulture, AadInstance, Tenant, "/v2.0", OidcMetadataSuffix),
            new[] { SignUpPolicyId, SignInPolicyId, ProfilePolicyId }),

        // This piece is optional - it is used for displaying the user's name in the navigation bar.
        TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name"
        }
    };

    app.UseOpenIdConnectAuthentication(options);
}

private Task OnRedirectToIdentityProvider(
        RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
    {
        var currentPolicy =
            notification.OwinContext.Authentication.AuthenticationResponseRevoke.AuthenticationTypes
                .FirstOrDefault(x => x.StartsWith("b2c"));
        notification.ProtocolMessage.IssuerAddress = notification.ProtocolMessage.IssuerAddress.Split('?')[0];
        notification.ProtocolMessage.Parameters.Add("p", currentPolicy);
    }
    else
    {
        **// The value right now for the state is sort of "hijacked" and assigned by Microsoft**
        //notification.ProtocolMessage.Parameters["state"] = "OpenIdConnect.AuthenticationProperties=sRt-teBcxsd239viWo...... ";

        var currentPolicy = notification.OwinContext.Authentication.AuthenticationResponseChallenge.Properties
            .Dictionary[PolicyKey];
        notification.ProtocolMessage.IssuerAddress = notification.ProtocolMessage.IssuerAddress.Split('?')[0];
        notification.ProtocolMessage.Parameters.Add("p", currentPolicy);
    }

    return Task.FromResult(0);
}

private async Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    await MyClass.CreatePrincipal(notification.AuthenticationTicket.Identity);
}

private Task AuthenticationFailed(
            AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    notification.HandleResponse();
    notification.Response.Redirect("/Home/Error?message=" + notification.Exception.Message);
    return Task.FromResult(0);
}

您可以将 ProjectId 参数作为 State 参数的值传递。请参阅下面的示例代码:

            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                RedirectToIdentityProvider = context =>
                    {
                        redirectUri = string.Format("{0}/", System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority));
                        postLogoutRedirectUri = redirectUri + "sign-out";
                        context.ProtocolMessage.RedirectUri = redirectUri;
                        context.ProtocolMessage.PostLogoutRedirectUri = postLogoutRedirectUri;
                        context.ProtocolMessage.State = "Your Project Id";
                        return Task.FromResult(0);
                    },
                AuthorizationCodeReceived = context =>
                    {
                        var projectId = context.ProtocolMessage.State;//Retrieve the state in AuthorizationCodeReceived event.
                        return Task.FromResult(0);
                    }
            }
        };

更新

本质上State接受一个字符串参数。在我们的项目中,我们需要在状态中提供许多值。我们在那里所做的是创建一个竖线分隔的字符串并将其作为状态传递。当我们收到返回的状态时,我们只需将其转换为数组并使用适当的元素。类似于:

var state = "param1|param2|...|paramx";

您可以做的另一件事是创建一个状态对象(一个简单的 class 具有一些属性),将其序列化为 JSON,将其转换为 base64 字符串,然后将该编码字符串作为状态传递正确 url 对其进行编码。当您收到状态时,您可以执行相反的过程,取回状态对象并使用它的属性值。

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

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

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

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

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

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 提取它,像这样:

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

你显然需要 improve/harden 这个,但这应该让你继续。

只需在 RedirectToIdentityProvider

中添加 context.ProtocolMessage.SetParameter(<ParameterName>, <value>);
Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                RedirectToIdentityProvider = context =>
                    {
                        context.ProtocolMessage.SetParameter("prompt", "login");
                        return Task.FromResult(0);
                    },
                
            }
        };