Junior — Middle
Is it possible to explain the authentication process using JSON Web Tokens and how to implement it?
sobes.tech AI
Answer from AI
JSON Web Token (JWT) is a compact, URL-safe way to transmit information between parties as a JSON object. The authentication process using JWT typically looks like this:
- The user sends their credentials (login and password) to the server.
- The server verifies the data, and if correct, creates a JWT containing the payload (e.g., user ID, roles, etc.) and signs it with a secret key.
- The JWT is returned to the client, which stores it (e.g., in localStorage or cookie).
- For subsequent requests, the client sends the JWT in the Authorization header (usually
Bearer <token>). - The server verifies the token's signature and, if valid, extracts user data from the token and grants access to resources.
Example of creating and verifying JWT in Java using the jjwt library:
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.Claims;
import java.util.Date;
public class JwtUtil {
private static final String SECRET_KEY = "mySecretKey";
public static String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
public static Claims validateToken(String token) {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
}
}
Thus, JWT allows secure transmission of user information without the need to store a session on the server.