在 SpringBoot 工程中,通过集成 Shiro 安全框架来完成对当前登录人的权限的控制。
需求如下:
如下图:
页面内容如下(没有权限判断):
 
 root 用户登录:
 
 当然,这个 ADD 链接是可以点击的,点击之后,便显示 add.html 页面内容:
 
 tom 用户登录:同 root 用户登录。只不过页面内容为 UPDATE
【开发环境】:
- IDEA-2020.2
 - SpringBoot-2.5.5
 - MAVEN-3.5.3
 - Shiro
 - Thymeleaf
 - Mybatis
 - Mysql
 - Druid
 
项目结构图
后台:

 前台:

sql 文件
CREATE TABLE `tab_user` (
  `id` varchar(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `pwd` varchar(30) NOT NULL,
  `perms` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
实体类
public class User {
    private String id;
    private String name;
    private String pwd;
    private String perms;
    // getter/setter
}
 
1、引入依赖:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--spring-shiro-->
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring-boot-web-starter</artifactId>
  <version>1.4.0</version>
</dependency>
<!--mybatis-->
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.0.0</version>
</dependency>
<!--mysql-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.38</version>
</dependency>
<!--druid-->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.20</version>
</dependency>
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.17</version>
</dependency>
<!--shiro-thymeleaf-->
<dependency>
  <groupId>com.github.theborakompanioni</groupId>
  <artifactId>thymeleaf-extras-shiro</artifactId>
  <version>2.0.0</version>
</dependency>
 
2、添加 application.yml 配置:
spring:
  thymeleaf:
    cache: false
    prefix: classpath:/templates/  # 配置模板(非必要) 默认是 templates
    suffix: .html
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/zzc?useUnicode=true&characterEncoding=utf8
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
    # SpringBoot 默认不注入下面这些属性值
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    # 配置监控统计拦截的 filters,去掉后监控界面 sql 无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
  type-aliases-package: com.zzc.pojo # 实体类别名
  mapper-locations: classpath:mapper/*.xml # mapper 配置文件(必要)
  configuration:
    #log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 日志输出位置
    map-underscore-to-camel-case: true # 驼峰命名
#logging:
#  level:
#    com.zzc.mapper: debug # 设置日志级别
 
3、后台路由控制器 RoutingController
@Controller
public class RoutingController {
    @GetMapping({"/", "/index"})
    public String index(Model model) {
        model.addAttribute("msg", "Hello Shior");
        return "index";
    }
    @GetMapping("/user/add")
    public String add() {
        return "user/add";
    }
    @GetMapping("/user/update")
    public String update() {
        return "user/update";
    }
    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }
    @PostMapping("/login")
    public String login(String username, String pwd, Model model) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }
    @GetMapping("/noauth")
    @ResponseBody
    public String noauth() {
        return "该页面未授权";
    }
}
 
4、Shiro 配置类 ShiroConfig
同 SpringSecurity,使用 Shiro 也需要添加一个配置类。这个配置类中需要配置三大组件:
- ShiroFilterFactoryBean
 - DefaultWebSecurityManager
 - 自定义 Realm
 
代码如下:
@Configuration
public class ShiroConfig {
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        // 关联 DefaultWebSecurityManager
        filterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 内置过滤器
        /**
         * anno:无需认证就可以访问
         * authc:必须认证才能访问
         * user:必须记住我才能访问
         * perms:拥有某个资源的权限才能访问
         * role:拥有某个角色权限才能访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        // 配置授权
        filterMap.put("/user/add", "perms[user:add]");
        filterMap.put("/user/update", "perms[user:update]");
        
        /*filterMap.put("/user/add", "authc");
        filterMap.put("/user/update", "authc");*/
        filterMap.put("/user/*", "authc");
        filterFactoryBean.setFilterChainDefinitionMap(filterMap);
        // 如果没有权限访问,则跳转到登录页面
        filterFactoryBean.setLoginUrl("/toLogin");
        // 如果没有授权成功,则跳转到未授权页面
        filterFactoryBean.setUnauthorizedUrl("/noauth");
        return filterFactoryBean;
    }
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联 Realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
	// 自定义 Realm
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}
 
说明:
getShiroFilterFactoryBean()方法:
filterMap.put("/user/add", "perms[user:add]");
filterMap.put("/user/update", "perms[user:update]");
 
这块代码表示:
- 访问 
/user/add的 url,需要有user 的 add权限 - 访问 
/user/update的 url,需要有user 的 update权限 
格式:perms[user:add] 是 Shiro 中权限操作的写法。
filterMap.put("/user/*", "authc");
 
