用springsecurity写一个登陆过滤器,包含token校验
时间: 2023-07-18 09:17:00 浏览: 99
springSecurity
好的,下面是一个简单的基于Spring Security的登录过滤器示例,包含token校验:
```java
public class TokenAuthenticationFilter extends OncePerRequestFilter {
private final TokenService tokenService;
public TokenAuthenticationFilter(TokenService tokenService) {
this.tokenService = tokenService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = getTokenFromRequest(request);
if (StringUtils.hasText(token) && tokenService.validateToken(token)) {
Authentication authentication = tokenService.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
private String getTokenFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
}
```
这个过滤器会从请求头中获取token,并通过TokenService进行校验。如果token有效,则将认证信息放入SecurityContextHolder中,否则继续执行过滤器链。
在配置Spring Security时,需要将该过滤器添加到过滤器链中:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final TokenService tokenService;
public SecurityConfig(TokenService tokenService) {
this.tokenService = tokenService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new TokenAuthenticationFilter(tokenService), UsernamePasswordAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
```
在配置中,我们将TokenAuthenticationFilter添加到了UsernamePasswordAuthenticationFilter之前,并且设置了sessionCreationPolicy为STATELESS,使得每次请求都需要进行认证。
阅读全文