SAML2发送断言

已经认证的用户,直接向应用发送断言

package com.xxx;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.joda.time.DateTime;
import org.opensaml.Configuration;
import org.opensaml.saml2.core.*;
import org.opensaml.saml2.core.impl.AssertionBuilder;
import org.opensaml.saml2.core.impl.ResponseBuilder;
import org.opensaml.saml2.metadata.AssertionConsumerService;
import org.opensaml.saml2.metadata.Endpoint;
import org.opensaml.xml.XMLObjectBuilderFactory;
import org.opensaml.xml.security.CriteriaSet;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.security.credential.CredentialResolver;
import org.opensaml.xml.security.credential.UsageType;
import org.opensaml.xml.security.criteria.EntityIDCriteria;
import org.opensaml.xml.security.criteria.UsageCriteria;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import com.xxx.saml.idp.BindingAdapter;
import com.xxx.saml.idp.IdpConfiguration;
import com.xxx.saml.idp.UIASAttributeStatementGenerator;
import com.xxx.saml.util.IDService;
import com.xxx.saml.util.TimeService;
import com.xxx.saml.xml.AttributeStatementGenerator;
import com.xxx.saml.xml.AuthnStatementGenerator;
import com.xxx.saml.xml.EndpointGenerator;
import com.xxx.saml.xml.IssuerGenerator;
import com.xxx.saml.xml.StatusGenerator;
import com.xxx.saml.xml.SubjectGenerator;
import com.xxx.uias.userInfo.pojo.Privilege;

public class TestServlet extends HttpServlet {
 private static final long serialVersionUID = 2572744487603163969L;

 private final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
 private TimeService timeService = new TimeService();
 private IDService idService = new IDService();
 
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  this.doPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  try {
   request.setCharacterEncoding("utf-8");  //设置编码
   response.setContentType("text/html; charset=utf-8");
   
   String appCode = "demo333";
   String issuingEntityName = "UIAS";
   
   String acURL = "http://172.16.15.109:5050/aaa/samlsp/acService";
   int validForInSeconds = 300;
   String username = "testccc";
   String ip = "172.16.15.109";
   String inResponseTo = "";
   
   DateTime authnInstant = new DateTime(System.currentTimeMillis());
   
   AuthnStatementGenerator authnStatementGenerator = new AuthnStatementGenerator();
   AttributeStatementGenerator attributeStatementGenerator = new AttributeStatementGenerator();
   
   IssuerGenerator issuerGenerator = new IssuerGenerator(issuingEntityName);
   SubjectGenerator subjectGenerator = new SubjectGenerator(timeService);
   StatusGenerator statusGenerator = new StatusGenerator();
   
   
   //1.生成authResponse
   EndpointGenerator endpointGenerator = new EndpointGenerator();
   Endpoint endpoint = endpointGenerator.generateEndpoint(AssertionConsumerService.DEFAULT_ELEMENT_NAME, acURL, null);
   
   
   //2.
   ResponseBuilder responseBuilder = (ResponseBuilder) builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
   Response authResponse = responseBuilder.buildObject();
   Issuer responseIssuer = issuerGenerator.generateIssuer();
   
   AssertionBuilder assertionBuilder = (AssertionBuilder)builderFactory.getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
   Assertion assertion = assertionBuilder.buildObject();
   
   Subject subject = subjectGenerator.generateSubject(acURL, validForInSeconds, username, inResponseTo, ip);
   
   Issuer issuer = issuerGenerator.generateIssuer();
   
   AuthnStatement authnStatement = authnStatementGenerator.generateAuthnStatement(authnInstant);
   
   assertion.setIssuer(issuer);
   assertion.setSubject(subject);
   assertion.setID(idService.generateID());
   assertion.setIssueInstant(timeService.getCurrentDateTime());
   assertion.getAuthnStatements().add(authnStatement);
   
   //权限
         Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();;
         for(Privilege p: Privilege.values()){
          authorities.add(new SimpleGrantedAuthority("ROLE_" + p.name()));
   }
   assertion.getAttributeStatements().add(attributeStatementGenerator.generateAttributeStatement(authorities));
   
   //其他属性
   UIASAttributeStatementGenerator attrState = new UIASAttributeStatementGenerator();
   Map<String, String> attrMap = new HashMap<String, String>();
   attrMap.put("appCode", appCode);
   attrMap.put("name", "张三");
   assertion.getAttributeStatements().add(attrState.generateAttributeStatement(attrMap));
   
   
   authResponse.getAssertions().add(assertion);
   authResponse.setIssuer(responseIssuer);
   authResponse.setID(idService.generateID());
   authResponse.setIssueInstant(timeService.getCurrentDateTime());
   authResponse.setInResponseTo(inResponseTo);
   authResponse.setDestination(acURL);
   authResponse.setStatus(statusGenerator.generateStatus(StatusCode.SUCCESS_URI));
   
   //JKS
   CriteriaSet criteriaSet = new CriteriaSet();
   criteriaSet.add(new EntityIDCriteria(issuingEntityName));
   criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
   CredentialResolver credentialResolver = IdpConfiguration.buildJKSCredentialResolver();
   Credential signingCredential = credentialResolver.resolveSingle(criteriaSet);
   
   
   BindingAdapter adapter = IdpConfiguration.buildBindingAdapter();
   adapter.sendSAMLMessage(authResponse, endpoint, signingCredential, response);
   
   
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 
 

}

该发送类为参考:

import java.io.PrintWriter;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import java.util.List;

import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.X509EncodedKeySpec;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.opensaml.common.binding.BasicSAMLMessageContext;
import org.opensaml.saml2.binding.decoding.HTTPPostDecoder;
import org.opensaml.ws.message.MessageContext;
import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.saml2.core.Response;
import org.opensaml.saml2.encryption.Decrypter;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.encryption.DecryptionException;
import org.opensaml.xml.encryption.InlineEncryptedKeyResolver;
import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver;
import org.opensaml.xml.security.x509.BasicX509Credential;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.SignatureValidator;
import org.opensaml.xml.validation.ValidationException;


public class ProcessSAML extends HttpServlet {
  
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        File signatureVerificationPublicKeyFile = new File("C:/IdPSigningCert.cer");
        File decryptionPrivateKeyFile = new File("C:/SPEncryptionCert.jks");
        String decryptionPrivateKeyName = "test";
        String decryptionPrivateKeyPassword = "test";

