I have a w760> boot rest api with jwt authentication. The problem is that I cannot get rid of the default 403 Access Denied rest answer, which looks like this:
{ "timestamp": 1516206966541, "status": 403, "error": "Forbidden", "message": "Access Denied", "path": "/api/items/2" }
I created a custom AccessDeniedHandler:
public class CustomAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest req, HttpServletResponse res, AccessDeniedException accessDeniedException) throws IOException, ServletException { ObjectMapper mapper = new ObjectMapper(); res.setContentType("application/json;charset=UTF-8"); res.setStatus(403); res.getWriter().write(mapper.writeValueAsString(new JsonResponse() .add("timestamp", System.currentTimeMillis()) .add("status", 403) .add("message", "Access denied"))); } }
and added it to the webconfig class
@EnableWebSecurity public class WebSecurity extends WebSecurityConfigurerAdapter { private UserDetailsService userDetailsService; private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired public WebSecurity(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) { this.userDetailsService = userDetailsService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override protected void configure(HttpSecurity http) throws Exception { http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.NEVER) .and() .csrf().disable() .authorizeRequests() .antMatchers(HttpMethod.POST, REGISTER_URL).permitAll() .anyRequest().authenticated() .and() .exceptionHandling().accessDeniedHandler(accessDeniedHandler()) .and() .addFilter(new JWTAuthenticationFilter(authenticationManager(), tokenProvider())) .addFilter(new JWTAuthorizationFilter(authenticationManager(), tokenProvider())); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } @Bean public TokenProvider tokenProvider(){ return new TokenProvider(); } @Bean public AccessDeniedHandler accessDeniedHandler(){ return new CustomAccessDeniedHandler(); } }
Despite this, I still get a default rejection response. When debugging, I realized that the handle method from the user exit was not even called. What's going on here?
source share