首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于SAML请求创建SAML响应

基于SAML请求创建SAML响应
EN

Stack Overflow用户
提问于 2014-10-30 07:54:50
回答 2查看 10.3K关注 0票数 1

我已经开发了一个Java应用程序,我想实现SAML。这些是我认为实现SAML的正确步骤。

  1. 服务提供者(在本例中为我的应用程序SP)向IdP发送SAML身份验证请求。
  2. 然后,IdP验证它并创建一个SAML响应断言,并使用证书对它进行签名,然后将其发送回SP。
  3. 然后在密钥存储库中使用证书的公钥对其进行验证,并在此基础上进行进一步的验证。

我有一个示例代码,我能够创建SAML请求,如下所示

代码语言:javascript
运行
复制
<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    ID="_c7b796f4-bc16-4fcc-8c1d-36befffc39c2" Version="2.0"
    IssueInstant="2014-10-30T11:21:08Z" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
    AssertionConsumerServiceURL="http://localhost:8080/mywebapp/consume.jsp">
    <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">http://localhost:8080/mywebapp
    </saml:Issuer>
    <samlp:NameIDPolicy
        Format="urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified"
        AllowCreate="true"></samlp:NameIDPolicy>
    <samlp:RequestedAuthnContext Comparison="exact">
        <saml:AuthnContextClassRef xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
        </saml:AuthnContextClassRef>
    </samlp:RequestedAuthnContext>
</samlp:AuthnRequest>

我可以对它进行编码并发送到IdP。

我希望创建示例Java代码来获取SAML请求,然后创建SAML响应。我如何解码请求并验证它并创建响应?我需要用证书签署saml响应吗?然后送回SP?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-30 08:23:06

您列出的步骤或多或少是正确的。我要指出的唯一一件事是,如果这个词(如前),你必须小心这个词的意思。在"SP .向IdP发送SAML身份验证请求“中)。SAML允许在SP和IdP之间实现零直接通信的身份验证方案。

另一个小的补充是SP也可能签署他的请求,所以你可能在双方都有签名验证。SP侧的验证是强制性的。

如果要实现SAML,则可能需要检查现有解决方案之一,例如希布贝勒斯。如果您在像Spring和JBoss这样的平台上,您可能需要检查Spring安全SAMLJBoss PicketLink。如果您想降低级别,请检查OpenSAML

在我的公司,我们以JBoss为标准,对PicketLink非常满意。

票数 2
EN

Stack Overflow用户

发布于 2015-05-14 10:15:25

虽然这是一篇老文章,但我正在添加示例代码和引用,我认为这是有用的。

代码语言:javascript
运行
复制
SAMLResponse = hreq.getParameter("SAMLResponse");
InputSource inputSource = new InputSource(new StringReader(SAMLResponse));
SAMLReader samlReader = new SAMLReader();                   
response2 = org.opensaml.saml2.core.Response)samlReader.readFromFile(inputSource);

现在验证数字签名:

代码语言:javascript
运行
复制
org.opensaml.saml2.core.Response response2 = (org.opensaml.saml2.core.Response)samlReader.readFromFile(inputSource);  
//To fetch the digital signature from the response.
Signature signature  = response2.getSignature(); 
X509Certificate certificate = (X509Certificate) keyStore.getCertificate(domainName);
//pull out the public key part of the certificate into a KeySpec
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(certificate.getPublicKey().getEncoded());
//get KeyFactory object that creates key objects, specifying RSA - java.security.KeyFactory
KeyFactory keyFactory = KeyFactory.getInstance("RSA");                  
//generate public key to validate signatures
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
//we have the public key                    
BasicX509Credential publicCredential = new BasicX509Credential();
//add public key value
publicCredential.setPublicKey(publicKey);
//create SignatureValidator
SignatureValidator signatureValidator = new SignatureValidator(publicCredential);
//try to validate
try{
signatureValidator.validate(signature); 
catch(Exception e){
//
} 

现在获取断言映射:

代码语言:javascript
运行
复制
samlDetailsMap = setSAMLDetails(response2);

在上面的逻辑中,使用下面的私有方法来提取所有断言属性。最后,您将得到所有字段的地图,发送给您。

代码语言:javascript
运行
复制
 private Map<String, String> setSAMLDetails(org.opensaml.saml2.core.Response  response2){
        Map<String, String> samlDetailsMap = new HashMap<String, String>();
        try {
            List<Assertion> assertions = response2.getAssertions();
            LOGGER.error("No of assertions : "+assertions.size());
            for(Assertion assertion:assertions){
                List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
                for(AttributeStatement attributeStatement: attributeStatements){
                    List<Attribute> attributes = attributeStatement.getAttributes();
                    for(Attribute attribute: attributes){
                        String name = attribute.getName();                          
                        List<XMLObject> attributes1 = attribute.getAttributeValues();
                        for(XMLObject xmlObject : attributes1){
                            if(xmlObject instanceof XSString){
                                samlDetailsMap.put(name, ((XSString) xmlObject).getValue());
                                LOGGER.error("Name is : "+name+" value is : "+((XSString) xmlObject).getValue());
                            }else if(xmlObject instanceof XSAnyImpl){
                                String value = ((XSAnyImpl) xmlObject).getTextContent();

                                samlDetailsMap.put(name, value);

                            }         
                    }
                }
            }       
       }
      } catch (Exception e) {             
          LOGGER.error("Exception occurred while setting the saml details");        
        }       
        LOGGER.error("Exiting from  setSAMLDetails method"); 
        return samlDetailsMap;
    }

添加新的类SAMLReader如下:

代码语言:javascript
运行
复制
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.opensaml.DefaultBootstrap;
import org.opensaml.xml.Configuration;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.UnmarshallingException;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class SAMLReader {

 private static DocumentBuilder builder;

 static{
        try{
            DefaultBootstrap.bootstrap ();
            DocumentBuilderFactory factory = 
                    DocumentBuilderFactory.newInstance ();
                factory.setNamespaceAware (true);        
            builder = factory.newDocumentBuilder ();
        }catch (Exception ex){
            ex.printStackTrace ();
        }
    }



/**
 * 
 * @param filename
 * @return
 * @throws IOException
 * @throws UnmarshallingException
 * @throws SAXException
 */
public XMLObject readFromFile (String filename)
            throws IOException, UnmarshallingException, SAXException{
            return fromElement (builder.parse (filename).getDocumentElement ());    
}
/**
 *      
 * @param is
 * @return
 * @throws IOException
 * @throws UnmarshallingException
 * @throws SAXException
 */
public XMLObject readFromFile (InputStream is)
                throws IOException, UnmarshallingException, SAXException{
                return fromElement (builder.parse (is).getDocumentElement ());    
}
/**
 *      
 * @param is
 * @return
 * @throws IOException
 * @throws UnmarshallingException
 * @throws SAXException
 */
public XMLObject readFromFile (InputSource  is)
                throws IOException, UnmarshallingException, SAXException{                   
                return fromElement (builder.parse (is).getDocumentElement ());    
}

/**
 * 
 * @param element
 * @return
 * @throws IOException
 * @throws UnmarshallingException
 * @throws SAXException
 */
public static XMLObject fromElement (Element element)
            throws IOException, UnmarshallingException, SAXException{   
    return Configuration.getUnmarshallerFactory ()
                .getUnmarshaller (element).unmarshall (element);    
 }

}

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26647664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档