00:00

OAuth2 vs JWT: What Is the Difference?

Last updated:

OAuth2 and JWT are often mentioned in the same sentence, as if they were alternatives. They are not. OAuth2 is an authorization framework: a set of rules for how an application obtains permission to call an API on someone's behalf. JWT is a token format: a compact, signed way to write down claims such as "this token was issued to the courier app and may read shipments".

An OAuth2 system can issue JWTs, opaque tokens or both, and JWTs can be used without OAuth2 at all. This page compares the two side by side, shows how they fit together in a typical Spring architecture, and ends with a small program that proves the most misunderstood fact about JWTs: their contents are readable by anyone.

1. What Are OAuth2 and JWT?

OAuth 2.0 (RFC 6749) defines four roles: the resource owner (usually a user), the client (the application that wants access), the authorization server (which issues tokens) and the resource server (the API). It also defines grant types, such as authorization code and client credentials, that describe how the client obtains an access token. It deliberately does not say what that token looks like. See OAuth2 introduction for the full picture.

JWT (JSON Web Token, RFC 7519) is a string of three Base64URL-encoded parts separated by dots: a header, a payload of claims and a signature. A server that holds the right key can verify the signature and trust the claims without a database lookup. The structure is explained in detail in JWT (JSON Web Token).

2. OAuth2 vs JWT: Key Differences

AspectOAuth2JWT
What it isAuthorization framework (a protocol)Token format (a data structure)
SpecificationRFC 6749 and related RFCsRFC 7519, with JWS for signatures (RFC 7515)
Answers the questionHow does a client obtain and use permission to call an API?How can claims be packaged so a receiver can verify them?
DefinesRoles, grant types, endpoints, scopes, token requestsHeader, claims (iss, sub, aud, exp...), signature
Contains user data?No, it is a processYes, claims in a readable payload
Can be used without the other?Yes, with opaque tokens checked by introspectionYes, for example tokens issued by your own application
Spring Security supportoauth2Login(), oauth2Client(), oauth2ResourceServer(), Spring Authorization ServerJwtDecoder, JwtEncoder (Nimbus), oauth2ResourceServer().jwt()

3. How OAuth2 and JWT Work Together

In most modern systems the authorization server issues access tokens as JWTs. OAuth2 governs how the token is obtained; JWT governs what the token looks like and how the API validates it.

OAuth2 flow with a JWT access tokenThe client requests a token from the authorization server using an OAuth2 grant. The server returns a signed JWT access token. The client sends it to the resource server, which verifies the signature with the server public keys and reads the scope claim. Client courier mobile app Authorization server OAuth2 grant, issues tokens Resource server (API) verifies JWT signature JWK Set public keys Decision scope: shipments.read 1. token request 2. Bearer JWT 3. fetch keys once
Figure 1: OAuth2 decides how the token is obtained; the JWT format lets the API verify it locally with public keys.

3.1 Where OpenID Connect Fits

OAuth2 is about authorization; it does not tell the client who the user is. OpenID Connect (OIDC) is a thin identity layer on top of OAuth2. It adds an ID token, which is always a JWT, describing the authenticated user to the client, plus a standard userinfo endpoint. "Sign in with Google" is OIDC, implemented in Spring by OAuth2 Login.

TokenDefined byFormatRead byPurpose
Access tokenOAuth2JWT or opaqueThe resource server (API)Permission to call the API
Refresh tokenOAuth2Usually opaqueThe authorization server onlyObtain new access tokens
ID tokenOpenID ConnectAlways JWTThe client applicationTell the client who logged in

4. Example: What a JWT Access Token Really Contains

The program below uses Spring Security's NimbusJwtEncoder to sign an access token the way an authorization server would, then decodes it without any key, verifies it with the public key, and finally tampers with it. It uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2 (the classes come from spring-security-oauth2-jose).

TokenAnatomy.java
package com.javabytechie.tokens;

import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;

public class TokenAnatomy {

