MVC4 - Android authentication via http POST and FormsAuthentication - android

I know there are plenty of resources like this on the web, and the closest I've come was the answer to this question: ASP.NET Web API Authentication.
Basically, this is my requirement. Log in via android to my account on an MVC4 internet application I created (which uses SimpleMembership). It is NOT an MVC Web Api app, which seems to confuse things when looking at the various ways of achieving this.
I am attempting to use FormsAuthentication to set an authentication cookie, but I have no idea how to configure my android httpclient to actually send through this authentication cookie, or how to get MVC to save a session from my android app.
So far, this is what I've come up with on the MVC side:
[HttpPost]
[AllowAnonymous]
public bool LoginMobi(LoginModel model)
{
var membership = (SimpleMembershipProvider)Membership.Provider;
if (membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return true;
}
else return false;
}
And I use the following java in my android app (sent over an SSL connection):
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://mysite/api/login");
List<NameValuePair> nameValue = new ArrayList<NameValuePair>();
nameValue.add(new BasicNameValuePair("UserName", "foo"));
nameValue.add(new BasicNameValuePair("Password", "bar"));
httppost.setEntity(new UrlEncodedFormEntity(nameValue));
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
// etc etc
What I haven't figured out is how to receive the authentication cookie on android and send it back with each request to controllers with the [Authorize] attribute. I'm rather new to this so please forgive my ignorance!

You are using FormsAuthentication which uses cookie to identify user for each request. You have two options here.
Use CookieStore for HttpClient. Check Android HttpClient and Cookies
OR
Combine BASIC auth and FormsAuthentication. Check Combining Forms Authentication and Basic Authentication
Hope this helps.

Related

What is the preferable method for sending request in mobile API in Rails

I have created an API controller to handle only json requests from an Android app. Naturally I'm using token authentication. What would be better:
To send a request using POST:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.170:3000/api/get_all");
httppost.setHeader("content-type", "application/json; charset= utf-8");
httppost.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("token", token);
StringEntity entity = new StringEntity(json.toString(), "utf-8");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
or GET:
httpget = new HttpGet("http://10.0.0.170:3000/api/get_all?"+"token="+token);
httpget.setHeader("content-type", "application/json; charset= utf-8");
httpget.setHeader("Accept", "application/json");
response = httpclient.execute(httpget);
result = EntityUtils.toString(response.getEntity());
clearly there is less code in GET, but is there some other reasons to prefer one over the other?
Even if you are using this token for simple lookup, i.e. without changing the state on server, use POST. If you use GET, web server will log all query parameters making it more vulnerable for log injection attacks for example.
You should also consider using HTTPS for authentication token in production.
In your code consider also handling return status from web server (e.g. when it is not 200).
In general, for the choice POST vs GET you can also refer to W3C:
Use GET if:
The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).
Use POST if:
The interaction is more like an order, or
The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
The user be held accountable for the results of the interaction.

Android app getting data from a third-party JSP & Servlet

I'm writing an Android app that should get data from a certain web application. That web app is based on Servlets and JSP, and it's not mine; it's a public library's service. What is the most elegant way of getting this data?
I tried writing my own Servlet to handle requests and responses, but I can't get it to work. Servlet forwarding cannot be done, due to different contexts, and redirection doesn't work either, since it's a POST method... I mean, sure, I can write my own form that access the library's servlet easily enough, but the result is a jsp page.. Can I turn that page into a string or something? Somehow I don't think I can.. I'm stuck.
Can I do this in some other way? With php or whatever? Or maybe get that jsp page on my web server, and then somehow extract data from it (with jQuery maybe?) and send it to Android? I really don't want to display that jsp page in a browser to my users, I would like to take that data and create my own objects with it..
Just send a HTTP request programmatically. You can use Android's builtin HttpClient API for this. Or, a bit more low level, the Java's java.net.URLConnection (see also Using java.net.URLConnection to fire and handle HTTP requests). Both are capable of sending GET/POST requests and retrieving the response back as an InputStream, byte[] or String.
At most simplest, you can perform a GET as follows:
InputStream responseBody = new URL("http://example.com").openStream();
// ...
A POST is easier to be performed with HttpClient:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("name1", "value1"));
params.add(new BasicNameValuePair("name2", "value2"));
HttpPost post = new HttpPost("http://example.com");
post.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
InputStream responseBody = response.getEntity().getContent();
// ...
If you need to parse the response as HTML (I'd however wonder if that "public library service" (is it really public?) doesn't really offer XML or JSON services which are way much easier to parse), Jsoup may be a life saver as to traversing and manipulating HTML the jQuery way. It also supports sending POST requests by the way, only not as fine grained as with HttpClient.

