Shiro 安全框架 2(springboot整合、认证、授权)

文章目录

    • 1、Shiro 与Spring boot整合
      • 1.1、搭建spring boot环境
      • 1.2、spring boot整合shiro
    • 2、认证实例
      • 2.1、登录\退出 实例
      • 2.2、连接数据库、MD5加密+“盐”
        • 2.2.1、数据库与mybatis
        • 2.2.2、页面
        • 2.2.3、密码加密(注册)
        • 2.2.4、验证密码(登录)
    • 3、报错
    • 4、授权实例
      • 4.1、授权持久化
        • 4.1.1、mysql建表与dao层
        • 4.1.2、服务层与控制层
    • 5、代码总结

1、Shiro 与Spring boot整合

1.1、搭建spring boot环境

创建需要勾选的依赖
Shiro 安全框架 2(springboot整合、认证、授权)_第1张图片
手动导入的jsp依赖

		
        <dependency>
            <groupId>org.apache.tomcat.embedgroupId>
            <artifactId>tomcat-embed-jasperartifactId>
            <version>7.0.59version>
        dependency>
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

因为有jsp,我们设置一下工作路径
Shiro 安全框架 2(springboot整合、认证、授权)_第2张图片
application.properties(配置端口、路径、jsp等)

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

spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

新建一个jsp页面
Shiro 安全框架 2(springboot整合、认证、授权)_第3张图片

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>

<html>
<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>jsp indextitle>
head>
<body>
    <h1>1111h1>
body>
html>

同样的代码,再新建一个login.jsp
Shiro 安全框架 2(springboot整合、认证、授权)_第4张图片

运行并访问试试
Shiro 安全框架 2(springboot整合、认证、授权)_第5张图片

1.2、spring boot整合shiro

依赖

		<dependency>
			<groupId>org.apache.shirogroupId>
			<artifactId>shiro-spring-boot-web-starterartifactId>
			<version>1.4.1version>
		dependency>

开始配置shiro环境
新建shiro配置类ShiroConfig.java

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;

/*
* 整合shiro框架
* */
@Configuration
public class ShiroConfig {

    @Bean( name="shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getFilter(DefaultWebSecurityManager defaultWebSecurityManager){
        // 负责拦截所有请求
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 配置公共资源和受限资源
        Map<String,String> map = new HashMap<String,String>();
        map.put("/","authc");             // authc 表示请求这个资源需要认证和授权
        map.put("/index.jsp","authc");
        // 默认认证界面路径(也就是不管你访问哪个界面,都会先跳到这个界面认证)
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

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


    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }
}

新建CustomerRealm.java

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/*
* 自定义Realm
* */
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        return null;
    }
}

所有请求都需要认证如下
Shiro 安全框架 2(springboot整合、认证、授权)_第6张图片
如上图,有个authc表示请求这个资源需要认证和授权,更多过滤器如下
Shiro 安全框架 2(springboot整合、认证、授权)_第7张图片

2、认证实例

2.1、登录\退出 实例

新建一个UserController.java

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.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("user")
public class UserController {
    // 处理身份认证
    @RequestMapping("login")
    public String login(String username,String password){
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
        } catch (UnsupportedTokenException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }
        return "redirect:/index.jsp";
    }

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

login.jsp
Shiro 安全框架 2(springboot整合、认证、授权)_第8张图片
index.jsp
Shiro 安全框架 2(springboot整合、认证、授权)_第9张图片
修改CustomerRealm.java
Shiro 安全框架 2(springboot整合、认证、授权)_第10张图片

        String principal = (String) authenticationToken.getPrincipal();

        if ("zhang".equals(principal)) {
            return new SimpleAuthenticationInfo(principal,"123",this.getName());
        }

修改ShiroConfig.java
指定公共资源和需要认证的资源
Shiro 安全框架 2(springboot整合、认证、授权)_第11张图片

2.2、连接数据库、MD5加密+“盐”

pom中引入mysql、mybatis、druid依赖

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.2version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
         <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.19version>
        dependency>

2.2.1、数据库与mybatis

在mysql中新建库shiro,新建表t_user

create database shiro;

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(40) NOT NULL,
  `password` varchar(40) NOT NULL,
  `salt` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

application.properties配置数据库与mybatis

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

spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

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.example.demo.entity
mybatis.mapper-locations=classpath:/mapper/*.xml

新建实体类User.java

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String username;
    private String password;
    private String salt;

}

Shiro 安全框架 2(springboot整合、认证、授权)_第12张图片
新建接口UserDao
Shiro 安全框架 2(springboot整合、认证、授权)_第13张图片

import com.example.demo.entity.User;
import org.springframework.stereotype.Service;

@Mapper
public interface UserDao {
    void save(User user);
}

新建User对应的mapper.xml
Shiro 安全框架 2(springboot整合、认证、授权)_第14张图片




<mapper namespace="com.example.demo.dao.UserDao">
    <insert id="save" parameterType="com.example.demo.entity.User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user values(#{id},#{username},#{password},#{salt})
    insert>
mapper>

新建接口UserService
Shiro 安全框架 2(springboot整合、认证、授权)_第15张图片

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;

public interface UserService {
    // 用户注册
    void register(User user);
}

2.2.2、页面

添加一个注册页面regedit.jsp (从登录页面复制过来修改的)
Shiro 安全框架 2(springboot整合、认证、授权)_第16张图片

在ShiroConfig,java里面放行注册页面、注册路径
Shiro 安全框架 2(springboot整合、认证、授权)_第17张图片

2.2.3、密码加密(注册)

新建工具类SaltUtils.java用来生成随机盐

import java.util.Random;

public class SaltUtils {
    public static String getSalt(int n){
        char[] chars = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP0123456789,./;'[]-=".toCharArray();
        StringBuilder s = new StringBuilder();
        for (int i=0;i<n;i++){
            char a = chars[new Random().nextInt(chars.length)];
            s.append(a);
        }
        return s.toString();
    }
}

新建UserServiceImpl.java里面完成注册业务

import com.example.demo.SaltUtils;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements UserService{
    @Autowired
    private UserDao userDao;
    @Override
    public void register(User user) {
        // 处理业务
        // 密码md5+salt+hash散列
        String salt = SaltUtils.getSalt(6);
        Md5Hash newPassword = new Md5Hash(user.getPassword(),salt,1024);

        user.setSalt(salt);
        user.setPassword(newPassword.toHex());

        userDao.save(user);

    }
}

Shiro 安全框架 2(springboot整合、认证、授权)_第18张图片
在UserController里面添加注册
Shiro 安全框架 2(springboot整合、认证、授权)_第19张图片

Shiro 安全框架 2(springboot整合、认证、授权)_第20张图片


    @Autowired
    private UserService userService;


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

运行项目试试能不能注册了
Shiro 安全框架 2(springboot整合、认证、授权)_第21张图片
注册完看看数据库
在这里插入图片描述
目前项目目录结构
Shiro 安全框架 2(springboot整合、认证、授权)_第22张图片

2.2.4、验证密码(登录)

在配置文件里面添加logging日志
Shiro 安全框架 2(springboot整合、认证、授权)_第23张图片

在UserDao接口中加入查询方法
Shiro 安全框架 2(springboot整合、认证、授权)_第24张图片
在UserDaoMapper.xml里面实现查询数据库
Shiro 安全框架 2(springboot整合、认证、授权)_第25张图片
在业务层接口添加上对应的方法
Shiro 安全框架 2(springboot整合、认证、授权)_第26张图片
在业务层接口实现类添加上对应的方法
Shiro 安全框架 2(springboot整合、认证、授权)_第27张图片新建ApplicationContextUtils.java (用来在工厂中获取service对象)

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
    // 根据bean的名字获取工厂中指定bean
    public static Object getBean(String beanName){
        return context.getBean(beanName);
    }
}

Shiro 安全框架 2(springboot整合、认证、授权)_第28张图片

定义realm到目前全部代码 (这里添加了md5验证、加盐、散列)
CustomerRealm.java

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.ObjectUtils;

/*
* 自定义Realm
* */
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        // 在工厂中获取service对象
        UserService us= (UserService) ApplicationContextUtils.getBean("userServiceImpl");
        User user = us.findByUsername(principal);

        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return null;
    }
}

ShiroConfig.java到目前为止所有代码

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;

/*
* 整合shiro框架
* */
@Configuration
public class ShiroConfig {

