Shiro 安全框架 3(授权、EhCache缓存、redis缓存、验证码认证、shiro提供的标签、整合thymeleaf)

本文详细介绍了如何使用Shiro进行权限管理,包括资源权限的定义、EhCache和Redis缓存的配置、验证码的生成与验证、Thymeleaf模板引擎的整合以及Shiro标签的使用。同时,展示了如何在Thymeleaf中使用Shiro标签实现用户认证和授权的相关功能。
摘要由CSDN通过智能技术生成

1、资源权限

上一章介绍了与springboot整合、认证、角色权限,下面开始资源权限的设计。

1.1、定义权限集合

在角色实体类Role里面定义权限集合

在这里插入图片描述
userdao添加根据角色id查询权限集合
在这里插入图片描述

服务层和服务实现层写上这个方法
在这里插入图片描述

在这里插入图片描述

在realm中拿到权限信息
在这里插入图片描述

数据库t_perms添加两条数据
在这里插入图片描述

t_role_perms
在这里插入图片描述

添加对应的mapper select标签在这里插入图片描述

    <select id="findPermsByRoleId" parameterType="int" resultType="Perms">
        SELECT * FROM t_role r
        LEFT JOIN t_role_perms rp ON r.id = rp.roleid
        LEFT JOIN t_perms p ON rp.permsid = p.id
        WHERE r.id=#{id}
    </select>

到此我们运行试试
在这里插入图片描述
访问

在这里插入图片描述
在这里插入图片描述
修改jsp中的权限标签
在这里插入图片描述
重启、访问
在这里插入图片描述

2、缓存权限数据

shiro为我们提供了CacheManager接口
在这里插入图片描述

2.1、EhCache缓存

EhCache缓存是shiro中默认实现的缓存

依赖

    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-ehcache</artifactId>
      <version>1.4.1</version>
    </dependency>

在shiro配置类中开启缓存管理
在这里插入图片描述

        // 开启缓存
        myRealm.setCacheManager(new EhCacheManager());
        // 全局都开启
        myRealm.setCachingEnabled(true);
        // 开启授权的缓存
        myRealm.setAuthorizationCachingEnabled(true);
        // 为授权缓存起一个名字(不起也可以,有默认的名字)
        myRealm.setAuthorizationCacheName("authorizationCache");
        // 开启认证的缓存
        myRealm.setAuthenticationCachingEnabled(true);
        // 为认证缓存起一个名字(不起也可以,有默认的名字)
        myRealm.setAuthenticationCacheName("authenticationCache");

接下来运行项目,登录、然后进入首页不断刷新,后台就不会出现频繁查数据库的操作了
在这里插入图片描述

2.2、redis缓存

上一章我们采用的EhCache缓存,这一章我们使用redis做缓存
我们把EhCache的依赖注释掉。

加上redis依赖

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

启动本机的redis服务(这里我是windows)

windows版下载地址:https://github.com/MSOpenTech/redis/tags

在这里插入图片描述
在项目里配置redis连接
在这里插入图片描述

spring.redis.port=6379
spring.redis.host=localhost
spring.redis.database=0
2.2.1、自定义一个redis缓存管理器

新建MyBySource.java (redis里面要序列化,shiro自带的ByteSource.Util不能序列化,这个类解决这个问题)
新建RedisCache.java (写增删改查操作,用一个map来存用户账户、密码)
新建RedisCacheManager.java (缓存管理器)
在这里插入图片描述

MyBySource.java

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 java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;

// 自定义salt 实现序列化接口
public class MyBySource implements ByteSource,Serializable {
    private byte[] bytes;
    private String cachedHex;
    private String cachedBase64;
    public MyBySource(){

    }
    public MyBySource(byte[] bytes) {
        this.bytes = bytes;
    }

    public MyBySource(char[] chars) {
        this.bytes = CodecSupport.toBytes(chars);
    }

    public MyBySource(String string) {
        this.bytes = CodecSupport.toBytes(string);
    }

    public MyBySource(ByteSource source) {
        this.bytes = source.getBytes();
    }

    public MyBySource(File file) {
        this.bytes = (new MyBySource.BytesHelper()).getBytes(file);
    }

