DEV Community

DevCorner
DevCorner

Posted on

OAuth 2.0 and JWT Tokens: One-Stop Interview Guide

Security is a critical aspect of modern web applications. OAuth 2.0 and JWT (JSON Web Tokens) are widely used authentication and authorization mechanisms. This guide provides a detailed, interview-ready explanation of these concepts.


1. What is OAuth 2.0?

OAuth 2.0 is an authorization framework that allows third-party applications to securely access user resources without exposing credentials. It enables secure delegated access through access tokens.

Key Terminologies:

  • Resource Owner: The user who owns the data.
  • Client: The application requesting access.
  • Authorization Server: Issues access tokens.
  • Resource Server: The API or service that requires authentication.

OAuth 2.0 Grant Types

OAuth 2.0 provides different flows (grant types) for various use cases:

1️⃣ Authorization Code Flow (Most Secure)

Use case: Web applications with a backend server.

✅ Steps:

  1. User logs in and authorizes the client.
  2. Client receives an authorization code.
  3. Client exchanges the code for an access token.
  4. Client uses the token to access resources.

2️⃣ Client Credentials Flow

Use case: Machine-to-machine (M2M) communication.

✅ Steps:

  1. Client authenticates itself with the authorization server.
  2. Client receives an access token.
  3. Client uses the token to access resources.

3️⃣ Implicit Flow (Deprecated)

Use case: Legacy single-page applications (SPA).

✅ Steps:

  • Access token is directly returned in the URL.

⚠️ Not recommended due to security vulnerabilities (e.g., token leakage).

4️⃣ Resource Owner Password Credentials Flow

Use case: Trusted applications (not recommended for third parties).

✅ Steps:

  • User provides username and password directly to the client.
  • Client exchanges credentials for an access token.

⚠️ Not recommended due to security risks (password exposure).


2. What is JWT (JSON Web Token)?

JWT is a compact, self-contained token used for authentication and information exchange. It is digitally signed to ensure integrity and authenticity.

Structure of JWT

JWT consists of three parts:

  1. Header: Contains metadata (e.g., signing algorithm)
   {
     "alg": "HS256",
     "typ": "JWT"
   }
Enter fullscreen mode Exit fullscreen mode
  1. Payload: Contains claims (user data, roles, expiration)
   {
     "sub": "1234567890",
     "name": "John Doe",
     "exp": 1710000000
   }
Enter fullscreen mode Exit fullscreen mode
  1. Signature: Ensures the token hasn’t been tampered with
   HMACSHA256(
     base64UrlEncode(header) + "." + base64UrlEncode(payload),
     secretKey
   )
Enter fullscreen mode Exit fullscreen mode

JWT example:

HEADER.PAYLOAD.SIGNATURE
Enter fullscreen mode Exit fullscreen mode

Types of JWTs:

  1. Access Tokens: Short-lived tokens for accessing resources.
  2. Refresh Tokens: Long-lived tokens used to obtain new access tokens.

3. OAuth 2.0 vs JWT

Feature OAuth 2.0 JWT
Purpose Authorization framework Token format
Usage API authentication Stateless authentication
Storage Can use JWT or opaque tokens Self-contained token
Expiration Short-lived tokens Expiration embedded
Signature Not mandatory Mandatory for integrity

4. Securing OAuth 2.0 and JWT

🔒 Best Practices for OAuth 2.0

✅ Use Authorization Code Flow for web applications.
✅ Keep client secrets confidential.
✅ Implement PKCE (Proof Key for Code Exchange) to prevent attacks.
✅ Use refresh tokens securely and rotate them.
✅ Validate redirect URIs to prevent phishing attacks.
✅ Apply scope restrictions for least privilege access.

🔐 Best Practices for JWT

✅ Use HS256 or RS256 for signing JWTs.
✅ Set expiration times for tokens (short for access tokens, longer for refresh tokens).
✅ Store JWTs securely (e.g., HttpOnly, Secure cookies).
✅ Validate issuer (iss) and audience (aud) claims.
✅ Do not store sensitive information in JWT payload.


5. Implementing OAuth 2.0 with JWT in Spring Boot

Step 1: Add Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.11.2</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure OAuth2 Resource Server

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withSecretKey(new SecretKeySpec("secret-key".getBytes(), "HMACSHA256")).build();
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Generate and Validate JWT

Generating JWT

public String generateToken(String username) {
    return Jwts.builder()
        .setSubject(username)
        .setIssuedAt(new Date())
        .setExpiration(new Date(System.currentTimeMillis() + 3600000))
        .signWith(SignatureAlgorithm.HS256, "secret-key")
        .compact();
}
Enter fullscreen mode Exit fullscreen mode

Validating JWT

public Claims validateToken(String token) {
    return Jwts.parser()
        .setSigningKey("secret-key")
        .parseClaimsJws(token)
        .getBody();
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

OAuth 2.0 and JWT are essential security mechanisms for authentication and authorization. Mastering their concepts, flows, and implementations will help you ace technical interviews and build secure applications.

✅ Key Takeaways:

  • OAuth 2.0 is a framework for delegated access.
  • JWT is a self-contained token format for authentication.
  • Use Authorization Code Flow with PKCE for web apps.
  • Store JWTs securely and validate claims.
  • Always follow security best practices.

🚀 Next Steps: Practice implementing OAuth 2.0 and JWT in a Spring Boot project to reinforce your understanding! Happy coding! 🎯

Top comments (0)