Home Backend Development Golang Understanding JWT Authentication: Spring Security&#s Architecture and Go Implementation

Understanding JWT Authentication: Spring Security&#s Architecture and Go Implementation

Dec 01, 2024 pm 02:15 PM

After setting up JWT stateless authentication (available here), I wanted to understand what happens under Spring Security's abstractions by identifying key components and their interactions. To make this exploration more engaging, I reimplemented a minimal version in Go using the standard HTTP library. By breaking down three core flows - registration, token generation, and protected resource access - and rebuilding them in Go, I set out to map Spring Security's authentication patterns to simpler components.

This post focuses specifically on authentication flows - how the system verifies user identity - rather than authorization. We'll explore the flows with sequence diagrams that trace requests through different components in Spring Security's architecture.

Main Components

The system provides three endpoints:

  1. User Registration: Accepts username and password from new users
  2. Token Generation (Login): Creates a JWT token when users successfully log in with valid credentials
  3. Protected Access: Enables authenticated users to access protected resources using their token. The getAuthenticatedUser endpoint serves as an example, returning profile information for the authenticated token holder

In the following sections, I explain the core components involved in each flow, with a sequence diagram for each.

Registration Flow

Understanding JWT Authentication: Spring Security

A registration request containing username and password passes through the Spring Security filter chain, where minimal processing occurs since the registration endpoint was configured to not require authentication in SecurityConfiguration. The request then moves through Spring's DispatcherServlet, which routes it to the appropriate method in UserController based on the URL pattern. The request reaches UserController's register endpoint, where the user information is stored along with a hashed password.

Token Generation Flow

Understanding JWT Authentication: Spring Security

A login request containing username and password passes through the Spring Security filter chain, where minimal processing occurs as this endpoint is also configured to not require authentication in SecurityConfiguration. The request moves through Spring's DispatcherServlet to UserController's login endpoint, which delegates to AuthenticationManager. Using the configured beans defined in ApplicationConfiguration, AuthenticationManager verifies the provided credentials against stored ones. After successful authentication, the UserController uses JwtService to generate a JWT token containing the user's information and metadata like creation time, which is returned to the client for subsequent authenticated requests.

Protected Resource Access Flow

Successful Authentication Flow (200)

Understanding JWT Authentication: Spring Security

Failed Authentication Flow (401)

Understanding JWT Authentication: Spring Security

When a request containing a JWT token in its Authorization header arrives, it passes through the JwtAuthenticationFilter - a custom defined OncePerRequestFilter - which processes the token using JwtService. If valid, the filter retrieves the user via UserDetailsService configured in ApplicationConfiguration and sets the authentication in SecurityContextHolder. If the token is missing or invalid, the filter allows the request to continue without setting authentication.

Later in the chain, AuthorizationFilter checks if the request is properly authenticated via SecurityContextHolder. When it detects missing authentication, it throws an AccessDeniedException. This exception is caught by ExceptionTranslationFilter, which checks if the user is anonymous and delegates to the configured JwtAuthenticationEntryPoint in SecurityConfiguration to return a 401 Unauthorized response.

If all filters pass, the request reaches Spring's DispatcherServlet which routes it to the getAuthenticatedUser endpoint in UserController. This endpoint retrieves the authenticated user information from SecurityContextHolder that was populated during the filter chain process.

Note: Spring Security employs a rich ecosystem of filters and specialized components to handle various security concerns. To understand the core authentication flow, I only focused on the key players in JWT token validation and user authentication.

Go Implementation: Mapping Components

The Go implementation provides similar functionality through a simplified architecture that maps to key Spring Security components:

FilterChain

  • Provides a minimal version of Spring Security's filter chain
  • Processes filters sequentially for each request
  • Uses a per-request chain instance (VirtualFilterChain) for thread safety

Dispatcher

  • Maps to Spring's DispatcherServlet
  • Routes requests to appropriate handlers after security filter processing

Authentication Context

  • Uses Go's context package to store authentication state per request
  • Maps to Spring's SecurityContextHolder

JwtFilter

  • Direct equivalent to Spring's JwtAuthenticationFilter
  • Extracts and validates JWT tokens
  • Populates authentication context on successful validation

AuthenticationFilter

  • Simplified version of Spring's AuthorizationFilter
  • Solely focusing on authentication verification
  • Checks authentication context and returns 401 if missing

JwtService

  • Similar to Spring's JwtService
  • Handles token generation and validation
  • Uses same core JWT operations but with simpler configuration

Test Coverage

Both implementations include integration tests (auth_test.go and AuthTest.java) verifying key authentication scenarios:

Registration Flow

  • Successful user registration with valid credentials
  • Duplicate username registration attempt

Login Flow

  • Successful login with valid credentials
  • Login attempt with non-existent username
  • Login attempt with incorrect password

Protected Resource Access

  • Successful access with valid token
  • Access attempt without auth header
  • Access attempt with invalid token format
  • Access attempt with expired token
  • Access attempt with valid token format but non-existent user

The Java implementation includes detailed comments explaining the flow of each test scenario through Spring Security's filter chain. These same flows are replicated in the Go implementation using equivalent components.

Journey Summary

I looked at Spring Security's JWT auth by breaking it down into flows and test cases. Then I mapped these patterns to Go components. Integration tests showed me how requests flow through Spring Security's filter chain and components. Building simple versions of these patterns helped me understand Spring Security's design. The tests proved both implementations handle authentication the same way. Through analyzing, testing, and rebuilding, I gained a deeper understanding of how Spring Security's authentication works.

The above is the detailed content of Understanding JWT Authentication: Spring Security&#s Architecture and Go Implementation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

See all articles