【问题标题】:Unable to retrieve auth token in Android client无法在 Android 客户端中检索身份验证令牌
【发布时间】:2015-01-20 22:01:08
【问题描述】:

我正在构建一个需要 oauth 2 身份验证的应用。检索 access_token 的端点是 https://10.0.2.2:8443/oauth/token(10.0.2.2 是环回主机上的本地主机)

当我通过浏览器发出请求时,它工作得很好,但是当我通过 Java 代码发出请求时,我收到了错误的请求,并且我没有获得足够的信息来进行故障排除。

我使用了不安全的 HttpClient(是的,我知道,这非常不安全)

public class UnsafeHttpsClient {

    public static HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(sf.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 8080));
            registry.register(new Scheme("https", sf, 8443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }

}

我也使用这个类。代码取自关于 SO 的这篇文章: 参考:Trusting all certificates using HttpClient over HTTPS

public class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}

最后,我使用这两个类来构建我的请求:

public class TaskAuthenticate extends AsyncTask<String, Integer, JSONArray> {

    private Context ctx;
    public IApiAccessResponse delegate=null;
    private HttpClient mHttpclient = UnsafeHttpsClient.getNewHttpClient();
    private HttpPost mHttppost;
    private String client_string = "mobile:";
    public TaskAuthenticate (Context ctx) {
        this.ctx = ctx;
    }


    protected JSONArray doInBackground(String... params) {
         String strTokenUrl = ctx.getResources().getString(R.string.oauth2_endpoint);

         mHttppost = new HttpPost();
         try {
             mHttppost.setURI(new URI(strTokenUrl));
         }
         catch (URISyntaxException e1) {
             e1.printStackTrace();
         }
         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
         nameValuePairs.add(new BasicNameValuePair("username", params[0]));
         nameValuePairs.add(new BasicNameValuePair("password", params[1]));
         nameValuePairs.add(new BasicNameValuePair("grant_type", "password"));
         nameValuePairs.add(new BasicNameValuePair("client_id", "mobile"));
//       nameValuePairs.add(new BasicNameValuePair("client_secret",));
         try {
            String header = "Basic " + Base64.encodeToString(client_string.getBytes("UTF-8"), Base64.DEFAULT);
            mHttppost.setHeader("Authorization", header);
            mHttppost.setHeader("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            mHttppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
         }
         catch (UnsupportedEncodingException e) {
            e.printStackTrace();
         }

        HttpResponse response;
        try {
            response  = mHttpclient.execute(mHttppost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            response = null;
        } catch (IOException e) {
            e.printStackTrace();
            response = null;
        }

        JSONArray result = null;
        try {
            result = new JSONArray(EntityUtils.toString(response.getEntity()));
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

当我执行此操作时,我会收到 400 - Bad request 响应。另外,如果我尝试使用以下代码获取响应正文

 HttpEntity respEntity = response.getEntity();
    if(respEntity!=null) {
        String res = EntityUtils.toString(respEntity);
    }

body 作为空字符串返回 到目前为止,我无法在我的浏览器中重现,所以我对问题可能是什么一无所知。 我从根本上做错了什么吗?任何调试此问题的提示将不胜感激

如果需要服务器代码,我会发布它,但我认为问题出在应用程序上,因为我可以在浏览器中进行请求。

【问题讨论】:

    标签: android spring https oauth-2.0


    【解决方案1】:

    我知道问题出在哪里。当您为请求添加标头时,行尾字符只会导致 POST 请求出现问题。解决方法是更改​​位掩码以确保不存在行尾字符。我替换了这一行:

    String header = "Basic " + Base64.encodeToString(client_string.getBytes("UTF-8"), Base64.DEFAULT);
    

    作者:

    String header = "Basic " + Base64.encodeToString(client_string.getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP);
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多