Spring Security自定义验证码登录

news2024/10/7 14:27:47

本文内容来自王松老师的《深入浅出Spring Security》,自己在学习的时候为了加深理解顺手抄录的,有时候还会写一些自己的想法。

        验证码登录也是项目中一个常见的需求,但是Spring Security并未提供自动化配置方案。所以需要开发者自行定义。这里我们通过自定义认证逻辑实现添加登录验证码功能。

        生成验证码我们使用开源库kaptcha,首先引入kaptcha依赖,代码如下:

        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

        然后对kaptcha进行配置:

@Configuration
public class KaptchaConfig {

    @Bean
    public Producer kaptcha() {
        Properties properties = new Properties();
        properties.setProperty("kaptcha.image.width", "150");
        properties.setProperty("kaptcha.image.height", "50");
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

        配置一个Producer实例,只要配置一个生成的图片验证码的宽带、长度、生成字符、验证码的长度等信息。配置完成可以在Controller中定义一个验证码接口了:

    @Autowired
    private Producer producer;

    @GetMapping("/vc.jpg")
    public void getVerifyCode(HttpServletResponse resp, HttpSession session) {
        resp.setContentType("image/jpeg");
        String text = producer.createText();
        session.setAttribute("kaptcha", text);
        BufferedImage image = producer.createImage(text);
        try (ServletOutputStream out = resp.getOutputStream()) {
            ImageIO.write(image, "jpg", out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        这个验证码接口中,主要做了两件事:

  • 生成验证码,并将文本存入HttpSession中
  • 根据验证码文本生成验证码图片,并通过IO流写出到前端。

        接下修改登录表单,加入验证码,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自定义登录</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<style>
    #login .container #login-row #login-column #login-box {
        border: 1px solid #9C9C9C;
        background-color: #EAEAEA;
    }
</style>
<body>
<div id="login">
    <div class="container">
        <div id="login-row" class="row justify-content-center align-items-center">
            <div id="login-column" class="col-md-6">
                <div id="login-box" class="col-md-12">
                    <form id="login-form" class="form" action="/doLogin" method="post">
                        <h3 class="text-center text-info">登录</h3>
                        <div class="form-group">
                            <label for="username" class="text-info">用户名:</label><br>
                            <input type="text" name="uname" id="username" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="password" class="text-info">密码:</label><br>
                            <input type="text" name="passwd" id="password" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="kaptcha" class="text-info">验证码:</label><br>
                            <input type="text" name="kaptcha" id="kaptcha" class="form-control">
                            <img src="/vc.jpg" alt="">
                        </div>
                        <div class="form-group">
                            <input type="submit" name="submit" class="btn btn-info btn-md" value="登录">
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

        在登录表单中增加一个输入验证码的输入框,验证码的图片地址就是我们在Controller中定义的验证码接口地址。

        接来下就是验证码的校验了。经过前面的学习,我们已经了解到身份认证实际上就是在AuthenticationProvider的authenticate方法中完成的。所以,验证码的校验,我们可以在该方法执行前进行,需要配置如下类:

/**
 * @author tlh
 * @date 2022/11/18 22:14
 */
public class KaptchaAuthenticationProvider extends DaoAuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String kaptcha = req.getParameter("kaptcha");
        String sessionKaptcha = (String) req.getSession().getAttribute("kaptcha");
        if (kaptcha != null && kaptcha.equalsIgnoreCase(sessionKaptcha)) {
            return super.authenticate(authentication);
        }
        throw new AuthenticationServiceException("验证码输入错误");
    }
}

        这里重写authenticate方法,在authenticate方法中从RequestContextHolder获取当前请求,进而取到验证码参数和存储在HttpSession中的验证码文本进行对比。比如通过的话就执行父类的authenticate方法,不通过的话就抛出异常。

        我们将我们定义的KaptchaAuthenticationProvider通过配置类放入Spring的IOC容器中去:

/**
 * @author tlh
 * @date 2022/11/18 21:22
 */
@Configuration
public class KaptchaConfig {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public AuthenticationProvider getAuthenticationProvider() {
        KaptchaAuthenticationProvider kaptchaAuthenticationProvider = new KaptchaAuthenticationProvider();
        kaptchaAuthenticationProvider.setUserDetailsService(userDetailsService);
        return kaptchaAuthenticationProvider;
    }
}

        这里需要注意的是我们在创建AuthenticationProvider的是需要一个UserDetailsService,这里的UserDetailsService是我们在前面学习的通过MyBatis从数据库中加载用户信息的时候定义的,如果有疑惑的的伙伴可以在去回顾下。

/**
 * @author tlh
 * @date 2022/11/17 23:52
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        user.setRoles(userMapper.getRolesByUid(user.getId()));
        return user;
    }
}

        最后在SecurityConfig中配置AuthenticationManager,代码如下:

/**
 * @author tlh
 * @date 2022/11/16 21:11
 */
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //放行验证码生成接口
                .antMatchers("/vc.jpg").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/doLogin")
                .successHandler(getAuthenticationSuccessHandler())
                .failureUrl("/login.html")
                .usernameParameter("uname")
                .passwordParameter("passwd")
                .permitAll()
                .and()
                .csrf().disable();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        ProviderManager providerManager = new ProviderManager(authenticationProvider);
        return providerManager;
    }

