How to develop a JWT based authentication system using Java
How to develop a JWT based authentication system using Java
JWT(JSON Web Token)是一种用于在网络应用之间传递安全信息的开放标准。它通过使用数字签名来验证数据的完整性,可以将用户的身份信息进行加密和传输,从而实现身份验证的功能。在Java开发中,我们可以利用JWT来构建一个安全的身份验证系统。
本文将介绍How to develop a JWT based authentication system using Java,同时提供具体的代码示例。
- 导入依赖库
首先,我们需要导入相关的依赖库。在Maven项目中,可以在pom.xml文件中添加以下依赖:
<dependencies> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies>
- 实现用户认证和授权功能
我们需要创建一个类来实现用户认证和授权的功能。可以创建一个名为JwtUserDetailsService的类,实现Spring Security的UserDetailsService接口,并重写其中的loadUserByUsername方法:
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; public class JwtUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 在此处实现用户认证逻辑 // 从数据库或其他地方获取用户信息并返回UserDetails对象 // 示例代码: if ("admin".equals(username)) { return new User("admin", "$2a$10$nlOlF0XzRpvVoOWyDKxwDuxyiwAwtOkhQiiKsRTgt28yTjC9Yt.6O", new ArrayList<>()); } else { throw new UsernameNotFoundException("User not found with username: " + username); } } }
在上述示例代码中,我们使用了Spring Security中的User类来表示用户信息。
- 创建JWT工具类
我们还需要创建一个工具类来生成和验证JWT。可以创建一个名为JwtUtil的类,实现如下方法:
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import java.security.Key; public class JwtUtil { private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256); private static final long EXPIRATION_TIME = 86400000L; // 有效期为24小时 public static String generateToken(String username) { return Jwts.builder() .setSubject(username) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SECRET_KEY) .compact(); } public static boolean validateToken(String token, UserDetails userDetails) { String username = getUsernameFromToken(token); return username.equals(userDetails.getUsername()) && !isTokenExpired(token); } public static String getUsernameFromToken(String token) { return Jwts.parserBuilder() .setSigningKey(SECRET_KEY) .build() .parseClaimsJws(token) .getBody() .getSubject(); } private static boolean isTokenExpired(String token) { Date expiration = Jwts.parserBuilder() .setSigningKey(SECRET_KEY) .build() .parseClaimsJws(token) .getBody() .getExpiration(); return expiration.before(new Date()); } }
- 创建身份验证过滤器
我们还需要创建一个过滤器来验证请求中的JWT。可以创建一个名为JwtRequestFilter的类,继承自Spring Security的OncePerRequestFilter类,并重写其中的doFilterInternal方法:
import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class JwtRequestFilter extends UsernamePasswordAuthenticationFilter { private JwtUserDetailsService userDetailsService; public JwtRequestFilter(JwtUserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String token = getTokenFromRequest(request); if (token != null && JwtUtil.validateToken(token, userDetailsService.loadUserByUsername("admin"))) { Authentication authentication = new JwtAuthenticationToken(userDetailsService.loadUserByUsername("admin")); SecurityContextHolder.getContext().setAuthentication(authentication); } chain.doFilter(request, response); } private String getTokenFromRequest(HttpServletRequest request) { String header = request.getHeader("Authorization"); if (header != null && header.startsWith("Bearer ")) { return header.substring(7); } return null; } }
在上述示例代码中,我们从请求头中获取JWT,并验证其有效性。如果验证通过,则将用户的认证信息存储到Spring Security的上下文中。
- 配置Spring Security
最后,我们需要在Spring Security的配置类中配置JwtUserDetailsService和JwtRequestFilter。可以创建一个名为SecurityConfig的类,继承自WebSecurityConfigurerAdapter类,并重写其中的configure方法:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtUserDetailsService userDetailsService; @Autowired private JwtRequestFilter jwtRequestFilter; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/authenticate").permitAll() .anyRequest().authenticated() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
在上述示例代码中,我们将认证和授权的逻辑委托给JwtUserDetailsService,并将JwtRequestFilter添加到认证过滤器链中。此外,我们还禁用了CSRF保护,并设置了无状态的会话管理策略。
至此,我们已经完成了基于JWT的身份验证系统的开发。通过以上步骤,我们可以使用Java开发一个基于JWT的身份验证系统,确保用户的身份信息在网络应用之间的安全传输。
以上所述仅是一个简单的示例,实际项目中可能还有其他授权策略和业务逻辑的实现。使用JWT进行身份验证可以提供更好的安全性和可扩展性,为Java开发者提供了一种优秀的身份验证解决方案。希望本文能对您有所帮助!
The above is the detailed content of How to develop a JWT based authentication system using Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4
