Created OAuth bearer token generated with jwt token is invalid for REST calls - rest

I am new to DocuSign and the REST-API. I created a developer account and added a new "Apps and Keys" entry for my application (Authentication = Implicit Grant and RSA key pairs). The keys were stored in two seperate files.
I activated the Keys using the following URL:
http://account-d.docusign.com/oauth/auth?response_type=code&scope=signature%20impersonation&client_id=_the_integration_key&redirect_uri=http://localhost
I am trying to write a JAVA application without spring security framework (or any other framework).
To read the key files I used and modified (a little bit) the functions from the DocuSign examples.
private static RSAPublicKey readPublicKeyFromFile(String filepath, String algorithm) throws IOException {
File pemFile = new File(filepath);
if (!pemFile.isFile() || !pemFile.exists()) {
throw new FileNotFoundException(String.format("The file '%s' doesn't exist.", pemFile.getAbsolutePath()));
}
PemReader reader = new PemReader(new FileReader(pemFile));
try {
PemObject pemObject = reader.readPemObject();
byte[] bytes = pemObject.getContent();
RSAPublicKey publicKey = null;
try {
KeyFactory kf = KeyFactory.getInstance(algorithm);
EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
publicKey = (RSAPublicKey) kf.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the public key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the public key");
}
return publicKey;
} finally {
reader.close();
}
}
private static RSAPrivateKey readPrivateKeyFromFile(String filepath, String algorithm) throws IOException {
File pemFile = new File(filepath);
if (!pemFile.isFile() || !pemFile.exists()) {
throw new FileNotFoundException(String.format("The file '%s' doesn't exist.", pemFile.getAbsolutePath()));
}
PemReader reader = new PemReader(new FileReader(pemFile));
try {
PemObject pemObject = reader.readPemObject();
byte[] bytes = pemObject.getContent();
RSAPrivateKey privateKey = null;
try {
Security.addProvider(new BouncyCastleProvider());
KeyFactory kf = KeyFactory.getInstance(algorithm, "BC");
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
privateKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the private key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the private key");
} catch (NoSuchProviderException e) {
System.out.println("Could not reconstruct the private key, invalid provider.");
}
return privateKey;
} finally {
reader.close();
}
}
private static RSAPrivateKey readPrivateKeyFromByteArray(byte[] privateKeyBytes, String algorithm) throws IOException {
PemReader reader = new PemReader(new StringReader(new String(privateKeyBytes)));
try {
PemObject pemObject = reader.readPemObject();
byte[] bytes = pemObject.getContent();
RSAPrivateKey privateKey = null;
try {
Security.addProvider(new BouncyCastleProvider());
KeyFactory kf = KeyFactory.getInstance(algorithm, "BC");
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
privateKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the private key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the private key");
} catch (NoSuchProviderException e) {
System.out.println("Could not reconstruct the private key, invalid provider.");
}
return privateKey;
} finally {
reader.close();
}
}
To get the JWT token I used the following function:
public static String generateJWTAssertion(String publicKeyFilename, String privateKeyFilename, String oAuthBasePath, String clientId, String userId, long expiresIn) throws JWTCreationException, IOException {
String token = null;
if (expiresIn <= 0L) {
throw new IllegalArgumentException("expiresIn should be a non-negative value");
}
if (publicKeyFilename == null || "".equals(publicKeyFilename) || privateKeyFilename == null || "".equals(privateKeyFilename) || oAuthBasePath == null || "".equals(oAuthBasePath) || clientId == null || "".equals(clientId)) {
throw new IllegalArgumentException("One of the arguments is null or empty");
}
try {
RSAPublicKey publicKey = readPublicKeyFromFile(publicKeyFilename, "RSA");
RSAPrivateKey privateKey = readPrivateKeyFromFile(privateKeyFilename, "RSA");
Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
long now = System.currentTimeMillis();
token = JWT.create()
.withIssuer(clientId) // integration key
.withSubject(userId) // null
.withAudience(oAuthBasePath) // account-d.docusign.com
.withNotBefore(new Date(now))
.withExpiresAt(new Date(now + expiresIn * 1000))
.withClaim("scope", "signature impersonation")
.sign(algorithm);
} catch (JWTCreationException e){
throw e;
} catch (IOException e) {
throw e;
}
return token;
}
I checked the generated token on https://jwt.io/ and the content looks fine.
To get the bearer token I use the following code:
public Boolean getBearer(long expiresIn) throws IOException {
String jwtToken = JwtUtils.generateJWTAssertion(
RESOURCES_DIR + "public.key",
RESOURCES_DIR + "private.key",
oAuthBasePath,
integrationKey,
null,
expiresIn
);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")
.addFormDataPart("assertion", jwtToken)
.build();
Request request = new Request.Builder()
.url("https://" + oAuthBasePath + "/oauth/token") // https://account-d.docusign.com/oauth/token
.method("POST", body)
.build();
Response response = client.newCall(request).execute();
int responseCode = response.code();
String responseText = response.body().string();
Gson gson = new Gson();
OAuthResponse oAuthResponse = gson.fromJson(responseText, OAuthResponse.class);
if (responseCode >= 200 && responseCode <= 299) {
bearerToken = oAuthResponse.getAccess_token();
return true;
}
System.out.println("Errorcode: " + oAuthResponse.getError());
System.out.println("Error: " + oAuthResponse.getError_description());
return false;
}
I get the bearer token and want to use it for the following REST calls.
For example:
public void getUsers () throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url(getRestBaseUrl() +"/users") // https://demo.docusign.net/restapi/v2.1/accounts/_API_account_id/users
.method("GET", null)
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Bearer " + bearerToken)
.build();
Response response = client.newCall(request).execute();
String responseText = response.body().string();
System.out.println(responseText);
}
But instead of a JSON structure with the users of my developer account, I got the following response:
{"errorCode":"AUTHORIZATION_INVALID_TOKEN","message":"The access token provided is expired, revoked or malformed. Authentication for System Application failed."}
When I use the API explorer and the bearer token, I can use it for authentication (it is shown as valid), but the REST call for "users" get the same error response.
So I used the API explorer for login and the REST call works.
I used the bearer token from the API explorer and used it (as fixed entered string value) as bearer token. And the JAVA REST calls works.
So, there must be an error in generating / requesting the JWT token or bearer token.
Any idea what's wrong?
Regards,
Rainer

