Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a authentication token using Java

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 standard way to create these tokens? maybe it exists in one of the API`s?

like image 992
Spring Avatar asked Dec 21 '12 15:12

Spring


People also ask

What is JWT token in Java?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.


3 Answers

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.

like image 129
Dmitriy Dumanskiy Avatar answered Oct 10 '22 04:10

Dmitriy Dumanskiy


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.  

like image 45
Daniel de Zwaan Avatar answered Oct 10 '22 03:10

Daniel de Zwaan


The scheme you are proposing effectively allows a client unlimited access to your service. After an initial login, the UID and 'userid' will be made available to the client, which can be simply combined with an always valid timestamp.

If you need a service with 'login' and a session token, then why not just use an HttpSession?

like image 44
ireddick Avatar answered Oct 10 '22 05:10

ireddick