SpringSecurity开发基于表单的认证(五)

实现图形验证码功能

  • 开发生产图形验证码接口
  • 在认证流程中加入图形验证码校验
  • 重构代码

开发生产图形验证码接口

  1. 根据随机数生成图片
  2. 将随机数存到Session中
  3. 将生成的图片写到响应的接口中

首先我们定义一个类专门用于表示图形验证码,代码如下:

package com.yun.security.core.validate.code;

import java.awt.image.BufferedImage;
import java.time.LocalDateTime;

public class ImageCode {
    public BufferedImage getImage() {
        return image;
    }

    public void setImage(BufferedImage image) {
        this.image = image;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public LocalDateTime getExpireTime() {
        return expireTime;
    }

    public void setExpireTime(LocalDateTime expireTime) {
        this.expireTime = expireTime;
    }

    private BufferedImage image;
    
    private String code;
    
    private LocalDateTime expireTime;
    
    public ImageCode(BufferedImage image,String code,LocalDateTime expireTime){
        this.image = image;
        this.code = code;
        this.expireTime =expireTime;
    }
    
    public ImageCode(BufferedImage image,String code,int expireIn){
        this.image = image;
        this.code = code;
        this.expireTime =LocalDateTime.now().plusSeconds(expireIn);
    }
    
    public Boolean isExpired(){
        return LocalDateTime.now().isAfter(expireTime);
    }
}

上述这个ImageCode类中,属性image保存了图片,code保存验证码的值,expireTime保存了过期时间。

接下来我们对登录页面进行修改,添加图形验证码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登陆页面</title>
</head>
<body>
    <h2>标准登陆页面</h2>
    <h3>表单登录</h3>
    <form action="/authentication/form" method="post">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="text" name="password"></td>
            </tr>
            <tr>
                <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>

从上述html代码中可以看出,验证码图片的来源是一个请求的url段,即在渲染页面的时候首先访问/code/image地址来获取图片。这个请求对应有一个控制器,其代码如下:

@RestController
public class ValidatorController {
    
    public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
    
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
    
    @GetMapping("/code/image")
    public void createCode(HttpServletRequest request,HttpServletResponse response) throws Exception{
        ImageCode imageCode = createImageCode(request);
        
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
        
        ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
    }
    
    private ImageCode createImageCode(HttpServletRequest request){
        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 sRand = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += 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(image, sRand, 60);
    }
    
    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);
    }
}
**粗体文本**

在上述代码中createCode方法处理/code/image请求,并通过createImageCode方法生成图片对象,生成的原理是生成随机数并结合java的awt绘图技术生成图片对象。生成图片验证码后,sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);这句代码表示将这个图片验证码对象放到session中,这样点击登录后,就可以拿这个保存到session中的验证码和实际我们在表单中填写的验证码进行比对判断验证码是否正确。

最后一步就是在填写完表单信息点击登录后首先判断验证码这一步操作,为此我们将这一步写在一个自定义的过滤器中,这个过滤器在UsernamePasswordAuthenticationFilter这个用户名密码验证过滤器之前执行。为此,我们要修改一个配置类:

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
    @Autowired 
    SecurityProperties securityProperties;
    
    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    
    @Autowired
    private MyAuthenticationFailHandler myAuthenticationFailHandler;
    
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        ValidateCodeFilter validateCodeFilter =new ValidateCodeFilter();

        validateCodeFilter.setAuthenticationFailureHandler(myAuthenticationFailHandler);
        
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
            .formLogin()
            .loginPage("/login.html") //跳转的登录页/authentication/require
            .loginProcessingUrl("/authentication/form") //登录时的请求
            .successHandler(myAuthenticationSuccessHandler) //表单登录成功时使用我们自己写的处理类
            .failureHandler(myAuthenticationFailHandler) //表单登录失败时使用我们自己写的处理类
            .and()
            .authorizeRequests()
            .antMatchers(
                    securityProperties.getBrowser().getLoginPage(),
                    "/code/image").permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .csrf().disable();
    }
}

上述代码中http.addFilterBefore这个方法就是在UsernamePasswordAuthenticationFilter过滤器之前加入我们的图片验证码过滤器。

接着看一下这个过滤器的具体实现:

public class ValidateCodeFilter extends OncePerRequestFilter {

    private AuthenticationFailureHandler authenticationFailureHandler;
    
    public AuthenticationFailureHandler getAuthenticationFailureHandler() {
        return authenticationFailureHandler;
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        if(StringUtils.equals("/authentication/form", request.getRequestURI())
                && StringUtils.equals(request.getMethod(), "POST")){
            try{
                validate(new ServletWebRequest(request));
            }
            catch(ValidateCodeException e){
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;//当失败时则不执行后面的过滤器
            }
        }
        else{
            filterChain.doFilter(request, response);
        }
    }
    
    private void validate(ServletWebRequest request) throws ServletRequestBindingException{
        ImageCode codeInSession = (ImageCode)sessionStrategy.getAttribute(request, ValidatorController.SESSION_KEY);
        
        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "imageCode");
        
        if("".equals(codeInRequest)){
            throw new ValidateCodeException("验证码不能为空");
        }
        
        if(codeInSession == null){
            throw new ValidateCodeException("验证码不存在");
        }
        
        if(codeInSession.isExpired()){
            sessionStrategy.removeAttribute(request, ValidatorController.SESSION_KEY);
            throw new ValidateCodeException("验证码已过期");
        }
        
        if(!StringUtils.equals(codeInSession.getCode(), codeInRequest)){
            throw new ValidateCodeException("验证码不匹配");
        }
        
        sessionStrategy.removeAttribute(request, ValidatorController.SESSION_KEY);
    }
}

上述代码中doFilterInternal方法就是过滤器的处理方法,当是表单登录并且是POST请求时调用validate方法进行校验。校验方法主要就是比对session中的验证码和当前请求中的验证码是否相同。

这样我们登录图形验证码功能就初步实现了,登陆页面显示如下:


image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,652评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,085评论 25 707
  • 在规则面前,你是怎么做的呢?也许你是明知故犯,也许你是坚决果断。而我,却犹豫了。 那一次,老师和同学们一起努力,创...
    躲进小楼看灯火阅读 321评论 0 0
  • 今天生意成交的三笔,他们三个人是自己来的,没有联系过任何人,特别感恩,这也是好的种子才开花。特别感恩财富的到来。我...
    温宛如瑜阅读 174评论 0 0
  • 伏羲桑梓,尧舜故里,乃菏泽也。其名南有荷山,北有雷泽。上古时代伏羲生于此,其母华胥因年少而踩上一大脚印,故...
    遗忘是最好的纪念阅读 1,641评论 1 4