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

How to realize the function of login and logout in springsecurity

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how to achieve login and logout function in springsecurity. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1. Introduce maven dependency

Org.springframework.boot spring-boot-starter-security

2. Security configuration class describes login method, login page, which url needs authentication, injection login failure / success filter

@ Configurationpublic class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {/ * inject Security attribute class configuration * / @ Autowired private SecurityProperties securityProperties; / * inject custom login success handling class * / @ Autowired private MyAuthenticationSuccessHandler mySuccessHandler; / * inject custom login failure handling class * / @ Autowired private MyAuthenticationFailHandler myFailHandler / * override the method in the PasswordEncoder interface. Instantiate the encryption policy * @ return and return the BCrypt encryption policy * / @ Bean public PasswordEncoder passwordEncoder () {return new BCryptPasswordEncoder ();} @ Override protected void configure (HttpSecurity http) throws Exception {/ / the successful login page address String redirectUrl = securityProperties.getLoginPage () / / basic login method / / http.httpBasic () / / form login method http.formLogin () .loginPage ("/ authentication/require") / / loginProcessingUrl ("/ authentication/form") .loginProcessingUrl ("/ authentication/form") .login Handler (mySuccessHandler) .failureH andler (myFailHandler) .and () / request authorization .authorizeRequests () / / url .antMatrices ("/ authentication/*") that does not require permission authentication RedirectUrl) .permitAll () / any request .anyRequest () / requires authentication .authenticated () .and () / / turns off cross-site request protection .csrf () .disable () / / default logout address: / logout http.logout (). / / Page logoutSuccessUrl ("/ authentication/require") that jumps after logout;}

3. Custom login success and failure processors

(1) logging in successfully

@ Component@Slf4jpublic class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {@ Override public void onAuthenticationSuccess (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {logger.info ("login success"); / / return authention information in json format to httpServletResponse.setContentType ("application/json;charset=UTF-8"); httpServletResponse.getWriter () .write ("login success");}}

(2) login failed

@ Component@Slf4jpublic class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {@ Override public void onAuthenticationFailure (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {logger.info ("login failure"); / / set the status code httpServletResponse.setStatus (500); / / package the login failure information into json format and return httpServletResponse.setContentType ("application/json;charset=UTF-8"); httpServletResponse.getWriter () .write ("login failure:" + e.getMessage ());}}

4. UserDetail class loads user data and returns UserDetail instance (which contains user information)

@ Component@Slf4jpublic class MyUserDetailsService implements UserDetailsService {@ Autowired private PasswordEncoder passwordEncoder; / * according to login * @ param username * @ return * @ throws UsernameNotFoundException * / @ Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {log.info ("login user name:" + username); String password = passwordEncoder.encode ("123456") / / User three parameters (username + password + permission) / / based on the found user information, determine whether the user is frozen log.info ("database password:" + password); return new User (username,password, AuthorityUtils.commaSeparatedStringToAuthorityList ("admin"));}}

5. Login path request class, .loginPage ("/ authentication/require")

@ RestController@Slf4j@ResponseStatus (code = HttpStatus.UNAUTHORIZED) public class BrowerSecurityController {/ * cache the current request in session * / private RequestCache requestCache = new HttpSessionRequestCache (); / * * redirect policy * / private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy (); / * * inject Security attribute class configuration * / @ Autowired private SecurityProperties securityProperties / * Redirect here when authentication is required * / @ RequestMapping ("/ authentication/require") public SimpleResponse requireAuthentication (HttpServletRequest request, HttpServletResponse response) throws IOException {/ / get the request object SavedRequest savedRequest = requestCache.getRequest (request, response); if (savedRequest! = null) {/ / get the jump url String targetUrl = savedRequest.getRedirectUrl (); log.info ("the request that triggered the jump is:" + targetUrl) / / determine whether the targetUrl ends with .html, if yes: jump to the login page (return view) if (StringUtils.endsWithIgnoreCase (targetUrl, ".html")) {String redirectUrl = securityProperties.getLoginPage (); redirectStrategy.sendRedirect (request,response,redirectUrl);}} / / if not, return a json string return new SimpleResponse ("the accessed service requires authentication, please guide the user to the login page");}

This is the end of this article on "how to achieve login and logout in springsecurity". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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

Development

Wechat

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

12
Report