springboot整合springsecurity jwt
时间: 2023-03-16 22:49:24 浏览: 185
springboot+spring security+JWT+mybatisplus
Spring Boot可以很方便地整合Spring Security和JWT(JSON Web Token)。
首先,需要在pom.xml文件中添加以下依赖:
```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>
```
然后,需要创建一个Security配置类,用于配置Spring Security和JWT:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// 配置用户认证方式
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.authorizeRequests().antMatchers("/authenticate").permitAll().
anyRequest().authenticated().and().
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
```
在上面的配置类中,需要注入JwtAuthenticationEntryPoint和JwtRequestFilter两个类。其中,JwtAuthenticationEntryPoint用于处理未经授权的请求,JwtRequestFilter用于验证JWT并将用户信息添加到Spring Security上下文中。
接下来,需要创建一个JwtTokenUtil类,用于生成和验证JWT:
```java
@Component
public class JwtTokenUtil {
private static final String SECRET_KEY = "secret";
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return Jwts.builder().setClaims(claims).setSubject(userDetails.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY).compact();
}
public boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
private boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
private Date getExpirationDateFromToken(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getExpiration();
}
private String getUsernameFromToken(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
}
}
```
在上面的类中,需要设置一个密钥,用于生成和验证JWT。generateToken方法用于生成JWT,validateToken方法用于验证JWT是否有效。
最后,需要创建一个JwtAuthenticationEntryPoint类和一个JwtRequestFilter类。JwtAuthenticationEntryPoint类用于处理未经授权的请求,JwtRequestFilter类用于验证JWT并将用户信息添加到Spring Security上下文中。
以上就是整合Spring Security和JWT的基本步骤。
阅读全文