SpringBoot整合Shiro,mybatis,thymeleaf学习笔记

1 理论
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。

用户名密码身份认证流程

在这里插入图片描述
授权流程
授权,即访问控制,控制谁能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资源,对于某些资源没有权限是无法访问的
在这里插入图片描述
完整的身份认证和权限管理(基于URL的拦截)
在这里插入图片描述

1.1 三个核心组件:Subject, SecurityManager 和 Realms.

1.1.1
Subject:即“当前操作用户”。
但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。但考虑到大多数目的和用途,你可以把它认为是Shiro的“用户”概念。
1.1.2
SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
1.1.3
Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。
也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。
从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。
1.1.4 图例
在这里插入图片描述
2 实践
2.1.0 目录结构
在这里插入图片描述

2.1.1 导入依赖

<dependencies>

    <!--
     Subject 用户
     SecurityManager 管理所有用户
     Realm 连接数据
     -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--thymeleaf模板 -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>
    <!--shiro 整合 Spring -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.4.1</version>
    </dependency>
    <!--shiro Thymeleaf 整合-->
    <dependency>
        <groupId>com.github.theborakompanioni</groupId>
        <artifactId>thymeleaf-extras-shiro</artifactId>
        <version>2.0.0</version>
    </dependency>

    <!--mysql-connector   驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!--jdbc  连接-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!--  druid 连接池    -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    <!--整合mybatis  映射-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.0</version>
    </dependency>


    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.16</version>
    </dependency>

</dependencies>

2.1.2 配置yml文件

server:
  port: 86

spring:
  datasource:
    username: root
    password: 1998060972ls
    url: jdbc:mysql://localhost:3306/springcould?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #Spring Boot 默认不注入这些属性值,需要自己注入
    #druid 专属配置
    druid:
      initial-size: 5  #初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
      min-idle: 5      # 最小连接池数量
      max-active: 20   #最大连接池数量
      max-wait: 60000   #获取连接时最大等待时间,单位毫秒
      time-between-eviction-runs-millis: 60000  #
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 1 FROM DUAL  #用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。
      test-while-idle: true         #建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效
      test-on-borrow: false       #申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
      test-on-return: false         #归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
      pool-prepared-statements: false   #是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。

      #设置拦截 stat: 监控同济 , wall :防御SQL注入 ,log4j: 日志记录
      filter: stat,wall,log4j


      max-pool-prepared-statement-per-connection-size: 20
      use-global-data-source-stat: true
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.atguigu.shire.pojo
  

2.1.3 主启动类

2.1.4 配置类

1 UserRealm类


public class UserRealm  extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User principal = (User) subject.getPrincipal();   //获取当前对象
        info.addStringPermission(principal.getPerms());   //从数据库中获取权限并且添加权限
        
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        Subject subject = SecurityUtils.getSubject();  //获取当前用户

        //用户名,密码  从数据库中取
       /* String  name = "root";
        String password= "123";*/
        UsernamePasswordToken usertoken = (UsernamePasswordToken) authenticationToken;  //令牌是全局变量

        User user = userService.queryUserByName(usertoken.getUsername());



       /* if(!usertoken.getUsername().equals(name)){
            return null;  //抛出 UnknownAccountException
        }*/

        if (null == user){
            return null;
        }

        Session session = subject.getSession();
        session.setAttribute("loginUser",user);  //将用户放入session域中,用于前端的判断

        //密码认证, shiro 做
        //可以将密码进行加密   MD5加密  MD5盐值加密(都不可逆)  user.getPwd()
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");  //将User对象加入到Subject
    }
}

2 ShiroConfig类


@Configuration
public class ShiroConfig {

    //1 创建 Realm对象
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }

    //2 DefaultWebSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联Realm对象
        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> map = new LinkedHashMap<>();

        //拦截
      /*  map.put("/user/add", "authc");
        map.put("/user/update", "anon");*/


        //授权
        map.put("/user/add","perms[user:add]");
        map.put("/user/update","perms[user:update]");

        bean.setFilterChainDefinitionMap(map);

        //设置登录的请求
        bean.setLoginUrl("/tologin");
        //未授权页面
        bean.setUnauthorizedUrl("/unauthorized");

        return bean;
    }

    @Bean  // ShiroDialect  : 用来整合shiro thymeleaf的实例,需要注入IOC容器
    public ShiroDialect getShiroDialect(){
        return  new ShiroDialect();
    }


}

2.1.5 业务类1(SpringBoot 整合 Shiro)

UserRealm类配合ShiroConfig类对Controller层的业务类进行身份认证和授权

@Controller
public class IndexController {

    @RequestMapping("/index")
    public String toIndex(Model model) {
        model.addAttribute("msg", "hello world");
        return "index";
    }

    @RequestMapping("/tologin")
    public String toLogin(Model model) {
        model.addAttribute("msg", "hello world");
        return "login";
    }


    @RequestMapping("/user/add")
    public String add(Model model) {
        model.addAttribute("msg", "hello world user add");
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update(Model model) {
        model.addAttribute("msg", "hello world user update");
        return "user/update";
    }

    @RequestMapping("/login")
    public String toLogin(String username, 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("/unauthorized")
    public String unauthorized(){

        return "unauthorized";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();  //获取当前用户
        subject.logout();
        return "login";
    }
}

2.1.6 业务类2 (SpringBoot 整合 mybatis )

UserMapper 类 相当于Dao层
对于数据库操作的接口

@Repository
@Mapper
public interface UserMapper {
    public User queryUserByName(String name);
}

配置的xml文件,相当于对于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.atguigu.shire.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.atguigu.shire.pojo.User">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <id column="name" property="name" jdbcType="VARCHAR"></id>
        <id column="pwd" property="pwd" jdbcType="VARCHAR"></id>
        <id column="perms" property="perms" jdbcType="VARCHAR"></id>
    </resultMap>


    <select id="queryUserByName" parameterType="String" resultMap="BaseResultMap">
        select * from user where name=#{id}
    </select>
</mapper>

2.1.7 业务类3(Shiro 与 thymeleaf 整合)
前端

<h1>首页</h1>
<p th:text="${msg}"></p>

<div th:if="${session.loginUser == null}">
    <a href="/tologin">登录</a>
</div>

<div shiro:hasPermission="user:add">
    <a href="/user/add">add</a>
    <a href="/logout">注销</a>
</div>

<div shiro:hasPermission="user:update">
    <a href="/user/update">update</a>
    <a href="/logout">注销</a>
</div>

3 错漏

3.1 关于Shiro
3.1.1
在ShiroConfig类中的三个方法都需要加@Bean注解,都需要注入IOC容器;而ShiroConfig类则需要加上@Configration注解,标明配置类,使其可以被扫描到
3.1.2
注意目录结构,只有与主启动类同层或者比主启动类低一层的代码(加上注解的)才可以被扫描到
3.2 关于mybatis
3.2.1
注意配置文件application.yml中的关于mybatis的配置,要将文件放入正确的路径

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.atguigu.shire.pojo
 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值