Search in sources :

Example 1 with org.opensaml.saml.saml2.core

use of org.opensaml.saml.saml2.core in project cas by apereo.

the class GoogleAccountsServiceResponseBuilder method constructSamlResponse.

/**
     * Construct SAML response.
     * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
     *
     * @param service the service
     * @return the SAML response
     */
protected String constructSamlResponse(final GoogleAccountsService service) {
    final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
    final ZonedDateTime notBeforeIssueInstant = ZonedDateTime.parse("2003-04-17T00:46:02Z");
    final RegisteredService registeredService = servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE);
    }
    final String userId = registeredService.getUsernameAttributeProvider().resolveUsername(service.getPrincipal(), service);
    final org.opensaml.saml.saml2.core.Response response = this.samlObjectBuilder.newResponse(this.samlObjectBuilder.generateSecureRandomId(), currentDateTime, service.getId(), service);
    response.setStatus(this.samlObjectBuilder.newStatus(StatusCode.SUCCESS, null));
    final String sessionIndex = '_' + String.valueOf(Math.abs(new SecureRandom().nextLong()));
    final AuthnStatement authnStatement = this.samlObjectBuilder.newAuthnStatement(AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime, sessionIndex);
    final Assertion assertion = this.samlObjectBuilder.newAssertion(authnStatement, casServerPrefix, notBeforeIssueInstant, this.samlObjectBuilder.generateSecureRandomId());
    final Conditions conditions = this.samlObjectBuilder.newConditions(notBeforeIssueInstant, currentDateTime.plusSeconds(this.skewAllowance), service.getId());
    assertion.setConditions(conditions);
    final Subject subject = this.samlObjectBuilder.newSubject(NameID.EMAIL, userId, service.getId(), currentDateTime.plusSeconds(this.skewAllowance), service.getRequestId());
    assertion.setSubject(subject);
    response.getAssertions().add(assertion);
    final StringWriter writer = new StringWriter();
    this.samlObjectBuilder.marshalSamlXmlObject(response, writer);
    final String result = writer.toString();
    LOGGER.debug("Generated Google SAML response: [{}]", result);
    return result;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) Assertion(org.opensaml.saml.saml2.core.Assertion) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) SecureRandom(java.security.SecureRandom) Conditions(org.opensaml.saml.saml2.core.Conditions) Subject(org.opensaml.saml.saml2.core.Subject) StringWriter(java.io.StringWriter) ZonedDateTime(java.time.ZonedDateTime) AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement)

Example 2 with org.opensaml.saml.saml2.core

use of org.opensaml.saml.saml2.core in project ddf by codice.

the class SoapResponseCreator method createEcpResponse.

private String createEcpResponse(AuthnRequest authnRequest) throws WSSecurityException {
    ResponseBuilder responseBuilder = new ResponseBuilder();
    org.opensaml.saml.saml2.ecp.Response response = responseBuilder.buildObject();
    response.setSOAP11Actor(HTTP_SCHEMAS_XMLSOAP_ORG_SOAP_ACTOR_NEXT);
    response.setSOAP11MustUnderstand(true);
    response.setAssertionConsumerServiceURL(getAssertionConsumerServiceURL(authnRequest));
    return convertXmlObjectToString(response);
}
Also used : ResponseBuilder(org.opensaml.saml.saml2.ecp.impl.ResponseBuilder)

Example 3 with org.opensaml.saml.saml2.core

use of org.opensaml.saml.saml2.core in project ddf by codice.

the class IdpEndpoint method doSoapLogin.

