上QQ阅读APP看书,第一时间看更新
Which authentication method to use?
We have covered the three main methods of authenticating, so which one is the best? Like all solutions, each comes with its pros and cons. You can find a summary of when to use a specific type of authentication by referring to the following list:
- SecurityContextHolder: Interacting directly with SecurityContextHolder is certainly the easiest way of authenticating a user. It works well when you are authenticating a newly created user or authenticating in an unconventional way. By using SecurityContextHolder directly, we do not have to interact with so many Spring Security layers. The downside is that we do not get some of the more advanced features that Spring Security provides automatically. For example, if we want to send the user to the previously requested page after logging in, we would have to manually integrate that into our controller.
- UserDetailsService: Creating a custom UserDetailsService object is an easy mechanism that allows for Spring Security to make security decisions based on our custom domain model. It also provides a mechanism to hook into other Spring Security features. For example, Spring Security requires UserDetailsService in order to use the built-in remember-me support covered in Chapter 7, Remember-Me Services. The UserDetailsService object does not work when authentication is not based on a username and password.
- AuthenticationProvider: This is the most flexible method for extending Spring Security. It allows a user to authenticate with any parameters that we wish. However, if we wish to leverage features such as Spring Security's remember-me, we will still need UserDetailsService.