SSL Handshake using httpclient respond with 403 - java

I am new to Https Protocol and want to consume soap based web service using apache httpclient.
When I call the web service from Soap UI client it is working fine but when I call same webservice from httpclient with same .jks file It is responding 403 forbidden.
Following is the my httpclient code
import java.io.ByteArrayOutputStream;
import javax.net.ssl.SSLContext;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.KeyManagementException;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
public class HttpClientFactory {
private static CloseableHttpClient client;
public HttpClient getHttpsClient() throws Exception {
if (client != null) {
return client;
}
SSLContext sslcontext = getSSLContext();
SSLConnectionSocketFactory factory =
new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy(){
#Override
public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
// TODO Implement this method
return 15000;
}
};
client = HttpClients.custom().setSSLSocketFactory(factory).setKeepAliveStrategy(myStrategy).setHostnameVerifier(new AllowAllHostnameVerifier()).build();
return client;
}
public static void releaseInstance() {
client = null;
}
private SSLContext getSSLContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
IOException, KeyManagementException {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream =
new FileInputStream(new File("Test.jks"));
try {
trustStore.load(instream, "password".toCharArray());
} finally {
instream.close();
}
final TrustStrategy trustStrategy = new TrustStrategy() {
public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
for (X509Certificate cer : chain)
printCertificate(cer);
return true;
}
};
return SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();
}
public static void main(String[] args) {
System.setProperty("javax.net.debug", "ssl:handshake");
CloseableHttpClient httpclient = null;
try {
httpclient = (CloseableHttpClient) new HttpClientFactory().getHttpsClient();
} catch (Exception e) {
e.printStackTrace();
}
HttpPost httpPost = new HttpPost("<POST URL>");
httpPost.setHeader("Accept-Encoding", "gzip,deflate");
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", "");
httpPost.setHeader("Connection", "Keep-Alive");
String payload = Constants.REQUEST;
HttpEntity entity = new StringEntity(payload,HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = null;
try {
System.out.println("Program started");
response = httpclient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
inputStream.close();
System.out.println(result.toString("UTF-8"));
} catch (ClientProtocolException e) {
System.out.println("ClientProtocol");
} catch (IOException e) {
System.out.println("IOException");
} finally {
}
}
}
Please help me to get rid of this issue.

Related

WebSocket server get client certificate onOpen

