如何从Android访问Bearer认证服务

时间:2013-11-22 13:54:18

标签: android authentication oauth http-headers apache-httpclient-4.x

我将使用正在使用Bearer身份验证的服务。我试图从Android取得它是徒劳的。这是我的代码。

String mytoken = "some token I am sure is right";
HttpClient witClient = new DefaultHttpClient();
Uri.Builder b = Uri.parse("www.somewebsite.com").buildUpon();
b.appendQueryParameter("q", "some query string");
String finalurl = b.build().toString();
HttpGet request = new HttpGet(new URI(finalurl));
request.setHeader("Authorization", "Bearer "+mytoken);
HttpResponse response = witClient.execute(request);

服务器会返回一个错误,说明需要进行身份验证。显然,标题会以某种方式丢弃。

11-22 21:50:42.180: W/DefaultRequestDirector(3408): Authentication error: Unable to respond to any of these challenges: {bearer=Www-Authenticate: Bearer realm="OAuth required"}

哪里错了

1 个答案:

答案 0 :(得分:6)

这可能有点复杂,但我已经成功了,所以我会尝试给你带来经验的好处。

你必须提供几件物品

  • org.apache.http.auth.Credentials
  • 的实现
  • org.apache.http.auth.AuthSchemeFactory的实现

您的凭据实施应类似于以下内容:

import java.security.Principal;

import org.apache.http.auth.BasicUserPrincipal;
import org.apache.http.auth.Credentials;

public class TokenCredentials implements Credentials {
    private Principal userPrincipal;

    public TokenCredentials(String token) {
        this.userPrincipal = new BasicUserPrincipal(token);
    }

    @Override
    public Principal getUserPrincipal() {
        return userPrincipal;
    }

    @Override
    public String getPassword() {
        return null;
    }

}

然后你需要实现AuthSchemeFactory:

import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.ContextAwareAuthScheme;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.message.BufferedHeader;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.CharArrayBuffer;

public class BearerAuthSchemeFactory implements AuthSchemeFactory {

    @Override
    public AuthScheme newInstance(HttpParams params) {
        return new BearerAuthScheme();
    }

    private static class BearerAuthScheme implements ContextAwareAuthScheme {
        private boolean complete = false;

        @Override
        public void processChallenge(Header header) throws MalformedChallengeException {
            this.complete = true;
        }

        @Override
        public Header authenticate(Credentials credentials, HttpRequest request) throws AuthenticationException {
            return authenticate(credentials, request, null);
        }

        @Override
        public Header authenticate(Credentials credentials, HttpRequest request, HttpContext httpContext)
                throws AuthenticationException {
            CharArrayBuffer buffer = new CharArrayBuffer(32);
            buffer.append(AUTH.WWW_AUTH_RESP);
            buffer.append(": Bearer ");
            buffer.append(credentials.getUserPrincipal().getName());
            return new BufferedHeader(buffer);
        }

        @Override
        public String getSchemeName() {
            return "Bearer";
        }

        @Override
        public String getParameter(String name) {
            return null;
        }

        @Override
        public String getRealm() {
            return null;
        }

        @Override
        public boolean isConnectionBased() {
            return false;
        }

        @Override
        public boolean isComplete() {
            return this.complete;
        }
    }
}

下一步是让HttpClient接受它作为一个有效的方案:

    HttpContext httpContext = new BasicHttpContext();

    AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry();
    authSchemeRegistry.register("Bearer", new BearerAuthSchemeFactory());
    httpContext.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, authSchemeRegistry);
    AuthScope sessionScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "Bearer");

    Credentials credentials = new TokenCredentials (token);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(sessionScope, credentials);
    httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);

我通常会在每个上下文的基础上创建这些内容,并在一段时间内保持上下文。

可以找到其他文档here。我建议远离“先发制人”认证,让famework在处理401挑战时发挥作用。

如果您想看看我在说什么,请打开HTTP客户端中的日志记录,以便您可以跟踪有线会话 - 您将看到初始请求带来挑战,然后客户端将利用凭证提供程序找到适当的凭据,并使用针对我们定义的方案的相应质询响应发送请求。

祝你好运!