I found the reason.
The API username was missing.
String jwtToken = JwtUtils.generateJWTAssertion(
RESOURCES_DIR + "public.key",
RESOURCES_DIR + "private.key",
oAuthBasePath,
integrationKey,
"_here_the_API_username",
expiresIn
);
After adding the username I could use the API.

Related

Server returned HTTP response code: 401 for URL: https://accounts.google.com/o/oauth2/token during generating access token

I am using the admin sdk API to retrieve all G Suite users. We require an access token for this. AWS is used to host our website. I've tried a few different codes to generate access token, but they always return error
"Server returned HTTP response code: 401 for URL: https://accounts.google.com/o/oauth2/token."
I have no idea why this error is occurring. My code is running smoothly, generating access token and retrieving every user domain wise in a local environment. Any help in why actually I am getting this error. have i missed something? any help in it.
This is my code.
private String getAccessToken()
{
String accessToken="";
try
{
Map<String,Object> params = new LinkedHashMap<>();
params.put("grant_type","refresh_token");
params.put("client_id",client_id);
params.put("client_secret",client_secret);
params.put("refresh_token",refresh_token);
StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet())
{
if(postData.length() != 0)
{
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(),"UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()),"UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
URL url = new URL("https://accounts.google.com/o/oauth2/token");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
accessToken = json.getString("access_token");
return accessToken;
}
catch (Exception ex)
{
ex.printStackTrace();
}
return accessToken;
}

Unity occurs a 400 Bad Request when calling a HTTP-Post on an SAP Rest API

I want to call a REST API with an Unity-Script but it occurs me the Error 400 Bad Request. It is maybe because of the http-header. May you can help me. SAP offers a Code Snippet in JAVA which I want to show you first:
DataOutputStream dataOut = null;
BufferedReader in =null;
try {
//API endpoint for API sandbox
String url = "https://sandbox.api.sap.com/mlfs/api/v2/image/scene-text-
recognition";
//Available API Endpoints
//https://mlfproduction-scene-text-
recognition.cfapps.eu10.hana.ondemand.com/api/v2/image
//https://mlfproduction-scene-text-
recognition.cfapps.us10.hana.ondemand.com/api/v2/image
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection)
urlObj.openConnection();
//setting request method
connection.setRequestMethod("POST");
//adding headers
connection.setRequestProperty("content-type","multipart/form-data;
boundary=---011000010111000001101001");
//API Key for API Sandbox
connection.setRequestProperty("APIKey","----api-Key---");
//Available Security Schemes for productive API Endpoints
//OAuth 2.0
connection.setDoInput(true);
//sending POST request
connection.setDoOutput(true);
dataOut = new DataOutputStream(connection.getOutputStream());
dataOut.writeBytes("-----011000010111000001101001\r\nContent-
Disposition: form-data; name=\"files\"; filename=\"<file_name>\"\r\nContent-Type: <file_type>\r\n\r\n<file_contents>\r\n-----011000010111000001101001--");
dataOut.flush();
int responseCode = connection.getResponseCode();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
//printing response
System.out.println(response.toString());
} catch (Exception e) {
//do something with exception
e.printStackTrace();
} finally {
try {
if(dataOut != null) {
dataOut.close();
}
if(in != null) {
in.close();
}
} catch (IOException e) {
//do something with exception
e.printStackTrace();
}
}
My UnityCode looks something like this:
public void ExecutePost()
{
Debug.Log("execute started");
byte[] img =
File.ReadAllBytes(#"C:\Users\InnovationLab\Documents\ECENTA\ECENTA
FSE\Bild1.jpg");
string url = "https://sandbox.api.sap.com/mlfs/api/v2/image/scene-
text-recognition";
coroutine = Post(url, img);
StartCoroutine(coroutine);
}
public IEnumerator Post(string url,byte[] image)
{
WWWForm form = new WWWForm();
form.AddBinaryData("imageField", image, "HoloImg");
var headers = new Dictionary<string, string> {
{"content-type", "multipart/form-data; boundary=---011000010111000001101001" },
{"APIKey", "---here I implemented the key---" }
};
WWW www = new WWW(url, image, headers);
yield return www;
if (www.error != null && www.error != "")
{ // on error, show information and return
Debug.Log("Network Error occured: " + www.error);
yield break;
}
while (!www.isDone)
{
Debug.Log(www.text);
}
}
}
So my question is, how to change the unity code so that it works?
I fixed it by using MultipartFormSections. The problem was that the api expected form-data not a binary Array.
public IEnumerator Upload(string url, byte[] img)
{
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
MultipartFormFileSection myFormFile = new MultipartFormFileSection("files", img,
"Bild1.jpg", "multipart/form-data");
formData.Add(myFormFile);
Debug.Log(formData.ToString());
UnityWebRequest www = UnityWebRequest.Post(url, formData);
www.SetRequestHeader("APIKey", "<api-key>");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
throw new Exception(www.downloadHandler.text ?? www.error);
}
else
{
Debug.Log("Done!!!!!");
}
Debug.Log(www.downloadHandler.text);
var ResultObject = JsonUtility.FromJson<TextPrediction>(www.downloadHandler.text);
foreach (var result in ResultObject.texts)
{
}
}

