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完成验证码校验的更多相关文章

  1. springboot集成shiro实现验证码校验

    github:https://github.com/peterowang/shiro/ 这里实现验证码校验的思路是自己添加一个Filter继承FormAuthenticationFilter,Form ...

  2. 18.Shiro与Springboot整合下登陆验证UserService未注入的问题

    Shiro与Springboot整合下登陆验证UserService未注入的问题 前言: 刚开始整合的情况下,UserService一执行,就会报空指针异常. 看了网上各位大神的讲解,什么不能用ser ...

  3. 补习系列(6)- springboot 整合 shiro 一指禅

    目标 了解ApacheShiro是什么,能做什么: 通过QuickStart 代码领会 Shiro的关键概念: 能基于SpringBoot 整合Shiro 实现URL安全访问: 掌握基于注解的方法,以 ...

  4. SpringBoot系列十二:SpringBoot整合 Shiro

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合 Shiro 2.具体内容 Shiro 是现在最为流行的权限认证开发框架,与它起名的只有最初 ...

  5. SpringBoot整合Shiro实现基于角色的权限访问控制(RBAC)系统简单设计从零搭建

    SpringBoot整合Shiro实现基于角色的权限访问控制(RBAC)系统简单设计从零搭建 技术栈 : SpringBoot + shiro + jpa + freemark ,因为篇幅原因,这里只 ...

  6. springboot整合Shiro功能案例

    Shiro 核心功能案例讲解 基于SpringBoot 有源码 从实战中学习Shiro的用法.本章使用SpringBoot快速搭建项目.整合SiteMesh框架布局页面.整合Shiro框架实现用身份认 ...

  7. SpringBoot整合Shiro实现权限控制,验证码

    本文介绍 SpringBoot 整合 shiro,相对于 Spring Security 而言,shiro 更加简单,没有那么复杂. 目前我的需求是一个博客系统,有用户和管理员两种角色.一个用户可能有 ...

  8. SpringBoot 整合Shiro 一指禅

    目标 了解ApacheShiro是什么,能做什么: 通过QuickStart 代码领会 Shiro的关键概念: 能基于SpringBoot 整合Shiro 实现URL安全访问: 掌握基于注解的方法,以 ...

  9. SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理|前后端分离(下)----筑基后期

    写在前面 在上一篇文章<SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理(上)----筑基中期>当中,我们初步实现了SpringBoot整合Shiro ...

随机推荐

  1. 题解-JSOI2011 分特产

    题面 JSOI2011 分特产 有 \(n\) 个不同的盒子和 \(m\) 种不同的球,第 \(i\) 种球有 \(a_i\) 个,用光所有球,求使每个盒子不空的方案数. 数据范围:\(1\le n, ...

  2. 《图解TCP/IP》笔记

    OSI参考模型 协议分层 为什么需要分层? 简化网络协议. 每一层只需要衔接上下层的服务. 利于模块化开发. 解耦. 分层的问题 过分模块化.提高数据处理的开销. OSI参考模型 作用及意义 将复杂的 ...

  3. TimSort源码详解

    Python的排序算法由Peter Tim提出,因此称为TimSort.它最先被使用于Python语言,后被多种语言作为默认的排序算法.TimSort实际上可以看作是mergeSort+binaryS ...

  4. [Python] 快速爬取当前城市所有租房网站房源及配置,一目了然

    Python爬取当前城市房源信息,以徐州为例代码效果图请看下方,其他部分请查看附件,一起学习,谢谢 # -*- coding: utf-8 -*- """ @Time : ...

  5. Jmeter(9)常用定时器

    测试计划中元件的执行顺序依次为: 配置元件--逻辑控制器--前置处理器--定时器--取样器--后置处理器--断言--监听器 一.定时器作用域 1.定时器是在每个取样器之前执行的,无论定时器是在取样器之 ...

  6. 软件工程与UML的第一次课

    | 这个作业属于哪个课程 | https://edu.cnblogs.com/campus/fzzcxy/2018SE1 | | 这个作业要求在哪里 | https://edu.cnblogs.com ...

  7. springmvc中ModelAttribute注解应用在参数中

    可以用@ModelAttribute来注解方法参数或方法.带@ModelAttribute创建的参数对象会被添加到Model对象中.注解在参数上时,可以从Form表单或URL参数中获取参数并绑定到mo ...

  8. robotframework中的参数展开

    robot调用关键字传参的方式是用分隔符分开不同参数,如 keyword arg1 arg2 arg3 arg4 当参数中传入了使用@符号的列表变量时,@符号会将列表展开: @{list1}= Cre ...

  9. Appium App UI 自动化测试理论知识

    (一)App自动化测试背景 随着移动终端的普及,手机应用越来越多,也越来越重要.App的回归测试用例数量越来越多,全量回归也越来越消耗时间.另外移动端碎片化严重(碎片化:兼容性测试,手机品牌多样.An ...

  10. Ubuntu系统的ifconfig命令不能执行

    新安装的Ubuntu想要用WinSCP传文件时发现,ifconfig命令用不了 ping www.baidu.com 获得回应,应该是ifconfig未安装 解决这个问题,首先如图(时间较长,获取:[ ...