【问题标题】:Thread.CurrentPrincipal is ClaimsIdentity returns false and how to get the claims from Thread.CurrentPrincipalThread.CurrentPrincipal 是 ClaimsIdentity 返回 false 以及如何从 Thread.CurrentPrincipal 获取声明
【发布时间】:2021-03-04 13:08:24
【问题描述】:

我有 asp.net Web 应用程序 (.NET Framework 4.8),此时它具有 ADFS 用于身份验证。现在我正在使用授权代码流和 OIDC 协议将 ADFS 身份验证迁移到 Azure AD。

我在 OIDC 中间件中添加了一个 SecurityTokenValidated 通知,我正在尝试执行验证并使用以下代码为自定义声明添加代码:

SecurityTokenValidated = notification =>
                        {
                           
                            AddUserClaimsToPrincipal(notification.AuthenticationTicket.Identity);                            

                            return Task.FromResult(0);
                        }

    private void AddUserClaimsToPrincipal(ClaimsIdentity identity)
    {
        string nameClaimValue = string.Empty; // Get Alias
        string emailClaimValue = string.Empty; // Get Email
        string displayClaimNameValue = string.Empty; // Get Display Name
        IPrincipal principal;
        Claim displayNameClaim = identity.FindFirst(t => t.Type == CLAIM_DISPLAYNAME);
        Claim emailClaim = identity.FindFirst(t => t.Type == CLAIM_EMAIL);
        if (displayNameClaim != null)
        {
            displayClaimNameValue = displayNameClaim.Value;
        }

        if (emailClaim != null)
        {
            emailClaimValue = emailClaim.Value;
        }

        nameClaimValue = emailClaimValue;
        List<string> roles;
        bool userExists = ValidateUser(nameClaimValue, out roles);
        identity.AddClaim(new Claim("SampleApp_UserAuthorized", userExists.ToString()));
        if (identity.FindFirst(t => t.Type == CLAIM_Role) == null)
        {
            foreach (var role in roles)
            {
                identity.AddClaim(new Claim(CLAIM_Role, role));
            }
        }
    }

现在我正在尝试使用以下事件验证 Global.asax 文件中的用户授权:Application_PostAuthenticateRequest

protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
  if (Thread.CurrentPrincipal.Identity.IsAuthenticated && Thread.CurrentPrincipal is ClaimsIdentity)
  {
     // Code to fetch the claims
     // If the incoming claim contains the custom claim : SampleApp_UserAuthorized then send the user to 
     // unaurhorized.html page
  }
}

在上面的代码中,我看到 Thread.CurrentPrincipal.Identity.IsAuthenticated 返回 true,但另一方面 Thread.CurrentPrincipal 是 ClaimsIdentity 返回 false。

我想在 Application_PostAuthenticateRequest 中获取自定义声明:SampleApp_UserAuthorized 以将用户发送到未授权的.html 页面

谁能帮我提供一些代码示例来解决这个问题。

【问题讨论】:

    标签: c# asp.net azure-active-directory openid-connect


    【解决方案1】:

    我已经用以下代码解决了这个问题,现在对我来说效果很好:

    protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
            if (!User.Identity.IsAuthenticated)
            {
                //this.Context.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, WsFederationAuthenticationDefaults.AuthenticationType);
                this.Context.GetOwinContext().Authentication.Challenge(new AuthenticationProperties{RedirectUri = "/"}, OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
    
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated && Thread.CurrentPrincipal is System.Security.Claims.ClaimsPrincipal)
            {
                if (!Convert.ToBoolean(((System.Security.Claims.ClaimsPrincipal)Thread.CurrentPrincipal).FindFirst(c => c.Type == "SampleApp_UserAuthorized").Value))
                {
                    //Avoid Redirection for static files (used in Access denied page)
                    List<string> staticcontentpaths = new List<string>{".css", ".js", ".png", ".gif", ".jpg", ".jpeg", ".ico", ".svg", ".woff", ".ttf"};
                    string extension = Path.GetExtension(HttpContext.Current.Request.PhysicalPath).ToLower();
                    if (!staticcontentpaths.Contains(extension))
                    {
                        Server.Execute("~/errors/auth.html");
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                    }
                }
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 2016-04-29
      相关资源
      最近更新 更多