Implementing authentication in the backend

As you can see in the commit record in Figure 10.15, the authentication service in the frontend sends a HTTP POST request to /api/authentications. This is different from the standard way of using Spring Security for authentication. As mentioned earlier, by default, Spring Security will process the login request at the /login path using HTTP POST method and we expect the content type of the request to be application/x-www-form-urlencoded. After successful authentication, by default, Spring Security will redirect the user to a target page. Usually, it is the home page. The redirection will be done using the sendRedirect() method of an instance of HttpServletResponse. When the authentication fails, it redirects the user to an error page. This default behavior of Spring Security won't work with our frontend login process. In the frontend, we send a login request using Ajax with content type application/json and expect a JSON response. 

We will need to customize the authentication part in Spring Security in order to make the backend work with the frontend. Here is what we will do:

  • Add AuthenticationFilter to replace Spring Security's built-in UsernamePasswordAuthenticationFilter so that we can retrieve the username and the password from a JSON format request body
  • Implement the UserDetailsService interface to provide the ability to load a user by either username or email address
  • Implement the UserDetails interface to control what will be saved in an authenticated Authentication that will be saved in HttpSession between requests
  • Add AuthenticationSuccessHandler to send the authentication success result in JSON
  • Add AuthenticationFailureHandler to send the authentication failure result in JSON
  • Add LogoutSuccessHandler to send the logout success result in JSON

This time we will skip introducing unit tests. You can find the details in the commit record. We will focus on the implementation of AuthenticationFilterUserDetailsService, and UserDetails

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

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