        try
        {
            //bootstrap the opensaml stuff
            org.opensaml.DefaultBootstrap.bootstrap();

            // get the message context
            MessageContext messageContext = new BasicSAMLMessageContext();
            messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(request));
            HTTPPostDecoder samlMessageDecoder = new HTTPPostDecoder();
            samlMessageDecoder.decode(messageContext);

            // get the SAML Response
            Response samlResponse = (Response)messageContext.getInboundMessage();

            //get the certificate from the file
            InputStream inputStream2 = new FileInputStream(signatureVerificationPublicKeyFile);
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate)certificateFactory.generateCertificate(inputStream2);
            inputStream2.close();

            //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
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            //generate public key to validate signatures
            PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

            //create credentials
            BasicX509Credential publicCredential = new BasicX509Credential();

            //add public key value
            publicCredential.setPublicKey(publicKey);

            //create SignatureValidator
            SignatureValidator signatureValidator = new SignatureValidator(publicCredential);

            //get the signature to validate from the response object
            Signature signature = samlResponse.getSignature();

            //try to validate
            try
            {
                signatureValidator.validate(signature);
            }
            catch (ValidationException ve)
            {
                out.println("Signature is not valid.");
                out.println(ve.getMessage());
                return;
            }

            //no validation exception was thrown
            out.println("Signature is valid.");

            //start decryption of assertion

            //load up a KeyStore
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(decryptionPrivateKeyFile), decryptionPrivateKeyPassword.toCharArray());

            RSAPrivateKey privateKey = (RSAPrivateKey) keyStore.getKey(decryptionPrivateKeyName, decryptionPrivateKeyPassword.toCharArray());

            //create the credential
            BasicX509Credential decryptionCredential = new BasicX509Credential();
            decryptionCredential.setPrivateKey(privateKey);

            StaticKeyInfoCredentialResolver skicr = new StaticKeyInfoCredentialResolver(decryptionCredential);

            //create a decrypter
            Decrypter decrypter = new Decrypter(null, skicr, new InlineEncryptedKeyResolver());

            //decrypt the first (and only) assertion
            Assertion decryptedAssertion;

            try
            {
                decryptedAssertion = decrypter.decrypt(samlResponse.getEncryptedAssertions().get(0));
            }
            catch (DecryptionException de)
            {
                out.println("Assertion decryption failed.");
                out.println(de.getMessage());
                return;
            }

            out.println("Assertion decryption succeeded.");

            //loop through the nodes to get the Attributes
            //this is where you would do something with these elements
            //to tie this user with your environment
            List attributeStatements = decryptedAssertion.getAttributeStatements();
            for (int i = 0; i < attributeStatements.size(); i++)
            {
                List attributes = attributeStatements.get(i).getAttributes();
                for (int x = 0; x < attributes.size(); x++)
                {
                    String strAttributeName = attributes.get(x).getDOM().getAttribute("Name");

                    List attributeValues = attributes.get(x).getAttributeValues();
                    for (int y = 0; y < attributeValues.size(); y++)
                    {
                        String strAttributeValue = attributeValues.get(y).getDOM().getTextContent();
                        out.println(strAttributeName + ": " + strAttributeValue + " ");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }

   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

   
    @Override
    public String getServletInfo() {
        return "This servlet processes a SAML 2.0 Response.  It verifies the signature, " +
                "decrypts an assertion, and parses out the data in the attribute statements.  " +
                "If you use this code as a base for your implementation please leave the @author comment intact.  " +
                "You should add your own name in addition.";
    }

}

猜你喜欢

转载自chun521521.iteye.com/blog/2397447