rails Devise http authenticating mobile

I'm trying to authenticate an android client app to my server ruby on rails app which uses Devise gem. But I've tried http authentication, and post requests to authenticate, and the server just responds 200 for any given username/password.
I've already set up the config.http_authenticatable = true and the :database_authenticable at the user model...
I'll post my authenticate method so u guys can have a look on it...
public static boolean authenticate(User user, String verb) throws IOException, JSONException
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(verb);
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(user.getMail(), user.getPassword()));
httpClient.setCredentialsProvider(credProvider);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", user.getMail()));
nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
//JSONObject resp = null;
if (statusCode < 200 || statusCode >= 300){
throw new IOException("Error");
}
return true;
}
If server is responding 200, it really sounds like server side configuration, so you should double-check your URLs are actually secured, using a desktop web browser and a tool like Fiddler so you can see everything. Pay particular attention to the Authentication headers, and the Status codes; at the least you should see a 401 from the server to start things off.
You can also turn on diagnostics for Apache HTTP on your device, and it will also dump headers and content to LOGCAT, so you can make sure everything is proceeding.
Check the WWW-Autnenticate header's contents, it will specify which schemes are accepted. The client side will re-request the URL, but it will put the Authorization header into its request.
In short, make sure your server side works outside of your application, in an environment that's easier to troubleshoot.
Client side, it looks like you are only activating BASIC authentication (everyone stop using it!), and your endpoint may only want DIGEST or NTLM or KERBEROS or any other authentication scheme than BASIC. Since it looks like you didn't set up for SSL, certainly use at least DIGEST or you have clear text issues!
Using form variables (for authentication) only works at the application level, and not the HTTP protocol level, which uses HTTP Headers (WWW-Autnenticate, Authorization) and Status codes (401, 403) for the authentication process. And again, if you aren't configuring your server (and client) for SSL-only, there will be clear text problems.

How can i connect a google app-engine application with my android?

I've a application deployed on google app-engine..it has a registration form.
now i've made a registration form in my android application and i want that on click submit...it should be sent to the application on google app-engine and it should be persisted in the particular db...
somebody told me to use http request and response method but i'm not aware of that thing..
can somebody please provide me with some sample code or something.....
thanksss....
You haven't specified if you're using Python or Java.
You have to decide how you want to connect. At the simplest level you could just POST the data to Google App Engine. In Java you would write a servlet which handles this. See Java EE tutorial. Alternatively you could write a web service (SOAP, RESTful) on the server which handles the data being sent from your application. Again Google this and there are countless examples.
Assume we're going down the simplest POST route. So in your servlet (running on GAE) you'd have something like this:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String value1 = request.getParameter("value1");
}
And in your android app you'd do something like:
DefaultHttpClient hc=new DefaultHttpClient();
ResponseHandler <String> res=new BasicResponseHandler();
HttpPost postMethod=new HttpPost("http://mywebsite.com/mappedurl");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("value1", "Value my user entered"));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response=hc.execute(postMethod,res);
Of course value1 in the servlet would be set to "Value my user entered".
EDIT: Google have now released their Google Cloud Endpoints - this makes building RESTful services on App Engine and creating clients for Android a lot easier. It does tie you in to App Engine even more though - but certainly worthy of consideration.

Windows authentication prior to posting data, what am I missing?

I have an android app that is working fine when connected to a production web server. A development server was created for testing future releases. It's an IIS server that's locked down with username/password.
I am trying to use httpclient.getCredentialsProvider() to send a username and password so I can authenticate to the page before doing anything else but it doesn't seem to be working correctly so I assume I am missing some code or doing something wrong.
I tried messing with the credentials and sending the port and full url but that didn't work either so I just switched it to null and -1 which from what I gather means it should work on any site any port, but every way I tried still got the same result of not authenticating.
Here is what I have now.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
httpclient.getCredentialsProvider().setCredentials(new AuthScope(null,-1), new UsernamePasswordCredentials("someusername", "somepassword"));
HttpPost httpost = new HttpPost("someURL");
Other non-relevant code to set Name Value Pair for posting
Then
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httpost.setEntity(formEntity);
HttpResponse response = httpclient.execute(httpost);
IIS supports HTTP authentication methods like Basic, Digest and Integrated. The problem is that all of them are hardwired to Windows accounts. This means that you need a Windows user on your server for every account you want to HTTP-auth enable.
Having the ability to do plain Basic Authentication agains account stored e.g. in a database would be very handy for a range of situations like web applications, (WCF) web services, REST services, Silverlight service backends etc.
enter link description here

Categories

Resources