当前位置: 代码网 > it编程>编程语言>Java > Spring Security图形验证码的实现代码

Spring Security图形验证码的实现代码

2024年10月28日 Java 我要评论
生成图形验证码添加maven依赖<dependency> <groupid>org.springframework.social</groupid&

生成图形验证码

添加maven依赖

<dependency>
            <groupid>org.springframework.social</groupid>
            <artifactid>spring-social-config</artifactid>
            <version>1.1.6.release</version>
        </dependency>

创建验证码对象

/**
 * @author chen bo
 * @date 2023/12
 * @des
 */
@data
public class imagecode {
    /**
     * image图片
     */
    private bufferedimage image;
    /**
     * 验证码
     */
    private string code;
    /**
     * 过期时间
     */
    private localdatetime expiretime;
    public imagecode(bufferedimage image, string code, int expirein) {
        this.image = image;
        this.code = code;
        this.expiretime = localdatetime.now().plusseconds(expirein);
    }
    /**
     * 判断验证码是否已过期
     * @return
     */
    public boolean isexpire() {
        return localdatetime.now().isafter(expiretime);
    }
}

创建imagecontroller

编写接口,返回图形验证码:

/**
 * @author chen bo
 * @date 2023/12
 * @des
 */
@restcontroller
public class imagecontroller {
    public final static string session_key_image_code = "session_verification_code";
    private sessionstrategy sessionstrategy = new httpsessionsessionstrategy();
    @getmapping("/code/image")
    public void createcode(httpservletrequest request, httpservletresponse response) throws ioexception {
        imagecode imagecode = createimagecode();
        sessionstrategy.setattribute(new servletwebrequest(request), session_key_image_code, imagecode);
        imageio.write(imagecode.getimage(), "jpeg", response.getoutputstream());
    }
    private imagecode createimagecode() {
        // 验证码图片宽度
        int width = 100;
        // 验证码图片长度
        int height = 36;
        // 验证码位数
        int length = 4;
        // 验证码有效时间 60s
        int expirein = 60;
        bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_rgb);
        graphics graphics = image.getgraphics();
        random random = new random();
        graphics.setcolor(getrandcolor(200, 500));
        graphics.fillrect(0, 0, width, height);
        graphics.setfont(new font("times new roman", font.italic, 20));
        graphics.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);
            graphics.drawline(x, y, x + xl, y + yl);
        }
        stringbuilder srand = new stringbuilder();
        for (int i = 0; i < length; i++) {
            string rand = string.valueof(random.nextint(10));
            srand.append(rand);
            graphics.setcolor(new color(20 + random.nextint(110), 20 + random.nextint(110), 20 + random.nextint(110)));
            graphics.drawstring(rand, 13 * i + 6, 16);
        }
        graphics.dispose();
        return new imagecode(image, srand.tostring(), expirein);
    }
    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);
    }
}

org.springframework.social.connect.web.httpsessionsessionstrategy对象封装了一些处理session的方法,包含了setattribute、getattribute和removeattribute方法,具体可以查看该类的源码。使用sessionstrategy将生成的验证码对象存储到session中,并通过io流将生成的图片输出到登录页面上。

v改造登录页面

添加验证码控件

在上一篇博文《springboot进阶教程(八十一)spring security自定义认证》中的"重写form登录页",已经创建了login.html,在login.html中添加如下代码:

<span style="display: inline">
            <input type="text" name="请输入验证码" placeholder="验证码" required="required"/>
            <img src="/code/image"/>
        </span>

img标签的src属性对应imagecontroller的createimagecode方法。

v认证流程添加验证码效验

定义异常类

在校验验证码的过程中,可能会抛出各种验证码类型的异常,比如“验证码错误”、“验证码已过期”等,所以我们定义一个验证码类型的异常类:

/**
 * @author chen bo
 * @date 2023/12
 * @des
 */
public class validatecodeexception extends authenticationexception {
    private static final long serialversionuid = 1715361291615299823l;
    public validatecodeexception(string explanation) {
        super(explanation);
    }
}

注意:这里继承的是authenticationexception而不是exception。

创建验证码的校验过滤器

spring security实际上是由许多过滤器组成的过滤器链,处理用户登录逻辑的过滤器为usernamepasswordauthenticationfilter,而验证码校验过程应该是在这个过滤器之前的,即只有验证码校验通过后才去校验用户名和密码。由于spring security并没有直接提供验证码校验相关的过滤器接口,所以我们需要自己定义一个验证码校验的过滤器validatecodefilter:

