Spring Boot 整合Shiro

Posted Tenton

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot 整合Shiro相关的知识,希望对你有一定的参考价值。

1、创建一个SpringBoot的Web项目

2、导入相关依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--spring-shiro 整合-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.6.0</version>
</dependency>
<!--Thymeleaf-shiro 整合-->
<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>
<!--thymeleaf模板-->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<!--log4j-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.21</version>
</dependency>
<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.1</version>
</dependency>
<!--mybaris-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>

3、创建UserRealm

自定义的 UserRealm

public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证方法");
        return null;
    }
}

4、创建Shiro配置类 ShiroConfig

@Configuration
public class ShiroConfig {
    /**
     * 1、创建realm对象,需要自定义
     * 我们自己写的类就被Spring托管了
     */
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
    /**
     * 2、DefaultWebSecurityManager
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    /**
     * 3、ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        /**添加Shiro的内置过滤器
         * anon:无需认证就可以访问
         * 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","anon");
        //用户的所有界面,认证了都可以访问
        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);
        //设置登录的请求
        bean.setLoginUrl("/toLogin");
        //设置未授权页面
        bean.setUnauthorizedUrl("/unauth");
        return bean;
    }
    /**
     * 4、调用ShiroDialect 用来整合Shiro  Thymeleaf
     */
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}

5、创建实体类 User

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String userName;
    private String password;
}

6、在Spring配置文件中配置数据源 application.yml

spring:
  datasource:
    #数据库驱动
    driver-class-name: com.mysql.cj.jdbc.Driver
    #数据库URL   serverTimezone=UTC 解决时区问题
    url: jdbc:mysql://localhost:3306/shiro?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    #用户名
    username: root
    #密码
    password: ******
    #自定义数据库类型
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot默认是不注入以下这些属性值的,需要自己绑定
    #druid 数据源的专有配置
    #初始化连接数目
    initial-size: 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, stat: 监控统计、log4j: 日志记录、wall: 防御sql注入
    #如果允许时报错java.Lang.CLassNotFoundException: org.apache.Log4j.Priority
    #则导入Log4j 依赖即可,Maven地址:https://mvnrepository.com/artifact/log4j/Log4j
    filters: stat, wall,1og4j
    maxPoolPreparedstatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSq1Millis=500

7、mapper层创建接口 UserMapper

@Repository
@Mapper
public interface UserMapper {
    /**
     * 根据姓名查询用户
     * @param userName
     * @return
     */
    User queryUserByName(String userName);
}

8、xml实现接口

在resources目录下创建mapper文件夹,在mapper下创建UserMapper.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.tenton.mapper.UserMapper">
    <select id="queryUserByName" parameterType="String" resultType="User">
        select * from shiro.user where userName = #{userName};
    </select>
</mapper>

9、配置文件中配置mybatis

mybatis:
  type-aliases-package: com.tenton.pojo
  mapper-locations: classpath:mapper/*.xml

10、service层创建接口 UserService

public interface UserService {
    /**
     * 根据姓名查询用户
     * @param userName
     * @return
     */
    User queryUserByName(String userName);
}

11、实现类实现接口

@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;
    @Override
    public User queryUserByName(String userName) {
        return userMapper.queryUserByName(userName);
    }
}

12、控制层创建 UserController

@Controller
public class UserController {
    /**
     * 增
     */
    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }
    /**
     * 改
     */
    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }
    /**
     * 跳转到登录页面
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    /**
     * 登录
     */
    @RequestMapping("/login")
    public String login(@RequestParam(required = true)String userName,
                        @RequestParam(required = true)String password,
                        Model model){
        //获取当前对象
        Subject subject = SecurityUtils.getSubject();
        //封装数据库的登录数据,生成令牌加密
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try{
            //执行登录方法,如果没有异常就说明登录成功了
            subject.login(token);
            return "index";
        }catch (UnknownAccountException e){//用户名不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){//密码不存在
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
    @RequestMapping("/unauth")
    public String unauthoried(){
        return "unauth";
    }
}

13、编写UserRealm

public class UserRealm extends AuthorizingRealm {
    @Resource
    UserServiceImpl userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");
//        info.addStringPermission("user:update");
        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证方法");
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        User user = userService.queryUserByName(userToken.getUsername());
        if (user == null){ //没有这个人
            return null;//抛出异常  UnknownAccountException
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);
        /**
         * 密码认证,让shiro完成 加密了  使用MD5
         */
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}

14、创建登录界面 login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="${msg}" style="color: red"/>
<form th:action="@{/login}" method="post">
    <P>用户名:<input type="text" name="userName"/></P>
    <P>密码:<input type="password" name="password"/></P>
    <p><input type="submit" value="登录"/></p>
</form>
</body>
</html>

15、创建首页 index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>首页</h1>
<div th:if="${session==null}">
    <a th:href="@{/toLogin}">登录</a>
</div>
<p th:text="${msg}"/>
<hr>
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">增加</a>
</div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">修改</a>
</div>
</body>
</html>

16、创建增加界面 add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>增加</p>
</body>
</html>

17、创建修改界面 update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>修改</p>
</body>
</html>

18、创建未授权显示页面 unauth.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>未经授权,无法访问此页面</p>
</body>
</html>

以上是关于Spring Boot 整合Shiro的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 整合 Shiro

spring boot整合shiro

Spring Boot 整合 Shiro ,两种方式全总结

Spring Boot 整合 Shiro+Thymeleaf

Spring Boot整合Shiro

spring boot2整合shiro安全框架实现前后端分离的JWT token登录验证