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!

How to avoid repeated execution of timed tasks in SpringBoot multi-node environment? In Spring...

Deeply discussing properties and states in object-oriented programming. In object-oriented programming, the concepts of properties and state are often confused, and there is a subtle between them...

How to deal with digital overflow errors when connecting to Oracle database in IDEA When we are using IntelliJ...

When studying the MyBatis framework, developers often encounter various problems about annotations. One of the common questions is how to use the @ResultType annotation correctly...

Methods of using natural language processing technology to query personnel data In modern enterprises, the management and query of personnel data is a common requirement. Suppose we...

Database access performance problem in Springboot project multi-data source configuration This article aims at using Atomikos for multi-data source configuration in a Springboot project...

When packaging a Java project into an executable JAR file, it encounters the problem of NoClassDefFoundError. Many Java developers may...

Regarding the analysis method of IntelliJIDEA cracking in the programming world, IntelliJ...


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool