在项目中使用了为了使用spring security的token方式进行鉴权,继承了AbstractAuthenticationProcessingFilter来对请求拦截处理,如下:
public class JwtAuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter {
private SelectUserInfoWebService selectUserInfoWebService;
private CacheClient cacheClient;
public void setCacheClient(CacheClient cacheClient) {
this.cacheClient = cacheClient;
}
public void setSelectUserInfoWebService(SelectUserInfoWebService selectUserInfoWebService) {
this.selectUserInfoWebService = selectUserInfoWebService;
}
public JwtAuthenticationTokenFilter() {
super("/auth/**");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
//部分代码
另外需要一个集成WebSecurityConfigurerAdapter的配置类,如下,一开始是这样写的:
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 根据用户id获取用户信息
*/
@HSFConsumer(serviceGroup = Constants.AUTHORITY_SERVICE_GROUP,serviceVersion = Constants.SERVICE_VERSION)
private SelectUserInfoWebService selectUserInfoWebService;
@Autowired
private JwtAuthenticationEntryPoint entryPoint;
@Autowired
private CacheClient cacheClient;
@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilter() throws Exception {
JwtAuthenticationTokenFilter filter = new JwtAuthenticationTokenFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandlerImpl());
filter.setAuthenticationFailureHandler(new AuthenticationFailureHandlerImpl());
filter.setCacheClient(cacheClient);
filter.setSelectUserInfoWebService(selectUserInfoWebService);
return filter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers("/auth/**").authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(entryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl();
}
}
问题出现了,AuthenticationSuccessHandlerImpl是
AbstractAuthenticationProcessingFilter成功后的执行方法,如下:
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
System.out.println("Successfully Authentication");
}
}
发现,每次都执行了两次
后来发现是@Bean注解导致的,继承了AbstractAuthenticationProcessingFilter的JwtAuthenticationTokenFilter本来就会被加载,加了bean注解,会被加载两次,删除后就好了。。。。