SpringBoot整合Shiro完成验证码校验
SpringBoot整合Shiro完成验证码校验
上一篇:SpringBoot整合Shiro使用Redis作为缓存
首先编写生成验证码的工具类
package club.qy.datao.utils;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* 图形验证码生成
*/
public class VerifyUtil {
// 默认验证码字符集
private static final char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
// 默认字符数量
private final Integer SIZE;
// 默认干扰线数量
private final int LINES;
// 默认宽度
private final int WIDTH;
// 默认高度
private final int HEIGHT;
// 默认字体大小
private final int FONT_SIZE;
// 默认字体倾斜
private final boolean TILT;
private final Color BACKGROUND_COLOR;
/**
* 初始化基础参数
*
* @param builder
*/
private VerifyUtil(Builder builder) {
SIZE = builder.size;
LINES = builder.lines;
WIDTH = builder.width;
HEIGHT = builder.height;
FONT_SIZE = builder.fontSize;
TILT = builder.tilt;
BACKGROUND_COLOR = builder.backgroundColor;
}
/**
* 实例化构造器对象
*
* @return
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* @return 生成随机验证码及图片
* Object[0]:验证码字符串;
* Object[1]:验证码图片。
*/
public Object[] createImage() {
StringBuffer sb = new StringBuffer();
// 创建空白图片
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 获取图片画笔
Graphics2D graphic = image.createGraphics();
// 设置抗锯齿
graphic.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 设置画笔颜色
graphic.setColor(BACKGROUND_COLOR);
// 绘制矩形背景
graphic.fillRect(0, 0, WIDTH, HEIGHT);
// 画随机字符
Random ran = new Random();
//graphic.setBackground(Color.WHITE);
// 计算每个字符占的宽度,这里预留一个字符的位置用于左右边距
int codeWidth = WIDTH / (SIZE + 1);
// 字符所处的y轴的坐标
int y = HEIGHT * 3 / 4;
for (int i = 0; i < SIZE; i++) {
// 设置随机颜色
graphic.setColor(getRandomColor());
// 初始化字体
Font font = new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE);
if (TILT) {
// 随机一个倾斜的角度 -45到45度之间
int theta = ran.nextInt(45);
// 随机一个倾斜方向 左或者右
theta = (ran.nextBoolean() == true) ? theta : -theta;
AffineTransform affineTransform = new AffineTransform();
affineTransform.rotate(Math.toRadians(theta), 0, 0);
font = font.deriveFont(affineTransform);
}
// 设置字体大小
graphic.setFont(font);
// 计算当前字符绘制的X轴坐标
int x = (i * codeWidth) + (codeWidth / 2);
// 取随机字符索引
int n = ran.nextInt(chars.length);
// 得到字符文本
String code = String.valueOf(chars[n]);
// 画字符
graphic.drawString(code, x, y);
// 记录字符
sb.append(code);
}
// 画干扰线
for (int i = 0; i < LINES; i++) {
// 设置随机颜色
graphic.setColor(getRandomColor());
// 随机画线
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
// 返回验证码和图片
return new Object[]{sb.toString(), image};
}
/**
* 随机取色
*/
private Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256));
return color;
}
/**
* 构造器对象
*/
public static class Builder {
// 默认字符数量
private int size = 4;
// 默认干扰线数量
private int lines = 10;
// 默认宽度
private int width = 80;
// 默认高度
private int height = 35;
// 默认字体大小
private int fontSize = 25;
// 默认字体倾斜
private boolean tilt = true;
//背景颜色
private Color backgroundColor = Color.LIGHT_GRAY;
public Builder setSize(int size) {
this.size = size;
return this;
}
public Builder setLines(int lines) {
this.lines = lines;
return this;
}
public Builder setWidth(int width) {
this.width = width;
return this;
}
public Builder setHeight(int height) {
this.height = height;
return this;
}
public Builder setFontSize(int fontSize) {
this.fontSize = fontSize;
return this;
}
public Builder setTilt(boolean tilt) {
this.tilt = tilt;
return this;
}
public Builder setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
return this;
}
public VerifyUtil build() {
return new VerifyUtil(this);
}
}
}
开发控制器,加载页面时生成新的验证码
@RequestMapping("/getVerifyCode")
public void getVerifyCode(HttpSession session, HttpServletResponse response) throws IOException {
// 生成默认的验证码图片
Object[] obj = VerifyUtil.newBuilder().build().createImage();
// obj[0]是验证码的字符串,放入session
session.setAttribute("verifyCode", obj[0]);
// obj[1]是验证码图片
BufferedImage image = (BufferedImage) obj[1];
OutputStream outputStream = response.getOutputStream();
// 设置响应类型
response.setContentType("image/png");
// IO输出图片
ImageIO.write(image, "png", outputStream);
}
注意在ShiroConfig配置类中药放行对应的验证码请求。
在login页面上添加验证码。
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1 class="">登录首页</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">
用户名:<input type="text" name="username"><br/>
密码: <input type="password" name="password"><br/>
验证码: <input type="text" name="verifyCode"><img src="${pageContext.request.contextPath}/user/getVerifyCode"><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
效果如下…
然后在控制层中修改登录的处理,首先验证输入的验证码是否正确,如果不正确就直接返回验证码错误,不进行后面的判断;如果正确,再验证用户名和密码。这里只是做抛出异常处理。
@PostMapping("/login")
public String login(String username, String password, String verifyCode, HttpSession session) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken passwordToken = new UsernamePasswordToken(username, password);
String code = (String) session.getAttribute("verifyCode");
try {
if (verifyCode.equalsIgnoreCase(code)) {
subject.login(passwordToken);
return "redirect:/index.jsp";
} else{
throw new RuntimeException("验证码错误!");
}
}catch(UnknownAccountException e){
System.out.println("用户名错误" + e.getMessage());
} catch(IncorrectCredentialsException e){
System.out.println("密码错误" + e.getMessage());
}catch (RuntimeException e){
System.out.println("验证码错误!"+e.getMessage());
e.printStackTrace();
}
return "redirect:/login.jsp";
}
因为自定义Realm中使用了随机盐加密,需要对盐进行序列化和反序列化处理(保存到缓存),因此需要对ByteSource建一个无参构造并实现相对应的接口。
package club.qy.datao.salt;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
public class MyByteSource implements ByteSource, Serializable {
public MyByteSource(){
}
private byte[] bytes;
private String cachedHex;
private String cachedBase64;
public MyByteSource(byte[] bytes) {
this.bytes = bytes;
}
public MyByteSource(char[] chars) {
this.bytes = CodecSupport.toBytes(chars);
}
public MyByteSource(String string) {
this.bytes = CodecSupport.toBytes(string);
}
public MyByteSource(ByteSource source) {
this.bytes = source.getBytes();
}
public MyByteSource(File file) {
this.bytes = (new MyByteSource.BytesHelper()).getBytes(file);
}
public MyByteSource(InputStream stream) {
this.bytes = (new MyByteSource.BytesHelper()).getBytes(stream);
}
public static boolean isCompatible(Object o) {
return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
}
@Override
public byte[] getBytes() {
return this.bytes;
}
@Override
public boolean isEmpty() {
return this.bytes == null || this.bytes.length == 0;
}
@Override
public String toHex() {
if (this.cachedHex == null) {
this.cachedHex = Hex.encodeToString(this.getBytes());
}
return this.cachedHex;
}
@Override
public String toBase64() {
if (this.cachedBase64 == null) {
this.cachedBase64 = Base64.encodeToString(this.getBytes());
}
return this.cachedBase64;
}
@Override
public String toString() {
return this.toBase64();
}
@Override
public int hashCode() {
return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof ByteSource) {
ByteSource bs = (ByteSource)o;
return Arrays.equals(this.getBytes(), bs.getBytes());
} else {
return false;
}
}
private static final class BytesHelper extends CodecSupport {
private BytesHelper() {
}
public byte[] getBytes(File file) {
return this.toBytes(file);
}
public byte[] getBytes(InputStream stream) {
return this.toBytes(stream);
}
}
}
自定义Realm
public class CustomRelam extends AuthorizingRealm {
@Autowired
UserService userService;
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = (String) principalCollection.getPrimaryPrincipal();
User roleByUserName = userService.findRoleByUserName(username);
if (!CollectionUtils.isEmpty(roleByUserName.getRoles())){
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
roleByUserName.getRoles().forEach(role->{
simpleAuthorizationInfo.addRole(role.getName());
//查询该角色下的所有权限然后添加到该角色中
List<Permission> permissions = userService.findPermissionsByRoleId(role.getId());
if (!CollectionUtils.isEmpty(permissions)){
permissions.forEach(permission -> {
simpleAuthorizationInfo.addStringPermission(permission.getName());
});
}
});
return simpleAuthorizationInfo;
}
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String principal = (String) authenticationToken.getPrincipal();
// 实际开发中 先确认传来的token用户名是否存在,如果存在且唯一,然后根据有户名查询密码返回,进而判断密码是否正确
User user = userService.findUserByUsername(principal);
if (!ObjectUtils.isEmpty(user)){
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUsername(),
user.getPassword(), new MyByteSource(user.getSalt()),this.getName());
// 用户名和密码都判断完成后可以返回
return simpleAuthenticationInfo;
}
return null;
}
}
当输入错误的验证码时,控制台会抛出异常,并重新刷新登录界面。


