Search in sources :

Example 1 with WsFederationCredential

use of org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential in project cas by apereo.

the class WsFederationAuthenticationHandler method doAuthentication.

@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final WsFederationCredential wsFederationCredentials = (WsFederationCredential) credential;
    if (wsFederationCredentials != null) {
        final Map attributes = wsFederationCredentials.getAttributes();
        final Principal principal = this.principalFactory.createPrincipal(wsFederationCredentials.getId(), attributes);
        return this.createHandlerResult(wsFederationCredentials, principal, new ArrayList<>());
    }
    throw new FailedLoginException();
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) Map(java.util.Map) Principal(org.apereo.cas.authentication.principal.Principal) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential)

Example 2 with WsFederationCredential

use of org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential in project cas by apereo.

the class WsFederationHelperTests method verifyCreateCredentialFromToken.

@Test
public void verifyCreateCredentialFromToken() throws Exception {
    final String wresult = testTokens.get(GOOD_TOKEN);
    final Assertion assertion = wsFederationHelper.parseTokenFromString(wresult, wsFedConfig);
    final WsFederationCredential expResult = new WsFederationCredential();
    expResult.setIssuedOn(ZonedDateTime.parse("2014-02-26T22:51:16.504Z"));
    expResult.setNotBefore(ZonedDateTime.parse("2014-02-26T22:51:16.474Z"));
    expResult.setNotOnOrAfter(ZonedDateTime.parse("2014-02-26T23:51:16.474Z"));
    expResult.setIssuer("http://adfs.example.com/adfs/services/trust");
    expResult.setAudience("urn:federation:cas");
    expResult.setId("_6257b2bf-7361-4081-ae1f-ec58d4310f61");
    final WsFederationCredential result = wsFederationHelper.createCredentialFromToken(assertion);
    assertNotNull("testCreateCredentialFromToken() - Not Null", result);
    assertEquals("testCreateCredentialFromToken() - IssuedOn", expResult.getIssuedOn(), result.getIssuedOn());
    assertEquals("testCreateCredentialFromToken() - NotBefore", expResult.getNotBefore(), result.getNotBefore());
    assertEquals("testCreateCredentialFromToken() - NotOnOrAfter", expResult.getNotOnOrAfter(), result.getNotOnOrAfter());
    assertEquals("testCreateCredentialFromToken() - Issuer", expResult.getIssuer(), result.getIssuer());
    assertEquals("testCreateCredentialFromToken() - Audience", expResult.getAudience(), result.getAudience());
    assertEquals("testCreateCredentialFromToken() - Id", expResult.getId(), result.getId());
}
Also used : Assertion(org.opensaml.saml.saml1.core.Assertion) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) Test(org.junit.Test)

Example 3 with WsFederationCredential

use of org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential in project cas by apereo.

the class WsFederationHelper method createCredentialFromToken.

/**
     * createCredentialFromToken converts a SAML 1.1 assertion to a WSFederationCredential.
     *
     * @param assertion the provided assertion
     * @return an equivalent credential.
     */