@POST
@Path("/login")
@Consumes({ "text/xml", "application/soap+xml" })
public Response doSoapLogin(InputStream body, @Context HttpServletRequest request) {
    if (!request.isSecure()) {
        throw new IllegalArgumentException("Authn Request must use TLS.");
    }
    SoapBinding soapBinding = new SoapBinding(systemCrypto, serviceProviders);
    try {
        String bodyStr = IOUtils.toString(body);
        AuthnRequest authnRequest = soapBinding.decoder().decodeRequest(bodyStr);
        String relayState = ((SoapRequestDecoder) soapBinding.decoder()).decodeRelayState(bodyStr);
        soapBinding.validator().validateRelayState(relayState);
        soapBinding.validator().validateAuthnRequest(authnRequest, bodyStr, null, null, null, strictSignature);
        boolean hasCookie = hasValidCookie(request, authnRequest.isForceAuthn());
        AuthObj authObj = determineAuthMethod(bodyStr, authnRequest);
        org.opensaml.saml.saml2.core.Response response = handleLogin(authnRequest, authObj.method, request, authObj, authnRequest.isPassive(), hasCookie);
        Response samlpResponse = soapBinding.creator().getSamlpResponse(relayState, authnRequest, response, null, soapMessage);
        samlpResponse.getHeaders().put("SOAPAction", Collections.singletonList("http://www.oasis-open.org/committees/security"));
        return samlpResponse;
    } catch (IOException e) {
        LOGGER.debug("Unable to decode SOAP AuthN Request", e);
    } catch (SimpleSign.SignatureException e) {
        LOGGER.debug("Unable to validate signature.", e);
    } catch (ValidationException e) {
        LOGGER.debug("Unable to validate request.", e);
    } catch (SecurityServiceException e) {
        LOGGER.debug("Unable to authenticate user.", e);
    } catch (WSSecurityException | IllegalArgumentException e) {
        LOGGER.debug("Bad request.", e);
    }
    return null;
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) ValidationException(ddf.security.samlp.ValidationException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SoapRequestDecoder(org.codice.ddf.security.idp.binding.soap.SoapRequestDecoder) IOException(java.io.IOException) SoapBinding(org.codice.ddf.security.idp.binding.soap.SoapBinding) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) Response(javax.ws.rs.core.Response) SimpleSign(ddf.security.samlp.SimpleSign) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 4 with org.opensaml.saml.saml2.core

use of org.opensaml.saml.saml2.core in project ddf by codice.

the class IdpEndpoint method createCookie.

private NewCookie createCookie(HttpServletRequest request, org.opensaml.saml.saml2.core.Response response) {
    LOGGER.debug("Creating cookie for user.");
    if (response.getAssertions() != null && response.getAssertions().size() > 0) {
        Assertion assertion = response.getAssertions().get(0);
        if (assertion != null) {
            UUID uuid = UUID.randomUUID();
            cookieCache.cacheSamlAssertion(uuid.toString(), assertion.getDOM());
            URL url;
            try {
                url = new URL(request.getRequestURL().toString());
                LOGGER.debug("Returning new cookie for user.");
                return new NewCookie(COOKIE, uuid.toString(), SERVICES_IDP_PATH, url.getHost(), NewCookie.DEFAULT_VERSION, null, -1, null, true, true);
            } catch (MalformedURLException e) {
                LOGGER.info("Unable to create session cookie. Client will need to log in again.", e);
            }
        }
    }
    return null;
}
Also used : MalformedURLException(java.net.MalformedURLException) SecurityAssertion(ddf.security.assertion.SecurityAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion) UUID(java.util.UUID) URL(java.net.URL) NewCookie(javax.ws.rs.core.NewCookie)

Example 5 with org.opensaml.saml.saml2.core

use of org.opensaml.saml.saml2.core in project cxf by apache.

the class SAMLSSOResponseValidator method matchSaml2AudienceRestriction.

private boolean matchSaml2AudienceRestriction(String appliesTo, List<AudienceRestriction> audienceRestrictions) {
    boolean oneMatchFound = false;
    if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
        for (AudienceRestriction audienceRestriction : audienceRestrictions) {
            if (audienceRestriction.getAudiences() != null) {
                boolean matchFound = false;
                for (org.opensaml.saml.saml2.core.Audience audience : audienceRestriction.getAudiences()) {
                    if (appliesTo.equals(audience.getAudienceURI())) {
                        matchFound = true;
                        oneMatchFound = true;
                        break;
                    }
                }
                if (!matchFound) {
                    return false;
                }
            }
        }
    }
    return oneMatchFound;
}
Also used : AudienceRestriction(org.opensaml.saml.saml2.core.AudienceRestriction)

Aggregations

Assertion (org.opensaml.saml.saml2.core.Assertion)6 IOException (java.io.IOException)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 SimpleSign (ddf.security.samlp.SimpleSign)3 ValidationException (ddf.security.samlp.ValidationException)3 SecurityServiceException (ddf.security.service.SecurityServiceException)3 NewCookie (javax.ws.rs.core.NewCookie)3 Response (javax.ws.rs.core.Response)3 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)3 MalformedURLException (java.net.MalformedURLException)2 X509Certificate (java.security.cert.X509Certificate)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Test (org.junit.Test)2 XMLObject (org.opensaml.core.xml.XMLObject)2 XSString (org.opensaml.core.xml.schema.XSString)2 AuthnStatement (org.opensaml.saml.saml2.core.AuthnStatement)2 Issuer (org.opensaml.saml.saml2.core.Issuer)2 NameID (org.opensaml.saml.saml2.core.NameID)2 SubjectConfirmation (org.opensaml.saml.saml2.core.SubjectConfirmation)2 SubjectConfirmationData (org.opensaml.saml.saml2.core.SubjectConfirmationData)2