javaspringspring-securityspring-cloud-security

How to override the response body of AuthenticationFailure using AbstractPreAuthenticatedProcessingFilter?


I'm using a Custom Filter to make the request Authetincation. Configuring the AutheticationFailureHandler, I want put the message error content, but it is attached to a existent default content, my goal is put together on the same body or just a new one.

Handler impl.:

 protected void configure(HttpSecurity httpSecurity) throws Exception {
APIKeyAuthFilter apiKeyAuthFilter = new APIKeyAuthFilter(HEADER_USER_AGENT, HEADER_APIKEY);

apiKeyAuthFilter.setAuthenticationFailureHandler((request, response, exception) -> {
                if(exception.getMessage().equals(MESSAGE_USER_AGENT_NOT_FOUND)) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("message",MESSAGE_USER_AGENT_NOT_FOUND);
                    response.getOutputStream()
                            .println(objectMapper.writeValueAsString(data));
                }
            });
}

Response body:

{
    "message": "User-Agent not found."
}
{
    "timestamp": "2020-07-16T16:26:59.438+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/api"
}

Like shows, this is returning two JSON contents. How I set just one or append to existent?

Whole code:

public class APIKeyAuthFilter extends AbstractPreAuthenticatedProcessingFilter {

    private String userAgentRequestHeader;
    private String apiKeyRequestHeader;

    public APIKeyAuthFilter(String userAgentRequestHeader, String apiKeyRequestHeader) {
        this.userAgentRequestHeader = userAgentRequestHeader;
        this.apiKeyRequestHeader = apiKeyRequestHeader;
    }

    @Override
    protected RequestAuthVo getPreAuthenticatedPrincipal(HttpServletRequest request) {
        String userAgent = request.getHeader(userAgentRequestHeader);
        String apiKey = request.getHeader(apiKeyRequestHeader);
        RequestAuthVo requestAuthVo = new RequestAuthVo(userAgent,apiKey);
        return requestAuthVo;
    }

    @Override
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
        return "N/A";
    }

}

Configure:

        @Override
        @Order(2)
        protected void configure(HttpSecurity httpSecurity) throws Exception {
                APIKeyAuthFilter apiKeyAuthFilter = new APIKeyAuthFilter(HEADER_USER_AGENT, HEADER_APIKEY);

            apiKeyAuthFilter.setAuthenticationManager(authentication -> {
                RequestAuthVo requestAuthVo = (RequestAuthVo) authentication.getPrincipal();

                if (!mapAuths.containsKey(requestAuthVo.getUserAgent())) {
                    throw new UserAgentNotFoundException(MESSAGE_USER_AGENT_NOT_FOUND);
                }

                if(mapAuths.containsKey(requestAuthVo.getUserAgent()) && mapAuths.get(requestAuthVo.getUserAgent()).equals(requestAuthVo.getApiKey())) {
                    authentication.setAuthenticated(true);
                    return authentication;
                }

                return authentication;
            });

            ObjectMapper objectMapper = new ObjectMapper();

 apiKeyAuthFilter.setAuthenticationFailureHandler((request, response, exception) -> {
                    if(exception.getMessage().equals(MESSAGE_USER_AGENT_NOT_FOUND)) {
                        Map<String, Object> data = new HashMap<>();
                        data.put("message",MESSAGE_USER_AGENT_NOT_FOUND);
                        response.getOutputStream()
                                .println(objectMapper.writeValueAsString(data));
                    }
                });

            httpSecurity.antMatcher("/**").
                    csrf().disable().
                    sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
                    and()
                    .addFilter(apiKeyAuthFilter).authorizeRequests().anyRequest().authenticated();
        }

    }

Solution

  • Can you try this?

        apiKeyAuthFilter.setAuthenticationFailureHandler(
                (request, response, exception) -> {
            if(exception.getMessage().equals(MESSAGE_USER_AGENT_NOT_FOUND)) {
                Map<String, Object> data = new HashMap<>();
                data.put("message",MESSAGE_USER_AGENT_NOT_FOUND);
                request.setAttribute("AGENT_NOT_FOUND", 
                                     objectMapper.writeValueAsString(data));
            }
        });
    
        http.exceptionHandling()
          .authenticationEntryPoint((request, response, e) ->
          {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            String value = request.getAttribute("AGENT_NOT_FOUND").toString();
            response.getWriter().write(value);
          });
        }