public WsFederationCredential createCredentialFromToken(final Assertion assertion) {
    final ZonedDateTime retrievedOn = ZonedDateTime.now();
    LOGGER.debug("Retrieved on [{}]", retrievedOn);
    final WsFederationCredential credential = new WsFederationCredential();
    credential.setRetrievedOn(retrievedOn);
    credential.setId(assertion.getID());
    credential.setIssuer(assertion.getIssuer());
    credential.setIssuedOn(ZonedDateTime.parse(assertion.getIssueInstant().toDateTimeISO().toString()));
    final Conditions conditions = assertion.getConditions();
    if (conditions != null) {
        credential.setNotBefore(ZonedDateTime.parse(conditions.getNotBefore().toDateTimeISO().toString()));
        credential.setNotOnOrAfter(ZonedDateTime.parse(conditions.getNotOnOrAfter().toDateTimeISO().toString()));
        if (!conditions.getAudienceRestrictionConditions().isEmpty()) {
            credential.setAudience(conditions.getAudienceRestrictionConditions().get(0).getAudiences().get(0).getUri());
        }
    }
    if (!assertion.getAuthenticationStatements().isEmpty()) {
        credential.setAuthenticationMethod(assertion.getAuthenticationStatements().get(0).getAuthenticationMethod());
    }
    //retrieve an attributes from the assertion
    final HashMap<String, List<Object>> attributes = new HashMap<>();
    assertion.getAttributeStatements().stream().flatMap(attributeStatement -> attributeStatement.getAttributes().stream()).forEach(item -> {
        LOGGER.debug("Processed attribute: [{}]", item.getAttributeName());
        final List<Object> itemList = IntStream.range(0, item.getAttributeValues().size()).mapToObj(i -> ((XSAny) item.getAttributeValues().get(i)).getTextContent()).collect(Collectors.toList());
        if (!itemList.isEmpty()) {
            attributes.put(item.getAttributeName(), itemList);
        }
    });
    credential.setAttributes(attributes);
    LOGGER.debug("Credential: [{}]", credential);
    return credential;
}
Also used : XSAny(org.opensaml.core.xml.schema.XSAny) ChainingEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.ChainingEncryptedKeyResolver) KeyPair(java.security.KeyPair) ExplicitKeySignatureTrustEngine(org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine) Assertion(org.opensaml.saml.saml1.core.Assertion) ZonedDateTime(java.time.ZonedDateTime) StaticCredentialResolver(org.opensaml.security.credential.impl.StaticCredentialResolver) LoggerFactory(org.slf4j.LoggerFactory) Security(java.security.Security) SamlUtils(org.apereo.cas.support.saml.SamlUtils) Conditions(org.opensaml.saml.saml1.core.Conditions) StaticKeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver) ByteArrayInputStream(java.io.ByteArrayInputStream) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) Document(org.w3c.dom.Document) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) UsageType(org.opensaml.security.credential.UsageType) SecurityException(org.opensaml.security.SecurityException) PEMParser(org.bouncycastle.openssl.PEMParser) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) ProtocolCriterion(org.opensaml.saml.criterion.ProtocolCriterion) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) OpenSamlConfigBean(org.apereo.cas.support.saml.OpenSamlConfigBean) List(java.util.List) KeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) RequestedSecurityToken(org.opensaml.soap.wsfed.RequestedSecurityToken) UnmarshallerFactory(org.opensaml.core.xml.io.UnmarshallerFactory) EncryptedData(org.opensaml.xmlsec.encryption.EncryptedData) EncryptedElementTypeEncryptedKeyResolver(org.opensaml.saml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver) IntStream(java.util.stream.IntStream) EncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.EncryptedKeyResolver) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) UsageCriterion(org.opensaml.security.criteria.UsageCriterion) HashMap(java.util.HashMap) SignaturePrevalidator(org.opensaml.xmlsec.signature.support.SignaturePrevalidator) ArrayList(java.util.ArrayList) Decrypter(org.opensaml.saml.saml2.encryption.Decrypter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) X509CertParser(org.bouncycastle.jce.provider.X509CertParser) SAMLSignatureProfileValidator(org.opensaml.saml.security.impl.SAMLSignatureProfileValidator) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) XMLObject(org.opensaml.core.xml.XMLObject) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) CredentialResolver(org.opensaml.security.credential.CredentialResolver) SignatureTrustEngine(org.opensaml.xmlsec.signature.support.SignatureTrustEngine) InlineEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver) RequestSecurityTokenResponse(org.opensaml.soap.wsfed.RequestSecurityTokenResponse) Logger(org.slf4j.Logger) Credential(org.opensaml.security.credential.Credential) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) Throwables(com.google.common.base.Throwables) InputStreamReader(java.io.InputStreamReader) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Element(org.w3c.dom.Element) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) BufferedReader(java.io.BufferedReader) SimpleRetrievalMethodEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.SimpleRetrievalMethodEncryptedKeyResolver) InputStream(java.io.InputStream) ZonedDateTime(java.time.ZonedDateTime) HashMap(java.util.HashMap) List(java.util.List) ArrayList(java.util.ArrayList) XMLObject(org.opensaml.core.xml.XMLObject) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) Conditions(org.opensaml.saml.saml1.core.Conditions) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) XSAny(org.opensaml.core.xml.schema.XSAny)

Example 4 with WsFederationCredential

use of org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential in project cas by apereo.

the class WsFederationAction method doExecute.

