Tag Archives: java

How to generate X-WSSE Token using Java

Learn how to generate X-WSSE Token and how to authorize requests using X-WSSE header authentication.

If you’re not familiar with X-WSSE Token Authentication and why you should use it, go ahead and read this article that contains the basics of this type of authentication.

In this article I’ll describe how to generate a X-WSSE Token using Java.

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;
import javax.xml.bind.DatatypeConverter;
 
public class xwsse {
 
    final protected static char[] hexArray = "0123456789abcdef".toCharArray();
 
    public static void main(String[] args) {
        String xwsse = getWsseHeader("CLIENT_ID", "CLIENT_SECRET");
        System.out.println(xwsse);
    }
 
    private static String getWsseHeader(String username, String secret) {
        String nonce = getNonce();
        String created = getUTCTimestamp();
        String digest = getPasswordDigest(nonce, created, secret);
 
        return String.format("UsernameToken Username=\"%s\", PasswordDigest=\"%s\", " + "Nonce=\"%s\", Created=\"%s\"", username, digest, nonce, created);
    }
 
    private static String getUTCTimestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        return sdf.format(new Date());
    }
 
    private static String getNonce() {
        byte[] nonceBytes = new byte[16];
        new Random().nextBytes(nonceBytes);
        return bytesToHex(nonceBytes);
    }
 
    private static String getPasswordDigest(String nonce, String created, String secret) {
        String digest = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.reset();
            String hashedString = String.format("%s%s%s", nonce, created, secret);
            messageDigest.update(hashedString.getBytes("UTF-8"));
            String sha256Sum = bytesToHex(messageDigest.digest());
            digest = DatatypeConverter.printBase64Binary(sha256Sum.getBytes("UTF-8"));
        } catch(NoSuchAlgorithmException ex) {
            System.out.println("No SHA-256 algorithm found");
        } catch(UnsupportedEncodingException ex) {
            System.out.println("Unable to use UTF-8 encoding");
        }
        return digest;
    }
 
    private static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length*2];
        for(int j=0; j<bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j*2] = hexArray[v >>> 4];
            hexChars[j*2+1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
 
}

That’s it. Check my other X-WSSE Articles and learn how to generate the token using other programming languages.

LibGDX send HTTP request

Check out Lines Galaxy Android game to view the results in action.

Most common ways to communicate between your mobile app to your backend servers are HTTP Requests and Websockets.

In this article I’ll describe how you can create, send and process a HTTP Request to backend servers from your LibGDX application. In this example I will demonstrate how to send a basic POST request.

First step is to prepare the request payload:

Map<String, String> parameters = new HashMap<String, String>();

parameters.put("token", "<TOKEN>");
parameters.put("some_value", 1234);

final Json json = new Json();
json.setTypeName(null);
json.setOutputType(JsonWriter.OutputType.json);
json.setUsePrototypes(false);
String requestJson = json.toJson(parameters);

Second step is to create an instance of the HTTP Agent:

Net.HttpRequest request = new Net.HttpRequest(Net.HttpMethods.POST);
request.setUrl("http://example.com/");
request.setContent(requestJson);

And finally, after we set the desired server url and prepared the payload, we can send the request and attach the callback listeners

Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
    public void handleHttpResponse(Net.HttpResponse httpResponse) {
        HttpStatus status = httpResponse.getStatus();
        if(status.getStatusCode() == 200) {
            String responseJson = httpResponse.getResultAsString();
        } else {
            // error :(
        }
    }
    public void failed(Throwable t) {
        String error = t.getMessage();
    }
    public void cancelled() {
        // request aborded
    }
});

And that’s it. ou can just copy the above code and send LibGDX HTTP Request. You can dig further by reading the official docs: HttpResponseListener, HttpRequest.

Check out Lines Galaxy Android game to view the results in action.