android - 没有发现身份验证挑战获取请求时出错

时间:2015-08-14 18:31:32

标签: android restful-authentication auth0

我第一次使用auth0生成令牌来保护与我的网络服务的连接。

我用它来记录 - 我通过电子邮件&密码这是我的网址,我得到了令牌

这是我的代码,工作正常

 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];

    }

我收到此错误未发现身份验证质询 任何建议谢谢

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分: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);            
    }
}