0

这是我第一次使用auth0生成令牌以保护与我的 Web 服务的连接。

我用它来记录 - 我通过我的网址传递电子邮件和密码,然后我得到了令牌

这是我的代码,它工作正常

 public String post_to_webservice() {
        final StringBuilder stringBuilder = new StringBuilder();
        final String[] line = {null};
        final BufferedReader[] reader = {null};


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("email", "test"));
                    params.add(new BasicNameValuePair("password", "test"));
                    URL url = new URL("https://validate.co.nz/api/public/api/authenticate");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    connection.setRequestMethod("POST");
                    connection.setReadTimeout(30000);

                    OutputStream outputStream = connection.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                    writer.write(getQuery(params));
                    writer.flush();
                    writer.close();
                    outputStream.close();
                    connection.connect();
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        reader[0] = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        while ((line[0] = reader[0].readLine()) != null) {
                            stringBuilder.append(line[0]);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();

                } finally {
                    if (reader[0] != null) {
                        try {
                            reader[0].close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String message = stringBuilder.toString();
                            JSONObject object = new JSONObject(message);
                            Token = (String) object.get("token");
                            Toast.makeText(MainActivity.this, "token is : " + Token, Toast.LENGTH_LONG).show();

                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }
                });

            }

        }).start();
        return stringBuilder.toString();
    }


private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }

但我需要使用相同的 url,但通过在标头中传递我的令牌来获取数据

这是我的尝试

 public String get_request() {

        final StringBuilder stringBuilder = new StringBuilder();
        final String[] line = {null};
        final BufferedReader[] reader = {null};
        final String[] result = {null};

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
// second try pass token here
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("token", Token));


                    URL url = new URL("https://validate.co.nz/api/public/api/authenticate");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// I try put my token in header but its fail 
                    String base64Auth = Base64.encodeToString(Token.getBytes(), Base64.NO_WRAP);
                    connection.setRequestProperty("Authorization", "Basic " + base64Auth);
                    connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                    connection.setRequestProperty("Accept-Charset", "UTF-8");
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                    connection.setRequestMethod("GET"); // get request
                    connection.setReadTimeout(300000);
                    connection.setDoOutput(true);
                    connection.setDoInput(true);

                    OutputStream outputStream = connection.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                    writer.write(getQuery(params));
                    writer.flush();
                    writer.close();
                    outputStream.close();
                    connection.connect();
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        reader[0] = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        while ((line[0] = reader[0].readLine()) != null) {
                            stringBuilder.append(line[0]);
                        }
                        result[0] =stringBuilder.toString();
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                    result[0] = e.getMessage();

                } finally {
                    if (reader[0] != null) {
                        try {
                            reader[0].close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                            Toast.makeText(MainActivity.this, "Result: " + result[0], Toast.LENGTH_LONG).show();


                    }
                });

            }

        }).start();
        return result[0];

    }

我收到此错误未找到身份验证挑战 任何建议谢谢

4

2 回答 2

1

我正在开发一个使用 OAuth 身份验证来验证对 RESTful Web 服务的请求的 Android 应用程序。我对您正在使用的特定 OAuth 包一无所知,也无法确定您遇到问题的原因。但是,基于你正在做的事情和我正在做的事情之间的差异,我看到了两个潜在的问题:

  1. 您可能没有在 HTTP 标头中使用正确的令牌。特别是,您使用的令牌可能是刷新令牌而不是访问令牌,您可能需要改用访问令牌。

  2. 您可能在标头中错误地插入了令牌。就我而言,我使用以下方法插入令牌:

    connection.setRequestProperty("Authorization", "Bearer " + accessToken);

于 2015-08-14T20:52:16.347 回答
1

我认为问题可能是setDoOutput(),我已经测试了这个示例代码,你可以阅读我的评论

private class APIRequest extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... params) {
        try {            
            String token = "0123456789";            
            URL url = new URL("https://validate.co.nz/api/public/api/authenticate");                
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setDoInput(true);         
            urlConnection.setDoOutput(true); //HERE: if TRUE, receive "No authentication challenges found"; if FALSE, receive "token_not_provided"              
            urlConnection.setRequestMethod("GET"); // I think if GET, should setDoOutput(false);
            urlConnection.setRequestProperty("Authorization", "Basic " + token);
            urlConnection.connect();
            InputStream inputStream;
            if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                inputStream = urlConnection.getErrorStream();
            } else {
                inputStream = urlConnection.getInputStream();
            }                
            return String.valueOf(urlConnection.getResponseCode()) + " " + urlConnection.getResponseMessage();
        } catch (Exception e) {
            return e.toString();
        }
    }

    @Override
    protected void onPostExecute(String response) {
        super.onPostExecute(response);            
    }
}
于 2015-08-15T02:37:01.860 回答