Search in sources :

Example 31 with Assertion

use of org.jasig.cas.client.validation.Assertion in project ddf by codice.

the class WebSSOTokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     */
@Override
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.debug("Validating SSO Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    LOGGER.debug("Setting validate state to invalid before check.");
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isBinarySecurityToken()) {
        LOGGER.debug("Validate target is not a binary security token, returning invalid response.");
        return response;
    }
    LOGGER.debug("Getting binary security token from validate target");
    BinarySecurityTokenType binarySecurityToken = (BinarySecurityTokenType) validateTarget.getToken();
    //
    // Decode the token
    //
    LOGGER.debug("Decoding binary security token.");
    String base64Token = binarySecurityToken.getValue();
    String ticket = null;
    String service = null;
    try {
        byte[] token = Base64.getDecoder().decode(base64Token);
        if (token == null || token.length == 0) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null.");
        }
        String decodedToken = new String(token, Charset.forName("UTF-8"));
        if (StringUtils.isNotBlank(decodedToken)) {
            LOGGER.debug("Binary security token successfully decoded: {}", decodedToken);
            // Token is in the format ticket|service
            String[] parts = StringUtils.split(decodedToken, CAS_BST_SEP);
            if (parts.length == 2) {
                ticket = parts[0];
                service = parts[1];
            } else {
                throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Was not able to parse out BST propertly. Should be in ticket|service format.");
            }
        } else {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null.");
        }
    } catch (WSSecurityException wsse) {
        String msg = "Unable to decode BST into ticket and service for validation to CAS.";
        LOGGER.info(msg, wsse);
        return response;
    }
    //
    try {
        LOGGER.debug("Validating ticket [{}] for service [{}].", ticket, service);
        // validate either returns an assertion or throws an exception
        Assertion assertion = validate(ticket, service);
        AttributePrincipal principal = assertion.getPrincipal();
        LOGGER.debug("User name retrieved from CAS: {}", principal.getName());
        response.setPrincipal(principal);
        LOGGER.debug("CAS ticket successfully validated, setting state to valid.");
        validateTarget.setState(STATE.VALID);
    } catch (TicketValidationException e) {
        LOGGER.debug("Unable to validate CAS token.", e);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Assertion(org.jasig.cas.client.validation.Assertion) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) RequestData(org.apache.wss4j.dom.handler.RequestData) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal) TicketValidationException(org.jasig.cas.client.validation.TicketValidationException)

Example 32 with Assertion

use of org.jasig.cas.client.validation.Assertion in project ddf by codice.

the class CasHandlerTest method createServletRequest.

private HttpServletRequest createServletRequest(boolean shouldAddCas) {
    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    HttpSession session = mock(HttpSession.class);
    when(session.getId()).thenReturn(SESSION_ID);
    when(servletRequest.getSession()).thenReturn(session);
    when(servletRequest.getSession(any(Boolean.class))).thenReturn(session);
    if (shouldAddCas) {
        // Mock CAS items
        Assertion assertion = mock(Assertion.class);
        when(session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION)).thenReturn(assertion);
        AttributePrincipal principal = mock(AttributePrincipal.class);
        when(principal.getProxyTicketFor(STS_ADDRESS)).thenReturn(MOCK_TICKET);
        when(principal.getProxyTicketFor(not(eq(STS_ADDRESS)))).thenThrow(new RuntimeException("Tried to create ticket for incorrect service."));
        when(assertion.getPrincipal()).thenReturn(principal);
    }
    return servletRequest;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSession(javax.servlet.http.HttpSession) Assertion(org.jasig.cas.client.validation.Assertion) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal)

Example 33 with Assertion

use of org.jasig.cas.client.validation.Assertion in project cas by apereo.

the class Saml1ArtifactResolutionProfileHandlerController method handlePostRequest.

/**
 * Handle post request.
 *
 * @param response the response
 * @param request  the request
 */
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML1_SOAP_ARTIFACT_RESOLUTION)
protected void handlePostRequest(final HttpServletResponse response, final HttpServletRequest request) {
    final MessageContext ctx = decodeSoapRequest(request);
    final ArtifactResolve artifactMsg = (ArtifactResolve) ctx.getMessage();
    try {
        final String issuer = artifactMsg.getIssuer().getValue();
        final SamlRegisteredService service = verifySamlRegisteredService(issuer);
        final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor = getSamlMetadataFacadeFor(service, artifactMsg);
        if (!adaptor.isPresent()) {
            throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
        }
        final SamlRegisteredServiceServiceProviderMetadataFacade facade = adaptor.get();
        verifyAuthenticationContextSignature(ctx, request, artifactMsg, facade);
        final String artifactId = artifactMsg.getArtifact().getArtifact();
        final String ticketId = artifactTicketFactory.createTicketIdFor(artifactId);
        final SamlArtifactTicket ticket = this.ticketRegistry.getTicket(ticketId, SamlArtifactTicket.class);
        final Service issuerService = webApplicationServiceFactory.createService(issuer);
        final Assertion casAssertion = buildCasAssertion(ticket.getTicketGrantingTicket().getAuthentication(), issuerService, service, CollectionUtils.wrap("artifact", ticket));
        this.responseBuilder.build(artifactMsg, request, response, casAssertion, service, facade, SAMLConstants.SAML2_ARTIFACT_BINDING_URI);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        request.setAttribute(SamlIdPConstants.REQUEST_ATTRIBUTE_ERROR, e.getMessage());
        samlFaultResponseBuilder.build(artifactMsg, request, response, null, null, null, SAMLConstants.SAML2_ARTIFACT_BINDING_URI);
    }
}
Also used : ArtifactResolve(org.opensaml.saml.saml2.core.ArtifactResolve) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) Assertion(org.jasig.cas.client.validation.Assertion) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) Service(org.apereo.cas.authentication.principal.Service) MessageContext(org.opensaml.messaging.context.MessageContext) SamlArtifactTicket(org.apereo.cas.ticket.artifact.SamlArtifactTicket) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 34 with Assertion

