【问题标题】:Token authorization for an android app安卓应用的令牌授权
【发布时间】:2013-11-21 03:25:40
【问题描述】:

我正在尝试使用我的 Android 应用程序中的安全 Web 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);
...

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我注意到在发出“已验证”请求时,我再次发送了用户凭据。这导致服务器忽略令牌并返回 401 未经授权的响应。

      所以解决方法是从我的“经过身份验证的请求”中删除以下行。

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

      需要明确的是,这行对于第一个请求仍然是必需的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-17
        • 2016-03-24
        • 2015-01-25
        • 1970-01-01
        • 2020-06-20
        • 1970-01-01
        • 1970-01-01
        • 2019-05-24
        相关资源
        最近更新 更多