Implementing AuthenticationFilter

Spring Security is very flexible and highly customizable. We can replace the built-in implementation with our own implementation easily. We sometimes do not need to write everything from scratch because Spring Security does a very good job at abstraction. For our AuthenticationFilter implementation, we can extend from AbstractAuthenticationProcessingFilter, which is also the base class that the built-in UsernamePasswordAuthenticationFilter extends. 

Since AuthenticationFilter deals with API requests, we will put it inside the com.taskagile.web.apis.authenticate package. Here is how AuthenticationFilter looks:

...
public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter {
...
public AuthenticationFilter() {
super(new AntPathRequestMatcher("/api/authentications", "POST"));
}

@Override
public Authentication attemptAuthentication(HttpServletRequest
request, HttpServletResponse response)
throws AuthenticationException, IOException {

log.debug("Processing login request");

String requestBody = IOUtils.toString(request.getReader());
LoginRequest loginRequest = JsonUtils.toObject(requestBody,
LoginRequest.class);
if (loginRequest == null || loginRequest.isInvalid()) {
throw new InsufficientAuthenticationException("Invalid
authentication request");
}

UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(loginRequest.username,
loginRequest.password);
return this.getAuthenticationManager().authenticate(token);
}
...
}

As you can see, in the constructor, we specify that this filter will process the requests with the /api/registrations path in the HTTP POST method. In the attemptAuthentication() method, all we do is read the request body from request.getReader() into a string, which we expect to be in JSON format. IOUtils is a utility class from the Apache Commons IO project. Then, we use JsonUtils to convert the JSON string into an instance of LoginRequestJsonUtils is a utility class that we create to handle JSON string conversion. LoginRequest is a simple inner class of the filter and is only used for parsing the JSON string. 

After converting, we throw AuthenticationException when loginRequest is not valid, either because the request body is not in JSON format or is missing required fields. The exception thrown here will eventually be handled by AuthenticationFailureHandler we need to implement. When loginRequest is valid, we will create UsernamePasswordAuthenticationToken, which, as mentioned earlier, is an Authentication object, similar to the one shown on the left in Figure 10.11. We then invoke AuthenticationManager to take care of the actual authentication. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.39.60