springboot记住密码jwt令牌
时间: 2023-09-22 13:09:09 浏览: 256
对于Spring Boot应用程序记住密码和使用JWT令牌进行身份验证的场景,你可以按照以下步骤进行操作:
1. 添加依赖:在`pom.xml`文件中添加Spring Security和JWT的依赖项。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
```
2. 创建Spring Security配置类:创建一个类来扩展`WebSecurityConfigurerAdapter`,并覆盖`configure`方法。
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/auth/**")
.permitAll()
.anyRequest()
.authenticated();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
@Bean
@Override
public UserDetailsService userDetailsService() {
// 实现自定义的UserDetailsService接口来获取用户信息并进行身份验证
return new CustomUserDetailsService();
}
@Bean
public PasswordEncoder passwordEncoder() {
// 使用BCryptPasswordEncoder来对密码进行加密和验证
return new BCryptPasswordEncoder();
}
}
```
3. 创建用户实体类:创建一个用户实体类,用于保存用户信息。
```java
@Entity
@Table(name = "users")
public class User implements UserDetails {
// 实现UserDetails接口的方法
// 用户名、密码等其他属性
// getter和setter方法
}
```
4. 创建自定义UserDetailsService:实现Spring Security的`UserDetailsService`接口,用于获取用户信息。
```java
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
return user;
}
}
```
5. 创建JWT工具类:创建一个JWT工具类,用于生成和解析JWT令牌。
```java
@Component
public class JwtTokenProvider {
private static final String SECRET_KEY = "yourSecretKey";
private static final long EXPIRATION_TIME = 86400000; // 24小时
public String generateToken(Authentication authentication) {
User user = (User) authentication.getPrincipal();
Date now = new Date();
Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME);
return Jwts.builder()
.setSubject(user.getUsername())
.setIssuedAt(new Date())
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (SignatureException ex) {
System.out.println("Invalid JWT signature");
} catch (MalformedJwtException ex) {
System.out.println("Invalid JWT token");
} catch (ExpiredJwtException ex) {
System.out.println("Expired JWT token");
} catch (UnsupportedJwtException ex) {
System.out.println("Unsupported JWT token");
} catch (IllegalArgumentException ex) {
阅读全文