Understanding Token Authentication, JWT, and OAuth with Java JJWT
This article explains token authentication, the structure and claims of JSON Web Tokens (JWT), their relationship with OAuth, and demonstrates how to create, sign, and verify JWTs in Java using the JJWT library, while also covering security best practices and useful tooling.
What Is Token Authentication?
Application authentication is the process of confirming a user's identity. Traditional session‑based authentication relies on server‑side session IDs stored in cookies, which forces developers to manage server‑specific session storage. Token authentication replaces session IDs with signed tokens, reducing server load, simplifying permission management, and supporting distributed or cloud‑based architectures.
JWT Overview
A JSON Web Token (JWT) consists of three Base64‑URL‑encoded parts: a header, a payload (claims), and a signature. The header describes the token type and signing algorithm, the payload contains the claims, and the signature ensures integrity.
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
.
eyJzdWIiOiJ1c2Vycy9Uek1Vb2NNRjRwIiwibmFtZSI6IlJvYmVydCBUb2tlbiBNYW4iLCJzY29wZSI6InNlbGYgZ3JvdXBzL2FkbWlucyIsImV4cCI6IjEzMDA4MTkzODAifQ
.
1pVOLQduFWW3muii1LExVBt2TK1-MdRI4QjhKryaDwcThe payload, when decoded, yields a clean JSON object such as:
{
"sub": "users/TzMUocMF4p",
"name": "Robert Token Man",
"scope": "self groups/admins",
"exp": "1300819380"
}Typical required claims include the subject (who the token represents), the scope (what the token grants access to), and the expiration time (used by APIs to reject expired tokens).
JWE, JWS, and JWT
According to the JWT specification, a JWT is a JSON object encoded as either a JWS (signed) or JWE (encrypted) structure. JWS provides a digital signature but leaves the payload readable, while JWE encrypts the payload for confidentiality.
What Is OAuth?
OAuth 2.0 is a framework for delegating authentication and authorization to external services. It defines access and refresh tokens; access tokens are short‑lived, while refresh tokens can be used to obtain new access tokens after expiration. JWTs are increasingly used as the token format in OAuth implementations.
Creating and Verifying JWTs in Java
Java developers can use the open‑source JJWT library to create and validate JWTs. The creation process involves defining claims (issuer, subject, expiration, etc.), signing the token to produce a JWS, and compacting it into a URL‑safe string.
String jwt = Jwts.builder()
.setSubject("users/TzMUocMF4p")
.setExpiration(new Date(1300819380))
.claim("name", "Robert Token Man")
.claim("scope", "self groups/admins")
.signWith(
SignatureAlgorithm.HS256,
"secret".getBytes("UTF-8")
)
.compact();Verification parses the token, checks the signature, validates the expiration, and extracts claims:
String jwt = <jwt passed in from above>
Jws<Claims> claims = Jwts.parser()
.setSigningKey("secret".getBytes("UTF-8"))
.parseClaimsJws(jwt);
String scope = claims.getBody().get("scope");
assertEquals(scope, "self groups/admins");If the signature is invalid, JJWT throws a SignatureException . Other runtime exceptions include ClaimJwtException , ExpiredJwtException , MalformedJwtException , PrematureJwtException , and UnsupportedJwtException , all found under the io.jsonwebtoken package.
Token Security Best Practices
Store JWTs in secure HttpOnly cookies to mitigate XSS attacks.
Implement CSRF protection when using cookies for token transmission.
Sign tokens with strong, authentication‑only keys and verify the signature on each request.
Avoid placing sensitive data in JWT payloads; encrypt the token if confidentiality is required.
Include a nonce (jti), expiration (exp), and issued‑at (iat) claims to defend against replay attacks.
Helpful Tools
Stormpath maintains several open‑source utilities for working with JWTs:
JJWT – a Java library for creating and verifying JWTs (Apache 2.0 license).
JSONWebToken.io – a web tool for decoding JWTs, powered by the Node.js nJWT library.
JWT Inspector – a Chrome extension that discovers and decodes JWTs in cookies, local/session storage, and headers.
Additional resources cover token authentication for single‑page applications, OAuth token management with Spring Boot, Java application token authentication, building secure user interfaces with JWT, and clarifying that OAuth is not single sign‑on.
Architects Research Society
A daily treasure trove for architects, expanding your view and depth. We share enterprise, business, application, data, technology, and security architecture, discuss frameworks, planning, governance, standards, and implementation, and explore emerging styles such as microservices, event‑driven, micro‑frontend, big data, data warehousing, IoT, and AI architecture.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.