private void assertHttpPostOrGetOrEmpty() throws ServiceException { String httpMethod = m_servletRequest.getMethod(); if (httpMethod == null || httpMethod.isEmpty()) { return; } if (!("GET".equalsIgnoreCase(httpMethod) || "POST".equalsIgnoreCase(httpMethod))) { throw new ServiceException("HTTP Method <" + httpMethod + " > not allowed. Use <POST> or <GET>.", httpMethod); } }
private void extractWssParamService() throws ServiceException { m_wssParamService = m_wssParams.get(WSSRequestContext.PARAM_SERVICE); if (m_wssParamService == null) { LOG.warn("Missing SERVICE parameter. Assuming 'WSS'."); return; } if (!"WSS".equalsIgnoreCase(m_wssParamService)) { throw new ServiceException("Invalid SERVICE parameter <" + m_wssParamService + ">.", ServiceException.INVALID_FORMAT); } }
private void initWSSProtocolParameters() throws DOMParserException, ServiceException { try { m_wssParams = initWSSRequestContext(m_servletRequest); } catch (IOException e) { LOG.error("Error reading WSS request", e); throw new ServiceException("Error processing WSS request", ServiceException.SERVICE_ERROR); } }
private Transferable createDefaultError() { return (new ServiceException(ServiceException.ERROR_MESSAGE, ServiceException.SERVICE_ERROR)).getAsTransferable(); }
private void checkForErrors(final Element licClientResp) throws ServiceException { // check if response is an error message // if so, retrieve message from response // and throw ServiceException if (!licClientResp.getNodeName().equals("ExceptionReport")) { return; } try { String exceptionText = "undefined"; NodeList nl = licClientResp.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) { NodeList snl = nl.item(i).getChildNodes(); for (int j = 0; j < snl.getLength(); j++) { if (snl.item(j).getNodeType() == Node.ELEMENT_NODE) { exceptionText = snl.item(j).getTextContent(); break; } } break; } } throw new ServiceException(exceptionText, ServiceException.SERVICE_ERROR); } catch (Exception e) { throw new ServiceException(e.getMessage(), ServiceException.SERVICE_ERROR); } }
@Override public Transferable doRequest(Transferable owsRequest, String pDCP, PreconditionContext context) throws ServiceException { assertAssertionSentToConsumer(context); Transferable transferable; if (pDCP.equalsIgnoreCase("HTTP_GET")) { transferable = forwardGet(owsRequest); } else if (pDCP.equalsIgnoreCase("HTTP_POST")) { transferable = forwardPost(owsRequest); } else { throw new ServiceException("Unsupported DCP type <" + pDCP + ">", ServiceException.SERVICE_ERROR); } return transferable; }
private AuthenticationContext loginSessionId(final SessionIDCredential sessionIDCredential) throws ServiceException { try { // session are explicite handled SessionInfo session = m_sessionService.getSession(sessionIDCredential.getSessionId()); AuthenticationContext authContext = session.getAuthenticationContext(); if (authContext != null && authContext.isAuthenticated()) { // touch the session only if state is valid m_sessionService.touchSession(session.getId()); } return authContext; } catch (SessionExpiredException ex) { throw new ServiceException("Session expired, please reauthenticate.", ServiceException.SESSION_EXPIRED); } catch (UnknownSessionException ex) { throw new ServiceException("No matching session found. Session may already be closed.", ServiceException.INVALID_SESSION); } catch (SessionClosedException ex) { throw new ServiceException("Session already closed.", ServiceException.INVALID_SESSION); } }
private Element requestAvailableLicenseRefs(String wssBaseUrlString, SAMLTicket samlTicket, LicensePrecondition precondition) throws UnsupportedEncodingException, DOMParserException, ServiceException { // return license references String licenseBrokerClientURL = precondition.getSsoGetUrl(); String ticketString = samlTicket.asBase64String(); // replace whitespaces and line breaks ticketString = ticketString.replaceAll("\r\n", "").trim(); // TODO Why encoding strings that need not to be // URL-encoded? // TODO Use StringBuffer!!! String data = URLEncoder.encode("WSS", "UTF-8") + "=" + URLEncoder.encode(wssBaseUrlString, "UTF-8"); data += "&" + URLEncoder.encode("ticket", "UTF-8") + "=" + URLEncoder.encode(ticketString, "UTF-8"); Element licClientResp = null; try { InputStream is = postData(licenseBrokerClientURL, data); Document doc = DOMParser.createNew().parse(new InputSource(is)); licClientResp = doc.getDocumentElement(); } catch (MalformedURLException e) { sLogger.error("Error while retrieving license references from " + licenseBrokerClientURL + "!", e); throw new ServiceException(e.getMessage(), ServiceException.SERVICE_ERROR, e); } catch (IOException e) { sLogger.error("Error while retrieving license references from " + licenseBrokerClientURL + "!", e); throw new ServiceException(e.getMessage(), ServiceException.SERVICE_ERROR, e); } checkForErrors(licClientResp); return licClientResp; }
private void sessionLogout(final String sessionID) throws ServiceException { SessionInfo sessioninfo; try { sessioninfo = m_sessionService.closeSession(sessionID); } catch (SessionException e) { throw new ServiceException("Invalid Session. Session may already be closed.", ServiceException.INVALID_SESSION, e); } try { AuthenticationContext authctx = sessioninfo.getAuthenticationContext(); if (authctx != null) { m_authenticationService.logout(authctx); } } catch (AuthenticationException ex) { LOG.warn("logout failed during close session request", ex); } }
escapedEndpointUrl = new URI(unescapedEndpointUrl.getProtocol(), null, unescapedEndpointUrl.getHost(), unescapedEndpointUrl.getPort(), unescapedEndpointUrl.getPath(), null, null).toASCIIString(); } catch (MalformedURLException | URISyntaxException e) { throw new ServiceException(e.getMessage(), ServiceException.SERVICE_ERROR, e); throw new ServiceException("Error forwarding request to <" + protectedServiceEndpoint + ">", ServiceException.SERVICE_ERROR, e);
request = LicenseBrokerRequestCreator.createOrderLicenseRequest(configurationParameters, productId); } catch (SOAPException e) { throw new ServiceException("OrderLicense request creation failed: " + e.getMessage(), ServiceException.INVALID_FORMAT); samlTicket = response.getBody().getFirstChild().getFirstChild(); } catch (AxisFault e) { throw new ServiceException("OrderLicense request to LicenseBroker failed. Check endpoint and network!", ServiceException.SERVICE_ERROR); } catch (SOAPException e) { throw new ServiceException("LicenseBroker response was malformed.", ServiceException.INVALID_SAMLRESPONSE);
private PAOSResponse requestPAOSResponse() throws ServiceException { GetMethod method = new GetMethod(getURL().toString()); method.addRequestHeader(new Header("Accept", "application/vnd.paos+xml")); method.addRequestHeader(new Header("PAOS", "ver='urn:liberty:paos:2003-08';'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'")); try { m_client.executeMethod(method); InputStream responseBodyStream = method.getResponseBodyAsStream(); PAOSResponse paosResponse = PAOSResponse.createFromXMLStream(responseBodyStream); return paosResponse; } catch (Exception e) { throw new ServiceException(String.format("Could not send basic GET request to <%s>.", getURL()), ServiceException.SERVICE_ERROR, e); } finally { method.releaseConnection(); } }
/** * Creates an instance of this class from an XML file. * * @param in * a service excpetion XML document * * @return * @throws org.xml.sax.SAXException * @throws IOException */ public static ServiceException createFromXML(InputSource in) { Document excDoc = DOMParser.createNew().parse(in); XMLPathCtx pathCtx = XMLPathCtx.createNew(); String cd = pathCtx.findIn(excDoc).text("//ServiceException/@code").get().trim(); if (cd.equals("")) cd = "No code available"; String msg = pathCtx.findIn(excDoc).text("//ServiceException/text()").get().trim(); if (msg.equals("")) msg = "No exception information available"; return new ServiceException(msg, cd); }
private Transferable forwardPost(Transferable owsRequest) throws ServiceException { PostMethod method = new PostMethod(getURL().toString()); String contentType = (String) owsRequest.getAttributeValue(HttpHeaderAttribute.HEADER_NAME_CONTENTTYPE); method.setRequestEntity(new InputStreamRequestEntity(owsRequest.getPayload().getAsStream(), contentType)); Transferable trans; try { trans = initBasicResponseTransferable(method); } catch (Exception e) { throw new ServiceException(String.format("Could not send basic GET request to <%s>.", getURL()), ServiceException.SERVICE_ERROR, e); } finally { method.releaseConnection(); } return trans; }
/** * Method login. * * @param credential the credential. * @return AuthenticationContext. * @throws ServiceException if error occurs. */ private AuthenticationContext login(final Credential credential) throws ServiceException { AuthenticationContext authContext; if ((credential instanceof SessionIDCredential)) { authContext = loginSessionId((SessionIDCredential) credential); } else { try { // support use of GetSAMLResponse without creation of a session. authContext = m_authenticationService.login(new CredentialsCallbackHandler().add(credential)); } catch (AuthenticationException e) { LOG.warn("Login failed for credentials " + credential); // todo: react on specialized exceptions (like account expired // etc.) throw new ServiceException(e.getMessage(), ServiceException.AUTHENTICATION_FAILED); } } return authContext; }
request = LicenseBrokerRequestCreator.createGetLicenseModelRequest(productIds); } catch (SOAPException e) { throw new ServiceException("GetLicenseModel request creation failed: " + e.getMessage(), ServiceException.INVALID_FORMAT); response = callSoapServiceForEnvelope(licBroURL, request); } catch (AxisFault e) { throw new ServiceException("GetLicenseModel request to LicenseBroker failed. Check endpoint and network!", ServiceException.SERVICE_ERROR);
/** * @param owsRequest * @return * @throws ServiceException */ private Transferable forwardGet(Transferable owsRequest) throws ServiceException { GetMethod method = new GetMethod(getURL().toString()); Payload payload = owsRequest.getPayload(); String baseQueryString = method.getQueryString(); if (baseQueryString != null && baseQueryString.length() > 0) { baseQueryString = baseQueryString + "&" + payload.toString(); } else { baseQueryString = payload.toString(); } method.setQueryString(baseQueryString); Transferable trans; try { trans = initBasicResponseTransferable(method); } catch (Exception e) { throw new ServiceException(String.format("Could not send basic GET request to <%s>.", getURL()), ServiceException.SERVICE_ERROR, e); } finally { method.releaseConnection(); } return trans; }
private SAML2ResponseMessage sendAssertionRequest(UsernamePasswordCredential cred, String request, PostMethod method) throws ServiceException { String username = cred.getUsername(); String password = new String(cred.getPassword()); m_client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); m_client.getParams().setAuthenticationPreemptive(true); method.setDoAuthentication(true); try { method.setRequestEntity(new StringRequestEntity(request, "application/vnd.paos+xml", XML_CHARSET)); m_client.executeMethod(method); InputStream responseStream = method.getResponseBodyAsStream(); return SAML2ResponseMessage.createFromSOAPMessage(new InputStreamReader(responseStream, method .getResponseCharSet())); } catch (Exception e) { throw new ServiceException("Could not request SAML response", ServiceException.SERVICE_ERROR, e); } finally { method.releaseConnection(); } }
public void sendSamlResponseToAssertionConsumer(SAML2ResponseMessage saml2ResponseMessage) throws DOMSerializerException, ServiceException { Element relayState = getPaosResponse().getRelayState(); saml2ResponseMessage = saml2ResponseMessage.insertRelayState(relayState); PostMethod postMethod = new PostMethod(getAssertionConsumerUrl()); try { postMethod.setRequestEntity(new StringRequestEntity(saml2ResponseMessage.toString(), "application/vnd.paos+xml", saml2ResponseMessage.getXmlEncoding())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { m_client.executeMethod(postMethod); String response = postMethod.getResponseBodyAsString(); m_assertionsSentToConsumer = true; } catch (Exception e) { throw new ServiceException(String.format("Could not send basic GET request to <%s>.", getURL()), ServiceException.SERVICE_ERROR, e); } finally { postMethod.releaseConnection(); } }
@Override public Transferable doRequest(Transferable owsRequest, String pDCP, PreconditionContext context) throws ServiceException { FacadeUrlPrecondition facadeUrlPrec = findFacadeUrlPrecondition(context); if (facadeUrlPrec == null) throw new ServiceException("Missing FacadeUrlPrecondition", ServiceException.INVALID_FORMAT); URL facadeUrl = facadeUrlPrec.getFacadeUurl(); IdentifyPrecondition idPrec = findIdentifyPrecondition(context); LicensePrecondition licPrec = findLicensePrecondition(context); LicenseReference licRef = null; if (licPrec != null) licRef = licPrec.getLicenseReference(); Credential credential = idPrec.getCredential(); return m_serviceAdapter.doService(owsRequest, credential, facadeUrl, pDCP, licRef); }