登录验证码功能

描述

1,首先验证码是一张图片,页面登录页面要以图片的形式来接受 即 <img> 标签

2,图片生成 是通过A-Z a-z 1-9 这些字母数字组成,以4位数的验证码来说,要先生成随机四位A-Z a-z 1-9编码,并且把编码放到session 里,主要是用于跟用户输入的验证码进行比较

3,根据随机编码,设置宽 高 ,指定图片输出流 来完成堆图片

4,点击图片 调用生成图片的clntroller 进行图片更新

代码:

<div class="form-group">
    验证码:<input type="text" class="validcode1" name="validcode" id="validcode"/>
<img src="" alt="验证码" id="codeYZ" class="validimg" οnclick="changeCode();"/>
 //点击图片生成验证码
function changeCode(){
    var imgObj = document.getElementById("codeYZ");
    imgObj.src = "/login/ajaxCode?ran=" + Math.random();
}
//页面初始化生生验证码
$(function () {
    var imgObj = document.getElementById("codeYZ");
    imgObj.src = "/login/ajaxCode?ran=" + Math.random();
})

// 生成验证码 controller

def ajaxCode(){
    String code = VerifyCodeUtil.generateVerifyCode(4)   //四位随机编码
    session.setAttribute(session.getId(),code)  //放到session 
    VerifyCodeUtil.outputImage(100,40,response.getOutputStream(),code) // 生成图片流
}

随机编码,生成图片流 参考我的另一篇文章

https://blog.csdn.net/lijinlong1989/article/details/90512320

 输入验证码,进行校验,一般项目都会使用 安全框架进行 注册登录,权限等校验

本项目使用的是spring security 进行登录(常用还有shiro)

spring security 项目在登录验证中想获得额外数据(验证码) 通过继承WebAuthenticationDetails 来实现

//获取额外数据 类

CustomWebAuthenticationDetails extends WebAuthenticationDetails
private final String validcode;

private final Boolean flag ;
validcode = request.getParameter("validcode") //获取用户输入的验证码
if(StringUtils.isNotBlank(validcode)){
    validcode = validcode.toLowerCase()
}
String value  = request.getSession().getAttribute(request.getSession().getId())//获取session 验证码
if(StringUtils.isNotBlank(value)){
    value = value.toLowerCase()
}
System.out.print("validcode"+validcode+":value="+value)
if(validcode.equals(value)){
    request.getSession().removeAttribute(request.getSession().getId())  如果true  删除sessionid  (key 可以使session_业务类型)
    flag = true
}else{
    flag=false
}

  // 校验用户名密码是否正确 类   spring security 

public class CustomAuthenticationProvider extends DaoAuthenticationProvider
{
    protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException
    {
        // 登录失败返回 验证码不正确
        def customWebAuthenticationDetails = details as CustomWebAuthenticationDetails
        def user = userDetails as CustomUserDetails
        if(!customWebAuthenticationDetails.getFlag()){
            throw new CustomCodeException("对不起验证码 不正确")
        }
}

// 最后上传一张图

到此  验证码登录 完成

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值