How to generate secure tokens dynamically

Asked

Viewed 3,851 times

7

Various applications use token authentication to maintain secure network communication. However, using dynamically generated tokens, the probability of breakage decreases greatly. So there is the question: How to generate dynamic tokens safely? What parameters to use or not to use? Are there good practices? Which ones?

1 answer

8


There is the pattern JSON Web Token (JWT) - RFC 7519 - defining a compact and independent mode for transmitting information securely between two parties in JSON format.

These data can be checked for authenticity because they are digitally signed. You can sign using a password (with the HMAC algorithm) or a public/private key pair using RSA.

Structure

Example of JWT token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEzODY4OTkxMzEsImlzcyI6ImppcmE6MTU0ODk1OTUiLCJxc2giOiI4MDYzZmY0Y2ExZTQxZGY3YmM5MGM4YWI2ZDBmNjIwN2Q0OTFjZjZkYWQ3YzY2ZWE3OTdiNDYxNGI3MTkyMmU5IiwiaWF0IjoxMzg2ODk4OTUxfQ.uKqU9dTB6gKwG6jQCuXYAiMNdfNRw98Hw_IWuA5Ma

Are three parts separated by ., coded by Base64 individually:

<base64-encoded header>.<base64-encoded claims>.<base64-encoded assinatura>

It is important to note that JWT does not encrypt payload, it just signs it. Therefore, you should not send confidential information by JWT. Only information to be verified/entrusted.

How it works?

Soon after successfully logging in, the server returns the generated JWT token to the client, which should send it to all subsequent requests in the header, as follows:

Authorization: Bearer <token>

The server receives, validates the token and uses the information from it to define whether the user can access the application or the protected routes. Thus, this authentication mechanism is characterized as stateless, being a great option to scale the application on multiple servers.

Which parameter to use?

This depends on each application. However, a practice quite common is to use only the user login and their ROLES as a basis for token generation. Thus, it is possible to determine through the token itself whether the user can access such route without even accessing the database.

Token generation

A good practice here is the use of expiration time and ROLES (Authority).

String secretKey = 35725c901c45f1c13f9e3fe8421a15dd26130118; // Chave privada de exemplo
String token = Jwts.builder()
                .setSubject(authentication.getName())
                .claim("auth", authentication.getAuthority())
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .setExpiration(validity)
                .compact();

Token validation

public boolean validateToken(String authToken) {
    try {
        Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
        return true;
    } catch (SignatureException e) {
        return false;
    }
}

Reading of token data

    Claims claims = Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody();

From the object Claims can get the saved ROLE with claims.get("auth").toString().

Languages

While adding examples in Java, JWT is available in most programming languages: . NET, Python, Node.js, Java, PHP, Ruby, Go, Javascript, and Haskell.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.