Search in sources :

Example 76 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.

the class LoginFilter method handleAuthenticationToken.

private Subject handleAuthenticationToken(HttpServletRequest httpRequest, SAMLAuthenticationToken token) throws ServletException {
    Subject subject;
    try {
        LOGGER.debug("Validating received SAML assertion.");
        boolean wasReference = false;
        boolean firstLogin = true;
        if (token.isReference()) {
            wasReference = true;
            LOGGER.trace("Converting SAML reference to assertion");
            Object sessionToken = httpRequest.getSession(false).getAttribute(SecurityConstants.SAML_ASSERTION);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Http Session assertion - class: {}  loader: {}", sessionToken.getClass().getName(), sessionToken.getClass().getClassLoader());
                LOGGER.trace("SecurityToken class: {}  loader: {}", SecurityToken.class.getName(), SecurityToken.class.getClassLoader());
            }
            SecurityToken savedToken = null;
            try {
                savedToken = ((SecurityTokenHolder) sessionToken).getSecurityToken(token.getRealm());
            } catch (ClassCastException e) {
                httpRequest.getSession(false).invalidate();
            }
            if (savedToken != null) {
                firstLogin = false;
                token.replaceReferenece(savedToken);
            }
            if (token.isReference()) {
                String msg = "Missing or invalid SAML assertion for provided reference.";
                LOGGER.debug(msg);
                throw new InvalidSAMLReceivedException(msg);
            }
        }
        SAMLAuthenticationToken newToken = renewSecurityToken(httpRequest.getSession(false), token);
        SecurityToken securityToken;
        if (newToken != null) {
            firstLogin = false;
            securityToken = (SecurityToken) newToken.getCredentials();
        } else {
            securityToken = (SecurityToken) token.getCredentials();
        }
        if (!wasReference) {
            // wrap the token
            SamlAssertionWrapper assertion = new SamlAssertionWrapper(securityToken.getToken());
            // get the crypto junk
            Crypto crypto = getSignatureCrypto();
            Response samlResponse = createSamlResponse(httpRequest.getRequestURI(), assertion.getIssuerString(), createStatus(SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null));
            BUILDER.get().reset();
            Document doc = BUILDER.get().newDocument();
            Element policyElement = OpenSAMLUtil.toDom(samlResponse, doc);
            doc.appendChild(policyElement);
            Credential credential = new Credential();
            credential.setSamlAssertion(assertion);
            RequestData requestData = new RequestData();
            requestData.setSigVerCrypto(crypto);
            WSSConfig wssConfig = WSSConfig.getNewInstance();
            requestData.setWssConfig(wssConfig);
            X509Certificate[] x509Certs = (X509Certificate[]) httpRequest.getAttribute("javax.servlet.request.X509Certificate");
            requestData.setTlsCerts(x509Certs);
            validateHolderOfKeyConfirmation(assertion, x509Certs);
            if (assertion.isSigned()) {
                // Verify the signature
                WSSSAMLKeyInfoProcessor wsssamlKeyInfoProcessor = new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument()));
                assertion.verifySignature(wsssamlKeyInfoProcessor, crypto);
                assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument())), requestData.getSigVerCrypto(), requestData.getCallbackHandler());
            }
            // Validate the Assertion & verify trust in the signature
            assertionValidator.validate(credential, requestData);
        }
        // if it is all good, then we'll create our subject
        subject = securityManager.getSubject(securityToken);
        if (firstLogin) {
            boolean hasSecurityAuditRole = Arrays.stream(System.getProperty("security.audit.roles").split(",")).filter(subject::hasRole).findFirst().isPresent();
            if (hasSecurityAuditRole) {
                SecurityLogger.audit("Subject has logged in with admin privileges", subject);
            }
        }
        if (!wasReference && firstLogin) {
            addSamlToSession(httpRequest, token.getRealm(), securityToken);
        }
    } catch (SecurityServiceException e) {
        LOGGER.debug("Unable to get subject from SAML request.", e);
        throw new ServletException(e);
    } catch (WSSecurityException e) {
        LOGGER.debug("Unable to read/validate security token from request.", e);
        throw new ServletException(e);
    }
    return subject;
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) SecurityServiceException(ddf.security.service.SecurityServiceException) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException) Document(org.w3c.dom.Document) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject) X509Certificate(java.security.cert.X509Certificate) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Response(org.opensaml.saml.saml2.core.Response) ServletResponse(javax.servlet.ServletResponse) ServletException(javax.servlet.ServletException) Crypto(org.apache.wss4j.common.crypto.Crypto) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Example 77 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.

the class SamlProtocol method createResponse.

