How to Pass Username and Password in GET Request in Java - java

Below is the Code Written by me.
But when i send the request i am getting Response Code 401 : Unathorized.
String url = "SAMPLE_URL";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
//con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

Add this code to your program after obj.openConnection();
String encoded = Base64.encode(username+":"+password);
con.setRequestProperty("Authorization", "Basic "+encoded);

Related

Alternative of Basic Auth - Sonar Critical Vulnerability

I need to fetch the access token before making the actual call to the OAuth2-protected API.
As of now, I am doing it in the below fashion
String credential = clientId + ":" + clientSecret;
String encoding = Base64.getEncoder().encodeToString((credential).getBytes(‌"UTF‌​-8"​));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
Sonar says this is Non-Compliant RSPEC-2647, therefore I want to know what are the alternatives I can use, and how to fix this issue?
--EDIT
In the body, I was passing grant_type, username, and password.
I tried adding client_id and client_secret as well and it works.
Now I have one more question, is passing these credentials in the body more secure?
String body = "grant_type="+grantType+"&username="+username+"&password="+password+"&client_id="+clientId+"&client_secret="+clientSecret;
byte[] postData = body.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
conn.connect();

Java Oauth request_token flow example, without libraries

I have this piece of code:
String yourUrl = "https://api.discogs.com/oauth/request_token";
String currentSeconds = String.valueOf(System.currentTimeMillis() / 1000);
String urlString = yourUrl + "?oauth_consumer_key=BaeIqWMTmCxjeJjwmkJr&oauth_nonce=random_string_or_timestamp&oauth_timestamp="+ currentSeconds + "&oauth_callback=http://localhost:8080&oauth_signature=ZWglyBtJasnJBqVnzyduYJggCduKeYks;
System.out.println(urlString);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "test");
int statusCode = conn.getResponseCode();
but I have this error:
Status Code: 401
Invalid signature. Expected signature base string: ZWglyBtJasnJBqVnzyduYJggCduKeYks&
According to the discogs oauth flow you shouldn't send params as request params, but rather should send it combined into Authorization header and do something like this:
String yourUrl = "https://api.discogs.com/oauth/request_token";
String currentSeconds = String.valueOf(System.currentTimeMillis() / 1000);
URL url = new URL(yourUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "test");
conn.setRequestProperty("Authorization",
"OAuth oauth_consumer_key=\"BaeIqWMTmCxjeJjwmkJr\"," +
"oauth_nonce=\"" + System.currentTimeMillis() + "\"," +
"oauth_signature=\"ZWglyBtJasnJBqVnzyduYJggCduKeYks&\"," +
"oauth_signature_method=\"PLAINTEXT\"," +
"oauth_timestamp=\"" + currentSeconds + "\"," +
"oauth_callback=\"your_callback\""
);
int statusCode = conn.getResponseCode();

HttpUrlConnection POST gives 400 Bad Request. All input fields are correct

I am trying a POST API, which works with cURL command or POSTMan. However, sending the same call through HttpURLConnection doesn't work.
Tried URL encoding the request params too. Still no luck. It's probably something wrong with the POST usage for HttpURLConnection.
String url = "CORRECT_URL";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String urlParameters = "first_name=John&middle_name=Alfred&last_name=Smith&email=john.smith#gmail.com&phone=5555555555&zipcode=90401&dob=1970-01-22&ssn=543-43-4645&driver_license_number=F211165&driver_license_state=CA";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Basic AUTH_TOKEN=");
con.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty( "charset", "utf-8");
con.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
con.setUseCaches( false );
try {
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postData);
wr.flush();
wr.close();
}
catch(Exception e) {
System.out.println("Server returned error!");
con.getResponseMessage();
}
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
System.out.println("Response : " + con.getResponseMessage());
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
...
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postData);
is overkill.
PrintWriter out = new PrintWriter(
new OutputStreamWriter(con.getOutputStream(), "UTF-8")
);
out.print(urlParameters);
should do the job.

curl response is different from the responce of java.net.URL

curl -v https://whatwg.org/html
header is:
HTTP/1.1 301 Moved Permanently
Location: https://html.spec.whatwg.org/multipage
however..
String link = "https://whatwg.org/html";
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int status = conn.getResponseCode();
System.out.println("Response Code ... " + status);
Response Code ... 200
The first and second results are different, what I am doing wrong and how should I receive 301 ?

convert curl request into URLConnection

I have this cURL request:
curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth <access_token>' \
-X PUT https://api.twitch.tv/kraken/users/<bot_name>/follows/channels/<channel_name>
I need to turn it into a Java URLConnection request. This is what I have so far:
String url = "https://api.twitch.tv/kraken/?oauth_token=" + bot.botOAuth.substring("oauth:".length());
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write("https://api.twitch.tv/kraken/users/" + bot.botName + "/follows/channels/" + gamrCorpsTextField.getText());
out.close();
new InputStreamReader(conn.getInputStream());
Any help will be appreciated!
The URL you are preparing to open in this code:
String url = "https://api.twitch.tv/kraken/?oauth_token=" + bot.botOAuth.substring("oauth:".length());
does not match your curl request URL:
https://api.twitch.tv/kraken/users/<bot_name>/follows/channels/<channel_name>
You appear to want something more like this:
URL requestUrl = new URL("https://api.twitch.tv/kraken/users/" + bot.botName
+ "/follows/channels/" + gamrCorpsTextField.getText());
HttpURLConnection connection = (HttpUrlConnection) requestUrl.openConnection();
connection.setRequestMethod("PUT");
connection.setRequestProperty("Accept", "application/vnd.twitchtv.v3+json");
connection.setRequestProperty("Authorization", "OAuth <access_token>");
connection.setDoInput(true);
connection.setDoOutput(false);
That sets up a "URLConnection request" equivalent to the one the curl command will issue, as requested. From there you get the response code, read response headers and body, and so forth via the connection object.

Categories

Resources