Read Body from HttpServletRequest in Spring Filter

This blog post is a short example of how you can read the body of HTTP request in the filter class of your Spring Boot application.

Let’s assume you have created an AuthenticationFilter class that needs to ready username and password when a request to /login URL path is performed. The AuthenticationFilter class will need to extend UsernamePasswordAuthenticationFilter and override the attemptAuthentication(HttpServletRequest req, HttpServletResponse res) method.

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private final AuthenticationManager authenticationManager;

    public AuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
                                                HttpServletResponse res) throws AuthenticationException {
         // Code
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

       // Code 
    }

The attemptAuthentication() method will be used to read HTTP request body and validate username and password.

Reading Body

To read HTTP request body from HttpServletRequest object, you can use the following code snippet.

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
                                                HttpServletResponse res) throws AuthenticationException {
        try {
            byte[] inputStreamBytes = StreamUtils.copyToByteArray(req.getInputStream());
            Map<String, String> jsonRequest = new ObjectMapper().readValue(inputStreamBytes, Map.class);

            String requestBodyJsonString = jsonRequest.get("body");

            // other code
             

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

You can then convert the JSON string from request body into an object of any class. Lets assume that we need to convert the JSON object from request body into an object of the following class.

public class UserLoginRequestModel {
    private String email;
    private String password;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

In this case the attemptAuthentication() method will look like this:

@Override
public Authentication attemptAuthentication(HttpServletRequest req,
                                            HttpServletResponse res) throws AuthenticationException {
    try {
        byte[] inputStreamBytes = StreamUtils.copyToByteArray(req.getInputStream());
        Map<String, String> jsonRequest = new ObjectMapper().readValue(inputStreamBytes, Map.class);

        UserLoginRequestModel creds = new ObjectMapper()
                .readValue(jsonRequest.get("body"), UserLoginRequestModel.class);

        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        creds.getEmail(),
                        creds.getPassword(),
                        new ArrayList<>())
        );

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

 

Happy learning!