Android应用程序的令牌授权

时间:2013-11-08 23:52:29

标签: android authorization android-service http-basic-authentication android-internet

我正在尝试使用Android应用中的安全网址API。 Web API使用基本身份验证和使用服务器生成的令牌。我已经能够使用curl使用web API,如下所示。

首先,对用户进行身份验证并获取令牌。

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

返回{"token":"0d63b512573dce7be5eb53bab58a5625"}

其次,我使用令牌将API作为经过身份验证的用户调用。

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

返回适当的json对象。

问题是当我尝试使用下面的代码从Android客户端调用Web API时,Web API不会获取Authorization标头,因此会抛出请求。

...
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);
...

我应该如何向Android API验证Android应用?

2 个答案:

答案 0 :(得分:0)

您需要先发送请求以获取令牌。然后,您可以使用令牌。

答案 1 :(得分:0)

我注意到我在进行“身份验证”后再次发送用户凭据。请求。这导致服务器忽略该令牌并返回401未经授权的响应。

因此,修复方法是从我的经过身份验证的请求中删除以下行。

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

要清楚,第一次请求仍然需要此行。

相关问题