Minecraft auth server returning 403? - java

So I'm trying to make a custom launcher for my custom Minecraft client but I need a session id to launch the game. This is the code I'm using to try and get a session ID:
package net.arachnamc;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Main {
public static void main(String[] args) throws IOException {
String AUTH_SERVER = "https://authserver.mojang.com/authenticate";
String json = String.format(
"{" +
"\"clientToken\":\"%s\"," +
"\"username\":\"%s\"," +
"\"password\":\"%s\"" +
"}",
UUID.randomUUID().toString(),
"Koolade446",
"MyPasswordCensored"
);
JSONObject jso = new JSONObject(json);
System.out.println(json);
URL url = new URL(AUTH_SERVER);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
os.write(json.getBytes(StandardCharsets.UTF_8));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
urlConnection.disconnect();
}
}
However, the server returns a 403 forbidden every time. I use a Microsoft account but I can't find any documentation on how to authenticate a Microsoft account so I assumed this was it. Any help is appreciated.

Related

How to fix javax.net.ssl.SSLHandShakeException accessing JIRA

I want to match issues in JIRA with other datasource.
I can use curl:
curl -u myname:mypassword
https://jira.myorganization.com/rest/api/latest/issue/TR-1234
This will return info about the issue, for exampel TR-1234, that I want to check some data for.
In java I want to do the same thing but I get javax.net.ssl.SSLHandShakeException
The program I try to run:
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("https://jira.myorganization.com/rest/api/latest/issue/TR-1234");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String userpass = "myusername:mypassword";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
System.out.println("Resp="+ con.getResponseCode()+" "+con.getResponseMessage());
String contentType = con.getHeaderField("Content-Type");
BufferedReader br = new BufferedReader(new InputStreamReader(
(con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can I somehow pass userid and password to the URL. The application is a tool and it would be ok to let the user input his name and password.

Download file using REST API

I am trying to call a REST API using Java client.
The Rest API https://api.gdc.cancer.gov/data has files data.
When I append file name to the URL (https://api.gdc.cancer.gov/data/556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c) I can download the given file from using browser.
here filename is 556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c.
can you please let me know,How can i achieve in this JAVA. The code I am using.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class DownloadFilesAPI {
public DownloadFilesAPI() {
super();
}
public static String sendPostRequest(String requestUrl) {
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("POST");
// connection.connect();
//Get the response status of the Rest API
// int responsecode = connection.getResponseCode();
//System.out.println("Response code is: " +responsecode);
//connection.getResponseMessage();
// System.out.println(connection.getResponseMessage());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
// System.out.println(connection.getResponseMessage());
// System.out.println( JsonPath.from(requestUrl));
OutputStreamWriter writer = new
OutputStreamWriter(connection.getOutputStream());
writer.write(requestUrl);
writer.close();
/* BufferedReader br = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close(); */
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
public static void main(String[] args) {
List<String> values = new ArrayList<>();
// values.add("556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c");
String requestUrl = "https://api.gdc.cancer.gov/data/556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c";
sendPostRequest(requestUrl);
}
private static String preparePayload(List<String> values) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append("\"" + value + "\",");
}
String Requiredvalue = sb.toString().substring(0, sb.toString().length() - 1);
return "{ \"ids\":[" + Requiredvalue + "] } } }";
}
}
You can't just output a String since you are trying to download a pdf. If you simply want to download the File there is an easier method adapted from this answer:
String requestUrl = "https://api.gdc.cancer.gov/data/556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c";
URL url = new URL(requestUrl);
InputStream in = url.openStream();
Files.copy(in, Paths.get("your_filename.pdf"), StandardCopyOption.REPLACE_EXISTING);
in.close();
System.out.println("finished!");
I have tested it for the URL you provided and got the pdf File without problems.

Requesting POST in Java using HttpUrlConnection is returning "propertyValue: false"

What i want?
I'm developing a Java application using the HttpUrlConnection library to send a POST and return the response from the site.
What is going on?
The code does not display syntax errors but when I execute it, it prints the message "propertyValue: false" even though I have not put any command to print anything.
What i need?
I need to know where this error is (propertyValue: false), because as I said, it does not show as if it had an error.
source:
import java.util.*;
import java.io.*;
import java.net.*;
public class Main
{
public static void main(String[] args) throws IOException
{
String target = "http://google.com";
String parameters = "contentOfPost";
URL url = new URL(target);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
try{
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", parameters + Integer.toString(parameters.getBytes().length));
conn.setRequestProperty("Content-Language", "pt-BR");
conn.setRequestProperty("Referer", "https://www.google.com");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line=null;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
} catch (IOException e){}
}
}
Out: propertyValue:false

Java and REST POST method - how to transform URL POST request to JSON Body POST Request?

I have class which works completely and sends POST request successfully toward the external system.
paramaters which are sent currently in the class are:
username:maxadmin
password:sm
DESCRIPTION: REST API test
Now I want to do copy paste of this class and transform it in that way so I could POST request using the JSON body but I am not sure how to do it.
I saw that I should probably have conn.setRequestProperty("Content-Type", "application/json"); instead of application/x-www-form-urlencoded
Can someone please transform my code in order to POST REQUEST using JSON body for parameters sending instead of URL?
This is my 'URL' working class (you will see username/password are in URL while parameters are send in array I have currently only one attribute DESCRIPTION which I am sending)
package com.getAsset;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.*;
public class GETAssetsPOST {
public static String httpPost(String urlStr, String[] paramName,
String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public static void main(String[] args) throws Exception {
String[] attr = new String[1];
String[] value = new String[1];
attr[0] = "DESCRIPTION";
value[0] = "REST API test";
String description = httpPost("http://192.168.150.18/maxrest/rest/os/mxasset/123?_lid=maxadmin&_lpwd=sm",attr,value);
System.out.println("\n"+description);
}
}
Thank you

I tried c2dm and i need server side

I have problem with : Google server said: 401, Unauthorized
I worked on the tomcat server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import com.liferay.portal.kernel.exception.SystemException;
import fr.intuitiv.dal.model.SmartPhone;
import fr.intuitiv.dal.service.SmartPhoneLocalServiceUtil;
public class URLCaller {
public static void callGoogle() throws IOException, SystemException {
URL url = new URL("https://android.clients.google.com/c2dm/send");
StringBuilder builder = new StringBuilder();
byte[] postData = null;
HttpsURLConnection conn = null;
String authorized_Key = getAuthorization();
// For each smartPhone
for(SmartPhone smartPhone : SmartPhoneLocalServiceUtil.getSmartPhones(0, SmartPhoneLocalServiceUtil.getSmartPhonesCount())) {
//Setup data
builder.append("registration_id=" + smartPhone.getRegistrationId());
builder.append("&collapse_key=").append("0");
builder.append("&data.payload=").append("The test work, drink a beer");
postData = builder.toString().getBytes("UTF-8");
//Calling server
conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new CustomizedHostnameVerifier());
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content_Lenght", Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authorized_Key);
// Issue the HTTP POST request
System.out.println("" + conn.getOutputStream());
OutputStream out = conn.getOutputStream();
out.write(postData);
out.flush();
System.out.println("Google server said: " + conn.getResponseCode() + ", " + conn.getResponseMessage());
out.close();
}
}
public static String getAuthorization() throws IOException {
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(user.config.EMAIL);
builder.append("&Passwd=").append(user.config.PASSWORD);
builder.append("&accountType=GOOGLE");
builder.append("&source=Google-C2DM-Example");
builder.append("&service=ac2dm");// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = conn.getOutputStream();
output.write(data);
output.flush();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String[] split = reader.readLine().split("=");
// Finally get the authentication token
String clientAuthToken = split[1];
// To something useful with it
output.close();
return clientAuthToken;
}
private static class CustomizedHostnameVerifier implements HostnameVerifier {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}
I get getAuthorization() i have a huge key.
I have my regId from the phone, i send it to the server when i get new one.
I have Android Market and i am log in.
I have registration to the google c2dm.
Are you sure, that this
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String[] split = reader.readLine().split("=");
// Finally get the authentication token
String clientAuthToken = split[1];
// To something useful with it
gives you the part after "Auth="?
Also you should trim the authToken because there might be a \n at the end that messes up the header:
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + StringUtils.trim(authorized_Key));

Categories