Azure AD后验证添加声明

Azure AD后验证添加声明,azure,access-token,azure-active-directory,azure-ad-graph-api,Azure,Access Token,Azure Active Directory,Azure Ad Graph Api,我正在使用Azure AD对用户进行身份验证。我想添加一些特定于我的应用程序的用户声明。我应该在global.asax中的应用程序\u PostAuthenticateRequest`中执行此操作吗?。是否有一种方法可以缓存我的声明?如果您使用的是ASP.NET OWIN中间件,则有一些特定的通知可用于此目的。以这种方式添加的声明将在会话cookie中结束,这样您就不必在后续调用中重复声明扩展逻辑。有关详细信息,请参阅。顺便说一句,您可以添加自定义cliam,但无法覆盖Azure广告添加的现有声

我正在使用Azure AD对用户进行身份验证。我想添加一些特定于我的应用程序的用户声明。我应该在global.asax中的应用程序\u PostAuthenticateRequest`中执行此操作吗?。是否有一种方法可以缓存我的声明?

如果您使用的是ASP.NET OWIN中间件,则有一些特定的通知可用于此目的。以这种方式添加的声明将在会话cookie中结束,这样您就不必在后续调用中重复声明扩展逻辑。有关详细信息,请参阅。

顺便说一句,您可以添加自定义cliam,但无法覆盖Azure广告添加的现有声明(到目前为止,我看到的可能是我错了)。你能做的就是像这样添加新的cliam

AuthorizationCodeReceived = context =>
                     {
                         List<System.Security.Claims.Claim> allcustomClaims = new List<System.Security.Claims.Claim>();
                         allcustomClaims.Add(new System.Security.Claims.Claim("customClaim", "YourDefindedValue"));
                         context.AuthenticationTicket.Identity.AddClaims(allcustomClaims);
                         return Task.FromResult(0);
                     }`

您可以通过以下方式以编程方式扩充声明:

    public async Task<ActionResult> AuthenticateAsync()
    {
        ClaimsPrincipal incomingPrincipal = System.Threading.Thread.CurrentPrincipal as ClaimsPrincipal;
        if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated == true)
        {
            ClaimsIdentity claimsIdentity = incomingPrincipal.Identity as ClaimsIdentity;

            if (!claimsIdentity.HasClaim(ClaimTypes.Role, "Admin"))
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, "AADGuide"));
                var ctx = Request.GetOwinContext();
                var authenticationManager = ctx.Authentication;

                AuthenticateResult authResult = await authenticationManager.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationType);
                authenticationManager.SignIn(authResult.Properties,claimsIdentity);
            }

        }
        return RedirectToAction("Index", "Start");

    }
public异步任务AuthenticateAsync()
{
ClaimsPrincipal incomingPrincipal=System.Threading.Thread.CurrentPrincipal作为ClaimsPrincipal;
if(incomingPrincipal!=null&&incomingPrincipal.Identity.IsAuthenticated==true)
{
ClaimsIdentity ClaimsIdentity=incomingPrincipal.Identity为ClaimsIdentity;
if(!claimsIdentity.HasClaim(ClaimTypes.Role,“Admin”))
{
AddClaim(新的Claim(ClaimTypes.Role,“Admin”,ClaimValueTypes.String,“AADGuide”);
var ctx=Request.GetOwinContext();
var authenticationManager=ctx.Authentication;
AuthenticateResult=Wait authenticationManager.AuthenticationAsync(CookieAuthenticationDefaults.AuthenticationType);
authenticationManager.SignIn(authResult.Properties,claimsIdentity);
}
}
返回重定向到操作(“索引”、“开始”);
}

此解决方案依赖AuthenticationManager的
AuthenticationAsync
方法来检索原始
AuthenticationProperties
。检索属性后,调用
SignIn
方法将新的ClaimsEntity持久保存在auth cookie中。

如果您正在使用:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
    {
      ...
这就是我如何使用新的OAuthBeareAuthenticationProvider添加其他自定义声明的方法:

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
  {
    // In this handler we can perform additional coding tasks...
    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);

          identity.AddClaim(new Claim(identity.RoleClaimType, "myRole"));
      }
      catch (Exception e)
      {
        throw;
      }
    }
  }
});

有关完整示例,请检查此项。

您能介绍一下您的应用程序吗。你在用WIF吗?您如何获取和验证令牌?
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
  {
    // In this handler we can perform additional coding tasks...
    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);

          identity.AddClaim(new Claim(identity.RoleClaimType, "myRole"));
      }
      catch (Exception e)
      {
        throw;
      }
    }
  }
});