当前位置:   article > 正文

SpringBoot实现生成验证码功能_springboot验证码生成

springboot验证码生成

利用kaptcha生成验证码,并转化为base64回传给前台

pom.xml

  1. <dependency>
  2. <groupId>com.github.penggle</groupId>
  3. <artifactId>kaptcha</artifactId>
  4. <version>2.3.2</version>
  5. </dependency>
KaptchaConfig配置文件
  1. @Configuration
  2. public class KaptchaConfig {
  3. @Bean
  4. public Producer kaptcha() {
  5. Properties properties = new Properties();
  6. properties.setProperty("kaptcha.image.width", "150");
  7. properties.setProperty("kaptcha.image.height", "50");
  8. properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
  9. properties.setProperty("kaptcha.textproducer.char.length", "4");
  10. Config config = new Config(properties);
  11. DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
  12. defaultKaptcha.setConfig(config);
  13. return defaultKaptcha;
  14. }
  15. }

controller前端获取base64接口,可将图片从存储在session转为存在redis,可实现设置过期时间

  1. @GetMapping("/vc.jpg")
  2. public String getVerifyCode(HttpSession session) throws IOException {
  3. //1.生成验证码
  4. String text = producer.createText();
  5. //2.放入 session redis 实现
  6. session.setAttribute("kaptcha", text);
  7. //3.生成图片
  8. BufferedImage bi = producer.createImage(text);
  9. FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
  10. ImageIO.write(bi, "jpg", fos);
  11. //4.返回 base64
  12. return Base64.encodeBase64String(fos.toByteArray());
  13. }

以下为整合springsecurity后,loginfilter过滤器

  1. public class LoginKaptchaFilter extends UsernamePasswordAuthenticationFilter {
  2. private static final String SPRING_SECURITY_FORM_KAPTCHA_KEY = "kaptcha";
  3. private String kaptchaParamter = SPRING_SECURITY_FORM_KAPTCHA_KEY;
  4. public String getKaptchaParamter() {
  5. return kaptchaParamter;
  6. }
  7. public void setKaptchaParamter(String kaptchaParamter) {
  8. this.kaptchaParamter = kaptchaParamter;
  9. }
  10. @Override
  11. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  12. if (!request.getMethod().equals("POST")) {
  13. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  14. }
  15. try {
  16. Map<String,String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
  17. String kaptcha = map.get(getKaptchaParamter());
  18. String username = map.get(getUsernameParameter());
  19. String password = map.get(getPasswordParameter());
  20. String sessionVerifyCode = (String) request.getSession().getAttribute("kaptcha");
  21. if(kaptcha.equalsIgnoreCase(sessionVerifyCode)){
  22. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
  23. // Allow subclasses to set the "details" property
  24. setDetails(request, authRequest);
  25. return this.getAuthenticationManager().authenticate(authRequest);
  26. }
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. throw new KaptchaNotMatchException("验证码不匹配!");
  31. }
  32. }

自定义认证异常类,用来替换SecurityConfig中的configure(HttpSecurity http)中的异常处理

  1. //自定义验证码认证异常
  2. public class KaptchaNotMatchException extends AuthenticationException {
  3. public KaptchaNotMatchException(String msg) {
  4. super(msg);
  5. }
  6. public KaptchaNotMatchException(String msg, Throwable cause) {
  7. super(msg, cause);
  8. }
  9. }

SecurityConfig

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Bean
  4. public UserDetailsService myUserDetailsService(){
  5. InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
  6. inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin").build());
  7. return inMemoryUserDetailsManager;
  8. }
  9. @Override
  10. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  11. auth.userDetailsService(myUserDetailsService());
  12. }
  13. @Override
  14. @Bean
  15. public AuthenticationManager authenticationManagerBean() throws Exception {
  16. return super.authenticationManagerBean();
  17. }
  18. @Override
  19. protected void configure(HttpSecurity http) throws Exception {
  20. http.authorizeRequests()
  21. .mvcMatchers("/vc.jpg").permitAll()
  22. .anyRequest().authenticated()
  23. .and()
  24. .formLogin()
  25. .and()
  26. .exceptionHandling()
  27. .authenticationEntryPoint(new AuthenticationEntryPoint() {
  28. @Override
  29. public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
  30. response.setStatus(HttpStatus.UNAUTHORIZED.value());
  31. response.setContentType("application/json;charset=UTF-8");
  32. response.getWriter().println("请先认证!");
  33. }
  34. })
  35. .and()
  36. .csrf().disable();
  37. http.addFilterAt(loginKaptchaFilter(), UsernamePasswordAuthenticationFilter.class);
  38. }
  39. @Bean
  40. public LoginKaptchaFilter loginKaptchaFilter(){
  41. LoginKaptchaFilter loginKaptchaFilter = new LoginKaptchaFilter();
  42. loginKaptchaFilter.setFilterProcessesUrl("/login");
  43. try {
  44. loginKaptchaFilter.setAuthenticationManager(authenticationManagerBean());
  45. loginKaptchaFilter.setUsernameParameter("username");
  46. loginKaptchaFilter.setPasswordParameter("password");
  47. loginKaptchaFilter.setKaptchaParamter("kap");
  48. loginKaptchaFilter.setAuthenticationSuccessHandler((req,resp,auth)->{
  49. HashMap<Object, Object> map = new HashMap<>();
  50. map.put("msg",auth.getAuthorities()+"用户已登录");
  51. resp.setContentType("application/json;charset=UTF-8");
  52. String s = new ObjectMapper().writeValueAsString(map);
  53. resp.getWriter().println(s);
  54. });
  55. loginKaptchaFilter.setAuthenticationFailureHandler((req,resp,exception)->{
  56. HashMap<Object, Object> map = new HashMap<>();
  57. map.put("msg","登陆失败"+exception.getMessage());
  58. resp.setContentType("application/json;charset=UTF-8");
  59. ObjectMapper mapper = new ObjectMapper();
  60. String s = mapper.writeValueAsString(map);
  61. resp.getWriter().println(s);
  62. });
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }
  66. return loginKaptchaFilter;
  67. }
  68. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/914783
推荐阅读
相关标签
  

闽ICP备14008679号