/**
     * Executes the webflow action.
     *
     * @param context the context
     * @return the event
     * @throws Exception all unhandled exceptions
     */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    try {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        final HttpSession session = request.getSession();
        final String wa = request.getParameter(WA);
        // it's an authentication
        if (StringUtils.isNotBlank(wa) && wa.equalsIgnoreCase(WSIGNIN)) {
            final String wResult = request.getParameter(WRESULT);
            LOGGER.debug("Parameter [{}] received: [{}]", WRESULT, wResult);
            if (StringUtils.isBlank(wResult)) {
                LOGGER.error("No [{}] parameter is found", WRESULT);
                return error();
            }
            // create credentials
            LOGGER.debug("Attempting to create an assertion from the token parameter");
            final Assertion assertion = this.wsFederationHelper.parseTokenFromString(wResult, configuration);
            if (assertion == null) {
                LOGGER.error("Could not validate assertion via parsing the token from [{}]", WRESULT);
                return error();
            }
            LOGGER.debug("Attempting to validate the signature on the assertion");
            if (!this.wsFederationHelper.validateSignature(assertion, this.configuration)) {
                LOGGER.error("WS Requested Security Token is blank or the signature is not valid.");
                return error();
            }
            try {
                final Service service = (Service) session.getAttribute(SERVICE);
                LOGGER.debug("Creating credential based on the provided assertion");
                final WsFederationCredential credential = this.wsFederationHelper.createCredentialFromToken(assertion);
                final String rpId = getRelyingPartyIdentifier(service);
                if (credential != null && credential.isValid(rpId, this.configuration.getIdentityProviderIdentifier(), this.configuration.getTolerance())) {
                    LOGGER.debug("Validated assertion for the created credential successfully");
                    if (this.configuration.getAttributeMutator() != null) {
                        LOGGER.debug("Modifying credential attributes based on [{}]", this.configuration.getAttributeMutator().getClass().getSimpleName());
                        this.configuration.getAttributeMutator().modifyAttributes(credential.getAttributes());
                    }
                } else {
                    LOGGER.warn("SAML assertions are blank or no longer valid based on RP identifier [{}] and IdP identifier [{}]", rpId, this.configuration.getIdentityProviderIdentifier());
                    final String url = authorizationUrl + rpId;
                    context.getFlowScope().put(PROVIDERURL, url);
                    LOGGER.warn("Created authentication url [{}] and returning error", url);
                    return error();
                }
                context.getFlowScope().put(SERVICE, service);
                restoreRequestAttribute(request, session, THEME);
                restoreRequestAttribute(request, session, LOCALE);
                restoreRequestAttribute(request, session, METHOD);
                LOGGER.debug("Creating final authentication result based on the given credential");
                final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, credential);
                LOGGER.debug("Attempting to create a ticket-granting ticket for the authentication result");
                WebUtils.putTicketGrantingTicketInScopes(context, this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult));
                LOGGER.info("Token validated and new [{}] created: [{}]", credential.getClass().getName(), credential);
                return success();
            } catch (final AbstractTicketException e) {
                LOGGER.error(e.getMessage(), e);
                return error();
            }
        } else {
            // no authentication : go to login page. save parameters in web session
            final Service service = (Service) context.getFlowScope().get(SERVICE);
            if (service != null) {
                session.setAttribute(SERVICE, service);
            }
            saveRequestParameter(request, session, THEME);
            saveRequestParameter(request, session, LOCALE);
            saveRequestParameter(request, session, METHOD);
            final String url = authorizationUrl + getRelyingPartyIdentifier(service);
            LOGGER.info("Preparing to redirect to the IdP [{}]", url);
            context.getFlowScope().put(PROVIDERURL, url);
        }
        LOGGER.debug("Returning error event");
        return error();
    } catch (final Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return error();
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSession(javax.servlet.http.HttpSession) Assertion(org.opensaml.saml.saml1.core.Assertion) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Aggregations

WsFederationCredential (org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential)4 Assertion (org.opensaml.saml.saml1.core.Assertion)3 Throwables (com.google.common.base.Throwables)1 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 StandardCharsets (java.nio.charset.StandardCharsets)1 KeyPair (java.security.KeyPair)1 Security (java.security.Security)1 ZonedDateTime (java.time.ZonedDateTime)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Collectors (java.util.stream.Collectors)1 IntStream (java.util.stream.IntStream)1 FailedLoginException (javax.security.auth.login.FailedLoginException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpSession (javax.servlet.http.HttpSession)1