CodeGym /Courses /Module 5. Spring /Introduction to OAuth2 and JWT for microservices

Introduction to OAuth2 and JWT for microservices

Module 5. Spring
Level 17 , Lesson 9
Available

Let's kick off our adventure with a simple question:

"So what is OAuth2?"

OAuth2 (Open Authorization 2.0) — a protocol for authorization that lets applications get limited access to resources on behalf of a user without handing over passwords directly. Sound a bit abstract? Let's break it down with an example.

How OAuth2 works: the story of one cupcake

Imagine this: you have a personal locker at a hip cafe where your favorite cupcakes are kept. But instead of giving the barista your personal key (password), you give them a temporary token with limited permissions.

What can the barista do with that token?

  • Open only your locker ✓
  • Take out only the cupcake ✓
  • Peek into other lockers ✗
  • Use the token tomorrow ✗

That's OAuth2 in action! Your personal key (login and password) stays with you, while services get temporary tokens with well-defined rights. No extra access, no risk of your credentials being leaked.

Just like you wouldn't give a stranger the keys to your house in real life, OAuth2 in web apps protects your data by issuing temporary passes with the minimum necessary permissions.

OAuth2 principles

To better understand the motivation and structure of the protocol, let's look at its main "flows".

OAuth2 uses so-called authentication flows. They define how a user gets an access token depending on the type of application.

Main authentication flows:

  1. Authorization Code (authorization code): used for server-side apps where the frontend talks to your server, and the server requests authorization from the user.
  2. Implicit (implicit flow): this flow is optimized for client-side apps (for example, SPAs). The access token is issued directly to the browser.
  3. Client Credentials (client credentials): used for server-to-server interactions where there's no user session involved.
  4. Password (password flow): the token is issued via the user's login and password. Used less often due to lower security.

How OAuth2 works in Spring

To use OAuth2 in Spring, you typically add the spring-security-oauth2 module. It provides everything needed for both the server and client sides of OAuth2, including token handling and verification.

OAuth2 documentation in Spring Security


JSON Web Token (JWT)

Now that we covered OAuth2, it's time to talk about JSON Web Token (JWT). This is a token format often used in microservice architectures.

JWT (JSON Web Token) — a compact, secure, self-contained token that carries user information and access rights. The main idea is that a JWT is encoded and signed, so it can act as a source of truth during authorization.

JWT consists of three parts separated by dots:


header.payload.signature
  • Header (header): contains information about the token type (usually JWT) and the signing algorithm (for example, HS256).
  • Payload (payload): contains useful data like user ID, roles, token expiration time, etc.
  • Signature (signature): this is the cryptographic signature that ensures token integrity and protects it from tampering.

Example of decoding a real JWT:


{
  "alg": "HS256",
  "typ": "JWT"
}


{
  "sub": "user123",
  "role": "ADMIN",
  "exp": 1698147200
}

How JWT works in microservices?

JWT pairs really well with microservice architecture because:

  1. It's self-contained. Signed data inside a JWT lets each microservice verify the token's authenticity without calling a central server.
  2. It's compact. The token is easy to pass between services via HTTP headers.
  3. It simplifies scalability. The authentication system can be distributed since each service can work with tokens independently.

Examples of integrating OAuth2 and JWT in Spring

1. Dependency setup

Add the dependency to your Spring Boot app's pom.xml:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

2. Configuration setup

In application.yml configure JWT:


spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://your-issuer-url

This tells Spring Security to use JWT for token verification.

3. Creating security configuration

Create a class to configure security:


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2ResourceServer()
                .jwt();
    }
}

4. Generating JWT

To generate JWTs use the jjwt library:

Add these dependencies:


<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.5</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.5</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.11.5</version>
</dependency>

Example code:


import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtTokenGenerator {

    private static final String SECRET_KEY = "my-secret-key";

    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour validity
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }
}

Real-world use cases

JWT and OAuth2 are widely used in microservice architectures for securing systems. Examples:

  • User authorization in REST APIs.
  • Secure data transfer between services.
  • Improving scalability, since tokens can be validated locally.

That's it! We covered OAuth2 and JWT, saw how to use them in microservices and how to set them up in a Spring application. In the next lecture we'll dive deeper into implementing and securing REST APIs using these technologies.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION