How to create a authentication token using Java
To create a hard to guess token in Java use java.security.SecureRandom
E.g.
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
String token = bytes.toString();
Rather than including the user name in the token it would be better to cache a user:token map in memory or in a database.
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.