验证图形验证码

图形验证码通常是用来防止恶意行为的,由于人眼阅读困难,因此机器也很难识别。为了防止用户利用机器人进行自动注册、登录和垃圾信息发布,许多网站采用验证码技术。验证码是将一串随机产生的数字或符号生成为一张图片,图片中加入了一些干扰。目前有一些需要手动滑动的图形验证码,这种验证码可以使用专门的第三方平台,如极验(https://www.geetest.com/)。本次课程的主要讲解内容是关于图形验证码。

Spring Security添加验证码大致分为三个步骤:

根据随机数生成验证码图片;

将验证码图片显示在登录页面上;

在认证流程中加入验证码校验。

Spring Security的认证校验由UsernamePasswordAuthenticationFilter过滤器完成,因此我们的验证码校验逻辑应该放在这个过滤器之前。只有通过了验证码才能继续后续的操作。流程如下:先生成验证码图片,再在登录页面上显示,最后在认证流程中加入验证码校验逻辑。

下面是验证码生成类的示例代码:

package com.lagou.controller;

import com.lagou.domain.ImageCode;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.util.Random;

import java.util.concurrent.TimeUnit;

/**

 * 处理生成验证码的请求

 */

@RestController

@RequestMapping("/code")

public class ValidateCodeController {

    private static final String REDIS_KEY_IMAGE_CODE = "REDIS_KEY_IMAGE_CODE";

    private static final int EXPIRE_TIME = 60;  // 验证码有效时间 60s

    private final StringRedisTemplate stringRedisTemplate;

    @Autowired

    public ValidateCodeController(StringRedisTemplate stringRedisTemplate) {

        this.stringRedisTemplate = stringRedisTemplate;

    }

    @GetMapping("/image")

    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String remoteAddr = request.getRemoteAddr();

        ImageCode imageCode = generateImageCode();

        stringRedisTemplate.boundValueOps(REDIS_KEY_IMAGE_CODE + "-" + remoteAddr)

                .set(imageCode.getCode(), EXPIRE_TIME, TimeUnit.SECONDS);

        ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream());

    }

    /**

     * 生成验证码对象

     */

    private ImageCode generateImageCode() {

        int width = 100;    // 验证码图片宽度

        int height = 36;    // 验证码图片长度

        int length = 4;     // 验证码位数

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics g = image.getGraphics();

        Random random = new Random();

        g.setColor(getRandomColor(200, 250));

        g.fillRect(0, 0, width, height);

        g.setFont(new Font("Times New Roman", Font.ITALIC, 20));

        g.setColor(getRandomColor(160, 200));

        for (int i = 0; i < 155; i++) {

            int x = random.nextInt(width);

            int y = random.nextInt(height);

            int xl = random.nextInt(12);

            int yl = random.nextInt(12);

            g.drawLine(x, y, x + xl, y + yl);

        }

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; i++) {

            String rand = String.valueOf(random.nextInt(10));

            sb.append(rand);

            g.setColor(getRandomColor(20, 130));

            g.drawString(rand, 13 * i + 6, 16);

        }

        g.dispose();

        return new ImageCode(image, sb.toString());

    }

    /**

     * 获取随机颜色

     */

    private Color getRandomColor(int min, int max) {

        Random random = new Random();

        if (min > 255) {

            min = 255;

        }

        if (max > 255) {

            max = 255;

        }

        int r = min + random.nextInt(max - min);

        int g = min + random.nextInt(max - min);

        int b = min + random.nextInt(max - min);

        return new Color(r, g, b);

    }

}

package com.lagou.filter;

import com.lagou.controller.ValidateCodeController;

import com.lagou.exception.ValidateCodeException;

import com.lagou.service.impl.MyAuthenticationService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.stereotype.Service;

import org.springframework.util.StringUtils;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

/**

 * 自定义验证码过滤器,OncePerRequestFilter 一次请求只会经过一次过滤器

 */

@Service

public class ValidateCodeFilter extends OncePerRequestFilter {

    @Autowired

    private StringRedisTemplate redisTemplate;

    @Autowired

    private MyAuthenticationService authenticationService;