Unable to access REST API’s in Camunda

In our project , we are trying to use camunda BPMN. using camunda standalone distro and deployed and running in Tomcat.
login as a admin user and able to access cockpit and task lists.But,when we try access the APIs using a Java client . we are getting an unauthorized (401) error. Though we are sending JSESSIONID as a “Cookie”
Tried both DefaultHttpClient and HttpURLConnection - It didn’t work out
Note : JSESSIONID is retrieved by calling the login api with admin username and password.
Help me to solve the issue
Attached below is the java client code
public static void main(String[] args) {
CamundaBMPNClient bpmnClient = new CamundaBMPNClient();
Map<Integer, String> cookieHeader = bpmnClient.getCookieHeader();
bpmnClient.getListofTasks(cookieHeader);
}
public Map<Integer, String> getCookieHeader() {
String jSessionID = null;
Map<Integer, String> headerValues = new HashMap<Integer, String>();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/"
+ "api/admin/auth/user/default/login/cockpit");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Accept", "application/json");
String jsonString = new Gson()
.toJson("username=admin&password=admin#123");
StringEntity params;
try {
params = new StringEntity(jsonString);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
Header[] cookieheader = response.getHeaders("Set-Cookie");
for (Header s : cookieheader) {
// Do your stuff here
System.out.println(s.getValue());
String[] str = s.getValue().split(";");
int i = 1;
for (String s1 : str) {
headerValues.put(i, s1.trim());
i++;
}
}
System.out.println("jSessionID::" + jSessionID);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return headerValues;
}
public void getListofTasks(Map<Integer, String> cookieHeader) {
int id = 0;
// DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/api/engine/engine/default/task");
request.addHeader("Content-type", "application/json");
String[] arrJSessionID = cookieHeader.get(1).split("=");
System.out.println("" + arrJSessionID[1]);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID=",
arrJSessionID[1]);
cookie.setDomain("http://localhost:8090");
cookie.setPath("/camunda-webapp-tomcat-standalone-7.2.0/");
// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookieStore.addCookie(cookie);
// httpclient.setCookieStore(cookieStore);
HttpClient httpclient = HttpClientBuilder.create()
.setDefaultCookieStore(cookieStore).build();
String jsonString = new Gson().toJson("{}");
StringEntity jsonStr;
try {
jsonStr = new StringEntity(jsonString);
request.setEntity(jsonStr);
HttpResponse response = httpclient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
Header[] header = response.getHeaders("Set-Cookie");
for (Header h : header) {
System.out.println(h.getValue());
}
System.out.println("statusCode::" + statusCode);
} catch (Exception e) {
e.printStackTrace();
}
}

