How to do HTTP authentication in android?
Asked Answered
I

6

73

I am checking out the class org.apache.http.auth. Any more reference or example if anyone has?

Incivility answered 28/12, 2009 at 7:39 Comment(2)
Is this a question about Android applications authentication or just about authentication for a general web app, which just might run on Android?Hybridize
For web authentication(http authentication) for user credentials(username,password)Incivility
A
80

I've not met that particular package before, but it says it's for client-side HTTP authentication, which I've been able to do on Android using the java.net APIs, like so:

Authenticator.setDefault(new Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("myuser","mypass".toCharArray());
    }});
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setUseCaches(false);
c.connect();

Obviously your getPasswordAuthentication() should probably do something more intelligent than returning a constant.

If you're trying to make a request with a body (e.g. POST) with authentication, beware of Android issue 4326. I've linked a suggested fix to the platform there, but there's a simple workaround if you only want Basic auth: don't bother with Authenticator, and instead do this:

c.setRequestProperty("Authorization", "basic " +
        Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));
Apocope answered 28/12, 2009 at 10:39 Comment(9)
Do u know any base64 encoding class present in android 2.0??Incivility
The platform has it in a few places, but oddly enough they don't expose it. They even left references to it in the docs of e.g. android.util. I was using ksoap2-android when I found this, and they have an implementation that depends only on java.io, so you could just grab that class (subject to its license of course) from: kobjects.cvs.sourceforge.net/kobjects/kobjects/src/org/kobjects/…Apocope
How do you handle the event that the authentication fails, say because the supplied credentials are bad?Pitiable
Base64 is not available in older versions of Android. Any suggestions there?Formalize
i'm getting an error when trying to c.connect(); , it says IOExceptionDemonology
@Demonology IOException is probably not related to authentication; I would expect a 401 Unauthorized response if authentication was bad.Apocope
The code with Authenticator is not working for me even for simple GET request. If after c.connect() i call c.getResponseCode(), this hangs indefinitely. My server is using digest authentication. I m using Android api level 15. Same works for non-android platforms.Hassanhassell
Somehow this doesn't work for me. I am getting "Error response code: 301". Any idea why?Fitzwater
You have to use Base64.encodeToString in your example with c.setRequestProperty otherwise you're concatenating a base64 array with a string.Zygosis
C
120

For me, it worked,

final String basicAuth = "Basic " + Base64.encodeToString("user:password".getBytes(), Base64.NO_WRAP);

Apache HttpCLient:

request.setHeader("Authorization", basicAuth);

HttpUrlConnection:

connection.setRequestProperty ("Authorization", basicAuth);
Conventionalize answered 21/2, 2012 at 12:24 Comment(8)
The NO_WRAP flag! That was key. I was just using the default and wondering why I kept getting a 400.Balls
Your answer saves me a lot of time. Thanx! My problem was really in wrong flag (DEFAULT).Morice
Finally, after a long time... no_wrap FTW!Dividers
wow - this NO_WRAP just ended my 5 hours problem solving against a server which had no logging... THANX!Zoochore
Thanks for the nice concise answer! Android Community FTW.Lachrymal
Base64.encodeToString() did the trick for me. Previously, I was using Base64.encode() which was resulting in a HTTP response code of 500.Flinger
Use connection.setRequestProperty as described in other answers if you are using the HttpURLConnection classFlogging
I use this: String basicAuth = Base64.encodeToString(String.format("%s:%s",user,passwd).getBytes(),Base64.DEFAULT); and with NO_WRAP and no way to add credentials... Only get "Basic MTIzNDU2NzhBOnR0YQ==\r\n"... WHY?Pullulate
A
80

I've not met that particular package before, but it says it's for client-side HTTP authentication, which I've been able to do on Android using the java.net APIs, like so:

Authenticator.setDefault(new Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("myuser","mypass".toCharArray());
    }});
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setUseCaches(false);
c.connect();

Obviously your getPasswordAuthentication() should probably do something more intelligent than returning a constant.

If you're trying to make a request with a body (e.g. POST) with authentication, beware of Android issue 4326. I've linked a suggested fix to the platform there, but there's a simple workaround if you only want Basic auth: don't bother with Authenticator, and instead do this:

c.setRequestProperty("Authorization", "basic " +
        Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));
Apocope answered 28/12, 2009 at 10:39 Comment(9)
Do u know any base64 encoding class present in android 2.0??Incivility
The platform has it in a few places, but oddly enough they don't expose it. They even left references to it in the docs of e.g. android.util. I was using ksoap2-android when I found this, and they have an implementation that depends only on java.io, so you could just grab that class (subject to its license of course) from: kobjects.cvs.sourceforge.net/kobjects/kobjects/src/org/kobjects/…Apocope
How do you handle the event that the authentication fails, say because the supplied credentials are bad?Pitiable
Base64 is not available in older versions of Android. Any suggestions there?Formalize
i'm getting an error when trying to c.connect(); , it says IOExceptionDemonology
@Demonology IOException is probably not related to authentication; I would expect a 401 Unauthorized response if authentication was bad.Apocope
The code with Authenticator is not working for me even for simple GET request. If after c.connect() i call c.getResponseCode(), this hangs indefinitely. My server is using digest authentication. I m using Android api level 15. Same works for non-android platforms.Hassanhassell
Somehow this doesn't work for me. I am getting "Error response code: 301". Any idea why?Fitzwater
You have to use Base64.encodeToString in your example with c.setRequestProperty otherwise you're concatenating a base64 array with a string.Zygosis
I
15

You can manually insert http header to request:

HttpGet request = new HttpGet(...);
request.setHeader("Authorization", "Basic "+Base64.encodeBytes("login:password".getBytes()));
Impacted answered 15/3, 2011 at 19:24 Comment(0)
L
13

Manual method works well with import android.util.Base64, but be sure to set Base64.NO_WRAP on calling encode:

String basicAuth = "Basic " + new String(Base64.encode("user:pass".getBytes(),Base64.NO_WRAP ));
connection.setRequestProperty ("Authorization", basicAuth);
Leopold answered 8/1, 2012 at 17:37 Comment(0)
J
3

For my Android projects I've used the Base64 library from here:

http://iharder.net/base64

It's a very extensive library and so far I've had no problems with it.

Junette answered 4/6, 2010 at 11:34 Comment(0)
S
1

This works for me

 URL imageUrl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) imageUrl
                            .openConnection();
                    conn.setRequestProperty("Authorization", "basic " +
                            Base64.encode("username:password".getBytes()));
                    conn.setConnectTimeout(30000);
                    conn.setReadTimeout(30000);
                    conn.setInstanceFollowRedirects(true);
                    InputStream is = conn.getInputStream();
Sikh answered 24/6, 2014 at 7:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.