    /**
     * 登录成功处理器
     *
     * @return
     */
    private AuthenticationSuccessHandler getAuthenticationSuccessHandler() {
        return new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                response.setContentType("application/json;charset=utf-8");
                Map<String, String> respMap = new HashMap<>(2);
                respMap.put("code", "200");
                respMap.put("msg", "登录成功");
                ObjectMapper objectMapper = new ObjectMapper();
                String jsonStr = objectMapper.writeValueAsString(respMap);
                response.getWriter().write(jsonStr);
            }
        };
    }
}

        另外需要注意,在configure(HttpSecurity)方法中给验证码接口配置放行:antMatchers("/vc.jpg").permitAll()。配置完成后,启动项目,浏览中输入:localhost:8080/login.html,就能看到如下图:

        此时,输入正确的用户名、密码以及验证码就可以成功登录。 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/19883.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Spring的创建和使用

1. 创建Spring项目 1.1 创建一个 Maven 项目 不需要使用任何模板, 点击下一步.注:所有的名称都不能包含中文.Maven仓库中的结构: 1.2 添加 Spring 框架支持 在Spring 的 配置文件 中添加依赖 spring-context: Spring的上下文spring-beans: 管理Spring对象(bean) <depende…

36、异常(Exception)

一、 引入: 不应该出现了一个不算致命的问题就导致整个系统崩溃&#xff0c;所以java设计者提供了一个异常处理机制来解决问题 快速入门&#xff1a; package exception_;public class Exception01 {public static void main(String[] args) {int num110;int num20;//异常处…

软件工程复习

文章目录&#xff08;一&#xff09;软件软件发展三阶段软件的概念什么是软件危机&#xff1f;内容包括&#xff1a;软件危机的表现&#xff1a;软件危机的原因(4)消除软件危机的途径&#xff1a;软件工程软件工程定义&#xff08;要背&#xff09;简称&#xff1a;软件工程的基…

【Java基础】第六章 | IO流

目录 | 总框架 | 文件路径相关知识 | Peoperties类与IO流、配置文件* | 1.文件流 文件字节输入流&#xff08;标准输入流&#xff09; FileInputStream 文件字节输出流 FileOutputStream 文件字符输入流 FileReader 文件字符输出流 FileWriter 应用&#xff1a;使用字…

MMDetection库中的一些模块介绍

本文目前仅包含1个主干网络和1个颈部网络。如果有机会&#xff0c;会继续补充更多模型。 若发现内容有误&#xff0c;欢迎指出。 MMDetection的图像数据一般会经历如下步骤/模块&#xff1a; #mermaid-svg-XxM18Ychr9OSpdV6 {font-family:"trebuchet ms",verdana,ari…

JavaScript 防抖与节流

目录1 函数1.1 调用函数1.2 闭包2 防抖与节流2.1 定义2.2 区别2.3 应用场景3 防抖3.1 非立即执行3.1.1 一般写法3.1.2 Vue2 中写法3.1.3 过程3.2 立即执行3.2.1 一般写法3.2.2 Vue2 中写法3.2.3 过程1 函数 应用防抖节流首先需理解以下知识 1.1 调用函数 js 函数内部 return…

电影售票系统

项目介绍 基于SpringBoot &#xff0c;Mybatis&#xff0c; Vue 的电影售票及影院管理系统&#xff08;前后端分离&#xff09;&#xff0c;具体功能见 下面演示截图 需要安装的软件 Java8 MySQL5.7或以上 Navicat或者其他管理工具 IDEA或者Eclipse Node.js 14或以上 运行项…

PLC学习笔记(三):PLC结构(2)

目录&#xff1a; PLC学习笔记&#xff08;一&#xff09;&#xff1a;概述 PLC学习笔记&#xff08;二&#xff09;&#xff1a;PLC结构&#xff08;1&#xff09; PLC学习笔记&#xff08;三&#xff09;&#xff1a;PLC结构&#xff08;2&#xff09; &#x1f981;&…

SpringBoot+Mybaits搭建通用管理系统实例八:系统权限控制实现

一、本章内容 实现自定义权限控制,通过自定义PermissionEvaluator实现操作权限的检测及控制,关于权限控制模型有ACL, DAC, MAC, RBAC, ABAC等,具体原理可参考:【权限系统设计】ACL, DAC, MAC, RBAC, ABAC 模型的不同应用场景 完整课程地址 二、开发视频 SpringBoot+Mybaits…