Integration of Market place with Integration bus in websphere

We have a requirement as below
Integration System needs to call our service
Our service needs to call FlipKart service appending the token in the request
Get the response back to Integration system
The above should work seamlessly for both GET and PUT requests.
I had developed a REST-project in eclipse and was able to get the GET and PUT response back to Integration.
However have few problems
In Get Requests, we are explicitly setting the headers and produces annotation to appication/json. How do we set it for all kind of requests?
In Post Response, we do not get the entire response and we are not able to set the application type in the response (Not sure how!)
All these requests are failing if the application type is pdf, img etc.
Can someone please help on the same?
Code implemented so far:
#GET
#Path("{pathvalue : (.+)?}")
#Produces("{application/json;application/octet-stream}")
public String getFlipKartResponse(#Context UriInfo uriInfo, #PathParam("pathvalue") String pathValue, #Context HttpServletRequest request) throws ClassNotFoundException,IOException {
String methodName = "getFlipKartResponse";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
//if(null == flipkartUrl || flipkartUrl.isEmpty())
flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
String queryParam = new String();
Iterator<String> iterator = queryParams.keySet().iterator();
while (iterator.hasNext()) {
String parameter = iterator.next();
queryParam = queryParam.concat(parameter + ServiceConstants.EQUALS + queryParams.getFirst(parameter) + ServiceConstants.AMPERSAND);
}
String modifiedflipkartUrl = flipkartUrl.concat(pathValue).concat(ServiceConstants.QUESTION).concat(queryParam);
if (modifiedflipkartUrl.endsWith(ServiceConstants.QUESTION) || modifiedflipkartUrl.endsWith(ServiceConstants.AMPERSAND)) {
modifiedflipkartUrl = modifiedflipkartUrl.substring(0, modifiedflipkartUrl.length()-1);
}
LOGGER.log(Level.INFO, "Flipkart URL framed : "+ modifiedflipkartUrl);
url = new URL(modifiedflipkartUrl);
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, request.getMethod());
return handleInvalidToken(connection.getResponseCode(), request);
}
private String handleInvalidToken(int responseCode, HttpServletRequest request){
try {
if (connection.getResponseCode() == 401) {
LOGGER.log(Level.INFO, "ResponseCode " + connection.getResponseCode());
connection.disconnect();
regenerateAccessToken();
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, request.getMethod());
inputLine = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else if (connection.getResponseCode() == 200) {
inputLine = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
inputLine = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
String responseInputLine;
String responseMessage = "";
while (null != (responseInputLine = inputLine.readLine())) {
responseMessage = responseMessage + responseInputLine;
}
inputLine.close();
connection.disconnect();
return responseMessage;
} catch (Exception e) {
LOGGER.log(Level.SEVERE,"Exception occured while calling service.Please try again after sometime : ", e);
return this.handleErrorResponse("Exception occured while calling service.Please try again after sometime.");
}
}
private void regenerateAccessToken() throws ClassNotFoundException, IOException, SQLException{
TokenGenerator tokenGenerator = new TokenGenerator();
accessToken= tokenGenerator.getAccessToken();
}
#POST
#Path("{pathvalue : (.+)?}")
#Produces({"application/json;application/octet-stream"})
public String getFlipKartPostResponse(#Context UriInfo uriInfo, #PathParam("pathvalue") String pathValue,#Context HttpServletRequest requestBody) throws ClassNotFoundException,IOException, SQLException {
String methodName = "getFlipKartPostResponse";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
//if(null == flipkartUrl || flipkartUrl.isEmpty())
flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
String modifiedflipkartUrl = flipkartUrl + pathValue;
url = new URL(modifiedflipkartUrl);
LOGGER.log(Level.INFO, "Flipkart URL framed : "+ flipkartUrl);
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, requestBody.getMethod());
InputStream requestInputStream = requestBody.getInputStream();
String reqBody = getStringFromInputStream(requestBody.getInputStream());
OutputStream outputStream = connection.getOutputStream();
outputStream.write(reqBody.getBytes());
outputStream.flush();
if(connection.getResponseCode() == 401) {
connection.disconnect();
regenerateAccessToken();
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, requestBody.getMethod());
outputStream = connection.getOutputStream();
outputStream.write(reqBody.getBytes());
outputStream.flush();
}
String output = getStringFromInputStream (connection.getInputStream());
connection.disconnect();
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
return output;
}
private static String getStringFromInputStream(InputStream is) {
String methodName = "getStringFromInputStream";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
return sb.toString();
}
/**
* Method to generate the access token
* #return String - Access token
* #throws IOException
*/
private String getAccessToken() throws IOException {
if (null != accessToken) {
return accessToken;
} else {
url = getClass().getResource(ServiceConstants.ACCESS_TOKEN_CONFIG_PATH);
file = new File(url.getPath());
reader = new BufferedReader (new InputStreamReader (new FileInputStream (file), ServiceConstants.UTF_ENCODING));
accessToken = reader.readLine();
reader.close();
return accessToken;
}
}
/**
* Method to construct error response for exception scenario
* #param errorMessage
* #return
*/
private String handleErrorResponse(String errorMessage) {
String methodName = "handleErrorResponse";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
JSONObject errorResponse = new JSONObject();
JSONArray errorMsg = new JSONArray();
errorResponse.put(ServiceConstants.STATUS, ServiceConstants.STATUS_FAILED);
errorResponse.put(ServiceConstants.ERROR_MESSAGE, errorMessage);
errorMsg.add(errorResponse);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
return errorResponse.toString();
}
/**
* Method to form the connection object
* #param url
* #param connection
* #param requestType
* #throws IOException
*/
private void setHeadersInConnectionObject(URL url, HttpsURLConnection connection, String requestType) throws IOException {
String methodName = "setHeadersInConnectionObject";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
if (null == accessToken) {
getAccessToken();
}
connection.setRequestMethod(requestType);
connection.setRequestProperty(ServiceConstants.AUTHORIZATION, ServiceConstants.BEARER + accessToken);
connection.setDoOutput(true);
if (requestType.equals(ServiceConstants.REQUEST_TYPE_GET)) {
connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.ACCEPT_ALL);
//connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);
}
if (requestType.equals(ServiceConstants.REQUEST_TYPE_POST)) {
connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);
connection.setRequestProperty(ServiceConstants.CONTENT_TYPE_HEADER, ServiceConstants.APPLICATION_JSON);
//connection.setDoInput(true);
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
}