    public static void main(String[] args) throws Exception {
        // The authorization server's signing key (normally loaded from secure storage)
        RSAKey key = new RSAKeyGenerator(2048).keyID("parcelhub-2026").generate();
        NimbusJwtEncoder encoder = new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(key)));

        Instant now = Instant.now();
        JwtClaimsSet claims = JwtClaimsSet.builder()
            .issuer("https://login.parcelhub.example")
            .subject("courier-app")
            .audience(List.of("shipments-api"))
            .claim("scope", "shipments.read")
            .issuedAt(now)
            .expiresAt(now.plusSeconds(300))
            .build();
        String token = encoder.encode(JwtEncoderParameters.from(
            JwsHeader.with(SignatureAlgorithm.RS256).build(), claims)).getTokenValue();

        String[] parts = token.split("\\.");
        System.out.println("parts:   " + parts.length + " (header.payload.signature)");
        System.out.println("header:  " + decode(parts[0]));
        System.out.println("payload: " + decode(parts[1]).replaceAll("\\d{10}", "<epoch seconds>"));

        // Verifying needs only the public key
        NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(key.toRSAPublicKey()).build();
        Jwt verified = decoder.decode(token);
        System.out.println("verified: subject=" + verified.getSubject() + ", scope=" + verified.getClaimAsString("scope"));

        // Change one claim but keep the old signature
        String forgedPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(
            decode(parts[1]).replace("shipments.read", "shipments.admin").getBytes(StandardCharsets.UTF_8));
        try {
            decoder.decode(parts[0] + "." + forgedPayload + "." + parts[2]);
        } catch (JwtException ex) {
            System.out.println("tampered: " + ex.getMessage());
        }
    }

    private static String decode(String part) {
        return new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8);
    }
}
Terminal
$ java TokenAnatomy
parts:   3 (header.payload.signature)
header:  {"kid":"parcelhub-2026","alg":"RS256"}
payload: {"iss":"https://login.parcelhub.example","sub":"courier-app","aud":"shipments-api","exp":<epoch seconds>,"iat":<epoch seconds>,"scope":"shipments.read"}
verified: subject=courier-app, scope=shipments.read
tampered: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature

The header and payload were printed without any key: Base64URL is an encoding, not encryption. Anyone holding the token can read its claims, so never put secrets or sensitive personal data in a JWT. What the key provides is integrity: changing a single claim breaks the signature, and the decoder rejects the token. (The program masks the timestamps only to keep the output stable; real tokens contain the numeric iat and exp values.) If confidentiality is required, use an encrypted token (JWE) or an opaque token.

5. When to Use What

  • Third-party or multi-service access: use OAuth2 with an authorization server. Let it issue JWT access tokens so each API can validate them locally; see OAuth2 resource server with JWT.
  • "Sign in with Google / Microsoft / Okta": use OpenID Connect through OAuth2 Login.
  • A single application with its own users and an API for its own front end: self-issued JWTs can be enough; see JWT authentication in Spring Security. Consider a session cookie too, which is often simpler for browsers.
  • Tokens that must be revocable immediately: prefer opaque tokens with introspection, or keep JWT lifetimes very short.

6. Common Mistakes and Best Practices

  • "We use JWT instead of OAuth2." This compares a format with a protocol. Decide how tokens are obtained (OAuth2 or your own login) and, separately, what format they have.
  • Treating JWT payloads as secret. They are only signed by default. Keep personal or sensitive data out of them.
  • Using the ID token to call APIs. ID tokens are meant for the client. APIs should receive access tokens.
  • Skipping claim validation. Check iss, exp and the audience (aud), not only the signature.
  • Long-lived access tokens. A JWT cannot be withdrawn before it expires without extra infrastructure. Keep lifetimes short and use refresh tokens.

7. Summary

  • OAuth2 is an authorization framework that defines how clients obtain access tokens; JWT is a signed token format.
  • OAuth2 access tokens may be JWTs or opaque strings; JWTs may also be issued without OAuth2.
  • OpenID Connect adds identity to OAuth2 through the ID token, which is always a JWT.
  • JWT payloads are readable by anyone; the signature protects integrity, not confidentiality.
  • Spring Security supports all of these: login, client, resource server, encoder and decoder.

8. References