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 are the ways to add CAPTCHA to Spring Security

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

Share

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

This article mainly introduces "what are the ways for Spring Security to add CAPTCHA". In daily operation, I believe that many people have doubts about the way Spring Security adds CAPTCHA. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the question of "what is the way of adding CAPTCHA to Spring Security?" Next, please follow the editor to study!

Catalogue

I. Custom authentication logic

II. Custom filter

I. Custom authentication logic

Generate CAPTCHA tool

Com.github.penggle kaptcha 2.3.2

Add Kaptcha configuration

@ Configurationpublic class KaptchaConfig {@ Bean Producer kaptcha () {Properties properties = new Properties (); properties.setProperty ("kaptcha.image.width", "150th"); properties.setProperty ("kaptcha.image.height", "50"); properties.setProperty ("kaptcha.textproducer.char.string", "0123456789"); properties.setProperty ("kaptcha.textproducer.char.length", "4") Config config = new Config (properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha (); defaultKaptcha.setConfig (config); return defaultKaptcha;}}

Generate CAPTCHA text and put it into HttpSession

The picture is generated according to the CAPTCHA text and written to the front end through the IO stream.

@ RestControllerpublic class LoginController {@ Autowired Producer producer; @ GetMapping ("/ vc.jpg") public void getVerifyCode (HttpServletResponse resp, HttpSession session) throws IOException {resp.setContentType ("image/jpeg"); String text = producer.createText (); session.setAttribute ("kaptcha", text); BufferedImage image = producer.createImage (text) Try (ServletOutputStream out = resp.getOutputStream ()) {ImageIO.write (image, "jpg", out);} @ RequestMapping ("/ index") public String index () {return "login success";} @ RequestMapping ("/ hello") public String hello () {return "hello spring security";}}

Form form

Log in to # login. Container # login-row # login-column # login-box {border: 1px solid # 9C9C9C; background-color: # EAEAEA } login user name:

Password:

CAPTCHA:

The CAPTCHA image address is the CAPTCHA interface address we defined in Controller.

Authentication is done by the authenticate method of AuthenticationProvider, so the CAPTCHA can be completed before:

Public class KaptchaAuthenticationProvider extends DaoAuthenticationProvider {@ Override public Authentication authenticate (Authentication authentication) throws AuthenticationException {HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes ()) .getRequest (); String kaptcha = req.getParameter ("kaptcha"); String sessionKaptcha = (String) req.getSession () .getAttribute ("kaptcha"); if (kaptcha! = null & & sessionKaptcha! = null & & kaptcha.equalsIgnoreCase (sessionKaptcha)) {return super.authenticate (authentication) } throw new AuthenticationServiceException ("CAPTCHA input error");}}

Configure AuthenticationManager:

@ Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {@ Bean AuthenticationProvider kaptchaAuthenticationProvider () {InMemoryUserDetailsManager users = new InMemoryUserDetailsManager (User.builder () .username ("xiepanapn") .password ("{noop} 123") .roles (" admin ") .build (); KaptchaAuthenticationProvider provider = new KaptchaAuthenticationProvider (); provider.setUserDetailsService (users); return provider } @ Override @ Bean public AuthenticationManager authenticationManagerBean () throws Exception {ProviderManager manager = new ProviderManager (kaptchaAuthenticationProvider ()); return manager } @ Override protected void configure (HttpSecurity http) throws Exception {http.authorizeRequests () .antMatch ("/ vc.jpg"). PermitAll () .anyRequest () .authenticated () .and () .formLogin () .log inPage ("/ mylogin.html") .loginProcessingUrl ("/ DoLogin ") .defaultSuccessUrl (" / index.html ") .failureForwardUrl (" / mylogin.html ") .usernameParameter (" uname ") .passwordParameter (" passwd ") .permitAll () .and () .csrf () .disable () }}

Configure the data source provided by UserDetailsService

Provide AuthenticationProvider instance and configure UserDetailsService

Override the authenticationManagerBean method to provide your own ProviderManager and customize the AuthenticationManager instance.

II. Custom filter

LoginFilter inherits the UsernamePasswordAuthenticationFilter override attemptAuthentication method:

Public class LoginFilter extends UsernamePasswordAuthenticationFilter {@ Override public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {if (! request.getMethod () .equals ("POST")) {throw new AuthenticationServiceException ("Authentication method not supported:" + request.getMethod ());} String kaptcha = request.getParameter ("kaptcha"); String sessionKaptcha = (String) request.getSession () .getAttribute ("kaptcha") If (! StringUtils.isEmpty (kaptcha) & &! StringUtils.isEmpty (sessionKaptcha) & & kaptcha.equalsIgnoreCase (sessionKaptcha)) {return super.attemptAuthentication (request, response);} throw new AuthenticationServiceException ("CAPTCHA input error");}}

Configure LoginFilter in SecurityConfig

@ Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication () .withUser ("javaboy") .password ("{noop} 123") .password ("admin");} @ Override @ Bean public AuthenticationManager authenticationManagerBean () throws Exception {return super.authenticationManagerBean () } @ Bean LoginFilter loginFilter () throws Exception {LoginFilter loginFilter = new LoginFilter (); loginFilter.setFilterProcessesUrl ("/ doLogin"); loginFilter.setAuthenticationManager (authenticationManagerBean ()); loginFilter.setAuthenticationSuccessHandler (new SimpleUrlAuthenticationSuccessHandler ("/ hello")); loginFilter.setAuthenticationFailureHandler (new SimpleUrlAuthenticationFailureHandler ("/ mylogin.html")); return loginFilter } @ Override protected void configure (HttpSecurity http) throws Exception {http.authorizeRequests () .antMatch ("/ vc.jpg") .permitAll () .anyRequest () .authenticated () .and () .formLogin () .log inPage ("/ mylogin.html") .permitAll () .and () .csrf () .disable () Http.addFilterAt (loginFilter (), UsernamePasswordAuthenticationFilter.class);}}

Obviously, the second one is relatively simple.

At this point, the study of "what are the ways to add CAPTCHA to Spring Security" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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