    public MyBySource(InputStream stream) {
        this.bytes = (new MyBySource.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 byte[] getBytes() {
        return this.bytes;
    }

    public boolean isEmpty() {
        return this.bytes == null || this.bytes.length == 0;
    }

    public String toHex() {
        if (this.cachedHex == null) {
            this.cachedHex = Hex.encodeToString(this.getBytes());
        }

        return this.cachedHex;
    }

    public String toBase64() {
        if (this.cachedBase64 == null) {
            this.cachedBase64 = Base64.encodeToString(this.getBytes());
        }

        return this.cachedBase64;
    }

    public String toString() {
        return this.toBase64();
    }

    public int hashCode() {
        return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
    }

    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里面的盐改成MyBySource对象
在这里插入图片描述
将三个实体类都加上序列化
在这里插入图片描述
RedisCache.java

import com.beaninj.shiro.util.ApplicationContextUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Collection;
import java.util.Set;


/*
 * @Author BeanInJ
 * @Date 17:22 2021/1/21
 *
 * 自定义redis缓存的实现
 **/
public class RedisCache<k,v> implements Cache<k,v> {
    private String cacheName;
    public RedisCache(){

    }
    public RedisCache(String cacheName) {
        this.cacheName=cacheName;
    }

    @Override
    public v get(k k) throws CacheException {
        System.out.println("redis缓存:get :"+k);
        return (v) getRedisTemplate().opsForHash().get(this.cacheName,k.toString());
    }

    @Override
    public v put(k k, v v) throws CacheException {
        System.out.println("redis缓存:put :"+k+","+v);
        // 存入redis
        getRedisTemplate().opsForHash().put(this.cacheName,k.toString(),v);
        return null;
    }

    @Override
    public v remove(k k) throws CacheException {
        return null;
    }

    @Override
    public void clear() throws CacheException {

    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public Set<k> keys() {
        return null;
    }

    @Override
    public Collection<v> values() {
        return null;
    }

    private RedisTemplate getRedisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        // 这里的k是一个字符串、v是一个对象,所以我们把redisTemplate的key的序列化方式,改成string类型的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

RedisCacheManager.java

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;

public class RedisCacheManager implements CacheManager {
    // getCache(String s) s传的是授权或认证缓存的名称
    @Override
    public <K, V> Cache<K, V> getCache(String s) throws CacheException {
        return new RedisCache<K, V>(s);
    }
}

在shiro配置类里面开启这个redis缓存管理器
在这里插入图片描述

        // 开启缓存
        myRealm.setCacheManager(new RedisCacheManager());
        // 全局都开启
        myRealm.setCachingEnabled(true);
        // 开启授权的缓存
        myRealm.setAuthorizationCachingEnabled(true);
        // 为授权缓存起一个名字(不起也可以,有默认的名字)
        myRealm.setAuthorizationCacheName("authorizationCache");
        // 开启认证的缓存
        myRealm.setAuthenticationCachingEnabled(true);
        // 为认证缓存起一个名字(不起也可以,有默认的名字)
        myRealm.setAuthenticationCacheName("authenticationCache");

然后重启项目,访问、登录
在这里插入图片描述
查看后台
在这里插入图片描述
查看redis
在这里插入图片描述

2.2.2、redis的增删改查

在上一节中的RedisCache中,我们只实现了get、put,下面把其他的也实现了

RedisCache.java中的完整内容

import com.beaninj.shiro.util.ApplicationContextUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Collection;
import java.util.Set;


/*
 * @Author BeanInJ
 * @Date 17:22 2021/1/21
 *
 * 自定义redis缓存的实现
 **/
public class RedisCache<k,v> implements Cache<k,v> {
    private String cacheName;
    public RedisCache(){

    }
    public RedisCache(String cacheName) {
        this.cacheName=cacheName;
    }

    @Override
    public v get(k k) throws CacheException {
        System.out.println("redis缓存:get :"+k);
        return (v) getRedisTemplate().opsForHash().get(this.cacheName,k.toString());
    }

    @Override
    public v put(k k, v v) throws CacheException {
        System.out.println("redis缓存:put :"+k+","+v);
        // 存入redis
        getRedisTemplate().opsForHash().put(this.cacheName,k.toString(),v);
        return null;
    }

    @Override
    public v remove(k k) throws CacheException {
        return (v) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString());
    }

    @Override
    public void clear() throws CacheException {
        getRedisTemplate().delete(this.cacheName);
    }

    @Override
    public int size() {
        return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
    }

    @Override
    public Set<k> keys() {
        return getRedisTemplate().opsForHash().keys(this.cacheName);
    }

    @Override
    public Collection<v> values() {
        return getRedisTemplate().opsForHash().values(this.cacheName);
    }

    private RedisTemplate getRedisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        // 这里的k是一个字符串、v是一个对象,所以我们把redisTemplate的key的序列化方式,改成string类型的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

当用户退出登录的时候,会执行以上代码中的remove方法

3、加入验证码

新建一个验证码工具类VerifyCodeUtils.java

package com.beaninj.shiro.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
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;

import javax.imageio.ImageIO;

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{
        File dir = new File("D:/upload/verifyCode");
        int w = 200, h = 80;
        for(int i = 0; i < 50; i++){
            String verifyCode = generateVerifyCode(4);
            File file = new File(dir, verifyCode + ".jpg");
            outputImage(w, h, file, verifyCode);
        }
    }
}

在UserController.java里面加一个验证码请求方法
在这里插入图片描述

    @RequestMapping("getImg")
    public void getImg(HttpSession session, HttpServletResponse httpServletResponse) throws IOException {
        // 生成验证码
        String s = VerifyCodeUtils.generateVerifyCode(4);
        // 放入session
        session.setAttribute("code",s);
        // 生成图片
        ServletOutputStream os = httpServletResponse.getOutputStream();
        httpServletResponse.setContentType("img/png");
        VerifyCodeUtils.outputImage(220,60,os,s);
    }

将/user/getImg这个资源放行
这里我直接将user下的所有资源都放行了
在这里插入图片描述

在用户登录页面加入一个图片标签,用来放验证码图片
在这里插入图片描述
改造UserController里的登录方法,login

// 处理身份认证、验证码
    @RequestMapping("login")
    public String login(String username, String password, String code, HttpSession session) {
        try {
            // 比较验证码
            String codeInSession = (String) session.getAttribute("code");
            System.out.println(codeInSession);
            if (codeInSession.equals(code)) {
                //获取主体对象
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username, password));
                return "redirect:/index.jsp";
            }
        } catch (UnsupportedTokenException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "redirect:/login.jsp";
    }

重启项目,访问
在这里插入图片描述

3.1、shiro为前端提供的标签

1、在页面加入登录后的身份信息(用户名)
在这里插入图片描述
在这里插入图片描述
2、认证之后才展示的内容
在这里插入图片描述
同样还有没有认证之前展示的内容

<shiro:notAuthenticated>
    没有认证展示的内容
</shiro:notAuthenticated>

4、整合thymeleaf

这里我新建了一个项目,把之前的代码拷过来
代码从另一个项目导过来,注意类里面导包的正确性。

pom.xml(去掉jsp相关依赖,加入thymeleaf依赖)
在这里插入图片描述

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--在html中写shiro标签-->
         <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

修改配置文件,去掉jsp的配置,加上thymeleaf的
在这里插入图片描述

server.port=8081
server.servlet.context-path=/shiro
spring.application.name=shiro

spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.mvc.view.prefix=classpath:/templates/
spring.resources.static-locations=classpath:/static/


spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/shiro?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
mybatis.type-aliases-package=com.beaninj.shiro_thymeleaf.entity
mybatis.mapper-locations=classpath:/mapper/*.xml
logging.level.com.example.demo.dao=debug

spring.redis.port=6379
spring.redis.host=localhost
spring.redis.database=0

4.1、mapper.xml

UserDaoMapper.xml (注意包名)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.beaninj.shiro_thymeleaf.dao.UserDao">
    <insert id="save" parameterType="com.beaninj.shiro_thymeleaf.entity.User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user values(#{id},#{username},#{password},#{salt})
    </insert>
    <select id="findByUsername" parameterType="String" resultType="com.beaninj.shiro_thymeleaf.entity.User">
        select id,username,password,salt from t_user
        where username = #{username}
    </select>
    <resultMap id="userMap" type="User">
        <id column="uid" property="id"/>
        <result column="username" property="username"/>
        <!--角色信息-->
        <collection property="roles" javaType="list" ofType="Role">
            <id column="id" property="id"/>
            <result column="rname" property="name"/>
        </collection>
    </resultMap>
    <select id="findRolesByUserName" parameterType="String" resultMap="userMap">
        SELECT u.id uid,u.username,r.id,r.name rname
        FROM t_user u
        LEFT JOIN t_user_role ur on u.id=ur.userid
        LEFT JOIN t_role r on ur.roleid=r.id
        WHERE u.username=#{username}
    </select>
    <select id="findPermsByRoleId" parameterType="int" resultType="Perms">
        SELECT * FROM t_role r
        LEFT JOIN t_role_perms rp ON r.id = rp.roleid
        LEFT JOIN t_perms p ON rp.permsid = p.id
        WHERE r.id=#{id}
    </select>
</mapper>

4.2、jsp文件改成html

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.com">
<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>thymeleaf login</title>
</head>
<body>
<h1>请先登录</h1>
<a th:href="@{registerhtml}">注册</a>
<form th:action="@{/user/login}" method="post">
    用户名:<input type="text" name="username"> <br>
    密码:<input type="text" name="password"> <br>
    请输入验证码:<input type="text" name="code"><img th:src="@{/user/getImg}"><br>
    <input type="submit" value="登录">
</form>
</body>
</html>

register.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.com">
<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>regedit</title>
</head>
<body>
<h1>注册页面</h1>
<form th:action="@{/user/register}">
    用户名:<input type="text" name="username"> <br>
    密码:<input type="text" name="password"> <br>
    <input type="submit" value="注册">
</form>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.com"
                xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<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>index</title>
</head>
<body>
<h1>index界面</h1>
<a href="@{/user/logout}">退出</a> 

用户名:<shiro:principal />   <br>

<shiro:authenticated>
    认证之后展示的内容
</shiro:authenticated>
<shiro:notAuthenticated>
    没有认证之后展示的内容
</shiro:notAuthenticated>
<!--user或admin组都可以看到-->
<shiro:hasRole name="admin">
    <li><a href="">商品管理</a></li>
    <li><a href="">订单管理</a></li>
</shiro:hasRole>

<!--只有admin可以看到-->
<shiro:hasAnyRoles name="admin,user">
    <li><a href="">用户管理</a>
        <ul>
            <shiro:hasPermission name="user:add:*">
                <li><a href="">添加</a></li>
            </shiro:hasPermission>
            <shiro:hasPermission name="user:del:*">
                <li><a href="">删除</a></li>
            </shiro:hasPermission>
            <shiro:hasPermission name="order:find:*">
                <li><a href="">查询</a></li>
            </shiro:hasPermission>
        </ul>
    </li>
    <li><a href="">物流管理</a></li>
</shiro:hasAnyRoles>

</body>
</html>

4.3、需要修改的java代码

ShiroConfig.java

import com.beaninj.shiro_thymeleaf.util.MyRealm;
import com.beaninj.shiro_thymeleaf.util.cache.RedisCacheManager;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getFilter(DefaultWebSecurityManager dwsManager) {
        // 负责拦截所有请求
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(dwsManager);

        // 配置公共资源和受限资源
        Map<String, String> map = new HashMap<String, String>();
        map.put("/**", "authc");                  // authc 表示请求这个资源需要认证和授权
        map.put("/user/**","anon");               // anon 这个资源不需要认证
        map.put("/register.html", "anon");
        map.put("/login.html", "anon");

        // 默认认证界面路径 (也就是不管你访问哪个界面,都会先跳到这个界面认证)
        shiroFilterFactoryBean.setLoginUrl("/user/loginhtml");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }
    @Bean
    public DefaultWebSecurityManager getManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    @Bean
    public Realm getRealm() {
        MyRealm myRealm = new MyRealm();
        // 修改凭证校验匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // MD5
        credentialsMatcher.setHashAlgorithmName("MD5");
        // 设置散列次数
        credentialsMatcher.setHashIterations(1024);

        myRealm.setCredentialsMatcher(credentialsMatcher);
        // 开启缓存
        myRealm.setCacheManager(new RedisCacheManager());
        // 全局都开启
        myRealm.setCachingEnabled(true);
        // 开启授权的缓存
        myRealm.setAuthorizationCachingEnabled(true);
        // 为授权缓存起一个名字(不起也可以,有默认的名字)
        myRealm.setAuthorizationCacheName("authorizationCache");
        // 开启认证的缓存
        myRealm.setAuthenticationCachingEnabled(true);
        // 为认证缓存起一个名字(不起也可以,有默认的名字)
        myRealm.setAuthenticationCacheName("authenticationCache");


        return myRealm;
    }
}

UserController.java

import com.beaninj.shiro_thymeleaf.entity.User;
import com.beaninj.shiro_thymeleaf.service.UserService;
import com.beaninj.shiro_thymeleaf.util.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    // 之前jsp的时候是直接访问.jsp到页面,这里用一个跳转到页面
    // 比如访问loginhtml就是跳转到login.html,登录提交信息就用login验证账号和密码

    // 跳转页面
    @RequestMapping("registerhtml")
    public String registerhtml() {
        return "register";
    }

    // 跳转页面
    @RequestMapping("loginhtml")
    public String loginhtml() {
        return "login";
    }

    @RequestMapping("getImg")
    public void getImg(HttpSession session, HttpServletResponse httpServletResponse) throws IOException {
        // 生成验证码
        String s = VerifyCodeUtils.generateVerifyCode(4);
        System.out.println("验证码已生成,正在存入session:"+s);
        // 放入session
        session.setAttribute("code", s);
        // 生成图片
        ServletOutputStream os = httpServletResponse.getOutputStream();
        httpServletResponse.setContentType("img/png");
        VerifyCodeUtils.outputImage(220, 60, os, s);
    }

    // 处理身份认证
    @RequestMapping("login")
    public String login(String username, String password, String code, HttpSession session) {
        try {
            // 比较验证码
            String codeInSession = (String) session.getAttribute("code");
            System.out.println(codeInSession);
            if (codeInSession.equals(code)) {
                //获取主体对象
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username, password));
                return "index";
            }
        } catch (UnsupportedTokenException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "login";
    }

    // 退出登录
    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    // 用户注册
    @RequestMapping("register")
    public String register(User user) {
        System.out.println(user.toString());
        try {
            // 注册成功,返回登录界面
            userService.register(user);
            return "login";
        } catch (Exception e) {
            // 失败继续待在注册页面
            e.printStackTrace();
            System.out.println("注册失败");
            return "register";
        }
    }
}

4.4、 Thymeleaf Shiro标签

使用 Thymeleaf Shiro标签需要的依赖

<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version> 
</dependency>

html需要插入的命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.com"
                xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

在配置类中加入方言处理(往ShiroConfig配置类里面加)

    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

Thymeleaf Shiro标签 (原本jsp里面使用的那些shiro标签还是有效的)

<shiro:guest>
    游客访问 <a href="login.jsp"></a>
</shiro:guest>
 
user 标签里面的内容,没登录是不显示的
<shiro:user>
	shiro:principal用来显示用户名,可以写成属性,也可以写成标签
	Subjec.getPrincipal()获取,即Primary Principal
	
    欢迎[<shiro:principal/>]登录 <a href="logout">退出</a>
    <span shiro:principal=""></span>  
</shiro:user>
 
authenticated标签:用户身份验证通过,即 Subjec.login 登录成功 不是记住我登录的
<shiro:authenticted>
    用户[<shiro:principal/>] 已身份验证通过
</shiro:authenticted>
 
notAuthenticated标签:用户未进行身份验证,即没有调用Subject.login进行登录,包括"记住我"也属于未进行身份验证
<shiro:notAuthenticated>
    未身份验证(包括"记住我")
</shiro:notAuthenticated>
 
hasRole标签:如果当前Subject有角色将显示body体内的内容
<shiro:hashRole name="admin">
    用户[<shiro:principal/>]拥有角色admin
</shiro:hashRole>
 
hasAnyRoles标签:如果Subject有任意一个角色(或的关系)将显示body体里的内容
<shiro:hasAnyRoles name="admin,user">
    用户[<shiro:pricipal/>]拥有角色admin 或者 user
</shiro:hasAnyRoles>
 
lacksRole:如果当前 Subjec没有角色将显示body体内的内容
<shiro:lacksRole name="admin">
    用户[<shiro:pricipal/>]没有角色admin
</shiro:lacksRole>
 
hashPermission:如果当前Subject有权限将显示body体内容
<shiro:hashPermission name="user:create">
    用户[<shiro:pricipal/>] 拥有权限user:create
</shiro:hashPermission>
 
lacksPermission:如果当前Subject没有权限将显示body体内容
<shiro:lacksPermission name="org:create">
    用户[<shiro:pricipal/>] 没有权限org:create
</shiro:lacksPermission>

很多标签都可以转为属性使用
比如shiro:hasRole 角色标签

当标签用:
<shiro:hasRole name="admin">
    用户[<shiro:pricipal/>]没有角色admin
</shiro:hasRole>

当属性用:
<span shiro:hasRole="admin">
    用户[<shiro:pricipal/>]没有角色admin
</span>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值