Search in sources :

Example 11 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class UsernameTokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.debug("Validating UsernameToken");
    if (parser == null) {
        throw new IllegalStateException("XMLParser must be configured.");
    }
    if (failedLoginDelayer == null) {
        throw new IllegalStateException("Failed Login Delayer must be configured");
    }
    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);
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(ReceivedToken.STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isUsernameToken()) {
        return response;
    }
    //
    // Turn the JAXB UsernameTokenType into a DOM Element for validation
    //
    UsernameTokenType usernameTokenType = (UsernameTokenType) validateTarget.getToken();
    JAXBElement<UsernameTokenType> tokenType = new JAXBElement<>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
    Document doc = DOMUtils.createDocument();
    Element rootElement = doc.createElement("root-element");
    List<String> ctxPath = new ArrayList<>(1);
    ctxPath.add(UsernameTokenType.class.getPackage().getName());
    Element usernameTokenElement = null;
    ParserConfigurator configurator = parser.configureParser(ctxPath, UsernameTokenValidator.class.getClassLoader());
    try {
        parser.marshal(configurator, tokenType, rootElement);
        usernameTokenElement = (Element) rootElement.getFirstChild();
    } catch (ParserException ex) {
        LOGGER.info("Unable to parse username token", ex);
        return response;
    }
    //
    try {
        boolean allowNamespaceQualifiedPasswordTypes = requestData.isAllowNamespaceQualifiedPasswordTypes();
        UsernameToken ut = new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, new BSPEnforcer());
        // The parsed principal is set independent whether validation is successful or not
        response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
        if (ut.getPassword() == null) {
            failedLoginDelayer.delay(ut.getName());
            return response;
        }
        Credential credential = new Credential();
        credential.setUsernametoken(ut);
        //Only this section is new, the rest is copied from the apache class
        Set<Map.Entry<String, Validator>> entries = validators.entrySet();
        for (Map.Entry<String, Validator> entry : entries) {
            try {
                entry.getValue().validate(credential, requestData);
                validateTarget.setState(ReceivedToken.STATE.VALID);
                break;
            } catch (WSSecurityException ex) {
                LOGGER.debug("Unable to validate user against {}" + entry.getKey(), ex);
            }
        }
        if (ReceivedToken.STATE.INVALID.equals(validateTarget.getState())) {
            failedLoginDelayer.delay(ut.getName());
            return response;
        }
        //end new section
        Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
        response.setPrincipal(principal);
        response.setTokenRealm(null);
        validateTarget.setState(ReceivedToken.STATE.VALID);
        validateTarget.setPrincipal(principal);
    } catch (WSSecurityException ex) {
        LOGGER.debug("Unable to validate token.", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) RequestData(org.apache.wss4j.dom.handler.RequestData) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) ParserException(org.codice.ddf.parser.ParserException) Credential(org.apache.wss4j.dom.validate.Credential) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) BSPEnforcer(org.apache.wss4j.common.bsp.BSPEnforcer) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) JAXBElement(javax.xml.bind.JAXBElement) ParserConfigurator(org.codice.ddf.parser.ParserConfigurator) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Validator(org.apache.wss4j.dom.validate.Validator) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) TokenValidator(org.apache.cxf.sts.token.validator.TokenValidator) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 12 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class MetacardMarshaller method getRegistryPackageAsXml.

/**
     * Converts the RegistryPackageType into an xml string
     *
     * @param registryPackage Registry package to convert
     * @return Ebrim xml string
     * @throws ParserException
     */
public String getRegistryPackageAsXml(RegistryPackageType registryPackage) throws ParserException {
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        JAXBElement<RegistryPackageType> registryObjectTypeJAXBElement = EbrimConstants.RIM_FACTORY.createRegistryPackage(registryPackage);
        parser.marshal(marshalConfigurator, registryObjectTypeJAXBElement, outputStream);
        return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new ParserException("Error parsing registry package to ebrim xml", e);
    }
}
Also used : ParserException(org.codice.ddf.parser.ParserException) RegistryPackageType(oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryPackageType) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 13 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class GeometryTransformer method transform.

public BinaryContent transform(Attribute attribute) throws CatalogTransformerException {
    ParserConfigurator parserConfigurator = getParserConfigurator().setHandler(new DefaultValidationEventHandler());
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream(BUFFER_SIZE);
        getParser().marshal(parserConfigurator, GeometryAdapter.marshalFrom(attribute), os);
        ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());
        return new BinaryContentImpl(bais, MIME_TYPE);
    } catch (ParserException e) {
        throw new CatalogTransformerException("Failed to marshall geometry data", e);
    }
}
Also used : ParserConfigurator(org.codice.ddf.parser.ParserConfigurator) ParserException(org.codice.ddf.parser.ParserException) ByteArrayInputStream(java.io.ByteArrayInputStream) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) DefaultValidationEventHandler(javax.xml.bind.helpers.DefaultValidationEventHandler)

Example 14 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class XmlParser method unmarshal.

private <T> T unmarshal(ParserConfigurator configurator, Function<Unmarshaller, T> func) throws ParserException {
    JAXBContext jaxbContext = getContext(configurator.getContextPath(), configurator.getClassLoader());
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(configurator.getClassLoader());
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        if (configurator.getAdapter() != null) {
            unmarshaller.setAdapter(configurator.getAdapter());
        }
        if (configurator.getHandler() != null) {
            unmarshaller.setEventHandler(configurator.getHandler());
        }
        for (Map.Entry<String, Object> propRow : configurator.getProperties().entrySet()) {
            unmarshaller.setProperty(propRow.getKey(), propRow.getValue());
        }
        return func.apply(unmarshaller);
    } catch (RuntimeException | JAXBException e) {
        LOGGER.debug("Error unmarshalling ", e);
        throw new ParserException("Error unmarshalling", e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }
}
Also used : ParserException(org.codice.ddf.parser.ParserException) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) Map(java.util.Map)

Example 15 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class XmlParser method getContext.

private JAXBContext getContext(List<String> contextPath, ClassLoader loader) throws ParserException {
    String joinedPath = CTX_JOINER.join(contextPath);
    JAXBContext jaxbContext;
    try {
        jaxbContext = jaxbContextCache.get(new CacheKey(joinedPath, loader));
    } catch (ExecutionException e) {
        LOGGER.info("Unable to create JAXB context using context path: {}", joinedPath, e);
        throw new ParserException("Unable to create XmlParser", e.getCause());
    }
    return jaxbContext;
}
Also used : ParserException(org.codice.ddf.parser.ParserException) JAXBContext(javax.xml.bind.JAXBContext) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

ParserException (org.codice.ddf.parser.ParserException)17 ArrayList (java.util.ArrayList)7 ParserConfigurator (org.codice.ddf.parser.ParserConfigurator)7 IOException (java.io.IOException)5 Map (java.util.Map)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 JAXBElement (javax.xml.bind.JAXBElement)4 RegistryPackageType (oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryPackageType)4 InputStream (java.io.InputStream)3 UsernameTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType)3 Metacard (ddf.catalog.data.Metacard)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Principal (java.security.Principal)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 CallbackHandler (javax.security.auth.callback.CallbackHandler)2 JAXBContext (javax.xml.bind.JAXBContext)2 ExternalIdentifierType (oasis.names.tc.ebxml_regrep.xsd.rim._3.ExternalIdentifierType)2 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)2 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)2 TokenValidator (org.apache.cxf.sts.token.validator.TokenValidator)2