use of org.jasig.cas.client.validation.Assertion in project cas by apereo.

the class SamlProfileSamlNameIdBuilder method prepareNameIdAttribute.

/**
 * Prepare name id attribute id p attribute.
 *
 * @param casAssertion  the assertion
 * @param nameFormat the name format
 * @param adaptor    the adaptor
 * @return the idp attribute
 */
protected IdPAttribute prepareNameIdAttribute(final Object casAssertion, final String nameFormat, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) {
    final Assertion assertion = Assertion.class.cast(casAssertion);
    final IdPAttribute attribute = new IdPAttribute(AttributePrincipal.class.getName());
    final String nameIdValue;
    switch(nameFormat.trim()) {
        case NameIDType.TRANSIENT:
            nameIdValue = persistentIdGenerator.generate(assertion.getPrincipal().getName(), adaptor.getEntityId());
            break;
        default:
            nameIdValue = assertion.getPrincipal().getName();
    }
    final IdPAttributeValue<String> value = new StringAttributeValue(nameIdValue);
    LOGGER.debug("NameID attribute value is set to [{}]", value);
    attribute.setValues(CollectionUtils.wrap(value));
    return attribute;
}
Also used : Assertion(org.jasig.cas.client.validation.Assertion) IdPAttribute(net.shibboleth.idp.attribute.IdPAttribute) StringAttributeValue(net.shibboleth.idp.attribute.StringAttributeValue) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal)

Example 35 with Assertion

use of org.jasig.cas.client.validation.Assertion in project cas by apereo.

the class SamlProfileSamlSubjectBuilder method buildSubject.

private Subject buildSubject(final HttpServletRequest request, final HttpServletResponse response, final RequestAbstractType authnRequest, final Object casAssertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final String binding) throws SamlException {
    final Assertion assertion = Assertion.class.cast(casAssertion);
    final ZonedDateTime validFromDate = ZonedDateTime.ofInstant(assertion.getValidFromDate().toInstant(), ZoneOffset.UTC);
    LOGGER.debug("Locating the assertion consumer service url for binding [{}]", binding);
    @NonNull final AssertionConsumerService acs = adaptor.getAssertionConsumerService(binding);
    final String location = StringUtils.isBlank(acs.getResponseLocation()) ? acs.getLocation() : acs.getResponseLocation();
    if (StringUtils.isBlank(location)) {
        LOGGER.warn("Subject recipient is not defined from either authentication request or metadata for [{}]", adaptor.getEntityId());
    }
    final NameID nameId = getNameIdForService(request, response, authnRequest, service, adaptor, binding, assertion);
    final Subject subject = newSubject(nameId, service.isSkipGeneratingSubjectConfirmationRecipient() ? null : location, service.isSkipGeneratingSubjectConfirmationNotOnOrAfter() ? null : validFromDate.plusSeconds(this.skewAllowance), service.isSkipGeneratingSubjectConfirmationInResponseTo() ? null : authnRequest.getID(), service.isSkipGeneratingSubjectConfirmationNotBefore() ? null : ZonedDateTime.now());
    LOGGER.debug("Created SAML subject [{}]", subject);
    return subject;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) NameID(org.opensaml.saml.saml2.core.NameID) NonNull(lombok.NonNull) Assertion(org.jasig.cas.client.validation.Assertion) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) Subject(org.opensaml.saml.saml2.core.Subject)

Aggregations

Assertion (org.jasig.cas.client.validation.Assertion)41 AssertionImpl (org.jasig.cas.client.validation.AssertionImpl)14 Test (org.junit.Test)13 AttributePrincipal (org.jasig.cas.client.authentication.AttributePrincipal)10 HashMap (java.util.HashMap)5 TicketValidationException (org.jasig.cas.client.validation.TicketValidationException)5 MessageContext (org.opensaml.messaging.context.MessageContext)5 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)5 ZonedDateTime (java.time.ZonedDateTime)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)3 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)3 LinkedHashMap (java.util.LinkedHashMap)2 HttpSession (javax.servlet.http.HttpSession)2 SneakyThrows (lombok.SneakyThrows)2 Authentication (org.apereo.cas.authentication.Authentication)2 AttributePrincipalImpl (org.jasig.cas.client.authentication.AttributePrincipalImpl)2 Cas30ServiceTicketValidator (org.jasig.cas.client.validation.Cas30ServiceTicketValidator)2 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2