re: Spring Security with JWT VIEW POST

FULL DISCUSSION
 

In JwtAuthenticationFilter, method attemptAuthentication, the authentication data (username and password) are got from request URL. I need that the username and password got from request body (example JSON: { "username": "john", "password":"mysecret" }). How can I made this?

 

It's very simple. You just need to update JwtAuthenticationFilter class to parse received JSON data.

Example:

// POJO with your login data
public class LoginData {
    private String username;
    private String password;
    /* getters, setters */
}
// JwtAuthenticationFilter.java
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
    var loginData = parseLoginData(request);
    var authenticationToken = new UsernamePasswordAuthenticationToken(loginData.getUsername(), loginData.getPassword());

    return authenticationManager.authenticate(authenticationToken);
}

private LoginData parseLoginData(HttpServletRequest request) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(request.getInputStream(), LoginData.class);
    } catch (IOException exception) {
        // Return empty "invalid" login data
        return new LoginData();
    }
}
code of conduct - report abuse