    @Bean( name="shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getFilter(DefaultWebSecurityManager defaultWebSecurityManager){
        // 负责拦截所有请求
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 配置公共资源和受限资源
        Map<String,String> map = new HashMap<String,String>();
        map.put("/user/login","anon");           // anon 这个资源不需要认证
        map.put("/user/register","anon");
        map.put("/regedit.jsp","anon");
        map.put("/**","authc");                  // authc 表示请求这个资源需要认证和授权
        // 默认认证界面路径(也就是不管你访问哪个界面,都会先跳到这个界面认证)
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

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


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

如上运行后就能成功认证了

3、报错

如果报错java.lang.NoSuchMethodError: org.apache.tomcat.JarScanner.scan…
Shiro 安全框架 2(springboot整合、认证、授权)_第29张图片

可能是因为自己引入的tomcat版本和springboot自带的不一致导致出现此问题
所以要么删除自己引入的tomcat,要么去掉springboot内置的tomcat
Shiro 安全框架 2(springboot整合、认证、授权)_第30张图片
这里我不需要外置tomcat,所以我删除了tomcat依赖
Shiro 安全框架 2(springboot整合、认证、授权)_第31张图片

4、授权实例

修改自定义Realm
Shiro 安全框架 2(springboot整合、认证、授权)_第32张图片
CustomerRealm.java目前全部代码

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.ObjectUtils;

/*
* 自定义Realm
* */
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取身份信息
        String pp = (String) principalCollection.getPrimaryPrincipal();
        // 根据主身份信息获取角色 和 权限信息
        if("a".equals(pp)){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRole("admin");
            simpleAuthorizationInfo.addRole("user");
//            simpleAuthorizationInfo.addStringPermission("user:*:* ");
            simpleAuthorizationInfo.addStringPermission("user:add:* ");
            simpleAuthorizationInfo.addStringPermission("user:del:* ");
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        // 在工厂中获取service对象
        UserService us= (UserService) ApplicationContextUtils.getBean("userService");
        User user = us.findByUsername(principal);

        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return null;
    }
}

index.jsp目前全部代码

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

<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>jsp indextitle>
head>
<body>
    <h1>index界面h1>
    <a href="${pageContext.request.contextPath}/user/logout">退出a>

    <%--user或admin组都可以看到--%>
    <shiro:hasAnyRoles name="user,admin">
        <li><a href="">商品管理a>li>
        <li><a href="">订单管理a>li>
    shiro:hasAnyRoles>

