CodeGym /Courses /Module 5. Spring /Lecture 243: Core functions of API Gateway: routing, auth...

Lecture 243: Core functions of API Gateway: routing, authentication, authorization

Module 5. Spring
Level 24 , Lesson 2
Available

API Gateway is like the concierge at a hotel: it accepts all incoming requests from external users, checks who they are, decides where to send them, and handles overall management. This makes the API Gateway the central control point between clients and microservices. In this lecture we'll dig into the core functions of an API Gateway.


Advanced routing capabilities

Routing in an API Gateway is the heart of what it does. It's responsible for getting requests to the right microservices that can handle them.

Example:

Imagine you have two microservices:

  1. User management service (UserService) at http://localhost:8081.
  2. Order service (OrderService) at http://localhost:8082.

You want:

  • Requests to /users/** routed to UserService.
  • Requests to /orders/** routed to OrderService.

Let's set this up in Spring Cloud Gateway:


@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("user_service_route", r -> r.path("/users/**")
                .uri("http://localhost:8081")) // Route to UserService
            .route("order_service_route", r -> r.path("/orders/**")
                .uri("http://localhost:8082")) // Route to OrderService
            .build();
    }
}

Now the API Gateway forwards requests based on the path. That's already pretty neat, but we can do more.


Handling authentication and authorization

Authentication is verifying who you are (for example, logging in with a username and password). Authorization is checking what you're allowed to do (for example, access only certain data).

The API Gateway can handle authentication and authorization in several ways:

  1. Token validation (for example, JWT).
  2. Integration with OAuth2/SSO systems.
  3. Saving your backend's life by rejecting unauthorized requests at the API Gateway level.

Advanced routing features

For complex routing scenarios the API Gateway supports predicates and filters.

Predicates are used to define routing rules. For example:

  • By Path (Path): route requests when their path matches /users/**.
  • By HTTP Method (Method): only GET requests.
  • By Host (Host): e.g., requests sent to api.example.com.

Predicate example:


@Bean
public RouteLocator advancedRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("user_service", r -> r
            .path("/users/**")
            .and()
            .method("GET") // Only GET requests
            .uri("http://localhost:8081"))
        .build();
}

Filters allow you to process requests and responses: modify them, add headers, validate params, etc.

Example: add a header to all requests:


@Bean
public RouteLocator routeWithFilters(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("order_service", r -> r
            .path("/orders/**")
            .filters(f -> f.addRequestHeader("X-Request-ID", "12345")) // Add header
            .uri("http://localhost:8082"))
        .build();
}

Authentication in API Gateway

Working with authentication is a key API Gateway responsibility when building secure apps.

JWT (JSON Web Token) is a token the client sends with requests, and the server (or API Gateway) verifies its authenticity using a secret key. It's handy because you don't have to hit the database every time: the token already carries the info.

Example of setting up JWT verification: Add the dependency to pom.xml:


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

Configure it like this:


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.oauth2ResourceServer()
            .jwt(); // Enable JWT support
    }
}

Now requests with tokens will be validated.


Authorization in API Gateway

Authorization is basically "are you allowed to go there?". It ensures users can only do what they're permitted to do.

Roles and permissions

In a microservices environment, roles (for example, ADMIN, USER) are used to limit functionality.

Let's set up role-based authorization:


@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/admin/**").hasRole("ADMIN") // Admins only
        .antMatchers("/user/**").hasRole("USER")   // Users only
        .anyRequest().authenticated();            // Other requests - authenticated users only
}

Managing security

Besides authentication and authorization, the API Gateway should protect against attacks like SQL injection, XSS, and CSRF.

Protecting against CSRF

CSRF (Cross-Site Request Forgery) is an attack where an attacker tricks a user into making a request on their behalf. Spring Security enables CSRF protection for forms by default.

For REST APIs you can disable it (but be careful!):

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable(); // Disable if using tokens
}

The API Gateway can also rate-limit requests to prevent DoS attacks. For example, configure request limits using filters.


Hands-on exercise

  1. Set up routing for two microservices: /users/** and /orders/**.
  2. Implement JWT authentication so users with tokens can make requests.
  3. Add authorization to restrict access:
    • Admins can perform POST on /orders.
    • Users can only GET on /users.

We've taken a big step forward — from simple routing to advanced scenarios with authentication and authorization. The API Gateway now not only routes requests but also protects your data and microservices. Let's keep going!

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