How to Generate Secure Tokens Dynamically

5

Misc applications use token authentication to securely communicate on the network. However, using dynamically generated tokens, the likelihood of it breaking significantly decreases. So here's the question: How to dynamically generate dynamic tokens? Which parameters to use or not to use? Are there good practices? Which ones?

    
asked by anonymous 22.02.2017 / 13:15

1 answer

6

There is the JSON Web Token (JWT) - RFC 7519 - which defines a compact and independent way to reliably transmit information between two parts in the JSON format.

This data can be checked for authenticity because it is digitally signed. It is possible to sign using a password (with the HMAC algorithm) or a public / private key pair using RSA.

Structure

JWT token example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEzODY4OTkxMzEsImlzcyI6ImppcmE6MTU0ODk1OTUiLCJxc2giOiI4MDYzZmY0Y2ExZTQxZGY3YmM5MGM4YWI2ZDBmNjIwN2Q0OTFjZjZkYWQ3YzY2ZWE3OTdiNDYxNGI3MTkyMmU5IiwiaWF0IjoxMzg2ODk4OTUxfQ.uKqU9dTB6gKwG6jQCuXYAiMNdfNRw98Hw_IWuA5Ma

There are three parts separated by . , base64 encoded individually:

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

It's important to note that JWT does not encrypt the payload, it just signs it. Therefore, confidential information should not be sent by JWT. Only information that should be verified / trusted.

How does it work?

Shortly after successfully logging in, the server returns the generated JWT token for the client, which must send it on 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 several servers.

Which parameter to use?

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

Token Generation

A good practice here is to use expiration time and ROLES ).

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 token data

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

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

Languages

In addition to adding Java examples, JWT is available in most programming languages: .NET, Python, Node.js, Java, PHP, Ruby, Go, JavaScript, and Haskell.

    
03.03.2017 / 17:55