Вопрос

I am trying to use secure web API from my Android app. The web API uses basic authentication and a the use of a server generated token. I have been able to use the web API using curl as shown below.

Firstly, to authenticate the user and get the token.

curl http://localhost:3000/api/api_keys -u 'user@example.com:UserPassword'

returns {"token":"0d63b512573dce7be5eb53bab58a5625"}

Secondly, I use the token to call the API as an authenticated user.

curl http://localhost:3000/api/exams -H 'Authorization: Token token="0d63b512573dce7be5eb53bab58a5625"'

return the appropriate json object.

The problem is when I try to call the web API from the Android client using the code below, the web API doesn't pick up the Authorization header and so throws the request out.

...
HttpClient client = new DefaultHttpClient(new BasicHttpParams());
HttpGet httpGet = new HttpGet(targetUrl.toString());
httpGet.setHeader("Content-type", "application/json");
httpGet.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("test-user@example.com", "Password!"), "UTF-8", false));
httpGet.addHeader("Authorization", "Token token=\"" + getToken() + "\"");

try {
    HttpResponse response = client.execute(httpGet);
...

How should I authenticate the Android app to the web API?

Это было полезно?

Решение 2

I noticed that I was sending the user credentials again when making the 'authenticated' request. This was causing the server to ignore the token and return a 401 unauthorised response.

So the fix was to the remove the following line from my 'authenticated request'.

httpGet.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("test-user@example.com", "Password!"), "UTF-8", false));

To be clear, this line is still necessary for the first request.

Другие советы

You need to send request first to get the token. Then, you can use the token.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top