0

What is the proper way to send back to client custom response in the case of an exception from a Spring filter? OR Is it possible at all?

I tried:

this @ControllerAdvice and @ExceptionHandler are out of rich with Filters

this response.sendError(status, msg); just does nothing

this absolutely no effect from these

and many many many other..

My security config:

@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain mySecurity(HttpSecurity http) throws Exception {
        http.requestMatchers((requests) -> requests.antMatchers("/**"))
                .authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll());
        http.csrf().disable();
        return http.build();
    }
}

The filter:

@Component
public final class MyFilter extends OncePerRequestFilter {

    private TypeA typeA;
    private TypeB typeB;

    public MyFilter(TypeA typeA, TypeB typeB) {
        this.typeA = typeA;
        this.typeB = typeB;
    }

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                                                                                  throws ServletException, IOException {
        if (request instanceof HttpServletRequest) {
            if (typeA.getCount() > 500 && typeB.getCount() > 400) {
                filterChain.doFilter(request, response);
            } else {
//                response.getWriter().write("some err");
//                response.sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized attempt.");
//                response.setStatus(HttpStatus.UNAUTHORIZED.value(), "Unauthorized .");
                throw new AccessDeniedException("Unauthorized attempt.");
            }
        }

    }

So - None of the above changes the default response:

{
    "timestamp": "2022-09-28T14:04:39.657+00:00",
    "status": 403,
    "error": "Forbidden",
    "path": "/api/some/path"
}

Is it possible to send back to client custom error message? I see a lot of people suggest Controller Exception Handling mechanisms, but they get in action only after the filter chain, when there is an exception from A CONTROLLER.

EDIT: PS: Please, do not mark my question as duplicate - there are tens of such questions - the answers are not working for me.

gai-jin
  • 653
  • 2
  • 10
  • 24
  • you are getting a 403 because your request most likely gets stopped by CORS – Toerktumlare Sep 28 '22 at 17:06
  • 1
    @Toerktumlare 403 is correct - this what I want in case of un-wanted request. I cannot customize the error message and this is the problem. Read the question – gai-jin Sep 29 '22 at 05:22
  • 1
    @Toerktumlare, of course that you're not obligated to do anything. I was making it clear that your suggestion, in the first comment, is wrong. – gai-jin Sep 29 '22 at 12:48

0 Answers0