Xfactor
Xfactor

Reputation: 79

How to fix an "401 Unauthorized. No Api Key provided"

I'm trying to pull data using api in java. When doing so, the api returns 401: Unauthorized. I'm currently registered as an admin user and I'm using an api key as a token. I've also tried using declaring my token and using a setRequestProperty("Authorization", "token", + access-token). Do you know what I might be doing wrong?

I've also tried using cURL and the UI to similar effect. and I have gotten back the output I expected but in java it is an authentication issue

public static void main(String[] args) {
        // TODO Auto-generated method stub
        //build each line and have a response to it 
        BufferedReader reader;
        String access_token = "abcde123 "; 
        String line;
        StringBuffer responseContentReader = new StringBuffer();
try {
    //URL url =  new URL("https://testurl.com");

    connection = (HttpsURLConnection) url.openConnection();

    connection.setRequestProperty("Authorization", "Token" + access_token);


    //here we should be able to "request" our setup
    //Here will be the method I will use 
    connection.setRequestMethod("GET");


    //after 5 sec if the connection is not successful time it out
    connection.setConnectTimeout(7000);
    connection.setReadTimeout(7000);

    int status = connection.getResponseCode();
    //System.out.println(status); //here the connect was established  output was 200 (OK)

    //here we are dealing with the connection isnt succesful
    if (status >299) {
        reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        while ((line = reader.readLine()) != null) {
            responseContentReader.append(" ");
            responseContentReader.append(line);
            responseContentReader.append("\n");
        }
        reader.close();
    //returns what is successful    
    }else {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = reader.readLine()) != null) {
            responseContentReader.append(" ");
            responseContentReader.append(line);
            responseContentReader.append("\n");
        }
        reader.close();
    }
    System.out.println(responseContentReader.toString());
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}catch (IOException e) {
    // TODO: handle exception
    e.printStackTrace();
}finally {
    connection.disconnect();
}
    }

}

the output I get from the console is

{"success":"false","error":"unauthorized","message":"401 Unauthorized. No API key provided."}

Upvotes: 1

Views: 4519

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

You are setting the X-Risk-Token header in your curl command. In Java you need to do the same:

connection.setRequestProperty("X-Risk-Token", access_token); 

Upvotes: 1

Related Questions