    <%--只有admin可以看到--%>
    <shiro:hasRole name="admin">
        <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>
            ul>
        li>
        <li><a href="">物流管理a>li>
    shiro:hasRole>

body>
html>

新建OrderController.java

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
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.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
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;

/**
 * @Author BeanInJ
 * @Date 16:04 2021/1/14
 **/
@Controller
@RequestMapping("order")
public class OrderController {
    @RequestMapping("save")
//    @RequiresRoles("admin")  //判断角色
//    @RequiresRoles(value = {"admin","user"})  //判断角色  同时具有admin、user
    @RequiresPermissions("user:del:01")    // 判断权限字符串
    public String save(){
        // 代码方式授权
        Subject subject = SecurityUtils.getSubject();
        if (subject.hasRole("admin")) {
            System.out.println("保存订单");
        }else {
            System.out.println("无权访问");
        }
        return "redirect:/index.jsp";
    }
}

4.1、授权持久化

4.1.1、mysql建表与dao层

在shiro数据库新建表t_role、t_perms、t_role_perms、t_user_role
Shiro 安全框架 2(springboot整合、认证、授权)_第33张图片

DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;


DROP TABLE IF EXISTS `t_pers`;
CREATE TABLE `t_pers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `url` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

DROP TABLE IF EXISTS `t_role_perms`;
CREATE TABLE `t_role_perms` (
  `id` int NOT NULL AUTO_INCREMENT,
  `roleid` int DEFAULT NULL,
  `permsid` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

添加几个用户
Shiro 安全框架 2(springboot整合、认证、授权)_第34张图片

添加三个角色
Shiro 安全框架 2(springboot整合、认证、授权)_第35张图片
为用户添加对应的角色
Shiro 安全框架 2(springboot整合、认证、授权)_第36张图片
新建表对应的实体类
Role.java

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Role {
    private int id;
    private String name;

}

Perms.java

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Perms {
    private int id;
    private String name;
    private String url;
}

在user实体类中定义角色集合
Shiro 安全框架 2(springboot整合、认证、授权)_第37张图片
在UserDao里面增加根据用户名获取角色信息
Shiro 安全框架 2(springboot整合、认证、授权)_第38张图片

在mapper里面添加上对应的查询sql语句
Shiro 安全框架 2(springboot整合、认证、授权)_第39张图片

    <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="">
        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>

4.1.2、服务层与控制层

UserService添加findRolesByUserName查询方法
Shiro 安全框架 2(springboot整合、认证、授权)_第40张图片
UserServiceImpl
Shiro 安全框架 2(springboot整合、认证、授权)_第41张图片
修改自定义realm中的权限部分
Shiro 安全框架 2(springboot整合、认证、授权)_第42张图片

        UserService us= (UserService) ApplicationContextUtils.getBean("userService");
        User user = us.findRolesByUserName(pp);
        // 授权角色
        if(!CollectionUtils.isEmpty(user.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
            });
            return simpleAuthorizationInfo;
        }

5、代码总结

到目前为止,做了认证、角色权限,项目目录结构我修改了一下,如下
Shiro 安全框架 2(springboot整合、认证、授权)_第43张图片
ShiroConfig.java

import com.beaninj.shiro.util.MyRealm;
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 = "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");
        map.put("/user/login", "anon");           // anon 这个资源不需要认证
        map.put("/user/register", "anon");
        map.put("/register.jsp", "anon");
        map.put("/login.jsp", "anon");
        // authc 表示请求这个资源需要认证和授权

        // 默认认证界面路径 (也就是不管你访问哪个界面,都会先跳到这个界面认证)
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        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);
        return myRealm;
    }
}

UserServiceImpl.java

import com.beaninj.shiro.dao.UserDao;
import com.beaninj.shiro.entity.User;
import com.beaninj.shiro.util.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("userService")
@Transactional  // 开启事务
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public void register(User user) {
        // 密码md5+salt+hash散列
        System.out.println("-----------------注册:存入md5+salt+hash散列的密码---------------");
        String salt = SaltUtils.getSalt(6);
        Md5Hash newPassword = new Md5Hash(user.getPassword(), salt, 1024);

        user.setSalt(salt);
        user.setPassword(newPassword.toHex());

        userDao.save(user);

    }

    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public User findRolesByUserName(String username) {
        return userDao.findRolesByUserName(username);
    }


}

ApplicationContextUtils.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    // 根据bean的名字获取工厂中指定bean
    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }
}

MyRealm.java

import com.beaninj.shiro.entity.User;
import com.beaninj.shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

public class MyRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取身份信息
        String pp = (String) principalCollection.getPrimaryPrincipal();
        // 根据主身份信息获取角色 和 权限信息
        UserService us = (UserService) ApplicationContextUtils.getBean("userService");
        User user = us.findRolesByUserName(pp);
        // 授权角色
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        // 在工厂中获取service对象
        UserService us= (UserService) ApplicationContextUtils.getBean("userService");
        User user = us.findByUsername(principal);

        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return null;
    }
}

SaltUtils.java

import java.util.Random;

public class SaltUtils {
    public static String getSalt(int n) {
        char[] chars = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP0123456789,./;'[]-=".toCharArray();
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char a = chars[new Random().nextInt(chars.length)];
            s.append(a);
        }
        return s.toString();
    }
}

UserDaoMapper.xml




<mapper namespace="com.beaninj.shiro.dao.UserDao">
    <insert id="save" parameterType="com.beaninj.shiro.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.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>
mapper>

application.properties

server.port=8081
server.servlet.context-path=/shiro
spring.application.name=shiro
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
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.entity
mybatis.mapper-locations=classpath:/mapper/*.xml
logging.level.com.example.demo.dao=debug

index.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

<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>jsp indextitle>
head>
<body>
<h1>index界面h1>
<a href="${pageContext.request.contextPath}/user/logout">退出a>

user或admin组都可以看到
<shiro:hasAnyRoles name="user,admin">
    <li><a href="">商品管理a>li>
    <li><a href="">订单管理a>li>
shiro:hasAnyRoles>

<%--只有admin可以看到--%>
<shiro:hasRole name="admin">
    <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>
        ul>
    li>
    <li><a href="">物流管理a>li>
shiro:hasRole>

body>
html>

logoin.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>

<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>jsp logintitle>
head>
<body>
<h1>请先登录h1>
<a href="register.jsp">注册a>
<form action="${pageContext.request.contextPath}/user/login">
    用户名:<input type="text" name="username"> <br>
    密码:<input type="text" name="password"> <br>
    <input type="submit" value="登录">
form>
body>
html>

register.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>

<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>jsp regedittitle>
head>
<body>
<h1>注册页面h1>
<form action="${pageContext.request.contextPath}/user/register">
    用户名:<input type="text" name="username"> <br>
    密码:<input type="text" name="password"> <br>
    <input type="submit" value="注册">
form>
body>
html>

pom.xml



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.4.1version>
    <relativePath/> 
  parent>

  <groupId>com.beaninjgroupId>
  <artifactId>springboot_shiroartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>
  <name>springboot_shironame>

  <properties>
    <java.version>1.8java.version>
  properties>


  <dependencies>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-devtoolsartifactId>
      <scope>runtimescope>
      <optional>trueoptional>
    dependency>
    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <optional>trueoptional>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-testartifactId>
      <scope>testscope>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-maven-pluginartifactId>
      <version>2.4.0version>
    dependency>
    
    <dependency>
      <groupId>org.apache.tomcat.embedgroupId>
      <artifactId>tomcat-embed-jasperartifactId>
    dependency>
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
    dependency>
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.1.19version>
    dependency>
    <dependency>
      <groupId>org.mybatis.spring.bootgroupId>
      <artifactId>mybatis-spring-boot-starterartifactId>
      <version>2.1.2version>
    dependency>
    
    <dependency>
      <groupId>org.apache.shirogroupId>
      <artifactId>shiro-spring-boot-web-starterartifactId>
      <version>1.4.1version>
    dependency>
  dependencies>

project>

你可能感兴趣的:(java系列,shiro,mybatis,mysql,spring,springboot)