ADAL JavaScript:添加其他声明 (ADAL JS)

本文关键字:ADAL JS 声明 其他 JavaScript 添加 | 更新日期: 2023-09-27 18:32:12

我针对我的Azure AD从Github运行了ADAL JS示例SPA项目。

这很好用,但我想在身份验证后向令牌添加声明。

在 SPA 示例中,按如下所示添加中间件:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience = ConfigurationManager.AppSettings["ida:Audience"],
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
            });

从这里开始,您是否必须添加其他OAuth中间件才能访问诸如通知之类的内容才能访问ClaimsIdentity和AddClaim?

ADAL JavaScript:添加其他声明 (ADAL JS)

您可以使用 TokenValidationParamenters。请参阅ValidateTokenTokenValidationParameters.CreateClaimsIdentity

我找到了一个很好的示例,可以准确地处理这个问题......魔术发生在Provider = new OAuthBearerAuthenticationProvider体内。

您会看到其他声明已添加到标识中。

// Add bearer token authentication middleware.
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
  // The id of the client application that must be registered in Azure AD.
  TokenValidationParameters = new TokenValidationParameters { ValidAudience = clientId },
  // Our Azure AD tenant (e.g.: contoso.onmicrosoft.com).
  Tenant = tenant,
  Provider = new OAuthBearerAuthenticationProvider
  {
    // This is where the magic happens. In this handler we can perform additional
    // validations against the authenticated principal or modify the principal.
    OnValidateIdentity = async context =>
    {
      try
      {
        // Retrieve user JWT token from request.
        var authorizationHeader = context.Request.Headers["Authorization"].First();
        var userJwtToken = authorizationHeader.Substring("Bearer ".Length).Trim();
        // Get current user identity from authentication ticket.
        var authenticationTicket = context.Ticket;
        var identity = authenticationTicket.Identity;
        // Credential representing the current user. We need this to request a token
        // that allows our application access to the Azure Graph API.
        var userUpnClaim = identity.FindFirst(ClaimTypes.Upn);
        var userName = userUpnClaim == null
          ? identity.FindFirst(ClaimTypes.Email).Value
          : userUpnClaim.Value;
        var userAssertion = new UserAssertion(
          userJwtToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);
        // Credential representing our client application in Azure AD.
        var clientCredential = new ClientCredential(clientId, applicationKey);
        // Get a token on behalf of the current user that lets Azure AD Graph API access
        // our Azure AD tenant.
        var authenticationResult = await authenticationContext.AcquireTokenAsync(
          azureGraphApiUrl, clientCredential, userAssertion).ConfigureAwait(false);
        // Create Graph API client and give it the acquired token.
        var activeDirectoryClient = new ActiveDirectoryClient(
          graphApiServiceRootUrl, () => Task.FromResult(authenticationResult.AccessToken));
        // Get current user groups.
        var pagedUserGroups =
          await activeDirectoryClient.Me.MemberOf.ExecuteAsync().ConfigureAwait(false);
        do
        {
          // Collect groups and add them as role claims to our current principal.
          var directoryObjects = pagedUserGroups.CurrentPage.ToList();
          foreach (var directoryObject in directoryObjects)
          {
            var group = directoryObject as Group;
            if (group != null)
            {
              // Add ObjectId of group to current identity as role claim.
              identity.AddClaim(new Claim(identity.RoleClaimType, group.ObjectId));
            }
          }
          pagedUserGroups = await pagedUserGroups.GetNextPageAsync().ConfigureAwait(false);
        } while (pagedUserGroups != null);
      }
      catch (Exception e)
      {
        throw;
      }
    }
  }
});