    @Override

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if (isLoginRequest(request)) {

            String imageCode = request.getParameter("imageCode");

            System.out.println(imageCode);

            try {

                validate(request, imageCode);

            } catch (ValidateCodeException e) {

                authenticationService.onAuthenticationFailure(request, response, e);

                return;

            }

        }

        filterChain.doFilter(request, response);

    }

    private boolean isLoginRequest(HttpServletRequest request) {

        return request.getRequestURI().equals("/login") && request.getMethod().equalsIgnoreCase("post");

    }

    private void validate(HttpServletRequest request, String imageCode) {

        String redisKey = ValidateCodeController.REDIS_KEY_IMAGE_CODE + "-" + request.getRemoteAddr();

        String redisImageCode = redisTemplate.boundValueOps(redisKey).get();

        if (!StringUtils.hasText(redisImageCode)) {

            throw new ValidateCodeException("验证码的值不能为空");

        }

        if (redisImageCode == null) {

            throw new ValidateCodeException("验证码已过期");

        }

        if (!redisImageCode.equals(imageCode)) {

            throw new ValidateCodeException("验证码不正确");

        }

        redisTemplate.delete(redisKey);

    }

}

自定义验证码异常类代码 

package com.lagou.exception;

import org.springframework.security.core.AuthenticationException;

/**

 * 验证码异常类

 */

public class ValidateCodeException extends AuthenticationException {

    public ValidateCodeException(String msg) {

        super(msg);

    }

}

package com.lagou.config;

import com.lagou.filter.ValidateCodeFilter;

import com.lagou.service.impl.MyAuthenticationService;

import com.lagou.service.impl.MyUserDetailsService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.authentication.dao.DaoAuthenticationProvider;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.builders.WebSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

import java.util.HashMap;

import java.util.Map;

@Configuration

@EnableWebSecurity

@EnableGlobalMethodSecurity(prePostEnabled = true)

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired

    private DataSource dataSource;

    @Autowired

    private MyAuthenticationService myAuthenticationService;

    @Autowired

    private ValidateCodeFilter validateCodeFilter;

    @Bean

    public UserDetailsService userDetailsService() {

        return new MyUserDetailsService();

    }

    @Bean

    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();

    }

    @Bean

    public DaoAuthenticationProvider daoAuthenticationProvider() {

        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();

        provider.setUserDetailsService(userDetailsService());

        provider.setPasswordEncoder(passwordEncoder());

        return provider;

    }

    @Override

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(daoAuthenticationProvider());

    }

    @Override

    public void configure(WebSecurity web) throws Exception {

        web.ignoring().antMatchers("/css/**", "/images/**", "/js/**", "/code/**");

    }

    @Override

    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)

                .authorizeRequests()

                .antMatchers("/toLoginPage").permitAll()

                .anyRequest().authenticated()

                .and()

                .formLogin()

                .loginPage("/toLoginPage")

                .loginProcessingUrl("/login")

                .usernameParameter("username")

                .passwordParameter("password")

                .successForwardUrl("/")

                .successHandler(myAuthenticationService)

                .failureHandler((request, response, exception) -> {

                    Map<Object, Object> result = new HashMap<>();

                    result.put("code", HttpServletResponse.SC_UNAUTHORIZED);

                    result.put("message", exception.getMessage());

                    response.setContentType("application/json;charset=UTF-8");

                    response.getWriter().write(objectMapper.writeValueAsString(result));

                })

                .and()

                .logout()

                .logoutUrl("/logout")

                .logoutSuccessHandler(myAuthenticationService)

                .and()

                .rememberMe()

                .rememberMeParameter("remember-me")

                .tokenRepository(getPersistentTokenRepository())

                .tokenValiditySeconds(1209600)

                .and()

                .headers()

                .frameOptions().sameOrigin()

                .and()

                .csrf().disable();

    }

@Bean

public PersistentTokenRepository getPersistentTokenRepository() {

JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();

tokenRepository.setDataSource(dataSource); // 设置数据源

tokenRepository.setCreateTableOnStartup(false); // 启动时自动帮我们创建一张表,第一次启动设置true,第二次启动设置为false或者注释掉

return tokenRepository;

}

如果上述代码遇到问题或已更新无法使用等情况可以联系Q:2633739505或直接访问www.ttocr.com测试对接(免费得哈)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值