《操作系统-真象还原》12. 进一步完善内核

文章目录Linux 的系统调用系统调用的实现 —— 图解系统调用的实现 —— 代码触发中断寻找 IDT 中断描述符执行对应的中断例程中断例程中通过用户传入的功能号去执行对应的功能函数关于 printf你需要知道可变参数的原理Linux 中的可变参数原理Linux 中的可变参数实现printf 只是…

【微服务】SpringCloud轮询拉取注册表及服务发现源码解析

&#x1f496; Spring家族及微服务系列文章 ✨【微服务】SpringCloud微服务剔除下线源码解析 ✨【微服务】SpringCloud微服务续约源码解析 ✨【微服务】SpringCloud微服务注册源码解析 ✨【微服务】Nacos2.x服务发现&#xff1f;RPC调用&#xff1f;重试机制&#xff1f; ✨【微…

机器学习:支持向量机SVM的SVC和SVR

支持向量机SVMSVM的工作原理及分类支持向量机的原理线性可分的SVM非线性可分的支持向量机支持向量机分类SVC支持向量机回归SVRSVR原理SVR模型时间序列曲线预测SVM的工作原理及分类 支持向量机的原理 支持向量机(Support Vector Machine&#xff0c;SVM)是一种二类分类器&…

积极融入信创生态 | 思腾合力软件产品完成多个信创产品适配

从2019年我国提出发展信创产业&#xff0c;2020年迈入信创发展元年&#xff0c;到2022信创开始向行业深水区迈进&#xff0c;逐渐延伸到金融、电信等重点行业、核心业务中&#xff0c;开启了“行业信创元年”。一个真正的“大信创”时代已开启&#xff0c;一个数万亿规模的市场…

MybatisPlus---从入门到深化

目录 MyBatisPlus入门 MyBatisPlus介绍 ​编辑Spring集成MyBatisPlus SpringBoot集成MyBatisPlus MyBatisPlus_CRUD 添加 CRUD_相关注解 修改 删除 查询 条件构造器 全局配置 ActiveRecord_概念 ActiveRecord_增删改查 MyBatisPlus插件_插件概述 MyBatisPlus插件_…

超神之路 数据结构 3 —— Stack栈实现及应用

栈也是一种线性表结构&#xff0c;相较于数组&#xff0c;栈对应的操作是数组的子集&#xff0c;我们只要实现从一端添加元素&#xff0c;并从这个一端取出元素&#xff0c;这一端我们称呼它为栈顶&#xff0c;正是由于这种结构&#xff0c;它具有“后入先出”&#xff08;LIFO…

PTA题目 计算工资

某公司员工的工资计算方法如下&#xff1a;一周内工作时间不超过40小时&#xff0c;按正常工作时间计酬&#xff1b;超出40小时的工作时间部分&#xff0c;按正常工作时间报酬的1.5倍计酬。员工按进公司时间分为新职工和老职工&#xff0c;进公司不少于5年的员工为老职工&#…

基于jsp+mysql+ssm健身信息交流网站-计算机毕业设计

项目介绍 随着全民健身运动的兴起&#xff0c;越来越多的人走进了健身房&#xff0c;而传统的管理模式已不能适应现代健身机构的发展趋势&#xff0c;如何增强健身房会员卡的管理和完善客户服务&#xff0c;成了健身房发展的当务之急。健身信息管理系统的研究与开发&#xff0…

文本摘要实战:基于句子相似度矩阵构建图结构实现文本摘要 代码+数据

任务描述: 自动文本摘要(Text Summarization)是指给出一段文本,我们从中提取出要点,然后再形成一个短的概括性的文本。自动的文本摘要是非常具有挑战性的,当我们作为人类总结一篇文章时,我们通常会完整地阅读它以发展我们的理解,然后写一个摘要突出其要点。由于计算机缺乏…

计算机毕业设计springboot+vue基本微信小程序的码高教育课后在线小程序

项目介绍 随着我国经济迅速发展,人们对手机的需求越来越大,各种手机软件也都在被广泛应用,但是对于手机进行数据信息管理,对于手机的各种软件也是备受用户的喜爱,码高教育课后在线小程序的设计与开发被用户普遍使用,为方便用户能够可以随时进行码高教育课后在线小程序的设计与开…

HTML期末大学生网页设计作业----锤子手机 1页

⛵ 源码获取 文末联系 ✈ Web前端开发技术 描述 网页设计题材&#xff0c;DIVCSS 布局制作,HTMLCSS网页设计期末课程大作业 | 在线商城购物 | 水果商城 | 商城系统建设 | 多平台移动商城 | H5微商城购物商城项目 | HTML期末大学生网页设计作业&#xff0c;Web大学生网页 HTML&a…