Hey all,
I've been trying to get my app to authenticate with a webserver. (Not my own webserver).
But I've been having major issues. I've looked all over for a proper way to authenticate and have tried different methods, but I keep getting the same errors.
I either get:
1. 401 authorization required
2. 400 bad request
3. Cookie gets rejected because of illegal path attribute.
4. 200 ok, but I'm not getting the proper site info that pertains to the authorized part of the site.
This all depends on the different methods I try.
Currently, this is the code I am using:
Code:
private int auth(String username, String password) throws IOException {
String login = username + ":" + password;
String auth = Base64.encodeToString(login.getBytes("US-ASCII"), Base64.DEFAULT);
int response = 0;
URL url = new URL(esims_login);
URLConnection conn = url.openConnection() ;
conn.setRequestProperty("Set-cookie", "OBBasicAuth=fromDialog");
conn.addRequestProperty("Authorization", "Basic " + auth);
conn.connect();
return response;
}
I end up getting a bad request response using this method.
The OBBasicAuth=fromDialog is a header from the server that is supposed to pop up a dialog that receives the username and password. So I added that to the initial request.
So my question is, what am I not doing/doing wrong?! I've been trying to accomplish this for weeks.
have you tried to trim the base64 encoded string ?
Code:
conn.addRequestProperty("Authorization", "Basic " + auth.trim());
Well, trimming the auth string helped, but now I am getting an expired session.
Related
Can't get rid of this error:
android.database.sqlite.SQLiteException: near "s": syntax error: , while compiling:
Select correct from answers where correct = 'Between the airplane's climb angle and the horizon.'
Obviously, it's finding the single quote in ( airplane's ) and considering that the end of the statement.
I've tried:
correct.replaceAll(" ' ", " ''' "); //replace 1 with 3
correct.replaceAll(" ' ", " '' "); // replace 1 with 2
correct.replaceAll(" ' ", " "); // replace 1 with space
(NOTE: the spaces are NOT in the code, I just did that to make it readable)
I have no idea what's going on, IMO, it should work. Maybe I need to try:
String single = "'"; // single '
String double = "''" // double ''
correct.replaceAll(single, double); // ????
Everything I"ve read about sqlite3 is to replace one with two....
TIA,
Roots
\'
\ is the escape character for most languages
so airplane's would be airplane\'s
Also, are you binding your queries with the "question mark" bind?
I'll try the escape and post back later. There are 1,000 rows in the database and I"m pulling a random subset of that, so it's not that often I get one of those situations.
I'm not sure what you mean by "binding with ?" Isn't that what you use for bind variable unknown at runtime? I know my bind variables and just use it in my dbquery. Please enlighten me...always happy to learn something new
Sample code...answerOne would contain the single quote that's killing me
Code:
Cursor c;
c = myDataBase.rawQuery("Select correct from answers where correct = '" + answerOne + "'", null);
if(c.moveToFirst())
answer = "1";
c.close();
binding with question marks should take care of escaping for you.
Basically the question mark is a place holder for a variable in the query.
What you are doing is manually creating the query string. This is considered bad practice these days especially with regards to security. Mostly because it opens up the DB to a SQL injection attack.
So instead of using the rawQuery just use query and you can put a ? in and android will substitute the value for you, all properly escaped:
Code:
String tableName = "answers";
String selectArgs = "correct=[COLOR="Red"]?[/COLOR]";
// if answerOne is string dont need String.valueOf
String[] selectVals = { String.valueOf ( answerOne ) };
String[] columnsProjection= new String[] {"correct" };
Cursor c = db.query(tableName, columnsProjection, selectArgs,selectVals,null);
So in that code the OS will replace the ? in selectArgs with the values in selectVals
This may seem like more writing at first but once you get in the habit it will be easy, reliable and more secure. It also allows you to bind multiple variables to mutiple question marks. It just binds then in the order it gets them.
so something like this:
Code:
String answerOne= "one";
String selectArgs = "correct=? AND age=? AND smiling=?";
String[] selectVals = { answerOne, "21", "yes" };
Ok, I'll try it. There are about 50 different queries in this program...for some reason I just decided to do a rawQuery on this one. I'll change it to "db.query(table name, new String[] {}....yada, yada).
Because, it just crashed and I decided to come back here and check for a solution.
Thank you very much!!!
Roots
Glad to be of help, just remember to hit the thanks booton ya Rooster
Still getting the error
Example: column is in table as text. Say it's equal to:
The driver's last name
Error comes back as "syntax error near 's' when compiling select correct from answers where correct = 'The driver's last name'
That single quote in driver's is killing my SQL.
Hallo,
I have the following function in my AsyncTask:
Code:
private SSLContext trustCert() throws Exception {
SSLContext context = null;
context = SSLContext.getInstance("TLS");
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = this.context.getResources().openRawResource(R.raw.cert);
Certificate ca = cf.generateCertificate(caInput);
caInput.close();
// Create a KeyStore containing our trusted CAs
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
context.init(null, tmf.getTrustManagers(), null);
return context;
}
In the doInBackground-Function im loading some resources from my server with a self-signed certificate:
Code:
SSLContext sslContext = this.trustCert();
HttpsURLConnection conn = (HttpsURLConnection) address.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
......
conn.connect(); //here i get the error
And sometimes (!) I get following Error on the last line of the code posted:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
But why?
..
anyone?
Hi
Are you sure your sever is well configured ? It seems that there are some intermediate certificates missing from the certificate chain but google "Trust anchor not found" you'll find some helpful links
TheDoubleTap said:
Hi
Are you sure your sever is well configured ? It seems that there are some intermediate certificates missing from the certificate chain but google "Trust anchor not found" you'll find some helpful links
Click to expand...
Click to collapse
I have met this issue before. My solution is setting the verifier host and ssl factory before you setting up the https utl connection
e.g. :
private static void trustAllHosts() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(notVerify);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
}
add this method before your https connection create method. Hope it can help you.
Look at my code, I'm already doing that..
I used this code:
Code:
mWebViewVertreungsplan = (WebView)findViewById(R.id.webViewVertretung);
mWebViewVertreungsplan.setVisibility(View.VISIBLE);
mWebViewVertreungsplan.setWebViewClient(new WebViewClient());
// Enable Javascript
WebSettings webSettings = mWebViewVertreungsplan.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebViewVertreungsplan.loadUrl("Username: Pasword @ domain. com");
On the on some devices it works, but on others it wont work. I geht the error 401 unauthorized.
Funny enough i am working on a project that has to do with a "substitution plan" as well (dunno what the correct english translation is) xD
You have to put the credentials inside the url header, and they have to be Base64 encoded
I use jsoup library to read the values from a pw protected site, so putting things into header is done differently, but same principle:
[...]Jsoup.connect("domain.com").header("Authorization", "Basic " + encodedString).post()
encodedString is done like that:
String text ="unamewd";
byte[] data = null;
data = text.getBytes("UTF-8");
encodedString = Base64.encode(data, Base64.DEFAULT);
So only thing you would have to google is how to set url header for webview
Hello!
Sorry for my bad english.
I'm trying to develop an app that send a push notification from device A (android) to device B (android).
How can I make this app?
I can't use GCM/Parse server, 'cause a push notification is sent ONLY from server to device!
I must use a DB that save MY contacts? And then, with a query (?), sent a push notif. to user B (B have downloaded the app, of course!)?
Thanks!
Venus88 said:
I can't use GCM/Parse server,
Click to expand...
Click to collapse
Yes you can, you would just need to create an API that would capture a message sent to the server from device A then send it to device B.
Jonny said:
Yes you can, you would just need to create an API that would capture a message sent to the server from device A then send it to device B.
Click to expand...
Click to collapse
Thanks a lot!
And how I can do that? The code for GCM server, i.e. gcm.php:
PHP:
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
and
PHP:
<?php
// response json
$json = array();
/**
* Registering a user device
* Store reg id in users table
*/
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"])) {
$name = $_POST["name"];
$email = $_POST["email"];
$gcm_regid = $_POST["regId"]; // GCM Registration ID
// Store user details in db
include_once './db_functions.php';
include_once './GCM.php';
$db = new DB_Functions();
$gcm = new GCM();
$res = $db->storeUser($name, $email, $gcm_regid);
$registatoin_ids = array($gcm_regid);
$message = array("product" => "shirt");
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
} else {
// user details missing
}
?>
allows send notification from server page to one/a group of devices.
Can i "reverse" the direction? from Device A to server (and then from server to device B) automatically?
Up :\
I'm trying to send data via Http but I keep getting this error: No encoding found. Expected encoding 'utf-8' to be present in message header. I tried adding:
connection.setRequestProperty("charset","utf-8"); but it still didn't work.
The full code is:
Java:
HttpURLConnection connection;
try {
//Open a new URL connection
connection = (HttpURLConnection) new URL(params[0])
.openConnection();
//Defines a HTTP request type
connection.setRequestMethod("POST");
//Sets headers: Content-Type
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset","utf-8");
//Add POST data in JSON format
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("Count", Integer.parseInt(Data));
} catch (JSONException e) {
e.printStackTrace();
}
//Create a writer object and make the request
OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());
outputStream.write(jsonParam.toString());
outputStream.flush();
outputStream.close();
Thanks so much!
Stack overflow is a better place for programming questions than here I suspect...
This looks like the same question. There's a good-looking answer there.
Java send http POST with UTF-8
I need to send HTTP POST with Google FCM. With code below, it's OK to send English message but Chinese characters. I did many trials by adding UTF-8 here and there... Need help. The payload of my
stackoverflow.com