Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What does the Spring security custom login look like after a successful login?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Spring security custom login after the success of the process is what kind of, I believe that many inexperienced people are helpless about this, this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Let's talk about how to customize the processing logic after successful login. Let's review what spring security does for us by default after a successful login: if we don't log in, we directly access the resources in the app, and the page will automatically jump to the login page; when the login is successful, the page will automatically redirect to the url I requested before logging in.

How to change the default processing result after successful login

For example, if we want to respond to a json string (including a prompt message such as "login successful", a response code, and a jump url) to the front end after successful login. What should I do?

Step 1

First copy the project Spring-security-02 from the previous section and rename it Spring-security-03. The maven dependency does not need to change, as follows:

org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-web Step 2

Define the processing class GoAuthenticationSuccessHandler after successful login

/** * Custom login success processing class */ [@Component](https://my.oschina.net/u/3907912) public class GoAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Autowired private ObjectMapper objectMapper; /** * {"code":200,"message":"operation successful","data":"login successful"} * [@param](https://my.oschina.net/u/2303379) request * [@param](https://my.oschina.net/u/2303379) response * [@param](https://my.oschina.net/u/2303379) authentication * @throws IOException * @throws ServletException */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { response.setHeader("Content-Type", "application/json;charset=utf-8"); response.getWriter().print(objectMapper.writeValueAsString(CommonResult.success("Login succeeded"))); response.getWriter().flush(); } Step 2

In the WebSecurityConfig configuration class, inject dependencies for custom processing classes:

@Autowiredprivate GoAuthenticationSuccessHandler successHandler;@Autowiredprivate GoAuthenticationFailureHandler failureHandler; Step 3

In the protected void configure(HttpSecurity http) method, append the following code:

//these are already there http.formLogin() The requested URL/loginPage.html was not found on this server. .loginProcessingUrl("/form/login")//custom login action, name any //The following are new additions .successHandler(successHandler)//custom login success handler class .failureHandler(failureHandler);//custom login failure handler class summary

From the above code we can see that two new configurations have been added. A processing class has been injected into the successHandler and failureHandler methods respectively. We focus on the GoAuthenticationSuccessHandler processing class. By rewriting the AuthenticationSuccessHandler method, we respond to a json to the front end. failureHandler is to do some processing when the login fails, where we will respond to the login failure message to the front end. We can customize these responses. You can choose whether you need to customize these processing classes according to your actual needs.

extended

Looking back, if the user did not log in to directly access our application resources, it will automatically jump to the login page. If the login is successful, it will give us an English prompt to access the url without permission. We can still customize these. For example, when we do not log in, we prompt the front end that "the user does not log in"; when we do not have permission, we prompt the front end that "the user does not have permission."

Step 1

Define two processing classes GoAuthenticationEntryPoint and GoAccessDeniedHandler

`

/** * Custom login or token invalidation class */@Componentpublic class GoAuthenticationEntryPoint implements AuthenticationEntryPoint { @Autowired private ObjectMapper objectMapper; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.getWriter().println(objectMapper.writeValueAsString(CommonResult.unauthorized(authException.getMessage()))); response.getWriter().flush(); }}/** * Custom No Access Handling Class */@Componentpublic class GoAccessDeniedHandler implements AccessDeniedHandler { @Autowired private ObjectMapper objectMapper; /** * @param request * @param response * @param e * @throws IOException * @throws ServletException * * @return {"code":403,"message":"no relevant permissions","data":"Access is denied"} */ @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException { response.setHeader("Content-Type", "application/json;charset=utf-8"); response.getWriter().print(objectMapper.writeValueAsString(CommonResult.forbidden(e.getMessage()))); response.getWriter().flush(); }}

`

Step 2

Inject two custom processing classes into the WebSecurityConfig class

` @Autowired private GoAccessDeniedHandler accessDeniedHandler;

@Autowiredprivate GoAuthenticationEntryPoint entryPoint;

`

Step 3

Open the WebSecurityConfig configuration class and append the following code to the configure method:

@Override protected void configure(HttpSecurity http) throws Exception { //omitting part of the code http.exceptionHandling() .accessDeniedHandler(accessDeniedHandler)//user does not have access to handler.authenticationEntryPoint(entryPoint);//user does not log in handler}

Above we define a total of four processing classes, which act on the following four situations:

When we log in successfully.

When we failed to log in.

When we do not log in to access resources.

When we access resources we don't have permission to access.

After reading the above content, do you know what kind of method Spring security custom login successfully handles? If you still want to learn more skills or want to know more related content, welcome to pay attention to the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report