I have a simple ServerEndpoint running on WildFly 10, which is configured as wss with mutual TLS, so client certificate required. I have no problems in connecting to endpoint, so the mutual authentication is correctly done, but I can't access client certificate in onOpen method. I am trying to do it using getUserPrincipal(), I'm always getting null.
I need to get client certificate for authorization purposes.
import java.io.IOException;
import java.security.Principal;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint(value = "/test", configurator = GetHttpSessionConfigurator.class)
public class TestWebSocketEndPoint {
private Session wsSession;
private HttpSession httpSession;
#OnOpen
public void onOpen(Session session, EndpointConfig config){
this.wsSession = session;
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
Principal userPrincipal = session.getUserPrincipal();
System.out.println(session.getId() + " has opened a connection");
try {
session.getBasicRemote().sendText("Connection Established");
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* When a user sends a message to the server, this method will intercept the message
* and allow us to react to it. For now the message is read as a String.
*/
#OnMessage
public void onMessage(String message, Session session){
System.out.println("Message from " + session.getId() + ": " + message);
try {
session.getBasicRemote().sendText(message);
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* The user closes the connection.
*
* Note: you can't send messages to the client from this method
*/
#OnClose
public void onClose(Session session){
System.out.println("Session " +session.getId()+" has ended");
}
}
GetHttpSessionConfigurator:
import java.security.Principal;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
#Override
public void modifyHandshake(ServerEndpointConfig config,
HandshakeRequest request,
HandshakeResponse response)
{
HttpSession httpSession = (HttpSession)request.getHttpSession();
Map<String, List<String>> map = request.getParameterMap();
Principal principal = request.getUserPrincipal();
config.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
RequestListener:
import java.security.Principal;
import java.security.cert.X509Certificate;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
#WebListener
public class RequestListener implements ServletRequestListener {
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
public void requestInitialized(ServletRequestEvent sre) {
((HttpServletRequest) sre.getServletRequest()).getSession();
Principal p = ((HttpServletRequest) sre.getServletRequest()).getUserPrincipal();
boolean secure = ((HttpServletRequest) sre.getServletRequest()).isSecure();
String authType = ((HttpServletRequest) sre.getServletRequest()).getAuthType();
X509Certificate[] certs = (X509Certificate[]) ((HttpServletRequest) sre.getServletRequest()).getAttribute("javax.servlet.request.X509Certificate");
}
}
The websocket client is a standalone application using TooTallNate/java-websocket and connecting securely:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Enumeration;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.java_websocket.WebSocketImpl;
public class TestClient {
private static final Log log = LogFactory.getLog(TestClient.class);
public static void main(String[] args) throws URISyntaxException {
WebSocketImpl.DEBUG = true;
WSRAClient wsRaClient = new WSRAClient(new URI("wss://localhost:8443/TestWebSocket-0.0.1-SNAPSHOT/test"));
String keystoreFile = "keystore.p12";
String keystorePassword = "keystore";
String truststoreFile = "truststore.jks";
String truststorePassword = "truststore";
try {
SSLContext ssl = SSLContext.getInstance("TLSv1.2");
log.info("Configuring SSL keystore");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
log.debug("Loading keystore");
store.load(new FileInputStream(keystoreFile), keystorePassword.toCharArray());
log.debug("Number of keystore certificates: " + store.size());
Enumeration<String> enumeration = store.aliases();
while(enumeration.hasMoreElements()) {
String alias = enumeration.nextElement();
log.debug("alias name: " + alias);
Certificate certificate = store.getCertificate(alias);
log.debug(certificate.toString());
}
kmf.init(store, keystorePassword.toCharArray());
KeyManager[] keyManagers = new KeyManager[1];
keyManagers = kmf.getKeyManagers();
log.info("Configuring SSL truststore");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
log.debug("Loading truststore");
truststore.load(new FileInputStream(truststoreFile), truststorePassword.toCharArray());
log.debug("Number of truststore certificates: " + truststore.size());
enumeration = truststore.aliases();
while(enumeration.hasMoreElements()) {
String alias = (String)enumeration.nextElement();
log.debug("alias name: " + alias);
Certificate certificate = truststore.getCertificate(alias);
log.debug(certificate.toString());
}
tmf.init(truststore);
TrustManager[] trustManagers = tmf.getTrustManagers();
ssl.init(keyManagers, trustManagers, new SecureRandom());
SSLSocketFactory factory = ssl.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault();
wsRaClient.setSocket(factory.createSocket());
wsRaClient.connectBlocking();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ( true ) {
String line = reader.readLine();
if(line.equals("close")) {
wsRaClient.close();
} else {
wsRaClient.send(line);
}
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (KeyStoreException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (CertificateException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (KeyManagementException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (InterruptedException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
}
}
}
See : Accessing HttpServletRequest properties within a WebSocket #ServerEndpoint
Create servlet filter on URL pattern matching websocket handshake request.
In filter, get request attribute of interest and put it in session before continuing chain.
Finally get it from the session which is in turn just available via handshake request

javax.net.ssl.SSLException: unexpected_message

We're trying to make secure http communication between client an server.
The server provided the certificates, we took them, install them and we start running, the point is to exchange an exact number of messages simultaneously between the client and server consecutively, the problem that's driving us crazy is that between the requests, at SSLHANDSHAKE we get randomly the exception javax.net.ssl.SSLException: Received fatal alert: unexpected_message exactly at ServerHello handshake phase, and i don't know how or why this is happening while it keeps working fine for 98% of the other requests.
it crashes at step 2.
Transporter.java : This is the class responsible for sending and receiving the data.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyStore;
import java.util.ResourceBundle;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
public class Transporter {
private static ResourceBundle resource = ResourceBundle.getBundle("resourece_00");
private static final String keystore = resource.getString("server_keystore");
private static final String truststore = resource.getString("server_truststore");
private static final String keypass = resource.getString("server_keystore_pwd");
private static final String trustpass = resource.getString("server_truststore_pwd");
// secure channel variables
private static SSLSocketFactory sslSocketFactory = null;
public Transporter() {
// setupSocketFactory();
}
static {
try {
String protocol = "TLS";
String type = "JKS";
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
// create and initialize an SSLContext object
SSLContext sslContext = SSLContext.getInstance(protocol);
sslContext.init(getKeyManagers(type, algorithm), getTrustManagers(type, trustAlgorithm), null);
// obtain the SSLSocketFactory from the SSLContext
sslSocketFactory = sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
private static KeyStore getStore(String type, String filename, String pwd) throws Exception {
KeyStore ks = KeyStore.getInstance(type);
InputStream istream = null;
try {
File ksfile = new File(filename);
istream = new FileInputStream(ksfile);
ks.load(istream, pwd != null ? pwd.toCharArray() : null);
} finally {
if (istream != null) {
istream.close();
}
}
return ks;
}
private static KeyManager[] getKeyManagers(String type, String algorithm) throws Exception {
KeyStore ks = getStore(type, keystore, keypass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, keypass.toCharArray());
return kmf.getKeyManagers();
}
private static TrustManager[] getTrustManagers(String type, String algorithm) throws Exception {
KeyStore ts = getStore(type, truststore, trustpass);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
tmf.init(ts);
return tmf.getTrustManagers();
}
public String sendToVD(String msg, String urll, Long timeOut) {
byte[] bytes = msg.getBytes();
HttpsURLConnection sconn = null;
URL url = null;
OutputStream out = null;
BufferedReader read = null;
String recu = null;
try {
url = new URL(urll);
sconn = (HttpsURLConnection) url.openConnection();
sconn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession sslSession) {
return true;
}
});
sconn.setSSLSocketFactory(sslSocketFactory);
// sconn.setReadTimeout((timeOut.intValue()) * 1000);// set timeout
sconn.setRequestMethod("POST");
sconn.addRequestProperty("Content-Length", "" + bytes.length);
sconn.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
sconn.setDoOutput(true);
sconn.setDoInput(true);
// send POST data
// This is the crash location
out = sconn.getOutputStream();
// OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
out.write(bytes);
out.flush();
// logger.info("flush!!!!!!!!!!!!!");
// out.close();
read = new BufferedReader(new InputStreamReader(sconn.getInputStream()));
String query = null;
recu = read.readLine();
while ((query = read.readLine()) != null) {
recu += query;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// close all connections here
if (out != null)
out.close();
if (read != null)
read.close();
if (sconn != null)
sconn.disconnect();
} catch (Exception ce) {
}
}
return recu;
}
}
The function sendToVD() does the main work of the exchange between the client and the server.
At Client-End :
A web application with JSF managing the front layer, spring managing the beans life cycle, the communication entry to the client is assured by Servlets.
The client is deployed in a RedHat Linux machine, all TLS_VERSIONS are enbaled, JDK_8.
At Server-Side: i can't post the detailed information about the target URL for security measures, but it follows the following pattern https://ip:port/path, and it supports TLS_v1.2.
Hope you can help me out.

unable to get signature value in SAMLResponse

I have integrated my web site with TFIM for SSO.
SSO is working fine but i am unable to get the Signature in SAMLResponse.
it's getting null. but it is already there in SAMLResponse.
When am trying to get the signature value from samlresponse it giving me nullpointerexception
package com.saml;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.opensaml.Configuration;
import org.opensaml.DefaultBootstrap;
import org.opensaml.saml2.core.Response;
import org.opensaml.saml2.core.Subject;
import org.opensaml.security.SAMLSignatureProfileValidator;
import org.opensaml.xml.ConfigurationException;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.Unmarshaller;
import org.opensaml.xml.io.UnmarshallerFactory;
import org.opensaml.xml.io.UnmarshallingException;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.security.x509.BasicX509Credential;
import org.opensaml.xml.signature.SignatureValidator;
import org.apache.commons.codec.binary.Base64;
import org.opensaml.xml.validation.ValidationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class ReceiveSAMLResponse {
public String receiveSAMLResponse(HttpServletRequest request)
throws ParserConfigurationException, SAXException, IOException,
UnmarshallingException, ValidationException, CertificateException {
/* Getting the response string from HTTP Request object */
String responseString = (String) request.getParameter("SAMLResponse");
/* Decoding Base64 response string to get the XML string */
String responseXml = new String(Base64.decodeBase64(responseString
.getBytes()));
System.out.println(responseXml);
/* Generating SAML Response object from XML string */
try {
DefaultBootstrap.bootstrap();
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = documentBuilderFactory
.newDocumentBuilder();
ByteArrayInputStream is = new ByteArrayInputStream(
responseXml.getBytes());
Document document = docBuilder.parse(is);
Element element = document.getDocumentElement();
UnmarshallerFactory unmarshallerFactory = Configuration
.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory
.getUnmarshaller(element);
XMLObject xmlObj = unmarshaller.unmarshall(element);
Response response = (Response) xmlObj;
/* Validating the signature on the response */
// validateSignature(response);
/* If validation was successful, get the username from the response. */
Subject subject = response.getAssertions().get(0).getSubject();
String username = subject.getNameID().getValue();
return username;
}
private void validateSignature(Response response)
throws ValidationException, FileNotFoundException,
CertificateException {
SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
try {
profileValidator.validate(response.getSignature());
} catch (ValidationException e) {
/* Indicates signature did not conform to SAML Signature profile */
e.printStackTrace();
throw e;
}
Credential verificationCredential = getVerificationCredential();
SignatureValidator sigValidator = new SignatureValidator(
verificationCredential);
try {
sigValidator.validate(response.getSignature());
} catch (ValidationException e) {
e.printStackTrace();
throw e;
}
}
private Credential getVerificationCredential()
throws FileNotFoundException, CertificateException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
"/pathToYourCertificte"));
CertificateFactory cf = CertificateFactory.getInstance("X509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(bis);
BasicX509Credential x509Credential = new BasicX509Credential();
x509Credential.setPublicKey(cert.getPublicKey());
x509Credential.setEntityCertificate(cert);
Credential credential = x509Credential;
return credential;
}
}
....................................
saml response in xml file
<samlp:Response xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Destination="https://10.44.90.29:8443/SAMLShareFile/saml/samlresponse" ID="FIMRSP_604af2be-0150-1ff0-adad-8154af08b58c" InResponseTo="-5346144739450824145" IssueInstant="2015-10-13T08:22:15Z" Version="2.0"><saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://10.44.189.168:444/apjct/sps/NewRelic/saml20</saml:Issuer><samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"></samlp:StatusCode></samlp:Status><saml:Assertion ID="Assertion-uuid604af281-0150-1512-8c38-8154af08b58c" IssueInstant="2015-10-13T08:22:15Z" Version="2.0"><saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://10.44.189.168:444/apjct/sps/NewRelic/saml20</saml:Issuer><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="uuid604af289-0150-1dab-a25e-8154af08b58c"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:CanonicalizationMethod><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod><ds:Reference URI="#Assertion-uuid604af281-0150-1512-8c38-8154af08b58c"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"><xc14n:InclusiveNamespaces xmlns:xc14n="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="xs saml xsi"></xc14n:InclusiveNamespaces></ds:Transform></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><ds:DigestValue>pMf0E/z1rS9OkTOLc+0aoD7cl30=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>SW9BaJm0rGJAOG62Il1v46YsqocHXNpmcQKAmSIKDX4tRN3EbUHeqFcVfJmmUGDe4uC1H115SOCehQAkJ35lLBnVsda2WHgu4kWdGC8j+kaw0y9zjzngrHZljBpzU2h87zk4X+fGXvtCmBUH7xfrID4tQ6ODdhoWjd6K8s21S50=</ds:SignatureValue><ds:KeyInfo><ds:X509Data><ds:X509Certificate>MIICBzCCAXCgAwIBAgIEQH26vjANBgkqhkiG9w0BAQQFADBIMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGVGl2b2xpMQ4wDAYDVQQLEwVUQU1lQjEYMBYGA1UEAxMPZmltZGVtby5pYm0uY29tMB4XDTA0MDQxNDIyMjcxMFoXDTE3MTIyMjIyMjcxMFowSDELMAkGA1UEBhMCVVMxDzANBgNVBAoTBlRpdm9saTEOMAwGA1UECxMFVEFNZUIxGDAWBgNVBAMTD2ZpbWRlbW8uaWJtLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAiZ0D1X6rk8+ZwNBTVZt7C85m421a8A52Ksjw40t+jNvbLYDp/W66AMMYD7rB5qgniZ5K1p9W8ivM9WbPxc2u/60tFPg0e/Q/r/fxegW1K1umnay+5MaUvN3p4XUCRrfg79OvurvXQ7GZa1/wOp5vBIdXzg6i9CVAqL29JGi6GYUCAwEAATANBgkqhkiG9w0BAQQFAAOBgQBXiAhxm91I4m+g3YX+dyGc352TSKO8HvAIBkHHFFwIkzhNgO+zLhxg5UMkOg12X9ucW7leZ1IB0Z6+JXBrXIWmU3UPum+QxmlaE0OG9zhp9LEfzsE5+ff+7XpS0wpJklY6c+cqHj4aTGfOhSE6u7BLdI26cZNdzxdhikBMZPgdyQ==</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature><saml:Subject><saml:NameID Format="urn:ibm:names:ITFIM:5.1:accessmanager">musaddique</saml:NameID><saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"><saml:SubjectConfirmationData InResponseTo="-5346144739450824145" NotOnOrAfter="2015-10-13T08:32:15Z" Recipient="https://10.44.90.29:8443/SAMLShareFile/saml/samlresponse"></saml:SubjectConfirmationData></saml:SubjectConfirmation></saml:Subject><saml:Conditions NotBefore="2015-10-13T08:12:15Z" NotOnOrAfter="2015-10-13T08:32:15Z"><saml:AudienceRestriction><saml:Audience>musaddique</saml:Audience></saml:AudienceRestriction></saml:Conditions><saml:AuthnStatement AuthnInstant="2015-10-13T08:22:15Z" SessionIndex="uuid604af260-0150-14b6-8127-8154af08b58c" SessionNotOnOrAfter="2015-10-13T09:22:15Z"><saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement><saml:AttributeStatement><saml:Attribute Name="AuthenticatingAuthority" NameFormat="urn:oasis:names:tc:SAML:2.0:assertion"><saml:AttributeValue xsi:type="xs:string">musaddique</saml:AttributeValue></saml:Attribute></saml:AttributeStatement></saml:Assertion></samlp:Response>
Your SAML has only assertion part () being signed, so you should get signature from assertion object not response object: try response.getAssertions().get(0).getSignature().
Base on SAML 2.0 specification, SAML response has to be signed, but not both response and sssertion are mandatory.
I wrote this code in my SamlProvider. I didn't used it because the Idp was not requesting the HTTPS protocol and certificates in saml so it's not a "certified solution" I load the certificate from a file so you migth directly inject your BufferedInputStream.
private Credential getCredential() {
BasicX509Credential credential = null;
try {
// read private key
File privateKeyFile = new File(derFile);
FileInputStream inputStreamPrivateKey = new FileInputStream(privateKeyFile);
byte[] encodedPrivateKey = new byte[(int) privateKeyFile.length()];
inputStreamPrivateKey.read(encodedPrivateKey);
inputStreamPrivateKey.close();
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
RSAPrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(
privateKeySpec);
// read the certificate
InputStream inStream = new FileInputStream(pemFile);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
// create credential
credential = new BasicX509Credential();
credential.setEntityCertificate((java.security.cert.X509Certificate) cert);
credential.setPrivateKey(privateKey);
} catch (Exception e) {
Logger.error("failed getting credential!", e);
}
return credential;
}
Hope it helps.

java.io.IOException: Server returned HTTP response code: 500 for URL while uploading JSON object

This is the code on server side, please help me to understand where I am going wrong.
I am uploading an byte array of image as JSON object. Converting the byte array and saving it on disk.
package com.file.up;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONObject;
#Path("/")
public class FileUp {
#POST
#Path("/crunchifyService")
#Consumes(MediaType.APPLICATION_JSON)
public Response crunchifyREST(JSONObject incomingData) {
String s="Success!";
try {
String jsonString = incomingData.getString("image");
byte[] a=jsonString.getBytes();
InputStream input=new ByteArrayInputStream(a);
BufferedImage b=ImageIO.read(input);
ImageIO .write(b,"png",new File("C:\\Users\\Uma\\Desktop\\WEB_AND"));
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
System.out.println("Data Received: ");
// return HTTP response 200 in case of success
return Response.status(200).entity(s).build();
}
}
This is my client side code.
package com.file.up;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import javax.imageio.ImageIO;
import org.json.JSONObject;
public class FileClient {
public static void main(String[] args) throws IOException {
BufferedImage image;
image = ImageIO.read(new File("12.png"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( image, "png", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
String base64String = Base64.getEncoder().encodeToString(imageInByte);
baos.close();
// Step2: Now pass JSON File Data to REST Service
try {
JSONObject jsonObject = new JSONObject("{\"image\":\"" + base64String + "\"}");
System.out.println(jsonObject);
URL url = new URL("http://<ip>:9999/FileUpload/api/crunchifyService");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
// out.write(jsonObject.toString());
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
while (in.readLine() != null) {
}
System.out.println("\nREST Service Invoked Successfully..");
in.close();
} catch (Exception e) {
System.out.println("\nError while calling REST Service");
System.out.println(e);
e.printStackTrace();
}
}
}
And the stack trace is
java.io.IOException: Server returned HTTP response code: 500 for URL: http://:9999/FileUpload/api/crunchifyService
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1838)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
at com.file.up.FileClient.main(FileClient.java:64)
I copied your classes in my TomEE server and from the client I am getting no body on the request, you should try using a jaxrs client

Use AuthenticatingSMTPClient and SSL?

I need to send an email using SSL (SMTPS) and authentification. In apache Commons Net however there seems to be either AuthenticatingSMTPClient (no SSL, though it extends SMTPSClient?) or SMTPSClient (no authentication?), I need a combination of both (SSL + authentication). Anyone knows how I can do this? Thanks!
I know it is too late to reply to this but for future reference for others, AuthenticatingSMTPClient does provide ssl + authentication as it is extending SMTPSClient. Below is the sample code, one has to do modifications where I have commented with numerals (e.g. //1).
Code:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.io.Util;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient.AUTH_METHOD;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
public final class SMTPMail
{
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException
{
String sender, recipient, subject, filename, server;
List<String> ccList = new ArrayList<String>();
FileReader fileReader = null;
Writer writer;
SimpleSMTPHeader header;
AuthenticatingSMTPClient client;
server = "<smtp server>"; // 1
try
{
sender = "<your user name>"; // 2
recipient = "<recipient>"; // 3
subject = "<mail subject>"; // 4
header = new SimpleSMTPHeader(sender, recipient, subject);
filename = "hello.txt"; //This will be the body of your mail //5
try
{
fileReader = new FileReader(filename);
}
catch (FileNotFoundException e)
{
System.err.println("File not found. " + e.getMessage());
}
client = new AuthenticatingSMTPClient("TLS", false);
client.addProtocolCommandListener(new PrintCommandListener(
new PrintWriter(System.out), true));
client.connect(server);
if (!SMTPReply.isPositiveCompletion(client.getReplyCode()))
{
client.disconnect();
System.err.println("SMTP server refused connection.");
System.exit(1);
}
client.login("hostname.testing.smtp.api"); //6
if(client.execTLS())
{
if(client.auth(AUTH_METHOD.LOGIN, "<your user name>", "<your password>")) //7
{
client.setSender(sender);
client.addRecipient(recipient);
for (String recpt : ccList) {
client.addRecipient(recpt);
}
writer = client.sendMessageData();
if (writer != null)
{
writer.write(header.toString());
Util.copyReader(fileReader, writer);
writer.close();
client.completePendingCommand();
}
if (fileReader != null ) {
fileReader.close();
}
}
}
client.logout();
client.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
}

Categories

Resources