这块代码表示:
- 访问以 
user开头的 url,必须要进行认证 
5、自定义的 Realm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();
        info.addStringPermission(currentUser.getPerms());
        return info;
    }
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken;
        // 用户名认证
        String username = userToken.getUsername();
        User user = userService.queryUserByName(username);
        if (null == user) {
            // 返回 null 后,将会抛出异常 UnknownAccountException
            return null;
        }
   
        // 密码认证:Shiro 帮我们做。可以加密
        return new SimpleAuthenticationInfo(user, user.getPwd(), "");
    }
}
 
说明:
- 认证方法 
doGetAuthenticationInfo()中,我们将登录成功的用户信息放入SimpleAuthenticationInfo构造方法中的第一个参数中,即:return new SimpleAuthenticationInfo(user, user.getPwd(), "");中的 user 。然后,授权时,我们才能获取用户信息。即:在 授权方法doGetAuthorizationInfo()中,我们通过代码:Subject subject = SecurityUtils.getSubject(); User currentUser = (User)subject.getPrincipal();获取当前登录用户 
6、UserMapper 接口
由于 UserService 中的代码与 UserMapper 中的代码类似,这里就直接省略 UserService 中的代码,直接贴出 UserMapper 接口代码:
@Repository
public interface UserMapper {
    User queryUserByName(String name);
}
 
与之对应的 UserMapper.xml 配置文件,内容如下:
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zzc.mapper.UserMapper">
    <select id="queryUserByName" parameterType="String" resultType="User">
        SELECT
            id,name,pwd,perms
        FROM TAB_USER
        WHERE 1=1
        AND name = #{name}
    </select>
</mapper>
 
注意:还要在主方法中进行配置扫描 Mapper。如下:
@MapperScan("com.zzc.mapper")
@SpringBootApplication
public class ShiroApplication {
    public static void main( String[] args ) {
        SpringApplication.run(ShiroApplication.class, args);
    }
}
 
7、首页 index.html 
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1 >Hello Shiro</h1>
<p th:text="${msg}">12</p>
<p>
    <a th:href="@{/toLogin}">登录</a>
</p>
<hr>
<a th:href="@{/user/add}">ADD</a>
<a th:href="@{/user/update}">UPDATE</a>
</body>
</html>
 
8、登录页面 login.html 
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<h1>登录</h1><hr>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}" method="post">
    <table>
        <tr>
            <td>用户名</td>
            <td>
                <input type="text" name="username" />
            </td>
        </tr>
        <tr>
            <td>密码</td>
            <td>
                <input type="password" name="pwd" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="登录" />
            </td>
        </tr>
    </table>
</form>
</body>
</html>
 
其实,到这里已经完成了大部分的需求。还剩下一点问题:root 用户只有 user:add 的权限,那它不应该显示 user:update。即:
 
 并且,当我们点击 UPDATE 链接时,会发现没有权限(这是正常的):
 
 所以,这里需要对前台进行处理!只显示当前用户有权限的内容!!
需要通过 Thymeleaf 对 Shiro 进行整合
9-1、引入依赖(上方已引入)
<dependency>
  <groupId>com.github.theborakompanioni</groupId>
  <artifactId>thymeleaf-extras-shiro</artifactId>
  <version>2.0.0</version>
</dependency>
 
9-2、修改配置类 ShiroConfig
需要注册一个 Bean -------- ShiroDialect
在原有的配置类中添加一个 Bean:
// Shiro-Thymeleaf
@Bean
public ShiroDialect getShiroDialect() {
    return new ShiroDialect();
}
 
9-3、修改自定义 Realm UserRealm 
只修改方法 doGetAuthenticationInfo()。
用户登录成功后,将用户信息存放到 Session 中
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken;
    // 用户名认证
    String username = userToken.getUsername();
    User user = userService.queryUserByName(username);
    if (null == user) {
        // 返回 null 后,将会抛出异常 UnknownAccountException
        return null;
    }
    // 登录成功后,将当前登录用户放入 Session 中
    Subject currentSubject = SecurityUtils.getSubject();
    Session session = currentSubject.getSession();
    session.setAttribute("user", user);
    // 密码认证:Shiro 帮我们做。可以加密
    return new SimpleAuthenticationInfo(user, user.getPwd(), "");
}
 
9-4、修改首页 index.html 
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1 >Hello Shiro</h1>
<p th:text="${msg}">12</p>
<div th:if="${session.user == null}">
    <p>
        <a th:href="@{/toLogin}">登录</a>
    </p>
</div>
<hr>
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">ADD</a>
</div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">UPDATE</a>
</div>
</body>
</html>
 
好了,SpringBoot 整合 Shiro 就到这了~~
源码地址










