Dear SO Community of Awesomeness,
I'm building a secure app that deals with sensitive information. The app communicates with my own RESTful API over SSL. I don't want to limit the app to the specific certificate I was issued, but rather to trust only certificates issued by my provider, e.g. Comodo. That way I can extend and reissue the certificate without having to release an app update.
I found a great resource for getting this done here but Android 6 deprecated HttpClient and switched to HttpsURLConnection. Google has their own approach posted here. On implementation, however, I noticed that instead of throwing a "not trusted" exception for a different certificate, it just forced the usage of the local CA cert which is not the behavior I intended.
Does anyone have a reference for trusting only a specific CA using HttpsURLConnection?
OK I solved it, figured I would post the solution in case anyone else hits the same problem. Here is the code to use to get a JSON file using HttpsUrlConnection:
(...)
public static class GetJsonTask extends AsyncTask<Void, Integer, AsyncResponse> {
protected String jsonData;
protected IGetJsonListener listener;
protected Context context = null;
protected String strUrl;
public GetJsonTask(Context c, IGetJsonListener l, String strUrl) {
super();
listener = l;
context = c;
this.strUrl = strUrl;
}
#Override
protected AsyncResponse doInBackground(Void... Void) {
JsonObject jsonObjectResult = new JsonObject();
APIStatus status;
if (isConnected(context)) {
HttpsURLConnection httpsURLConnection=null;
try {
//THIS IS KEY: context contains only our CA cert
SSLContext sslContext = getSSLContext(context);
if (sslContext != null) {
//for HTTP BASIC AUTH if your server implements this
//String encoded = Base64.encodeToString(
// ("your_user_name" + ":" + "your_pwd").getBytes(),
// Base64.DEFAULT);
URL url = new URL(strUrl);
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("GET");
httpsURLConnection.setRequestProperty("Content-length", "0");
httpsURLConnection.setUseCaches(false);
httpsURLConnection.setAllowUserInteraction(false);
//FOR HTTP BASIC AUTH
//httpsURLConnection.setRequestProperty("Authorization", "Basic " + encoded);
//THIS IS KEY: Set connection to use custom socket factory
httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
//httpsURLConnection.setConnectTimeout(timeout);
//httpsURLConnection.setReadTimeout(timeout);
httpsURLConnection.connect();
status = getStatusFromCode(httpsURLConnection.getResponseCode());
listener.getJsonShowProgress(90);
if (status == APIStatus.OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
JsonParser parser = new JsonParser();
String s = stringBuilder.toString();
jsonObjectResult = (JsonObject) parser.parse(s);
}
} else
status = APIStatus.AUTH_ERROR;
listener.getJsonShowProgress(99);
//THIS IS KEY: this exception is thrown if the certificate
//is signed by a CA that is not our CA
} catch (SSLHandshakeException e) {
status = APIStatus.AUTH_ERROR;
//React to what is probably a man-in-the-middle attack
} catch (IOException e) {
status = APIStatus.NET_ERROR;
} catch (JsonParseException e) {
status = APIStatus.JSON_ERROR;
} catch (Exception e) {
status = APIStatus.UNKNOWN_ERROR;
} finally {
if (httpsURLConnection != null)
httpsURLConnection.disconnect();
}
} else {
status = APIStatus.NET_ERROR;
}
// if not successful issue another call for the next hour.
AsyncResponse response = new AsyncResponse();
response.jsonData = jsonObjectResult;
response.opStatus = status;
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (listener != null)
listener.getJsonStartProgress();
}
#Override
protected void onProgressUpdate(Integer... progress) {
listener.getJsonShowProgress(progress[0]);
}
#Override
protected void onPostExecute(AsyncResponse result) {
listener.getJsonFinished(result.jsonData, result.opStatus);
}
public interface IGetJsonListener {
void getJsonStartProgress();
void getJsonShowProgress(int percent);
void getJsonFinished(JsonObject resJson, APIStatus status);
}
}
private static SSLContext getSSLContext(Context context){
//Mostly taken from the Google code link in the question.
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
AssetManager am = context.getAssets();
//THIS IS KEY: Your CA's cert stored in /assets/
InputStream caInput = new BufferedInputStream(am.open("RootCA.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
//System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
return sslContext;
} catch (Exception e){
return null;
}
}
public enum APIStatus {
OK("OK.", 200), //all went well
JSON_ERROR("Error parsing response.", 1),
NET_ERROR("Network error.", 2), //we couldn't reach the server
UNKNOWN_ERROR("Unknown error.", 3), //some sh*t went down
AUTH_ERROR("Authentication error.", 401), //credentials where wrong
SERVER_ERROR("Internal server error.", 500), //server code crashed
TIMEOUT("Operation timed out.", 408); //network too slow or server overloaded
private String stringValue;
private int intValue;
private APIStatus(String toString, int value) {
stringValue = toString;
intValue = value;
}
#Override
public String toString() {
return stringValue;
}
}
private static APIStatus getStatusFromCode(int code) {
if (code==200 || code==201) {
return APIStatus.OK;
}else if (code == 401) {
return APIStatus.AUTH_ERROR;
} else if (code == 500) {
return APIStatus.SERVER_ERROR;
} else if (code == 408) {
return APIStatus.TIMEOUT;
} else {
return APIStatus.UNKNOWN_ERROR;
}
}
private static class AsyncResponse {
public APIStatus opStatus;
public JsonObject jsonData;
}
(...)
Usage is fairly straightforward:
public class MyClass implements IGetJsonListener {
(...)
new GetJsonTask(context, this, "https://your.url.com/").execute();
#Override
public void getJsonFinished(JsonObject resJson, APIStatus status) {
//Handle JSON content from web here
(...)
}
(...)
}
I'd love to hear any improvements you have.
Related
I'm writing a mod for a game in Java to check to see if the player has voted using a server methods to get the Steam ID. I can't get a good response from what I'm seeing. Every response is an IOException which I've had print out "Invalid Response Code".
I've tried implementing what I've seen in similar mods for https connections, but I am not getting anywhere with it.
try {
HttpsURLConnection connection = (HttpsURLConnection) new URL( "https://somewebsite.com/"
).openConnection();
connection.setSSLSocketFactory(createTrustAllSocketFactory());
int responseCode = connection.getResponseCode();
if (responseCode != 200) throw new IOException("Invalid response code.");
InputStream in = connection.getInputStream();
ByteArrayOutputStream stringBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int len = 0;
while (len != -1) {
stringBuffer.write(buffer, 0, len);
len = in.read(buffer);
}
String result = new String(stringBuffer.toByteArray(), StandardCharsets.UTF_8);
if (result.equals("1")) {
try {
performer.addMoney(MonetaryConstants.COIN_COPPER * 5);
performer.getCommunicator().sendNormalServerMessage("Thanks for voting! Your rewards have been added to your bank.");
} catch (IOException ex) {
performer.getCommunicator().sendAlertServerMessage("Failed to add reward. Please submit a support ticket.");
ex.printStackTrace();
}
}
private static SSLSocketFactory createTrustAllSocketFactory() throws IOException {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = {
new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
/* empty */
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
/* empty */
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
ctx.init(null, trustManagers, null);
return ctx.getSocketFactory();
} catch (GeneralSecurityException ex) {
throw new IOException(ex);
}
}
The expectation is that when the command is issued in-game, the server will call the external site with the player's steam ID and generate either a 0 or 1 based on if they have voted.
Actual is getting a bad response code.
I am using the following code to create a custom JMX server with TLS and JMXMP following the Oracle documentation. It works well and I can connect to the server with no problem, however I would like to add "USER" and "PASSWORD" to the authentication, however specifying the "password.properties" and the "access.properties" is not working, JMX seems to be ignoring these two options. Can somebody shed some light on the correct way to configure USER and PASSWORD and correct this problem? Thanks
private JMXServiceURL url() {
final String url = String.format( "service:jmx:jmxmp://%s:%s", host(), port() );
try {
return new JMXServiceURL( url );
} catch( Throwable exception ) {
throw new RuntimeException( String.format( "Failed to create JMX Service URL: %s", url ), exception );
}
}
private Map<String, Object> env() {
final Map<String, Object> env = new LinkedHashMap<String, Object>();
try {
String keystore = "jmx.keystore";
char keystorepass[] = "12345678".toCharArray();
char keypassword[] = "12345678".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keystore), keystorepass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, keypassword);
SSLContext ctx = SSLContext.getInstance("TLSv1");
ctx.init(kmf.getKeyManagers(), null, null);
SSLSocketFactory ssf = ctx.getSocketFactory();
env.put("jmx.remote.profiles", "TLS");
env.put("jmx.remote.tls.socket.factory", ssf);
env.put("jmx.remote.tls.enabled.protocols", "TLSv1");
env.put("jmx.remote.tls.enabled.cipher.suites","SSL_RSA_WITH_NULL_MD5");
env.put("jmx.remote.x.password.file", "password.properties");
env.put("jmx.remote.x.access.file","access.properties");
} catch (Exception e) {
e.printStackTrace();
}
return env;
}
private MBeanServer server() {
return ManagementFactory.getPlatformMBeanServer();
}
private JMXConnectorServer connector() {
try {
ServerProvider.class.getName();
return JMXConnectorServerFactory.newJMXConnectorServer( url(), env(), server() );
}catch( Throwable exception ) {
throw new RuntimeException( "Failed to create JMX connector server factory", exception );
}
}
I was finally able to configure the additional user and password for the JMXMP connection with the following code from the Oracle documentation
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
Security.addProvider(new com.sun.jdmk.security.sasl.Provider());
HashMap env = new HashMap();
env.put("jmx.remote.profiles", "TLS SASL/PLAIN");
env.put("jmx.remote.sasl.callback.handler",
new PropertiesFileCallbackHandler("password.properties"));
env.put("jmx.remote.x.access.file",access.properties");
JMXServiceURL url = new JMXServiceURL("jmxmp", null, 5555);
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url,
env,
mbs);
cs.start();
I implemented a simple callBackHandler for the password validation
public final class PropertiesFileCallbackHandler
implements CallbackHandler {
private Properties pwDb;
/**
* Contents of files are in the Properties file format.
*
* #param pwFile name of file containing name/password
*/
public PropertiesFileCallbackHandler(String pwFile) throws IOException {
if (pwFile != null) {
File file = new File(pwFile);
if(file.exists()) {
pwDb = new Properties();
pwDb.load(new FileInputStream(file));
} else {
throw new IOException("File " + pwFile + " not found");
}
}
}
public void handle(Callback[] callbacks)
throws UnsupportedCallbackException {
AuthorizeCallback acb = null;
AuthenticateCallback aucb = null;
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof AuthorizeCallback) {
acb = (AuthorizeCallback) callbacks[i];
} else if (callbacks[i] instanceof AuthenticateCallback) {
aucb = (AuthenticateCallback)callbacks[i];
} else {
throw new UnsupportedCallbackException(callbacks[i]);
}
}
// Process retrieval of password; can get password if
// username is available
if (aucb != null) {
String username = aucb.getAuthenticationID();
String password = new String(aucb.getPassword());
String pw = pwDb.getProperty(username);
if (pw != null) {
if(pw.equals(password)){
aucb.setAuthenticated(true);
}
}
}
// Check for authorization
if (acb != null) {
String authid = acb.getAuthenticationID();
String authzid = acb.getAuthorizationID();
if (authid.equals(authzid)) {
// Self is always authorized
acb.setAuthorized(true);
}
}
}
}
I am trying to access my server using two of the goDaddy certificates that are listed under my endpoint. The three certs in the stack are My cert > Go Daddy Secure Certificate Authority -G2 > Go Daddy Root Certificate Authority - G2. I downloaded both the secure and root certs from the Go Daddy Repository and now have added both to my android app raw resource folder. Even with both in there it still gives me this error
javax.net.ssl.SSLPeerUnverifiedException: Hostname not verified:
I don't know what i should do next. I tried a lot of combinations so I think i need a different way of doing this.
Here is what I have so far;
My HttpsClient code;
public class MyHttpsGet extends AsyncTask<String, Void, String> {
Context context;
int cert;
int interCert;
boolean allowHost;
private String username;
private String password;
//this is used if you need a password and username
//mainly for logins to a webserver
public MyHttpsGet(String username, String password, Context context, int cert, int intermedCert)
{
this.context = context;
this.cert = cert;
this.interCert = intermedCert;
this.username = username;
this.password = password;
}
//used for image downloading
public MyHttpsGet(){}
#Override
protected String doInBackground(String... params) {
String url = params[0];
return httpsDownloadData(url, context, cert, interCert);
}
public String httpsDownloadData (String urlString, Context context, int certRawResId, int certIntermedResId)
{
String respone = null;
try {
// build key store with ca certificate
KeyStore keyStore = buildKeyStore(context, certRawResId, certIntermedResId);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
// Create a connection from url
URL url = new URL(urlString);
if (username != null) {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
}
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
int statusCode = urlConnection.getResponseCode();
Log.d("Status code: ", Integer.toString(statusCode));
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
respone = streamToString(inputStream);
inputStream.close();
}
}catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
Log.d("MyHttps Respones: ", respone);
return respone;
}
private static KeyStore buildKeyStore(Context context, int certRawResId, int interCert){
// init a default key store
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
// read and add certificate authority
Certificate cert2 = readCert(context, interCert);
Certificate cert = readCert(context, certRawResId);
keyStore.setCertificateEntry("ca" , cert2);
keyStore.setCertificateEntry("ca", cert);
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return keyStore;
}
private static Certificate readCert(Context context, int certResourceId) throws IOException {
// read certificate resource
InputStream caInput = context.getResources().openRawResource(certResourceId);
Certificate ca = null;
try {
// generate a certificate
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ca = cf.generateCertificate(caInput);
} catch (CertificateException e) {
e.printStackTrace();
} finally {
caInput.close();
}
return ca;
}
//this is used for downloading strings from an http or https connection
private String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
And here is how I call it/use it:
MyHttpsGet task = new MyHttpsGet(username, password,myContext, R.raw.gdroot_g2, R.raw.gdintermed);
try {
myJson = task.execute(myUrl).get();
Log.d("Json: " , myJson);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new runningMan().execute();
Thank you for any help with this.
Here is a picture of my Cert Chain
The error message says apivitacrm.elasticbeanstalk.com, but you then black out the wildcard name in your certificate. Why?
Well, regardless of what it is, it looks like it starts with an a, so it is definitely not a *.elasticbeanstalk.com wildcard certificate.
That means that the error message is correct. The certificate does not belong to the domain name given.
Even if it is a *.apivitacrm.elasticbeanstalk.com wildcard (blackout doesn't seem wide enough for that, though), it still wouldn't match apivitacrm.elasticbeanstalk.com, since it only matches subdomains.
I am trying to use a cert that I downloaded from goDaddy that is hosting my server. I want to connect to it via my android app using an https connection. This connection needs to be authenticated as well. I got it all working with http but when I try to use the local certificate it just fatal crashes saying that I am trying to cast an httpUrlConnection to an HttpsUrlConnection.
Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
I don't know what I am doing wrong there is no httpurlConneciton in the code at all and I don't cast anything to https either. Any help with this will be appreciated.
Here is my HttpsGet Client.
public class MyHttpsGet extends AsyncTask<String, Void, String> {
Context context;
int cert;
boolean allowHost;
private String username;
private String password;
//this is used if you need a password and username
//mainly for logins to a webserver
public MyHttpsGet(String username, String password, Context context, int cert)
{
this.context = context;
this.cert = cert;
this.allowHost = allowHost;
this.username = username;
this.password = password;
}
//used for image downloading
public MyHttpsGet(){}
#Override
protected String doInBackground(String... params) {
String url = params[0];
return httpsDownloadData(url, context, cert);
}
public String httpsDownloadData (String urlString, Context context, int certRawResId)
{
String respone = null;
try {
// build key store with ca certificate
KeyStore keyStore = buildKeyStore(context, certRawResId);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
// Create a connection from url
URL url = new URL(urlString);
if (username != null) {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
}
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
int statusCode = urlConnection.getResponseCode();
Log.d("Status code: ", Integer.toString(statusCode));
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
respone = streamToString(inputStream);
inputStream.close();
}
}catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
Log.d("MyHttps Respones: ", respone);
return respone;
}
private static KeyStore buildKeyStore(Context context, int certRawResId) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
// init a default key store
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
// read and add certificate authority
Certificate cert = readCert(context, certRawResId);
keyStore.setCertificateEntry("ca", cert);
return keyStore;
}
private static Certificate readCert(Context context, int certResourceId) throws CertificateException, IOException {
// read certificate resource
InputStream caInput = context.getResources().openRawResource(certResourceId);
Certificate ca;
try {
// generate a certificate
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ca = cf.generateCertificate(caInput);
} finally {
caInput.close();
}
return ca;
}
//this is used for downloading strings from an http or https connection
private String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
And here is how I am using it /calling it.
MyHttpsGet task = new MyHttpsGet(username, password,myContext, R.raw.gdroot_g2);
try {
myJson = task.execute(myUrl).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new runningMan().execute();
This was caused not by my code but by the missing s in a https//www.godsjasdifdsaidsf.com
My application makes multiple web calls in order to get authentication. I need to store this session in a cookie. I wanted to use Cookie Manager but after doing some research, I found out it is only available to API 9 and above and my application needs to be backward compatible.
I make my web connections using HTTPURLConnection to a secure HTTPS. Quick example of my code
public String iStream_to_String(InputStream is)
{
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096);
String line;
StringBuilder sb = new StringBuilder();
try
{
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
} catch (IOException e)
{
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
/**
* Trust every server - dont check for any certificate
*/
private static void trustAllHosts()
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]
{ new X509TrustManager()
{
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return new java.security.cert.X509Certificate[]
{};
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException
{
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException
{
}
} };
// Install the all-trusting trust manager
try
{
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e)
{
e.printStackTrace();
}
}
Then I make a request like so
try
{
url = new URL(url1);
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
InputStream in = new BufferedInputStream(http.getInputStream());
sAuthenticateP1 = iStream_to_String(in);
in.close();
} catch (Exception e)
{
e.printStackTrace();
}
The full authentication is done in 4 steps. I need to have it so the session is remembered throughout the 4 steps. Seeing I can't use CookieManager, I have been looking around for other ways of doing this, but can't seem to find any. Would anyone be able to point me in the right direction.
Thanks in advance!!
Figured it out. Incase anyone else is having similar problem, will give quick outline of code. As I said before mine is a several step authentication process. So after the first request, after you have received a response, take the cookie like so
String cookie = http.getRequestProperty("Cookie");
if (cookie != null && cookie.length() > 0)
{
sCookie = cookie;
Log.v("cookie2", sCookie);
}
sCookie is a static string variable I have set up. Then in the next request, after this line
https = (HttpsURLConnection) url.openConnection();
Just put
https.setRequestProperty("Cookie", sCookie);
https.setRequestMethod("POST");
https.setDoInput(true);
https.setDoOutput(true);
And do the same thing for each request after that requires the session, and it should work fine