四、SpringSecurity自定义过滤器

在登录时添加图片验证码认证
添加获取图片验证码的接口:

@RestController
public class ImageCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/code/image")
    public void createCode(HttpServletResponse response) throws IOException {
        ImageCode imageCode = createImageCode();
        //将验证码存到redis中,有效期5分钟
        redisTemplate.opsForValue().set("IMAGE_CODE",imageCode.getCode(),5, TimeUnit.MINUTES);
        // 把生成的图片以JPEG的格式写到响应的输出流里面
        ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());
    }

    /**
     * 生成图形验证码
     */
    private ImageCode createImageCode() {
        // 图形验证码的宽高
        int width = 67;
        int height = 23;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        Random random = new Random();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
        g.setColor(getRandColor(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);
        }
        String code = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            code += rand;
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + 6, 16);
        }
        g.dispose();
        return new ImageCode(code, image);
    }
    /**
     * 生成随机背景条纹
     */
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}

登陆页面,这里只是简单显示验证码,可以用ajax来异步获取,方便刷新

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<h2>后台管理登录页面</h2>
<form action="/user/login" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td>图形验证码</td>
            <td>
                <input type="text" name="imageCode">
                <img src="/code/image">
            </td>
        </tr>
        <tr>
            <td colspan="2"><button type="submit">登录</button></td>
        </tr>
    </table>
</form>
</body>
</html>

添加过滤器类:

/**
 * @auther Mr.Liao
 * @date 2019/8/20 11:23
 */
public class ImageCodeFilter extends OncePerRequestFilter {
    private AuthenticationFailureHandler failureHandler;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (StringUtils.equals("/user/login", request.getRequestURI()) &&
            StringUtils.equalsAnyIgnoreCase(request.getMethod(), "post")){
            try {
                validate(request);
            } catch (ImageCodeException e) {
                //验证出现异常,使用自定义的失败处理器来处理,并且直接return,不执行后面的过滤器
                failureHandler.onAuthenticationFailure(request,response,e);
                return;
            }
        }
        filterChain.doFilter(request,response);
    }

    /**
     * 验证的逻辑
     * @param request
     */
    private void validate(HttpServletRequest request) {
        String saved_code = null;
        try {
            saved_code = (String)redisTemplate.opsForValue().get("IMAGE_CODE");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println("redis中保存的验证码是:"+saved_code);
        String code = request.getParameter("imageCode");
        System.out.println("参数中的验证码是:"+code);
        if (StringUtils.isBlank(saved_code)){
            throw new ImageCodeException("验证码已过期");
        }
        if (StringUtils.isBlank(code)){
            throw new ImageCodeException("请出入验证码");
        }
        if (!StringUtils.equals(saved_code,code)){
            throw new ImageCodeException("验证码错误");
        }
        //不抛出异常,验证码正确,删除保存的验证码
        redisTemplate.delete("IMAGE_CODE");
    }
}

验证异常类

public class ImageCodeException extends AuthenticationException {
    private static final long serialVersionUID = -2273000953918465626L;

    public ImageCodeException(String msg) {
        super(msg);
    }
}

配置到过滤器链:

@Override
protected void configure(HttpSecurity http) throws Exception {
	ImageCodeFilter imageCodeFilter = new ImageCodeFilter();
    imageCodeFilter.setFailureHandler(failureHandler);
    http.addFilterBefore(imageCodeFilter, UsernamePasswordAuthenticationFilter.class)
    	.formLogin()
        .loginPage("/authentication/request").loginProcessingUrl("/user/login")
        .successHandler(successHandler).failureHandler(failureHandler)
        .and()
            //记住我配置
            .rememberMe()
            .tokenRepository(persistentTokenRepository())
            .tokenValiditySeconds(30)
            .userDetailsService(userLoginService)
        .and()
            // 授权的配置
            .authorizeRequests()
            // 不需要身份验证的请求
            .antMatchers("/authentication/request","/login_p.html","/code/image").permitAll()
            // 任何请求
            .anyRequest()
            // 都需要身份认证
            .authenticated()
        .and()// 关闭跨站请求伪造防护
            .csrf().disable();
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值