I have a problem doing my first filter and checking the SecurityContextHolder.getContext (). GetAuthentication () returns null.
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ConfigSecurity extends WebSecurityConfigurerAdapter {
private final ApplicationUserService applicationUserService;
private final PasswordEncoder passwordEncoder;
private final TokenHeader tokenHeader;
private final UserService userService;
public ConfigSecurity(ApplicationUserService applicationUserService,
PasswordEncoder passwordEncoder,
TokenHeader tokenHeader,
UserService userService) {
this.applicationUserService = applicationUserService;
this.passwordEncoder = passwordEncoder;
this.tokenHeader = tokenHeader;
this.userService = userService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.formLogin().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/users/register").permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers(HttpMethod.POST, "/users/token/refresh").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.addFilterAfter(new TokenHeaderFilter(this.tokenHeader,this.userService),
BasicAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(this.applicationUserService);
provider.setPasswordEncoder(this.passwordEncoder);
return provider;
}
my filter
public class TokenHeaderFilter extends GenericFilterBean {
private final TokenHeader tokenHeader;
private final UserService userService;
@Autowired
public TokenHeaderFilter(TokenHeader tokenHeader, UserService userService) {
this.tokenHeader = tokenHeader;
this.userService = userService;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpServletResponse servletResponse = (HttpServletResponse) response;
String header = servletRequest.getHeader("Authorization");
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
System.out.println(authentication);
}
On Debug:
If you need me to show some more class, you can tell me and in the same way debug, this problem is already happening to me 3 times one day it works and for the other it stops working