spring security校验jwt token的代码
时间: 2023-07-28 19:06:48 浏览: 196
Spring Security校验JWT Token的代码可以参考如下:
首先,需要创建JWT Token的验证过滤器类。该类继承自OncePerRequestFilter,并在doFilterInternal()方法中实现了JWT Token的校验逻辑:
```java
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = jwtTokenProvider.resolveToken(request);
try {
if (token != null && jwtTokenProvider.validateToken(token)) {
Authentication auth = jwtTokenProvider.getAuthentication(token);
if (auth != null) {
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
} catch (JwtException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
return;
}
filterChain.doFilter(request, response);
}
}
```
然后,需要创建JWT Token的提供者类,该类负责创建Token并验证Token:
```java
@Component
public class JwtTokenProvider {
@Value("${jwt.secret}")
private String secretKey;
@Value("${jwt.token.validity}")
private long validityInMilliseconds;
private Key getSecretKey() {
return Keys.hmacShaKeyFor(secretKey.getBytes());
}
public String createToken(String username, List<Role> roles) {
Claims claims = Jwts.claims().setSubject(username);
claims.put("auth", roles.stream().map(role -> new SimpleGrantedAuthority(role.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliseconds);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(validity)
.signWith(getSecretKey())
.compact();
}
public Authentication getAuthentication(String token) {
UserDetails userDetails = new User(getUsername(token), "", getAuthorities(token));
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
private String getUsername(String token) {
return Jwts.parserBuilder().setSigningKey(getSecretKey()).build().parseClaimsJws(token).getBody().getSubject();
}
private List<GrantedAuthority> getAuthorities(String token) {
Claims claims = Jwts.parserBuilder()
.setSigningKey(getSecretKey())
.build()
.parseClaimsJws(token)
.getBody();
List<LinkedHashMap<String, String>> roles = (List<LinkedHashMap<String, String>>) claims.get("auth");
return roles.stream().map(role -> new SimpleGrantedAuthority(role.get("authority"))).collect(Collectors.toList());
}
public boolean validateToken(String token) {
try {
Jwts.parserBuilder().setSigningKey(getSecretKey()).build().parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
e.printStackTrace();
return false;
}
}
public String resolveToken(HttpServletRequest req) {
String bearerToken = req.getHeader("Authorization");
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
}
```
最后,需要把上述过滤器类和提供者类添加到Spring Security的配置中:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/v1/auth/login").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new JwtTokenAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
}
@Bean
public UserDetailsService userDetailsService() {
return new UserServiceImpl();
}
}
```
以上代码用来实现Spring Security校验JWT Token的功能,提供了创建Token、校验Token和获取Token中存储的用户和权限信息等相关方法。您可以根据您的实际需求进行修改和调整。
阅读全文