所有信息都验证正确后才进入首页

SpringBoot整合Shiro完成验证码校验的更多相关文章
- springboot集成shiro实现验证码校验
github:https://github.com/peterowang/shiro/ 这里实现验证码校验的思路是自己添加一个Filter继承FormAuthenticationFilter,Form ...
- 18.Shiro与Springboot整合下登陆验证UserService未注入的问题
Shiro与Springboot整合下登陆验证UserService未注入的问题 前言: 刚开始整合的情况下,UserService一执行,就会报空指针异常. 看了网上各位大神的讲解,什么不能用ser ...
- 补习系列(6)- springboot 整合 shiro 一指禅
目标 了解ApacheShiro是什么,能做什么: 通过QuickStart 代码领会 Shiro的关键概念: 能基于SpringBoot 整合Shiro 实现URL安全访问: 掌握基于注解的方法,以 ...
- SpringBoot系列十二:SpringBoot整合 Shiro
声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合 Shiro 2.具体内容 Shiro 是现在最为流行的权限认证开发框架,与它起名的只有最初 ...
- SpringBoot整合Shiro实现基于角色的权限访问控制(RBAC)系统简单设计从零搭建
SpringBoot整合Shiro实现基于角色的权限访问控制(RBAC)系统简单设计从零搭建 技术栈 : SpringBoot + shiro + jpa + freemark ,因为篇幅原因,这里只 ...
- springboot整合Shiro功能案例
Shiro 核心功能案例讲解 基于SpringBoot 有源码 从实战中学习Shiro的用法.本章使用SpringBoot快速搭建项目.整合SiteMesh框架布局页面.整合Shiro框架实现用身份认 ...
- SpringBoot整合Shiro实现权限控制,验证码
本文介绍 SpringBoot 整合 shiro,相对于 Spring Security 而言,shiro 更加简单,没有那么复杂. 目前我的需求是一个博客系统,有用户和管理员两种角色.一个用户可能有 ...
- SpringBoot 整合Shiro 一指禅
目标 了解ApacheShiro是什么,能做什么: 通过QuickStart 代码领会 Shiro的关键概念: 能基于SpringBoot 整合Shiro 实现URL安全访问: 掌握基于注解的方法,以 ...
- SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理|前后端分离(下)----筑基后期
写在前面 在上一篇文章<SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理(上)----筑基中期>当中,我们初步实现了SpringBoot整合Shiro ...
随机推荐
- ARC109F - 1D Kingdom Builder
一行格子,其中小于\(0\)的格子为白色,大于\(n\)的格子为黑色,中间的格子颜色由题目给出. 有一些格子需要被标记.标记按照以下规则进行:选择一个颜色\(c\),找到一个未标记的 旁边有标记点的 ...
- I/O接口
目录 I/O接口的功能 接口的功能(要解决的问题) 接口的功能(具体操作) I/O接口的基本结构 接口和端口 I/O端口及编址 统一编址 独立编址 I/O接口的类型 小结 接口可以看作是两个部件之间的 ...
- 【Jenkins】环境配置及安装
下载地址: 国外官网:https://www.jenkins.io/zh/download/(版本最新) 国内镜像:http://mirrors.jenkins-ci.org/windows/ 清华镜 ...
- 3分钟快速搞懂Java的桥接方法
什么是桥接方法? Java中的桥接方法(Bridge Method)是一种为了实现某些Java语言特性而由编译器自动生成的方法. 我们可以通过Method类的isBridge方法来判断一个方法是否是桥 ...
- Elasticsearch.Net
今天使用Elasticsearch作开发,很简单的查询,就出现Elasticsearch.Net.UnexpectedElasticsearchClientException异常,看样子像是序列化的异 ...
- WP | BUGKU 论剑
题目:bugku Misc论剑 第一步:在winhex里分析 发现文件头有两个 两个jpg文件中间还有一段二进制码 在kali里分离出两个一样jpg图片,但是没有什么发现 二进制码解出来也没有flag ...
- 第九章 Nacos Config--服务配置
今天咱们接着 上一篇 第八章 SMS–短信服务 继续写 SpringCloud Alibaba全家桶 -> 第九章 Nacos Config–服务配置,废话不多说,开干 9.1 服务配置中心介绍 ...
- C# 如何查询字符串前面有几个0
有几个0 string t = "0001203"; int tLen = t.Length - t.TrimStart('0').Length; charAt方法 using S ...
- C#获取时间戳的几种方式
Console.WriteLine(Convert.ToDouble(DateTime.UtcNow.Ticks - 621355968000000000) / (10 * 1000 * 1000)) ...
- Selenium Web元素操作
我们定位到Web页面元素之后,可以对元素进行一系列的操作,实现跟页面的交互.包括点击.文本输入.元素属性获取等.常用的方法列举如下: 方法 描述 click() 点击元素 send_keys(**va ...