Basic Authentication on Android - android

I found an example
try {
String data = "YOUR REQUEST BODY HERE";
//
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials("YOUR USER NAME HERE", "YOUR PASSWORD HERE"));
//
DefaultHttpClient http = new DefaultHttpClient();
http.setCredentialsProvider(credProvider);
//
HttpPut put = new HttpPut("YOUR HTTPS URL HERE");
try {
put.setEntity(new StringEntity(data, "UTF8"));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "UnsupportedEncoding: ", e);
}
put.addHeader("Content-type","SET CONTENT TYPE HERE IF YOU NEED TO");
HttpResponse response = http.execute(put);
Log.d(TAG, "This is what we get back:"+response.getStatusLine().toString()+", "+response.getEntity().toString());
} catch (ClientProtocolException e) {
//
Log.d(TAG, "Client protocol exception", e);
} catch (IOException e) {
//
Log.d(TAG, "IOException", e);
}
but I have to send a string in the format of the authorization: <Login>#<ID>:<Passsword>
how to do this?

Are you sure that your server is indeed using basic authentication? If it is, you should set the credentials like this:
new UsernamePasswordCredentials("Login#ID", "Passsword");
Otherwise check what the actual authentication protocol is and implement it (send auth info in header, or as part of URL or as POST parameters, etc.)

You should have a look first what actually HTTP Basic is: http://en.m.wikipedia.org/wiki/Basic_access_authentication#section_3
Your question aims not at HTTP Basic and should not be used at all due to being inherently insecure.
I presume what you ask for should be part of the URL. Even with additional measures like SSL I still would not embed credentials in the URL.
HTTP Basic defines how the username and password must be encrypted (actually hashed). No way to have HTTP and the format you asked for.

Related

Hide JSON file from public; only access for my Android app

I want to hide my JSON file from the public. So that noone can download this JSON data or go through the browser in my JSON file.
I want only that my own developed app can get the information of this JSON file.
Is there a way to code this? Thanks for answering.
what you need to do is to use token which is only known to your server and your client (mobile app) while making call to your server to get the json data. checkout the following tutorial on how to fetch data from server using token.
android token authentication
retrofit token authentication
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://yourbackend.example.com/tokensignin");
try {
List nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair("idToken", idToken));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
final String responseBody = EntityUtils.toString(response.getEntity());
Log.i(TAG, "Signed in as: " + responseBody);
} catch (ClientProtocolException e) {
Log.e(TAG, "Error sending ID token to backend.", e);
} catch (IOException e) {
Log.e(TAG, "Error sending ID token to backend.", e);
}
Or add a token to retrofit NetworkInterceptor
builder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", authToken);
}
});
}

Recieving HTML file as responce instead of JSON Object through get request

