1. Scenarios in which login results need to be customized
In my previous article, I did a source code analysis of the login authentication process. One of the most important is
- When we login successfully, it is carried out by AuthenticationSuccessHandler login processing result, jump to defaultSuccessUrl configuration by default path corresponding resource page (usually page index. The HTML).
- When we login failed, it is carried out by AuthenticationfailureHandler login processing result, jump to failureUrl configuration by default path corresponding resource page (usually login page to login. HTML).
However, in the process of Web application development, requirements are ever-changing, and sometimes we need to do personalized processing for login results, such as:
- We want different people to log in and see different home pages
- Our application is front – and back-separated, verifying that the response results in JSON data rather than a page jump
In each of these cases, using Spring Security as a Security framework requires you to use the knowledge learned in this section for custom login authentication results handling.
Second, custom login successful result processing
In order to meet the above requirements, how can we do it? Let’s explain this in the next section. AuthenticationSuccessHandler interface is provided in the Security authentication success processor interface, we only need to attain it. But generally speaking, we won’t realize AuthenticationSuccessHandler interface directly, instead of inheriting SavedRequestAwareAuthenticationSuccessHandler class, the class will remember the resource path users request last time, For example, when a user requests books.html and doesn’t log in, it is blocked to the login page. When you log in, you are automatically redirected to books.html instead of the main page.
@Component public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { / / in the application configuration file types are configured in the log in the JSON data response or page response @ Value (" ${spring. Security. Logintype} ") private String logintype; private static ObjectMapper objectMapper = new ObjectMapper(); @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { if (loginType.equalsIgnoreCase("JSON")) { response.setContentType("application/json; charset=UTF-8"); response.getWriter().write(objectMapper.writeValueAsString(AjaxResponse.success())); } else {/ / will help us to jump to the last page request. Super onAuthenticationSuccess (request, response, authentication); }}}Copy the code
- In the preceding custom login result processing, it applies to the application login result processing that is separated from the front and back ends of JSON and the application login result processing that is used to jump to the template page
- ObjectMapper is a class in Jackson, Spring Boot’s default integrated JSON data-processing library.
- AjaxResponse is a custom generic JSON data interface response class.
3. Handle the result of customized login failure
Here we also have no direct implementation AuthenticationFailureHandler interface, but SimpleUrlAuthenticationFailureHandler class inheritance. By default, this class implements the jump logic for login authentication failure, that is, return to the login page after a login failure. We can take advantage of this to simplify our code.
@Component public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { / / in the application configuration file types are configured in the log in the JSON data response or page response @ Value (" ${spring. Security. Logintype} ") private String logintype; private static ObjectMapper objectMapper = new ObjectMapper(); @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if (loginType.equalsIgnoreCase("JSON")) { response.setContentType("application/json; charset=UTF-8"); response.getWriter().write( objectMapper.writeValueAsString( AjaxResponse.error( new CustomException( Customexceptiontype. USER_INPUT_ERROR, "Incorrect username or password, please check and log in again ")))); } else { response.setContentType("text/html; charset=UTF-8"); super.onAuthenticationFailure(request, response, exception); }}}Copy the code
- The preceding custom login failure processing applies not only to the application login failure results that are separated from the JSON front and back ends, but also to the application login failure results that are redirected to the template page
- After the login fails, the login page is redirected to the default failureUrl.
4. Configure SecurityConfig
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Resource private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler; @Resource private MyAuthenticationFailureHandler myAuthenticationFailureHandler; @override protected void configure(HttpSecurity HTTP) throws Exception {http.csrf().disable() Later chapters will specifically explained. FormLogin () successHandler (myAuthenticationSuccessHandler). FailureHandler (myAuthenticationFailureHandler) DefaultSuccessUrl ("/index")// Default path to hop after successful login authentication. FailureUrl ("/login.html") // Login authentication is redirected page}Copy the code
- The custom AuthenticationSuccessHandler and AuthenticationFailureHandler into Spring Security configuration class
- Using FromLogin mode, configure successHandler and failureHandler.
- DefaultSuccessUrl and failureUrl are configured
We look forward to your attention
- The blogger has recently written a new book: “SpringBoot Series – Chapter 16, Verse 97.”
- This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.