How to create a authentication token using Java

Spring picture Spring · Dec 21, 2012 · Viewed 89.6k times · Source

On my Java EE6, REST service, I want to use authentication tokens for login from mobile devices, User will send their username, password and server will send back a token, which will be used to authorize the user on their further requests for a given time.

Can I simply create a token myself like this?(I guess I do not need to encrypt this since I will use HTTPS.)

String token = UUID.randomUUID().toString().toUpperCase() 
            + "|" + "userid" + "|"
            + cal.getTimeInMillis();

Or there is a more standart way to create my tokens? maybe it exists in one of API's

Answer

Dmitriy Dumanskiy picture Dmitriy Dumanskiy · Jun 17, 2019

For Java 8 and above the fastest and simplest solution would be:

private static final SecureRandom secureRandom = new SecureRandom(); //threadsafe
private static final Base64.Encoder base64Encoder = Base64.getUrlEncoder(); //threadsafe

public static String generateNewToken() {
    byte[] randomBytes = new byte[24];
    secureRandom.nextBytes(randomBytes);
    return base64Encoder.encodeToString(randomBytes);
}

Output example:

wrYl_zl_8dLXaZul7GcfpqmDqr7jEnli
7or_zct_ETxJnOa4ddaEzftNXbuvNSB-
CkZss7TdsTVHRHfqBMq_HqQUxBGCTgWj
8loHzi27gJTO1xTqTd9SkJGYP8rYlNQn

Above code will generate random string in base64 encoding with 32 chars. In Base64 encoding every char encodes 6 bits of the data. So for 24 bytes from the above example you get the 32 chars. You can change the length of the output string by changing the number of random bytes. This solution is more secure than UUID (that uses only 16 random bytes) and generates string that safely could be used in HTTP urls.