I am developing an android app where user logs on to his/her account. After logging in I will receive XSRF token and Laravel Session Id to recognise the specific user. I have to send these tokens for every request I send to the API's to get the appropriate information. But when I am sending the required details as shown in the image, I am getting HTMl file as response instead of getting JSON Object. I was seriously stuck at this problem. Correct Solution may take forward the whole app.
class RegisterConnection extends AsyncTask<String,String,JSONObject> {
protected JSONObject doInBackground(String... arg0) {
JSONObject output = new JSONObject();
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 5000); //Timeout Limit
HttpResponse response = null;
try {
HttpGet get = new HttpGet(statsURL);
get.setHeader("Accept", "application/json");
CookieStore store = new BasicCookieStore();
BasicClientCookie cookie1 = new BasicClientCookie("XSRF-TOKEN", XSRF);
BasicClientCookie cookie2 = new BasicClientCookie("laravel_session", laravel);
store.addCookie(cookie1);
store.addCookie(cookie2);
client.setCookieStore(store);
response = client.execute(get);
if(response!=null){
InputStream in = response.getEntity().getContent();
String resultstring = Utilities.convertStreamToString(in);
Log.i("Result1", resultstring);
output = new JSONObject(resultstring);
Log.i("Result2", output.toString());
}
} catch(Exception e) {
e.printStackTrace();
try {
output.put("sai","error");
Log.i("MainActivity", output.toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
return output;
}
return output;
}
These are the server requirements
http://imgur.com/OY9Q673
This is the Output received
http://imgur.com/IB5AEcT
As far as I can tell, there is nothing wrong with your Android client code.
You are getting HTML from the server so the main reason could be that your Laravel server is rendering the views and sending you back html instead of JSON. Instead of rendering the views on the server, you should send JSON response on your Laravel server side.
Add Jsoup dependency in your gradle file
implementation 'org.jsoup:jsoup:1.11.2'
Document document = Jsoup.parse("http://imgur.com/IB5AEcT");
Elements el = doc.select("button");
Log.i("..........",""+el.attr("data-invite-details"));
Jsoup tutorial
http://jsoup.org/apidocs/org/jsoup/Jsoup.html

How can I pass data from my android application and receive it on my ASP.NET MVC website?

I want to send the some varibeles from my android application to my ASP.NET website, so I can use it there and I don't know how to do that.
If your ASP.NET application has some type of public API that would allow it to interact with external applications, you should be able to make a Web Request to it and post the appropriate values that you needed.
I'm not terribly familiar with Android syntax, but an example like this one on making HTTP GET/POST requests from Android should point you in the right direction :
// Build your client
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("your-asp-mvc-application/Home/AcceptData");
// Build a collection of data that you want to send
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", "test_user"));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
// Encoding POST data
try
{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
// Make the request
try
{
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
}
catch (ClientProtocolException e)
{
// Log exception
e.printStackTrace();
}
catch (IOException e)
{
// Log exception
e.printStackTrace();
}
Basically, once you make make requests, you should be able to target your application and create a Controller Action that can actually accept what you are sending it :
public ActionResult AcceptData(string username, string password)
{
// Do something here
}
First, what form of ASP.NET are you using - Forms or MVC? Also, what do you mean by "send?" Where exactly do you want the data to end up and what exactly do you want your ASP.NET application to do once it receives the data? If you simply mean that you're creating data in your phone and you want your ASP.NET web site to be able to access it too, you can just insert the data into a database that your ASP.NET web site also has access to (e.g. through a web service call or something like that).

Android authentication using JSON

I have a Python/Django server that is the API for a web service.
I'm building an Android application that will communicate with the API and authenticate users, and enable them do all pulls/pushes from the server.
My trouble is with the particular communication with the server. Currently I use my WiFi network, and run the server like so python manage.py runserver 192.168.1.3:8000 so that it is available to any test device on my LAN.
The API is written so it returns http status messages with every response, so that I can tell the success or failure of a request before parsing the JSON reply.
On my Android side, I have used HttpURLConnection because it has the getHeaderField(null) method that I use to pick the http status message from the response. I get a status message 200 [success] when I 'ping' my server - this is a sort-of proof of concept.
My real issue is authentication. My API requires I send it a JSON with data, and it returns a JSON response [with an http status message in the head].
I can't seem to figure out how to do this. The JSON action I've seen around the interwebs are merely picking, or posting.
I am wondering how I can POST and pick up a response from the server.
Extra information
- Server supports HEAD and GET and OPTIONS.
- Assuming server home is 192.168.1.3, user login/register would be in 192.168.1.3/user, events would be in 192.168.1.3/events and so on..
- This was the closest I got to figuring out a solution, but not quite..
CODE from the AsyncTask
protected JSONObject doInBackground(String... params) {
publishProgress(true);
/*Create a new HttpClient and Post Header*/
JSONObject result=null;
HttpClient httpclient = new DefaultHttpClient();
try {
URL url = new URL(cons.PROTOCOL,cons.SERVER,cons.PORT,"/user");
HttpPost httppost = new HttpPost(url.toURI());
HttpResponse response =null;
/*Add your data*/
JSONObject j1=new JSONObject();
JSONObject json=new JSONObject();
j1.put("username", "test");
j1.put("email","test#test.com");
j1.put("password","password");
j1.put("first_name","John");
j1.put("last_name","Doe");
json.put("user",j1);
json.put("mobile_number","256774622240");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
/*Execute HTTP Post Request*/
response= httpclient.execute(httppost);
Log.i("jazz","It's ALIVE!!!!!");
Log.i("jazz",response.getStatusLine().toString());
} catch (ClientProtocolException e) {
/* TODO Auto-generated catch block*/
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
If your are building your HttpPostRequest well, and you only want to know how to attach JSON, here you are a possible solution for it:
StringEntity formEntity = new StringEntity(yourJsonObject.toString());
yourPostRequest.setEntity(formEntity);
I hope this helps!
PS:In addition, let me recommend you the use of this component:
https://github.com/matessoftwaresolutions/AndroidHttpRestService
I've used it in an Android app that is connecting to a python server API and it makes http request easier for your Android client.
Okay, so I'm now answering my own question :D
The issue was with the path variable in the URL string.
This is the format of one of the URL constructors based on this document.
URL(String protocol, String host, int port, String file)
Since I am posting the JSON to the /user path, that's the one I insert into the constructor as the directory.
So, my URL was formed like so:
URL url= new URL("http",cons.SERVER,cons.PORT,"/user/");
My mistake in the beginning was using /user instead of /user/
but other than that, the URL structure and connections are all alright.

http request to password protected files

The php files on my server are password protect with htaccess. How can I make request to these files through my android app?
I couldnt find any relevant answers with google search.
Here you can find your answer:
Basic HTTP Authentication on Android
Basically:
HttpUriRequest request = new HttpGet(YOUR_URL); // Or HttpPost(), depends on your needs
String credentials = YOUR_USERNAME + ":" + YOUR_PASSWORD;
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Authorization", "Basic " + base64EncodedCredentials);
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(request);
// You'll need to handle the exceptions thrown by execute()
You can replace the last line with:
EDITED:
You can try someting like this:
try {
HttpResponse response = httpclient.execute(request);
//this is the login response, logged so you can see it - just use the second part of the log for anything you want to do with the data
Log.d("Login: Response", EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
//if something went badly wrong
}
So you can view your response, maybe the problem is parsing the JSON.
Assuming your PHP files are protected by HTTP Basic Authentication, you can request your php files using this special URL syntax:
http://validuser:validpassword#www.domain.com/validfile.php

Categories

Resources