public static Response createResponse(Issuer issuer, Status status, String requestId, Element samlAssertion) throws WSSecurityException {
    Response response = responseSAMLObjectBuilder.buildObject();
    response.setIssuer(issuer);
    response.setStatus(status);
    response.setID("_" + UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(requestId);
    response.setVersion(SAMLVersion.VERSION_20);
    if (samlAssertion != null) {
        SamlAssertionWrapper samlAssertionWrapper = new SamlAssertionWrapper(samlAssertion);
        response.getAssertions().add(samlAssertionWrapper.getSaml2());
    }
    return response;
}
Also used : Response(org.opensaml.saml.saml2.core.Response) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) DateTime(org.joda.time.DateTime)

Example 78 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class JAXRSOAuth2Test method testSAML2BearerAuthenticationDirect.

@Test
public void testSAML2BearerAuthenticationDirect() throws Exception {
    String address = "https://localhost:" + PORT + "/oauth2-auth/token";
    WebClient wc = createWebClient(address);
    Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
    SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");
    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
    samlCallbackHandler.setIssuer("alice");
    String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
    samlCallbackHandler.setAudience(audienceURI);
    SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler, signInfo);
    Document doc = DOMUtils.newDocument();
    Element assertionElement = assertionWrapper.toDOM(doc);
    String assertion = DOM2Writer.nodeToString(assertionElement);
    String encodedAssertion = Base64UrlUtility.encode(assertion);
    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
    assertNotNull(at.getTokenKey());
}
Also used : SelfSignInfo(org.apache.cxf.rs.security.saml.SAMLUtils.SelfSignInfo) HashMap(java.util.HashMap) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) Element(org.w3c.dom.Element) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Document(org.w3c.dom.Document) WebClient(org.apache.cxf.jaxrs.client.WebClient) SamlCallbackHandler(org.apache.cxf.systest.jaxrs.security.oauth2.common.SamlCallbackHandler) Crypto(org.apache.wss4j.common.crypto.Crypto) Test(org.junit.Test)

Example 79 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class JAXRSOAuth2Test method testSAMLHolderOfKey.

@Test
public void testSAMLHolderOfKey() throws Exception {
    String address = "https://localhost:" + PORT + "/oauth2-auth/token";
    WebClient wc = createWebClient(address);
    String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
    // Create the SAML Assertion
    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
    samlCallbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
    samlCallbackHandler.setSubjectName("alice");
    samlCallbackHandler.setAudience(audienceURI);
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
    if (samlCallback.isSignAssertion()) {
        samlAssertion.signAssertion(samlCallback.getIssuerKeyName(), samlCallback.getIssuerKeyPassword(), samlCallback.getIssuerCrypto(), samlCallback.isSendKeyValue(), samlCallback.getCanonicalizationAlgorithm(), samlCallback.getSignatureAlgorithm());
    }
    String assertion = samlAssertion.assertionToString();
    String encodedAssertion = Base64UrlUtility.encode(assertion);
    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
    try {
        OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
        fail("Failure expected on a bad subject confirmation method");
    } catch (OAuthServiceException ex) {
    // expected
    }
}
Also used : SamlCallbackHandler(org.apache.cxf.systest.jaxrs.security.oauth2.common.SamlCallbackHandler) HashMap(java.util.HashMap) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) WebClient(org.apache.cxf.jaxrs.client.WebClient) Test(org.junit.Test)

Example 80 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class SamlElementCallbackHandler method getSAMLAssertion.

/**
 * Mock up a SAML Assertion by using another SAMLCallbackHandler
 * @throws Exception
 */
private Element getSAMLAssertion(Document doc) throws Exception {
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(new SamlCallbackHandler(saml2), samlCallback);
    SamlAssertionWrapper assertionWrapper = new SamlAssertionWrapper(samlCallback);
    return assertionWrapper.toDOM(doc);
}
Also used : SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback)

Aggregations

SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)141 Element (org.w3c.dom.Element)68 Document (org.w3c.dom.Document)55 WSSecurityEngineResult (org.apache.wss4j.dom.engine.WSSecurityEngineResult)44 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)40 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)35 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)27 Crypto (org.apache.wss4j.common.crypto.Crypto)26 Response (org.opensaml.saml.saml2.core.Response)23 URL (java.net.URL)22 Bus (org.apache.cxf.Bus)20 SpringBusFactory (org.apache.cxf.bus.spring.SpringBusFactory)19 ArrayList (java.util.ArrayList)18 WebClient (org.apache.cxf.jaxrs.client.WebClient)18 Status (org.opensaml.saml.saml2.core.Status)18 HashMap (java.util.HashMap)16 Test (org.junit.Test)16 Principal (java.security.Principal)15 WSHandlerResult (org.apache.wss4j.dom.handler.WSHandlerResult)14 Response (javax.ws.rs.core.Response)13