Shiro 整合SpringBoot 开发
导入整合依赖
<!--shiro 整合springboot 依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.5</version>
</dependency>
配置文件:
/**
* @ClassName ShiroConfig
* @author: fangwenjun
* @date: Created in 2021/5/25 13:23
* @description: shiro配置文件
* @version: 1.0
*/
@Configuration
public class ShiroConfig {
// shiro 过滤器
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(){
ShiroFilterFactoryBean factoryFilter = new ShiroFilterFactoryBean();
factoryFilter.setSecurityManager(defaultWebSecurityManager());
// 设置默认登录路径
factoryFilter.setLoginUrl("/login.html");
// 封装每个路径对应的权限过滤器
Map<String,String> filters = new HashMap<>();
// anon 这是匿名访问过滤器,不需要认证
filters.put("/login","anon");
filters.put("/register.html","anon");
filters.put("/register","anon");
// authc 是需要认证过滤器,
filters.put("/**","authc");
factoryFilter.setFilterChainDefinitionMap(filters);
return factoryFilter;
}
// 安全管理器
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager(){\
// 默认的web应用安全管理器, spring会指定放入SecurityUtils中,方便之后使用
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm());
return securityManager;
}
// realm
@Bean
public Realm realm(){
// 自定义的Realm领域, 使用它来实现身份认证和授权的过程
CustomizeRealm realm = new CustomizeRealm();
// 设置加密算法,和哈希散列次数
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
matcher.setHashAlgorithmName("md5");
matcher.setHashIterations(1024);
realm.setCredentialsMatcher(matcher);
return realm;
}
}
自定义Realm
/**
* @ClassName CustomizeRealm
* @author: fangwenjun
* @date: Created in 2021/5/25 13:33
* @description:
* @version: 1.0
*/
public class CustomizeRealm extends AuthorizingRealm {
// 当前realm类已经在配置文件中加入到了IOC容器中,这里直接注入
@Autowired
private UserSerivce userSerivce;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String primaryPrincipal = (String) principals.getPrimaryPrincipal();
// 查询数据库进行授权
User user = userSerivce.findUserRelationInfoByUserName(primaryPrincipal);
// 对数据库中的指定用户的相关权限进行封装
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (Role role : user.getRoleList()) {
info.addRole(role.getRoleName());
for (Permission permission : role.getPermissionList()) {
info.addStringPermission(permission.getUrl());
}
}
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String principal = (String) token.getPrincipal();
// 查询数据库,获取登录用户信息,进行身份认证
User user = userSerivce.findUserByUsername(principal);
if (!ObjectUtils.isEmpty(user)){
// 查询到信息后,进行封装, shiro会使用封装的盐和md5进行密码的匹配
return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this
.getName());
}
return null;
}
}
基本的一些权限相关实体类
public class User {
private String id;
private String username;
private String password;
private String salt;
private List<Role> roleList;
}
public class UserRole {
private String id;
private String userId;
private String roleId;
}
public class Role {
private String id;
private String roleName;
private List<Permission> permissionList;
}
public class RolePermission {
private String id;
private String roleId;
private String permissionId;
}
public class Permission {
private String id;
private String permissionName;
private String url;
}
controller控制层
在controller层编写与配置文件中路径一致的登录接口,进行登录身份验证,除公共资源外,其他受限资源都需要进行授权,使用注解的方式在每个接口上进行权限的限制.
/**
* @ClassName IndexController
* @author: fangwenjun
* @date: Created in 2021/5/25 11:07
* @description:
* @version: 1.0
*/
@Controller
public class IndexController {
@Autowired
private UserSerivce userSerivce;
@GetMapping("/index.html")
public String index(){
return "index";
}
@GetMapping("/login.html")
public String login(){
return "login";
}
@GetMapping("/register.html")
public String register(){
return "register";
}
@PostMapping("/login")
public String loginUser(String username,String password){
// 使用安全工具类获取到登录的主体
Subject subject = SecurityUtils.getSubject();
try {
subject.login(new UsernamePasswordToken(username, password));
if (subject.isAuthenticated()){
return "index";
}
}catch (UnknownAccountException e){
System.out.println("用户名错误");
}catch (IncorrectCredentialsException e){
System.out.println("密码错误");
}
return "login";
}
@PostMapping("/register")
public String register(User user){
try {
userSerivce.registerUser(user);
}catch (Exception e){
e.printStackTrace();
return "register";
}
return "login";
}
@PostMapping("/logout")
public String logout(){
SecurityUtils.getSubject().logout();
return "login";
}
@GetMapping("/order")
@ResponseBody
@RequiresPermissions("order:*:*")
//@RequiresRoles("admin")
public String order(){
return "success";
}
@GetMapping("/item")
@ResponseBody
@RequiresPermissions({"user:add:*"})
public String item(){
return "success";
}
}
缓存认证和授权信息
基础的shiro身份认证和授权的过程已经完成,但是当用户认证成功后的每次授权都会去查询数据库进行获取权限数据,非常耗费性能,因为权限相关的一些信息不是经常修改的,所以可以进行缓存,shiro有自带的本地缓存功能如下:
本地缓存
- 导入缓存依赖
<!-- 引入 shiro缓存依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.5.3</version>
</dependency>
- 在shiro配置文件中的Realm那一块设置开启本地缓存功能
@Bean
public Realm realm(){
CustomizeRealm realm = new CustomizeRealm();
// 设置加密算法,和哈希散列次数
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
matcher.setHashAlgorithmName("md5");
matcher.setHashIterations(1024);
realm.setCredentialsMatcher(matcher);
// shiro 集成本地缓存
realm.setCacheManager(new EhCacheManager());
// 开启授权缓存并设置缓存名称
realm.setAuthorizationCachingEnabled(true);
realm.setAuthorizationCacheName("cacheAuthorization");
// 开启身份认证缓存并设置名称
realm.setAuthenticationCachingEnabled(true);
realm.setAuthenticationCacheName("cacheAuthentication");
return realm;
}
但是当应用宕机或其他原因停止运行时,由于缓存信息是存放在本地内存中,应用一旦停止运行,缓存信息也不复存在.所以可以采用分布式缓存,使用redis替代
redis缓存
- 导入redis spring boot依赖并配置yaml文件中相关基础信息
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 注意: 所有缓存到redis中的相关实体类都必须实现序列化接口,通过自定义redis的缓存管理器,让shiro使用自定义的缓存管理器进行缓存相关数据,
/**
* @ClassName RedisManager
* @author: fangwenjun
* @date: Created in 2021/5/26 14:56
* @description:
* @version: 1.0
*/
public class RedisManager implements CacheManager {
@Override
public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
System.out.println("缓存管理器名称" + cacheName);
return new RedisCache<K,V>(cacheName);
}
}
/**
* @ClassName RedisCache
* @author: fangwenjun
* @date: Created in 2021/5/26 14:57
* @description:
* @version: 1.0
*/
public class RedisCache<K, V> implements Cache<K, V> {
private String cacheName;
public RedisCache(String cacheName) {
this.cacheName = cacheName;
}
@Override
public V get(K k) throws CacheException {
System.out.println("get" + k);
return (V) getRedisTemplate().opsForHash().get(this.cacheName, k.toString());
}
@Override
public V put(K k, V v) throws CacheException {
System.out.println("put key" + k);
System.out.println("put value" + v);
getRedisTemplate().opsForHash().put(this.cacheName, k.toString(), v);
return null;
}
@Override
public V remove(K k) throws CacheException {
System.out.println("remove " + k);
return (V) getRedisTemplate().opsForHash().delete(this.cacheName, k.toString());
}
@Override
public void clear() throws CacheException {
getRedisTemplate().opsForHash().delete(this.cacheName);
}
@Override
public int size() {
return Integer.parseInt(getRedisTemplate().opsForHash().size(this.cacheName).toString());
}
@Override
public Set<K> keys() {
return getRedisTemplate().opsForHash().keys(this.cacheName);
}
@Override
public Collection<V> values() {
return getRedisTemplate().opsForHash().values(this.cacheName);
}
public RedisTemplate getRedisTemplate() {
// 通过spring上下文对象获取容器中指定名称的bean
RedisTemplate redisTemplate = (RedisTemplate) ApplicationFactory.getBean("redisTemplate");
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
}
注意:
这种通过自定义实现redis 管理器的方法去做缓存时,在一开始的进行身份认证的方法时,使用ByteSource.Utils时这个类没有实现序列化接口,所以在进行缓存时会报序列化异常,这时就要通过实现ByteSource接口自己创建一个实现序列化接口的类,使用这个类解析salt
/**
* 解决:
* shiro 使用缓存时出现:java.io.NotSerializableException: org.apache.shiro.util.SimpleByteSource
* 序列化后,无法反序列化的问题
*/
public class MySimpleByteSource implements ByteSource, Serializable {
private static final long serialVersionUID = 1L;
private byte[] bytes;
private String cachedHex;
private String cachedBase64;
public MySimpleByteSource(){
}
public MySimpleByteSource(byte[] bytes) {
this.bytes = bytes;
}
public MySimpleByteSource(char[] chars) {
this.bytes = CodecSupport.toBytes(chars);
}
public MySimpleByteSource(String string) {
this.bytes = CodecSupport.toBytes(string);
}
public MySimpleByteSource(ByteSource source) {
this.bytes = source.getBytes();
}
public MySimpleByteSource(File file) {
this.bytes = (new MySimpleByteSource.BytesHelper()).getBytes(file);
}
public MySimpleByteSource(InputStream stream) {
this.bytes = (new MySimpleByteSource.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;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@Override
public byte[] getBytes() {
return this.bytes;
}
@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 boolean isEmpty() {
return this.bytes == null || this.bytes.length == 0;
}
@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);
}
}
}
整合登录时返回图片验证码进行校验
- controller控制层
@PostMapping("/login")
public String loginUser(String username, String password, String code, HttpSession servletSession) {
String codes = (String) servletSession.getAttribute("code");
try {
if (code.equalsIgnoreCase(codes)) {
Subject subject = SecurityUtils.getSubject();
subject.login(new UsernamePasswordToken(username, password));
if (subject.isAuthenticated()) {
return "index";
}
} else {
throw new RuntimeException("验证码错误");
}
} catch (UnknownAccountException e) {
System.out.println("用户名错误");
} catch (IncorrectCredentialsException e) {
System.out.println("密码错误");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return "login";
}
@GetMapping("/getCode")
public void verifyCode(HttpSession servletSession, HttpServletResponse response) throws IOException {
String code = VerifyCodeUtils.generateVerifyCode(4);
servletSession.setAttribute("code", code);
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("image/png");
VerifyCodeUtils.outputImage(220, 110, outputStream, code);
}
生成图片验证码工具类
package com.block.shiro.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
public class VerifyCodeUtils{
//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 使用系统默认字符源生成验证码
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources){
if(sources == null || sources.length() == 0){
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
}
return verifyCode.toString();
}
/**
* 生成随机验证码文件,并返回验证码值
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 输出随机验证码图片流,并返回验证码值
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 生成指定验证码图像文件
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
if(outputFile == null){
return;
}
File dir = outputFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
}
try{
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch(IOException e){
throw e;
}
}
/**
* 输出指定验证码图片流
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for(int i = 0; i < colors.length; i++){
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h-4);
//绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h-4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for(int i = 0; i < verifySize; i++){
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
private static Color getRandColor(int fc, int bc) {
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);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
public static void main(String[] args) throws IOException {
//获取验证码
String s = generateVerifyCode(4);
//将验证码放入图片中
outputImage(260,60,new File("C:\\Users\\Thinkpad\\Desktop\\a.jpg"),s);
System.out.println(s);
}
}