OAuth 2.0 Authorization

The "Bearer" OAuth Access Token is required to authenticate. Here is an example of how to create that token (in Java 6 or later).

• First define a token object similar to this:

      
public class Token implements java.io.Externalizable {

    private static final long serialVersionUID = 48346345L;

    // password of the user you are trying to authenticate,
    // omit for a new user
    private String password;

    // current timestamp (UTC),
    // token becomes invalid within one minute
    private long timestamp;

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public void writeExternal(
            java.io.ObjectOutput out) throws java.io.IOException {
        out.writeObject(password);
        out.writeLong(timestamp);
    }

    @Override
    public void readExternal(java.io.ObjectInput in)
            throws java.io.IOException, ClassNotFoundException {
        password = (String) in.readObject();
        timestamp = in.readLong();
    }
}
    

• Then read this public key as byte array.

• Then, with this token object and public key, you are ready to create a token String:


    String encrypt(Token token, byte[] publicKey) throws Exception {
        String algorithm = "RSA";
        javax.crypto.Cipher cipher
                = javax.crypto.Cipher.getInstance(algorithm);

        java.security.spec.X509EncodedKeySpec keySpec
                = new java.security.spec.X509EncodedKeySpec(publicKey);

        cipher.init(javax.crypto.Cipher.ENCRYPT_MODE,
                java.security.KeyFactory.getInstance(
                        algorithm).generatePublic(keySpec));

        java.io.ByteArrayOutputStream tokenByteStream
                = new java.io.ByteArrayOutputStream();

        java.io.ObjectOutputStream tokenObjectStream
                = new java.io.ObjectOutputStream(tokenByteStream);
        tokenObjectStream.writeObject(token);
        tokenObjectStream.close();

        java.io.ByteArrayOutputStream encryptedTokenStream
                = new java.io.ByteArrayOutputStream();
        javax.crypto.CipherOutputStream cipherOutStream
                = new javax.crypto.CipherOutputStream(
                        encryptedTokenStream, cipher);
        cipherOutStream.write(tokenByteStream.toByteArray());
        cipherOutStream.close();

        return javax.xml.bind.DatatypeConverter
                .printBase64Binary(encryptedTokenStream.toByteArray());
    }
    

The output of the above function should be used in Authorization header as "Bearer ...", e.g. "Bearer bN9B2rMAtWG7xC/pYc="