Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

APIs · Lesson 8

Authentication and Authorization (JWT)

Authentication and Authorization

Authentication identifies a caller, while authorization decides what that caller may do. JSON Web Tokens (JWTs) carry signed claims that a service can verify without storing every request token in a session database. A valid token is not automatically permission to perform every action.

Representing Verified Claims

After signature and expiration checks, an API can map selected claims into a principal. Never treat unverified decoded token data as trustworthy.

import java.time.Instant;

public record AuthenticatedUser(String userId, String role, Instant expiresAt) {
    public boolean isExpired(Instant currentTime) {
        return !currentTime.isBefore(expiresAt);
    }

    public static void main(String[] arguments) {
        AuthenticatedUser user = new AuthenticatedUser(
                "learner-42", "learner", Instant.now().plusSeconds(900));
        System.out.println("Expired: " + user.isExpired(Instant.now()));
    }
}

Security Comparison

ConcernAuthenticationAuthorization
QuestionWho is calling?What may they do?
JWT dataSubject and expiryRoles or scopes
Failure401 Unauthorized403 Forbidden
CheckSignature and lifetimeResource policy

Common Mistake and Practices

Common Mistake: Trusting a JWT because it can be decoded. Decoding is not verification; the signature, issuer, audience, and expiration must be checked with a trusted key and policy.

  • Use short token lifetimes.
  • Validate issuer, audience, signature, and expiry.
  • Keep claims minimal.
  • Enforce authorization at the resource boundary.
  • Rotate signing keys with a planned strategy.

Real-World Use Case

A learner token allows reading course lessons but cannot publish content. An instructor token passes both authentication and an authorization policy for lesson management.

Quiz Check

Quick Knowledge Test

Loading quiz questions...