Securing REST APIs with JWT and OAuth2

Interview Preparation Hub for Backend and Cloud-Native Engineering Roles

1. Introduction

REST APIs are the backbone of modern applications, powering everything from mobile apps to microservices. Security is critical to protect sensitive data and ensure only authorized users can access resources. Two widely adopted mechanisms for securing REST APIs are JSON Web Tokens (JWT) and OAuth2.

This guide covers everything from fundamentals to advanced topics: JWT structure, OAuth2 flows, implementation in Spring Security, token validation, refresh tokens, microservices integration, best practices, common mistakes, and interview notes. By the end, you will have mastered securing REST APIs with JWT and OAuth2.

2. JWT Fundamentals

JSON Web Tokens (JWT) are compact, URL-safe tokens used for authentication and authorization. A JWT consists of three parts:

  • Header: Contains metadata, including the signing algorithm.
  • Payload: Contains claims (user ID, roles, expiration).
  • Signature: Ensures integrity, created using a secret or private key.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZXMiOlsiQURNSU4iXSwiZXhwIjoxNjEyMzQ1Njc4fQ
.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
    
Diagram: JWT Structure

Header → Payload → Signature → Encoded as Base64URL → Combined with dots

3. OAuth2 Fundamentals

OAuth2 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service. It defines several flows:

  • Authorization Code Flow: Used by server-side apps.
  • Implicit Flow: Used by single-page apps (deprecated).
  • Client Credentials Flow: Used by machine-to-machine communication.
  • Resource Owner Password Flow: Used when credentials are directly exchanged (not recommended).
Diagram: OAuth2 Authorization Code Flow

Client → Authorization Server → User Consent → Authorization Code → Token Exchange → Access Token → Resource Server

4. Implementing JWT in Spring Security

public class JwtAuthenticationFilter extends OncePerRequestFilter {
  @Override
  protected void doFilterInternal(HttpServletRequest request,
                                  HttpServletResponse response,
                                  FilterChain filterChain) throws ServletException, IOException {
    String token = request.getHeader("Authorization");
    if(token != null && validateToken(token)) {
      Authentication auth = getAuthentication(token);
      SecurityContextHolder.getContext().setAuthentication(auth);
    }
    filterChain.doFilter(request, response);
  }
}
    

JWTs are validated on each request. If valid, the user is authenticated and authorized based on claims.

5. Implementing OAuth2 in Spring Security

spring.security.oauth2.client.registration.google.client-id=your-client-id
spring.security.oauth2.client.registration.google.client-secret=your-secret
spring.security.oauth2.client.registration.google.scope=profile,email
    

Spring Security provides built-in support for OAuth2 login and resource server functionality.

6. Token Management

Tokens must be managed carefully:

  • Access Tokens: Short-lived, used for resource access.
  • Refresh Tokens: Longer-lived, used to obtain new access tokens.
  • Revocation: Tokens can be revoked if compromised.

7. Securing Microservices with JWT and OAuth2

In microservices, JWTs are often used to propagate user identity across services. OAuth2 provides centralized authorization via an identity provider.

@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/secure-data")
public String getSecureData() {
  return "Sensitive information";
}
    

8. Best Practices

  • Use HTTPS to protect tokens in transit.
  • Keep access tokens short-lived.
  • Use refresh tokens for long-lived sessions.
  • Validate tokens on every request.
  • Store secrets securely, never hardcode.
  • Log and monitor authentication attempts.

9. Common Mistakes

  • Not validating JWT signatures.
  • Using long-lived access tokens without refresh tokens.
  • Storing tokens insecurely (e.g., local storage without protection).
  • Hardcoding secrets in code.
  • Ignoring token revocation.

10. Interview Notes

  • Be ready to explain JWT structure and validation.
  • Discuss OAuth2 flows and their use cases.
  • Explain implementation in Spring Security.
  • Discuss token management strategies, including access and refresh tokens.
  • Be able to describe OAuth2 flows (Authorization Code, Client Credentials, etc.) and when to use each.
  • Explain how JWTs are structured, signed, and validated.
  • Discuss microservices integration and how tokens propagate across services.
  • Know best practices for securing REST APIs with JWT and OAuth2.
  • Identify common mistakes and how to avoid them.
Diagram: Interview Prep Map

JWT Fundamentals → OAuth2 Flows → Spring Security Implementation → Token Management → Microservices Integration → Best Practices → Pitfalls

11. Final Mastery Summary

Securing REST APIs with JWT and OAuth2 is essential for building modern, distributed applications. JWT provides a lightweight, stateless mechanism for authentication and authorization, while OAuth2 offers a robust framework for delegated authorization and integration with identity providers.

Mastery of these concepts means understanding how tokens are generated, validated, and managed, as well as how to integrate them into frameworks like Spring Security. It requires balancing usability with security, ensuring that tokens are short-lived, securely stored, and properly validated on every request.

In microservices architectures, JWTs and OAuth2 enable consistent, centralized security across services. Identity providers issue tokens that carry user claims, which are then validated by each service. This ensures scalability and maintainability while reducing duplication of security logic.

Best practices include using HTTPS, keeping access tokens short-lived, employing refresh tokens, validating signatures, externalizing secrets, and monitoring authentication attempts. Common mistakes, such as failing to validate tokens or hardcoding secrets, can lead to severe vulnerabilities.

For interviews, emphasize your ability to explain JWT structure, OAuth2 flows, Spring Security implementation, token management, and microservices integration. Demonstrating awareness of best practices and pitfalls shows that you can design secure, scalable REST APIs.

Diagram: Mastery Roadmap

Fundamentals → JWT → OAuth2 → Spring Security → Token Management → Microservices → Best Practices → Interview Prep → Mastery