Jetty Java websocket client doesn't connect to server

I am using Java Jetty client written [websocket-client 9.3.8.RC0]. Websocket server is little wierd in our case.
It accepting request in format.
wss://192.168.122.1:8443/status?-xsrf-=tokenValue
Token Value is received in first Login POST request in which i get Token Value & Cookie header. Cookie is added as a header whereas token is given as a param.
Now question is : -
When i run below code it just call awaitclose() function in starting. But there is not other function called i.e. Onconnected or even Onclose.
Any help would be appreciated to debug it further, to see any logs or environment issue to see why Socket is not connected.
Trying to figure out following points to debug.
1. To check if client certificates are causing issue.
Tried with my python code wspy.py it work seemlessly fine.
Code is
public final class websocketxxx {
WebSocketClient client=null;
public websocketxxx (){
}
public void run(String host,String cookieVal, String xsrfVal, String resource) throws IOException {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
WebSocketClient client = new WebSocketClient(sslContextFactory);
MyWebSocket socket = new MyWebSocket();
try {
client.start();
ClientUpgradeRequest request = new ClientUpgradeRequest();
// Add the authentication and protocol to the request header
// Crate wss URI from host and resource
resource = resource + xsrfVal;
URI destinationUri = new URI("wss://" + host + resource); // set URI
request.setHeader("cookie",cookieVal);
request.setHeader("Sec-WebSocket-Protocol", "ao-json");
//System.out.println("Request Headers print : " request.getHeaders())
System.out.println("Connecting to : " + destinationUri);
client.connect(socket, destinationUri, request);
socket.awaitClose(5000, TimeUnit.SECONDS);
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
client.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#WebSocket
public class MyWebSocket {
private final CountDownLatch closeLatch = new CountDownLatch(1);
#OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("WebSocket Opened in client side");
try {
System.out.println("Sending message: Hi server");
session.getRemote().sendString("Hi Server");
} catch (IOException e) {
e.printStackTrace();
}
}
#OnWebSocketMessage
public void onMessage(String message) {
System.out.println("Message from Server: " + message);
}
#OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("WebSocket Closed. Code:" + statusCode);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}
}
public Client getBypassCertVerificationClient() {
Client client1 = null;
try {
// Create a HostnameVerifier that overrides the verify method to accept all hosts
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String host, SSLSession sslSession) {
return true;
}
};
// Create a TrustManager
TrustManager[] trust_mgr = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String t) {
}
public void checkServerTrusted(X509Certificate[] certs, String t) {
}
}
};
// Create the SSL Context
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trust_mgr, new SecureRandom());
// Create the client with the new hostname verifier and SSL context
client1 = ClientBuilder.newBuilder()
.sslContext(sslContext)
.hostnameVerifier(hostnameVerifier)
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return client1;
}
public String[] simple_Login_POST_request(String host, String user, String password, String resource, String data) {
String resp = null;
String[] headers = new String[2];
try {
// Create a Client instance that supports self-signed SSL certificates
Client client = getBypassCertVerificationClient();
// Create a WebTarget instance with host and resource
WebTarget target = client.target("https://" + host).path(resource);
// Build HTTP request invocation
Invocation.Builder invocationBuilder = target.request();
// Encode the user/password and add it to the request header
invocationBuilder.header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
Form form = new Form();
form.param("userid", user);
form.param("password", password);
// Invoke POST request and get response as String
//post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
Response response = invocationBuilder.method("POST", Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
resp = (String) response.readEntity(String.class);
// Print input URL, input data, response code and response
System.out.println("URL: [POST] " + target.getUri().toString());
System.out.println("HTTP Status: " + response.getStatus());
System.out.println("HTTP Status: " + response.getHeaders());
headers[0] = response.getHeaderString("Set-Cookie");
//response.getStringHeaders()
headers[1] = response.getHeaderString("X-XSRF-TOKEN");
System.out.println("Response: \n" + resp);
response.close();
} catch (Exception e) {
e.printStackTrace();
}
return headers;
}
public static void main(String[] args) throws IOException {
String host = "";
String user = "";
String password = "";
String resource = "";
host ="192.168.122.1:8443";
user = "ADMIN";
password ="ADMIN";
websocketXXX wsNotification = new websocketxxx();
/////////////////////////////////////////////////////////////////
// Simple POST LOGIN Request
resource = "/api/login";
String headers[]= wsNotification.simple_Login_POST_request(host, user, password, resource, null);
////////////////////////////////////////////////////////////////
headers[0] = headers[0].substring(headers[0].lastIndexOf(",") + 1);
System.out.println("headers[0]: " + headers[0] + "\n");
String cookie = headers[0];
String XSRFToken = headers[1];
resource = "/status?-xsrf-=";
//wsNotification.simple_websocket_example(host, cookie, XSRFToken, resource);
wsNotification.run(host, cookie, XSRFToken, resource);
}
}
The implementation is mostly correct.
Setting raw Cookie and Sec-WebSocket-* headers is forbidden, you have to use the API.
Cookie handling from:
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("cookie",cookieVal);
To ClientUpgradeRequest.setCookies() :
ClientUpgradeRequest request = new ClientUpgradeRequest();
List<HttpCookie> cookies = new ArrayList<>();
cookies.add(new HttpCookie(...));
request.setCookies(cookies);
Note: if you are using the java CookieStore, then you can pass the CookieStore instance to the client as well, using the setCookiesFrom(CookieStore) method.
Sub Protocol Selection from:
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("Sec-WebSocket-Protocol", "ao-json");
To ClientUpgradeRequest.setSubProtocols():
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setSubProtocols("ao-json");