I have a Spring Boot REST API that is authenticating via JWT. My issue is that I have configured Spring Security to allow unrestricted access to the the path used to authenticate /auth/token
, but it is still hitting my security filter when it shouldn't be. Not sure where I've got wrong here any advice is greatly appropriated
The security config
public class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder)
throws Exception {
authenticationManagerBuilder
.userDetailsService(this.userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JwtAuthenticationFilter authenticationTokenFilter() throws Exception {
return new JwtAuthenticationFilter();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/auth/token").permitAll() // do not authenticate
.anyRequest().authenticated()
// TODO: configure
.cors()
.and()
// TODO enable and configure
.csrf().disable()
// Unauthorized request handler
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// Keep application security stateless
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// JWT security filter
httpSecurity.addFilterBefore(authenticationTokenFilter(),
UsernamePasswordAuthenticationFilter.class);
// Disable page caching to prevent cached REST responses
httpSecurity.headers().cacheControl();
}
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity.ignoring().antMatchers(HttpMethod.POST, "/auth/token");
}
}
the filter
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
// this runs
}
}
The controller
@RestController
public class AuthenticationController {
// Authenticate user
@RequestMapping(value = "/auth/token", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(HttpServletResponse response,
@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
// never gets to run
}
}