SoFunction
Updated on 2025-04-05

Use Spring Security and JWT to implement security authentication mechanism

introduction

In modern web applications, secure authentication and authorization are the core mechanisms that protect data security and user privacy.Spring SecurityIt is a module designed for security under the Spring framework, with high configurability and scalability. andJWT(JSON Web Token)It is currently a popular certification solution, and is widely used in microservices and mobile applications due to its statelessness and strong scalability.

This article will introduce in detail how to use Spring Security and JWT to implement a complete authentication mechanism from the following sections:

  1. Overview of JWT Certification Process
  2. Basic configuration of Spring Security
  3. JWT generation and analysis
  4. JWT security configuration based on Spring Security
  5. Implement user login and authentication

1. Overview of JWT certification process

The authentication process of JWT is as follows:

  • User login: The user sends a request to the server through the username and password.
  • Server Verification: The server verifies the user's identity, and generates a JWT Token after the verification is passed.
  • Token issuance: The server returns the generated token to the client.
  • Request to bring Token: The client adds the JWT Token to the request header in subsequent requests, and the server confirms the legitimacy of the request by parsing and verifying the token.

The core advantage of this method is that the token is stateless, the server does not need to maintain user's session information, and the JWT can implement shared authentication in a distributed system.

2. Basic configuration of Spring Security

Create a simple Spring Boot project and add Spring Security and JWT dependencies:

<dependencies>
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
</dependencies>

Config the SecurityConfig class

CreateSecurityConfigClass to configure Spring Security basic settings:

import ;
import ;
import ;
import ;
import ;
import ;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ().disable()
            .authorizeRequests()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated();
    }
}

The above configuration specification/loginThe interface is publicly accessed, and the remaining interfaces need to be authenticated before accessing.

3. JWT generation and analysis

Generate and parse tokens using the JWT library. CreateJwtUtilTool class, methods to generate and verify JWT:

import ;
import ;
import ;

import ;

public class JwtUtil {

    private static final String SECRET_KEY = "mySecretKey";

    // Generate JWT    public static String generateToken(String username) {
        return ()
                   .setSubject(username)
                   .setIssuedAt(new Date())
                   .setExpiration(new Date(() + 86400000)) // 24 hours valid                   .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                   .compact();
    }

    // Analysis JWT    public static Claims parseToken(String token) {
        return ()
                   .setSigningKey(SECRET_KEY)
                   .parseClaimsJws(token)
                   .getBody();
    }
}

4. JWT security configuration based on Spring Security

Add a JWT filter to the Spring Security filter chain. Implement aJwtAuthenticationFilterClass, intercept and verify the Token on each request:

import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    public JwtAuthenticationFilter(AuthenticationManager authManager) {
        super(authManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        String token = ("Authorization");
        if (token == null || !("Bearer ")) {
            (request, response);
            return;
        }

        Claims claims = (("Bearer ", ""));
        String username = ();

        if (username != null) {
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
            ().setAuthentication(auth);
        }
        (request, response);
    }
}

WillJwtAuthenticationFilterFilter added toSecurityConfigmiddle:

@Override
protected void configure(HttpSecurity http) throws Exception {
    ().disable()
        .authorizeRequests()
        .antMatchers("/login").permitAll()
        .anyRequest().authenticated()
        .and()
        .addFilter(new JwtAuthenticationFilter(authenticationManager()));
}

5. Implement user login and authentication

Create a login controllerAuthController, generate JWT after verifying the user:

import .*;
import ;

@RestController
public class AuthController {

    @PostMapping("/login")
    public void login(@RequestParam String username, @RequestParam String password, HttpServletResponse response) {
        // Here is a simple verification of username and password        if ("user".equals(username) &amp;&amp; "password".equals(password)) {
            String token = (username);
            ("Authorization", "Bearer " + token);
        } else {
            (HttpServletResponse.SC_UNAUTHORIZED);
        }
    }
}

The above code implements a simple login interface. After the user logs in successfully, it will return the JWT token and store the token in the response header.

6. Testing and Verification

  1. Get Token: Request using client (such as Postman)/loginInterface, get the response header containing the JWT Token.
  2. Accessing protected interfaces: Add the token to the request headerAuthorization, request the protected interface again to verify whether it can be accessed successfully.

in conclusion

Through the above steps, we implement a security authentication system based on Spring Security and JWT. In actual projects, this function can be further expanded, such as integrating database to implement user management, configuring JWT automatic renewal, etc. This JWT-based stateless authentication is suitable for distributed systems and microservice architectures, helping to improve system security and scalability.

The above is the detailed content of using Spring Security and JWT to implement the security authentication mechanism. For more information about Spring Security JWT security authentication, please follow my other related articles!