I'm posting to an API server and I'm getting the following reply:
Server Response: {"detail":"Authentication credentials were not provided."}
I'm writing the requests in Java and I'm not sure exactly why it's saying credentials were not provided.
Here is a snippet of my code:
hconn.setRequestProperty("Content-Type", "application/json");
hconn.setRequestProperty( "Accept", "application/json" );
if( urlconn instanceof HttpsURLConnection )
{
String encoded = new String(Base64.getEncoder().encode( ( username + ":" + password).getBytes()));
String auth = "Basic " + encoded;
urlconn.setRequestProperty("Encoded Authorization", auth );
}
Where hconn is of type HttpURLConnection
This is the only relvant snippet that you guys need. Are there properties i'm missing to set here?
I know the server response is from a Django framework but the documentation is not clear on spotting what IS required to prevent this.
Any help appreciated.
Authorization is the correct request header name and not 'Encoded Authorization'. So, you should set
urlConn.setRequestProperty("Authorization", auth);
Related
Basically i'm new to groovy, and i'm trying to use it to add a device to "netbox" using API, i tried some GET requests that needed authentication and they worked fine, but i couldn't make any POST request work, i'm always getting 403 no matter what method i try to authenticate Basic using creds or using API Token.
Here's the code i wrote for the POST request :
def url = "http://192.168.12.89:8000/api/dcim/devices"
def connection = url.toURL().openConnection()
def message = '{"name":"R4","device_type":"1","device_role":"1","site":"1"}'
connection.setRequestMethod("POST")
connection.setDoOutput(true)
connection.setDoInput(true)
connection.addRequestProperty("Accept", "application/json;charset=UTF-8")
connection.addRequestProperty("Content-Type", "application/json")
//def auth = "admin:admin".bytes.encodeBase64()
//connection.setRequestProperty("Authorization", "Basic ${auth}")
connection.setRequestProperty("Authorization", "Token 63091d94b00d40e9e0a4e1286e181c09deca6e89")
connection.getOutputStream().write(message.getBytes("UTF-8"))
def responseCode = connection.getResponseCode()
InputStream response = null
println "${responseCode}"
if (responseCode != 200) {
response = connection.getErrorStream()
} else {
response = connection.getInputStream()
}
def responseBody = response?.text
response?.close()
println responseBody
My API key works fine with the get method and it has the write permissions included, also tried a python POST request works perfectly fine, so i guess the problem is in my groovy coding.
I hope i can get a bit of help cause i've been trying for two days :x
Thank you :x
Explination
I am working on a Java App that sends a text message via a CPAS API (Similar to Tweepy). I am using CURL to request the message send. The request from Java seems to be sent but I am getting a 401 code. I'm assuming there is an issue with the encoding of my Authentication for the request. The code is as follows:
URL url = new URL("https://api.zang.io/v2/Accounts/ACe1889084d37de951ef064200aecbe4b2/SMS/Messages");
String auth = AUTH + ":" + TOKEN;
String encodeedAuth = Base64.getEncoder().withoutPadding().encodeToString(auth.getBytes());
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("Authorization", "Basic " + encodeedAuth);
String data = "From=+14132698029&To=17817381451&Body=New Test";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
"""
An HTTP 401 response is commonly an HTTP endpoint authorization failure. The best way to see why your auth credentials are failing is to capture the request/response pair in transit (at the receiving end would be optimal) and then compare that request/response pair to one that works.
I want to consume rest api from url with http basic authentication that returns a big json & then i want to parse that json without POJO to get some values out of it. How can i achieve that in java spring?
I know this is common question but i could not get proper solution that worked for me.
Please help me someone.
Using the Apache HttpClient, the following Client Code snipped has been copied from the following URL. The comments have been added by myself.
https://www.baeldung.com/httpclient-4-basic-authentication
HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
// Combine the user and password pair into the right format
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
// Encode the user-password pair string in Base64
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
// Build the header String "Basic [Base64 encoded String]"
String authHeader = "Basic " + new String(encodedAuth);
// Set the created header string as actual header in your request
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
I am using Restful Services on server and trying to maintain the same session after performing login:
URL endpoint = new URL(getString(R.string.url_login));
// Create connection
HttpURLConnection myConnection = (HttpURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
// Create the data
String myData = "username=" + username + "&password=" + pwd;
// Enable data writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
rc = myConnection.getResponseCode();
if (rc == 200) {
String Cookie= myConnection.getHeaderField("Set-Cookie");
URL endpoint2 = new URL(getString(R.string.url_checkUserType));
HttpURLConnection myConnection2 =
(HttpURLConnection)endpoint2.openConnection();
myConnection2.setRequestMethod("GET");
myConnection2.setRequestProperty("User-Agent", "my-rest-app-v0.1");
myConnection2.setRequestProperty("Cookie", Cookie);
rc2 = myConnection2.getResponseCode();
....
}....
The problem is that rc2 is every time 401 as WebService doesn't recognize that requiest is part of the same session. What am I doing wrong?
You may do as follows
on the server side, it checks if the incoming request has a "sessionId" in cookie: if not, create one and return it in response; if yes, it knows the request belongs to a known session
on the client side, after a successful login, retrieve the "sessionId" from the response, and set it in the following requests
==
connection.setRequestProperty("Cookie", "JSESSIONID=" + URLEncoder.encode(jSessionId, "UTF-8"));
The solution was to use Spring RESTful services for Android that worked great for me.
I am trying to convert this line to resteasy stuff.
curl -X GET --digest -u myuser:mypassword --header 'Accept:application/json; charset=utf-8' http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/instances
this is how I am trying to connect to that endpoint
clientREST = new ResteasyClientBuilder().build();
clientREST.register(new BasicAuthentication(userWowza, passWowza));
String targetStr = "http://" + host + ":" + portEndpoint + endPoint + red5App + "/instances";
System.out.println(targetStr);
ResteasyWebTarget target = clientREST
.target(targetStr);
Response response = target.request().post(Entity.entity("", "application/json"));
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
But I get HTTP error code : 401. So it is like user and password is no working. Am I sending the headers correctly?
Update
So I couldnt find any example of resteasy with digest auth, so I found that wowza seems to suppport basic and digest at the same time
Actually your curl uses --digest not BASIC authentication. So it looks like Server does not accept BASIC Authorization schema.