Mastering Login Authentication with Spring Cloud Gateway and JWT

This tutorial walks through implementing login authentication using Spring Cloud Gateway and JWT, covering core concepts of authentication, authorization, credential handling, token generation, gateway validation, service integration, and token refresh strategies within a microservice architecture.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Mastering Login Authentication with Spring Cloud Gateway and JWT

Preface

In the previous article we explained the principles and practice of Spring Cloud. This time we combine JWT to implement login authentication.

Authentication, Authorization, Credential

1.1 Authentication

Authentication identifies who you are, e.g., by verifying username and password.

1.2 Authorization

Authorization determines what you can do, i.e., which data and functions you have permission to access.

1.3 Credential

A credential proves your identity and ensures the commitment between user and system is accurate, complete, and non‑repudiable.

Authentication Principle

The authentication sequence involves the following roles:

Client : the front‑end page on APP or PC.

Gateway : Spring Cloud Gateway service.

Authentication Service : receives login, logout, and token refresh requests.

Business Service : micro‑services related to system business.

The authentication and identity verification flow consists of nine steps:

User Login : client submits username and password to the login API.

Request Forwarding : the login request is forwarded from the gateway (passjava‑gateway) to the authentication service (passjava‑auth).

Authentication : the authentication service compares the submitted credentials with the stored user data.

Token Generation : generates access_token and refresh_token (the latter is discussed later).

Client Caches Token : the client stores the tokens in cookies or LocalStorage.

Request with Token : the client includes access_token in the request header for subsequent calls.

Gateway Validates Token : the gateway checks the token’s legality and expiration.

Gateway Forwards User Info : the gateway extracts user_id from the token and adds it to the request header before forwarding.

Business Logic Processing : the business service retrieves user_id from the header and processes the request.

Project Overall Structure

PassJava‑Platform consists of the following modules:

Authentication Service: passjava-auth Gateway Service: passjava-gateway JWT Common Project: passjava-jwt (shared by authentication and gateway)

Business Service: passjava-member (member micro‑service used in this demo)

Nacos Configuration Center

Authentication Service (passjava-auth)

The core class is JwtAuthController, which provides login and token refresh endpoints.

Gateway Service (passjava-gateway)

The core component is the global filter JwtAuthCheckFilter.

JWT Common Project

The utility class PassJavaJWTTokenUtil generates and validates JWT tokens.

Business Service (passjava-member)

The service extracts userId from the request header and queries member information.

How to Implement Login Authentication

Login authentication verifies that the submitted username and password match the records in the database. The process includes three steps.

Step 1: Submit Username and Password

Using Postman, send a POST request to the gateway: http://localhost:8060/api/auth/login The request is routed to the authentication service at http://localhost:10001/auth/login.

Step 2: Forward Login Request

The gateway forwards the request according to the routing rule defined in application-routers.yml:

spring:
  cloud:
    gateway:
      routes:
        - id: route_auth
          uri: lb://passjava-auth
          predicates:
            - Path=/api/auth/**
          filters:
            - RewritePath=/api/(?<segment>.*),/${segment}

Step 3: Verify Credentials

The AuthController in the authentication service checks the user’s credentials. Upon success, a JWT token is generated.

How to Generate Token

The token is created by PassJavaJwtTokenUtil. The JWT library jjwt is added to the passjava-jwt module’s pom.xml.

After calling the login API, the generated token looks like:

The payload contains the user ID and username. The secret key is configured in application-jwt.yml.

How to Carry JWT in Requests

The client stores the JWT in cookies, LocalStorage, or memory, and includes it in the Authorization header (Bearer token) for subsequent requests.

When the gateway parses the header, it removes the Bearer prefix:

Gateway Validation and Request Forwarding

The gateway checks the Authorization header, validates the token, extracts userId and username, adds them to the header, and forwards the request to the business service.

The global filter JwtAuthCheckFilter implements this logic.

Member Service Business Logic

The member service receives the forwarded request, obtains the user identity from the header, and queries member details.

Note: In many cases business logic also needs to verify the user’s permissions, which can be embedded in the token (covered in a future article on authorization).

How to Refresh Token

When the access_token expires, the client can call a refresh endpoint using the refresh_token to obtain a new token, avoiding frequent re‑login.

Two refresh modes are described:

Hungry Mode : the client proactively refreshes the token before expiration.

Lazy Mode : the client refreshes only after the token has expired, which may cause a brief request failure.

Refresh tokens can be single‑use; the server caches them (e.g., in Redis) and removes them after use, though this introduces statefulness.

Summary

Although this article focuses on practical implementation, it also covers fundamental concepts such as gateway routing and JWT principles. By combining theory with hands‑on examples, readers should now have a solid understanding of how to achieve login authentication with Spring Cloud Gateway and JWT. Authorization will be addressed in the next article.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Microservicesbackend-developmentAuthenticationgatewaySpring CloudJWT
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.