如何从AzureAD读取SAML响应?

时间:2019-12-05 16:02:36

标签: c# azure-active-directory

我已经使用WsFederation创建了登录请求,如下所示:

        if (!Request.IsAuthenticated)
        {
            HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, WsFederationAuthenticationDefaults.AuthenticationType);
        }

我从AzureAD收到了saml RequestSecurityTokenResponse,并正确列出了我的声明。

如何从响应中获取详细信息?到目前为止,我已经尝试了以下方法:

  ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value;

1 个答案:

答案 0 :(得分:0)

   string strVarCallResult = string.Empty;  
            string ClaimUserID = string.Empty;  
            string ClaimEmployeeID = string.Empty;  

            try  
            {  
                foreach (string s in Request.Params.Keys)  
                {  
                    if (s.ToString() == "SAMLResponse")  
                    {  
                        rawSamlData = Request.Params[s];  
                        break;  
                    }  
                }  

                byte[] samlData = Convert.FromBase64String(rawSamlData);  

                // read back into a UTF string  
                string samlAssertion = Encoding.UTF8.GetString(samlData);  

                XmlDocument doc = new XmlDocument();  
                XmlNamespaceManager xMan = new XmlNamespaceManager(doc.NameTable);  
                xMan.AddNamespace("saml2p", "urn:oasis:names:tc:SAML:2.0:protocol");  
                xMan.AddNamespace("saml2", "urn:oasis:names:tc:SAML:2.0:assertion");  
                xMan.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");  

                doc.LoadXml(Encoding.UTF8.GetString(samlData));  
                //Response.Write(doc.LastChild.ChildNodes[3].ChildNodes[2].ChildNodes[0].InnerXml);  
                XmlNode xNode = doc.SelectSingleNode("/saml2p:Response/saml2:Assertion/saml2:Subject/saml2:NameID", xMan);  

                if (xNode != null)  
                {  
                    UserId = xNode.InnerText;  
                    ClaimUserID = xNode.InnerText;  

                }  
    }  
            catch (Exception ex)  
            {  

            }  

此代码块对我有用。有关详细说明,请找到链接here。 Sankara Krishnan Venugopal撰写的文章。