I have
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/v1/account/import").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
I want that all users can come to /api/v1/account/import
without any JWT token check. For all other endpoints I want a JWT token check in class JWTAuthenticationFilter
. I tried many different scenarios but all failed. I always get to JWTAuthenticationFilter
. I don't want to get to JWTAuthenticationFilter
if I go to /api/v1/account/import
.
My controller:
@RestController
@RequestMapping(value = "/api/v1/account")
public class AccountController {
private final AccountService accountService;
public AccountController(final AccountService accountService) {
this.accountService = accountService;
}
@PostMapping(path = "/import")
@ResponseStatus(HttpStatus.ACCEPTED)
public String importAccount(@Valid @RequestBody final ImportAccountDto importAccountDto) {
return this.accountService.importAccount(importAccountDto);
}
My JWT filter:
public class JWTAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
final String token = request.getHeader("Authorization");
final JJWTService jjwtService = new JJWTService();
if (token == null || !jjwtService.parseJWTToken(token)) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} else {
filterChain.doFilter(req, res);
}
}
My test:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AccountIT {
@Autowired
MockMvc mockMvc;
@Autowired
private AccountRepository accountRepository;
@Test
public void importAccount() throws Exception {
this.mockMvc.perform(post("/api/v1/account/import")
.contentType(MediaType.APPLICATION_JSON)
.content(toJson(importAccountDto)))
.andExpect(status().isAccepted())
.andReturn();
}