/**
 * @author chen bo
 * @date 2023/12
 * @des
 */
@component
public class validatecodefilter extends onceperrequestfilter {
    @autowired
    private myauthenticationfailurehandler myauthenticationfailurehandler;
    private sessionstrategy sessionstrategy = new httpsessionsessionstrategy();
    @override
    protected void dofilterinternal(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, filterchain filterchain) throws servletexception, ioexception {
        if ("/login".equalsignorecase(httpservletrequest.getrequesturi())
                && "post".equalsignorecase(httpservletrequest.getmethod())) {
            try {
                validatecode(new servletwebrequest(httpservletrequest));
            } catch (validatecodeexception e) {
                myauthenticationfailurehandler.onauthenticationfailure(httpservletrequest, httpservletresponse, e);
                return;
            }
        }
        filterchain.dofilter(httpservletrequest, httpservletresponse);
    }
    private void validatecode(servletwebrequest servletwebrequest) throws servletrequestbindingexception, validatecodeexception {
        imagecode codeinsession = (imagecode) sessionstrategy.getattribute(servletwebrequest, imagecontroller.session_key_image_code);
        string codeinrequest = servletrequestutils.getstringparameter(servletwebrequest.getrequest(), "imagecode");
        if (stringutils.isempty(codeinrequest)) {
            throw new validatecodeexception("验证码不能为空!");
        }
        if (codeinsession == null) {
            throw new validatecodeexception("验证码不存在!");
        }
        if (codeinsession.isexpire()) {
            sessionstrategy.removeattribute(servletwebrequest, imagecontroller.session_key_image_code);
            throw new validatecodeexception("验证码已过期!");
        }
        if (!codeinrequest.equalsignorecase(codeinsession.getcode())) {
            throw new validatecodeexception("验证码不正确!");
        }
        sessionstrategy.removeattribute(servletwebrequest, imagecontroller.session_key_image_code);
    }
}

validatecodefilter继承了org.springframework.web.filter.onceperrequestfilter,该过滤器只会执行一次。validatecodefilter继承了org.springframework.web.filter.onceperrequestfilter,该过滤器只会执行一次。

dofilterinternal方法中我们判断了请求url是否为/login,该路径对应登录form表单的action路径,请求的方法是否为post,是的话进行验证码校验逻辑,否则直接执行filterchain.dofilter让代码往下走。当在验证码校验的过程中捕获到异常时,调用spring security的校验失败处理器authenticationfailurehandler进行处理。

我们分别从session中获取了imagecode对象和请求参数imagecode(对应登录页面的验证码input框name属性),然后进行了各种判断并抛出相应的异常。当验证码过期或者验证码校验通过时,我们便可以删除session中的imagecode属性了。

v更新配置类

验证码校验过滤器定义好了,怎么才能将其添加到usernamepasswordauthenticationfilter前面呢?很简单,只需要在browsersecurityconfig的configure方法中添加些许配置即可,顺便配置验证码请求不配拦截: "/code/image"。

/**
 * @author chen bo
 * @date 2023/12
 * @des
 */
@configuration
public class securityconfig extends websecurityconfigureradapter {
    @override
    protected void configure(httpsecurity http) throws exception {
        http.addfilterbefore(new validatecodefilter(), usernamepasswordauthenticationfilter.class) //添加验证码效验过滤器
                .formlogin() // 表单登录
                .loginpage("/login.html")       // 登录跳转url
//                .loginpage("/authentication/require")
                .loginprocessingurl("/login")   // 处理表单登录url
//                .successhandler(authenticationsuccesshandler)
                .failurehandler(new myauthenticationfailurehandler())
                .and()
                .authorizerequests()            // 授权配置
                .antmatchers("/login.html", "/css/**", "/authentication/require", "/code/image").permitall()  // 无需认证
                .anyrequest()                   // 所有请求
                .authenticated()                // 都需要认证
                .and().csrf().disable();
    }
    @bean
    public passwordencoder passwordencoder() {
        return new bcryptpasswordencoder();
    }
}

上面代码中,我们注入了validatecodefilter,然后通过addfilterbefore方法将validatecodefilter验证码校验过滤器添加到了usernamepasswordauthenticationfilter前面。

v运行效果图

其他参考/学习资料:

v源码地址

https://github.com/toutouge/javademosecond/tree/master/security-demo

到此这篇关于spring security图形验证码的文章就介绍到这了,更多相关spring security验证码内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com