ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Shiro框架学习

2021-02-27 20:57:35  阅读:189  来源: 互联网

标签:Realm 框架 用户 认证 学习 权限 Shiro Subject


文章目录

1、Shiro简介

1.1 介绍

​ Apache Shiro 是 Java 的一个安全框架。目前,使用 Apache Shiro 的人越来越多,因为它相当简单,对比 Spring Security,可能没有 Spring Security 做的功能强大,但是在实际工作时可能并不需要那么复杂的东西,所以使用小而简单的 Shiro 就足够了。对于它俩到底哪个好,这个不必纠结,能更简单的解决项目问题就好了。

​ Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境,也可以用在 JavaEE 环境。Shiro 可以帮助我们完成:认证、授权、加密、会话管理、与 Web 集成、缓存等。

1.2 功能

在这里插入图片描述

  • Authentication:身份认证 / 登录,验证用户是不是拥有相应的身份;
  • Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
  • Session Management:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通 JavaSE 环境的,也可以是如 Web 环境的;
  • Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
  • Web Support:Web 支持,可以非常容易的集成到 Web 环境;
  • Caching:缓存,比如用户登录后,其用户信息、拥有的角色 / 权限不必每次去查,这样可以提高效率;
  • Concurrency:shiro 支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去;
  • Testing:提供测试支持;
  • Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
  • Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了。

记住一点,Shiro 不会去维护用户、维护权限;这些需要我们自己去设计 / 提供;然后通过相应的接口注入给 Shiro 即可。

1.3 Shiro构架(外部)

1、外部构架 ==>> API

在这里插入图片描述

  • Subject:主体,代表了当前 “用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是 Subject,如网络爬虫,机器人等;即一个抽象概念;所有 Subject 都绑定到 SecurityManager,与 Subject 的所有交互都会委托给 SecurityManager;可以把 Subject 认为是一个门面;SecurityManager 才是实际的执行者;
  • SecurityManager:安全管理器;即所有与安全有关的操作都会与 SecurityManager 交互;且它管理着所有 Subject;可以看出它是 Shiro 的核心,它负责与后边介绍的其他组件进行交互。
  • Realm:域,Shiro 从 Realm 获取安全数据(如用户、角色、权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定用户身份是否合法;也需要从 Realm 得到用户相应的角色 / 权限进行验证用户是否能进行操作;可以把 Realm 看成 DataSource,即安全数据源。

2、简单的Shiro应用的实现步骤

  1. 应用代码通过 Subject 来进行认证和授权,而 Subject 又委托给 SecurityManager;
  2. 我们需要给 Shiro 的 SecurityManager 注入 Realm,从而让 SecurityManager 能得到合法的用户及其权限进行判断。

1.4 Shiro构架(内部)

从内部来看的话,有一个可扩展的架构,即非常容易插入用户自定义实现,因为任何框架都不能满足所有需求。

在这里插入图片描述

  • Subject:主体,主体可以是任何可以与应用交互的 “用户”;
  • SecurityManager:相当于 SpringMVC 中的 DispatcherServlet 或者 Struts2 中的 FilterDispatcher;是 Shiro 的心脏;所有具体的交互都通过 SecurityManager 进行控制;它管理着所有 Subject、且负责进行认证和授权、及会话、缓存的管理。
  • Authenticator:认证器,负责主体认证的,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;
  • Authorizer:授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能;
  • Realm:可以有 1 个或多个 Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是 JDBC 实现,也可以是 LDAP 实现,或者内存实现等等;由用户提供;注意:Shiro 不知道你的用户 / 权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的 Realm;
  • SessionManager:管理Session的生命周期。而 Shiro 并不仅仅可以用在 Web 环境,也可以用在如普通的 JavaSE 环境、EJB 等环境;所以,Shiro 就抽象了一个自己的 Session 来管理主体与应用之间交互的数据;这样的话,比如我们在 Web 环境用,刚开始是一台 Web 服务器;接着又上了台 EJB 服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到 Memcached 服务器);
  • SessionDAO:数据访问对象,用于会话的 CRUD,比如我们想把 Session 保存到数据库,那么可以实现自己的 SessionDAO,通过如 JDBC 写到数据库;比如想把 Session 放到 Memcached 中,可以实现自己的 Memcached SessionDAO;另外 SessionDAO 中可以使用 Cache 进行缓存,以提高性能;
  • CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能
  • Cryptography:密码模块,Shiro 提供了一些常见的加密组件用于如密码加密 / 解密的。

2、快速开始Demo

2.1 快速开始

1、导入依赖

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.7.0</version>
    </dependency>

    <!-- configure logging -->
    <!-- https://mvnrepository.com/artifact/org.slf4j/jcl-over-slf4j -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.30</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>	

2、配置日志文件

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n

# General Apache libraries
log4j.logger.org.apache=WARN

# Spring
log4j.logger.org.springframework=WARN

# Default Shiro logging
log4j.logger.org.apache.shiro=INFO

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

3、配置ini文件

[users] #用户
# user 'root' with password 'secret' and the 'admin' role
#用户名 = 密码, 角色
root = secret, admin

# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
presidentskroob = 12345, president

# 用户名=密码,角色1,角色2
darkhelmet = ludicrousspeed, darklord, schwartz
lonestarr = vespa, goodguy, schwartz

[roles]  #角色
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

4、分析QuickStart.java

  1. Subject用户对象代码

    //关键代码
    //获取当前的用户对象 Subject
    Subject currentUser = SecurityUtils.getSubject();
    //通过当前用户获取session(shiro的session)
    Session session = currentUser.getSession();
    
    //利用session存取值
    session.setAttribute("someKey", "aValue");
    String value = (String) session.getAttribute("someKey");
    if (value.equals("aValue")) {
        log.info("Retrieved the correct value! [" + value + "]");
    }
    
  2. 判断当前用户是否被认证

    if (!currentUser.isAuthenticated()) {
        //根据用户和密码生成一个令牌token
        //这个地方没有与ini文件连接起来
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        //设置记住我
        token.setRememberMe(true);
        try {
            //登录,即身份验证
            currentUser.login(token);
        } catch (UnknownAccountException uae) {  //用户名不存在
            log.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {  //
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                     "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to your application?
        catch (AuthenticationException ae) {
            //身份验证失败
        }
    }
    
    //print their identifying principal (in this case, a username):
    log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
    //test a role:
    if (currentUser.hasRole("schwartz")) {
        log.info("May the Schwartz be with you!");
    } else {
        log.info("Hello, mere mortal.");
    }
    
    
    //all done - log out!
    currentUser.logout();
    
    System.exit(0);
    
  3. 退出登录,注销

    //all done - log out!
    currentUser.logout();
    System.exit(0);
    

重点方法:

Subject currentUser = SecurityUtils.getSubject();	//获取当前的用户对象
Session session = currentUser.getSession();  		//获取当前用户对象的session

currentUser.isAuthenticated();		//判断当前用户对象是否被认证
currentUser.login(token);			//根据由用户和密码生成的token进行登录

currentUser.getPrincipal(); 		//获取当前授权对象的信息
currentUser.hasRole(" ");			//判断当前用户对象是否有角色权限
currentUser.isPermitted("");		//判断当前用户是否有资源操作权限

currentUser.logout();				//登出

2.2 认证与授权流程

在这里插入图片描述

  1. 首先调用 Subject.login(token) 进行登录,其会自动委托给 Security Manager,调用之前必须通过 SecurityUtils.setSecurityManager() 设置;
  2. SecurityManager 负责真正的身份验证逻辑;它会委托给 Authenticator 进行身份验证;
  3. Authenticator 进行身份验证。Shiro中核心的身份认证入口;
  4. 调用AuthenticationStrategy进行多Realm身份验证
  5. 调用对应Realm进行登录校验,认证成功则返回用户属性,失败则抛出对应异常

常见的异常

  • DisabledAccountException(禁用的帐号)
  • LockedAccountException(锁定的帐号)
  • UnknownAccountException(错误的帐号)
  • ExcessiveAttemptsException(登录失败次数过多)
  • IncorrectCredentialsException (错误的凭证)
  • ExpiredCredentialsException(过期的凭证)

3、集成SpringBoot

Shiro三大对象分别对应

  • 第三步:Subject:ShiroFilterFactoryBean
  • 第二步:SecurityManager:DefaultWebSecurityManager。需要关联Realm
  • 第一步:创建 Realm 对象。需要自定义类 UserRealm.class
    • 授权:AuthorizationInfo
    • 认证:AuthenticationInfo

3.1 环境搭建

1、创建一个SpringBoot项目

2、导入maven依赖

<!--导入shiro依赖 -->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.7.0</version>
</dependency>

3、测试环境搭配是否成功

  • 在启动项目时出现的问题1:

    Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
    Reason: Failed to determine a suitable driver class
    

    解决方式:配置连接数据库文件application.yaml

    spring:
      dataSource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
        username: root
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource #自定义数据源,使用Druid数据源,需要导包
    
  • 出现的问题2:

    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring-boot-web-starter</artifactId>
        <version>1.7.0</version>
    </dependency>
    
    <!-- 导入如上的shiro-spring-boot-web-starter依赖时出现的问题
    Description:
    No bean of type 'org.apache.shiro.realm.Realm' found.
    
    Action:
    Please create bean of type 'Realm' or add a shiro.ini in the root classpath (src/main/resources/shiro.ini) or in the META-INF folder (src/main/resources/META-INF/shiro.ini).
    -->
    

    未解决,直接使用shiro-spring依赖即可。

  • 测试

    • 在templates目录中创建首页Index.html文件。(位于templates目录下的所有页面,只能通过controller进行跳转,并且需要模板引擎的支持)
    • 创建一个RouterController进行页面跳转
    @Controller
    public class RouterController {
    
        @RequestMapping({"/index","/"})
        public String toIndex(Model model){
            model.addAttribute("msg","hello,shiro!!");
            return "index";
        }
        /*
        	@RequestMapping{"/index","/"}:表示/或者/index都可以访问到首页
        	@GetMapping("/"):只能使用一种方式访问
        */
    }
    

4、**自定义Realm,**只需要继承 AuthorizingRealm(授权)即可;其继承了 AuthenticatingRealm(即身份验证),而且也间接继承了 CachingRealm(带有缓存实现):

public class UserRealm extends AuthorizingRealm{
    //实现授权:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情
    @Override 
    protected AuthorizationInfo doGetAuthorizationInfo(
        PrincipalCollection principals){
        System.out.println("授权方法");
        return null;
    }
    //实现认证:用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码,系统通过校验用户名和密码来完成认证过程。
    @Override
    protected AuthenticationInfo doGeAuthenticationInfo(
        PrincipalCollection principals) throws AuthenticationException{
        System.out.println("认证方法");
        return null;
    }
}

​ Shiro默认提供的Realm关系图:

在这里插入图片描述

将一个类放入Spring容器中

@Bean
public CreateClass createClass{
    return new CreateClass;
}
//createClass:相当于该类的别名

5**、实现Shiro配置ShiroConfig.java**(权限操作的类),实现shiro三大主题Subject、SecurityManager和Realm

@Configuration
public class ShiroConfig{
    //第一步:创建 Realm 对象。需要自定义类 UserRealm.class
    @Bean(name="userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }
    
    //第二步:SecurityManager:DefaultWebSecurityManager。需要关联Realm
    //@Qualifer("userRealm"),与上述的UserRealm关联,userRealm为上述的方法名。也可以是上述方法中Bean中的name属性
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifer("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联创建的Realm对象
        securityManager.setRealm(userRealm);
        return securityManager; 
    }
    
    //第三步:Subject:ShiroFilterFactoryBean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(
        @Qualifier("securityManager") 
        DefaultWebSecurityManager getDefaultWebSecurityManager){
        
        ShiroFilterFactoryBean shiroBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroBean.setSecurityManager(getDefaultWebSecurityManager);
        return shiroBean;
    }
}

3.2 实现登录拦截

Shiro的内置过滤器:

  • anon:无需认证就可以访问;
  • authc:必须认证了才能访问;
  • user:必须拥有功能 记住我才能使用;
  • perms:拥有对某个资源的权限才能访问;
  • role:拥有某个角色权限才能访问
@Bean
public ShiroFilterFactoryBean getShiroFilterFactory(@Qualifier("securityManager") DefaultWebSecurityManager getDefaultWebSecurityManager){
    ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
    //设置安全管理器、即关联SecurityManager
    filterFactoryBean.setSecurityManager(getDefaultWebSecurityManager);
    /*
        Shiro的内置过滤器:
            - anon:无需认证就可以访问;
            - authc:必须认证了才能访问;
            - user:必须拥有功能 `记住我`才能使用;
            - perms:拥有对某个资源的权限才能访问;
            - role:拥有某个角色权限才能访问
        */
    Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
    //表示认证了才能去访问user目录下的两个文件
    filterChainDefinitionMap.put("/user/add","authc");
    filterChainDefinitionMap.put("/user/update","authc");

    //可以使用通配符*
    //filterChainDefinitionMap.put("/user/*","authc");
    filterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

    //如果没有权限,则跳转到哪一个页面
    filterFactoryBean.setLoginUrl("/login");
    return filterFactoryBean;
}

【注意】要是没有拦截成功:

  1. 注意是否加上了@Bean
  2. 是否关联了对象,需要使用@Qualifier(" ")
  3. 类是否加上@Configuration注解,表示该类是一个配置类

3.3 实现用户认证

用户认证需要放在Realm对象中。

用户认证:即在应用中谁能证明他就是他本人。一般提供如他们的身份 ID 一些标识信息来表明他就是他本人,如提供身份证,用户名 / 密码来证明。 在 shiro 中,用户需要提供 principals (身份)和 credentials(证明)给 shiro,从而应用能验证用户身份:

  • principals:身份,即主体的标识属性,可以是任何东西,如用户名、邮箱等,唯一即可。一个主体可以有多个 principals,但只有一个 Primary principals,一般是用户名 / 密码 / 手机号。
  • credentials:证明 / 凭证,即只有主体知道的安全值,如密码 / 数字证书等。
  • 最常见的 principalscredentials 组合就是用户名 / 密码了。

1、根据官方文档的快速开始案例,可得

  1. 获取当前的用户;
  2. 封装用户的登录数据;
  3. 登录。需要捕获异常,这个异常就是在Realm中抛出的
    • 用户名不正确
    • 密码不正确
  • 使用前端传送过来的数据:String username, String password

  • 在前端需要进行传送

    <form th:action="@{/getLoginMess}">
        <p>用户名:<input type="text" name="username"> </p>
        <p>密码: <input type="text" name="password"> </p>
        <input type="submit" value="login in"/>
    </form>
    <!--提交的action中的url应该与controller中的RequestMapping("url")的url相对应,而不是与文件相对应 -->
    
  • 代码实现:

    //用于接收前端传送的数据
    @RequestMapping("/getLoginMess")
    public String getLoginMessage(String username, String password,Model model){
        //获取当前的用户
        Subject currentUser = SecurityUtils.getSubject();
        //封装当前的登录信息为一个Token
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try{
            //执行登录操作
            currentUser.login(token);
            //登录成功,跳转到首页
            return "index";
        } catch (UnknownAccountException e) {  //用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException ie){  //密码
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
    
  • 在前端添加一个提示信息。接收msg的值

    <p th:text="${msg}" style="color: red"> </p>
    

2、上述代码运行后打印执行了认证方法(AuthenticationInfo ), 所以可以在Realm中的认证方法中添加功能

//UserRealm中的认证方法
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    System.out.println("执行认证方法 ==> doGetAuthorizationInfo ");

    //用户名、密码。需要从数据库中取。现在没有实现数据库,所以直接伪造数据
    String name = "admin";
    String password = "123456";

    //将token转换为用户名密码Token
    UsernamePasswordToken userToken = (UsernamePasswordToken)token;
    if( !userToken.getUsername().equals(name) ){
        return null; //这条语句就会抛出一个异常,抛出的这个异常就是UnknownAccountException
    }
    //密码认证Shiro来实现
    return new SimpleAuthenticationInfo("",password,"");
}

3.4 整合Mybatis

搭建环境

  1. 导入Mybatis依赖

    <!--JDBC -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!--Mysql数据库驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!--使用Druid数据源 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.3</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.4</version>
    </dependency>
    
    
    
  2. 配置数据库连接信息

  3. 关联mapper文件的路径以及包的别名使用

    mybatis.type-aliases-package=com.wei.pojo
    mybatis.mapper-locations=classpath:mapper/*.xml
    
  4. 编写实体类pojo

    • 导入lombok

      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
      </dependency>
      
    • 编写pojo

      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      public class User {
          private Integer id;
          private String username;
          private String password;
      }
      
  5. 编写mapper接口

    @Repository  //表示该类位于Dao层
    @Mapper  //表示该类是mybatis的一个类
    public interface UserMapper {
        List<User> getUsers();
        
        User getUserById(Integer id);
    }
    
    • 从mybatis3.4.0开始加入了@Mapper注解,目的就是为了不再写mapper映射文件

      <!--使用@Mapper需要导入如下依赖 -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.5.4</version>
      </dependency>
      
  6. 在Resources目录下创建mapper文件夹用于保存mapper.xml文件。创建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.wei.mapper.UserMapper">
        <select id="getUsers" resultMap="userMap">
            select * from user
        </select>
        <resultMap id="userMap" type="User">
            <id property="id" column="id"/>
            <result property="username" column="username"/>
            <result property="password" column="password"/>
        </resultMap>
        
        <select id="getUserByName" resultType="User" parameterType="int">
            select * from user where id = #{id}
        </select>
    </mapper>
    
  7. 创建Service层实现业务方法

    public interface UserService {
        List<User> getUsers();
    
        User getUserById(Integer id);
    }
    
  8. 创建一个包impl用于实现service层

    @Service   //表示该类位于service层
    public class UserServiceImpl implements UserService {
        @Autowired  //自动注入bean,调用dao层的方法
        private UserMapper userMapper;
        
        @Override
        public List<User> getUsers() {
            return userMapper.getUsers();
        }
    
        @Override
        public User getUserById(Integer id) {
            return userMapper.getUserById(id);
        }
    }
    
  9. 测试

    @SpringBootTest
    class SpringbootShiroApplicationTests {
    
        @Autowired
        private UserServiceImpl userService;
    	//UserServiceImpl注意此处是service的实现类,而不是接口
        @Test
        void contextLoads() {
            System.out.println(userService.getUserById(2));
        }
    }
    
    

    出现的问题:

    Field userMapper in com.wei.service.impl.UserServiceImpl required a bean of type 'com.wei.mapper.UserMapper' that could not be found.
    
    The injection point has the following annotations:
    	- @org.springframework.beans.factory.annotation.Autowired(required=true)
    
    Action:
    Consider defining a bean of type 'com.wei.mapper.UserMapper' in your configuration.
    
    
    发现配置文件中的UserMapper定义没有出现问题,导入的mybatis依赖有问题。
    导入成了mybatis-spring包,需要导入的是:mybatis-spring-boot-starter
    

在自定义的Realm的认证方法AuthenticationInfo()中使用数据库的信息认证登录的对象是否合法

public class UserRealm extends AuthorizingRealm {
    
    @Autowired
    private UserService userService;
    
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行授权方法 ==> doGetAuthorizationInfo ");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证方法 ==> doGetAuthorizationInfo ");
        //将token转换为用户名密码Token
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        
        //用户名、密码。需要从数据库中取。
        User user = userService.getUserByName(userToken.getUsername());
        if( user == null ){  //如果当前用户在数据库中不存在
            return null; //这条语句就会抛出一个异常,抛出的这个异常就是UnknownAccountException
        }
        //密码认证Shiro来实现
        return new SimpleAuthenticationInfo("", user.getPassword(),"");
    }
}

【注】

  • 负责加密的接口:CredentialsMatcher

  • 可以加密的有:MD5、MD5盐值加密

3.5 实现授权实现

AuthorizationInfo 授权==>> 权限操作

授权,也叫访问控制,即在应用中控制谁能访问哪些资源(如访问页面/编辑数据/页面操作等)。在授权中需了解的几个关键对象:主体(Subject)、资源(Resource)、权限(Permission)、角色(Role)。

  1. 主体Subject:即访问应用的用户,在 Shiro 中使用 Subject 代表该用户。用户只有授权后才允许访问相应的资源。

  2. 资源Resource:应用中用户可以访问的URL,比如访问 JSP 页面、查看/编辑某些数据、访问某个业务方法、打印文本等等都是资源。用户只要授权后才能访问。

  3. 权限Permission:安全策略中的原子授权单位,通过权限我们可以表示在应用中用户有没有操作某个资源的权力。即权限表示在应用中用户能不能访问某个资源,如: 访问用户列表页面 查看/新增/修改/删除用户数据(即很多时候都是 CRUD(增查改删)式权限控制)打印文档等。

    • Shiro 支持粗粒度权限(如用户模块的所有权限)

      if (currentUser.isPermitted("lightsaber:wield")) {
          log.info("You may use a lightsaber ring.  Use it wisely.");
      } else {
          log.info("Sorry, lightsaber rings are for schwartz masters only.");
      }
      
    • 和细粒度权限(操作某个用户的权限,即实例级别的)

      if (currentUser.isPermitted("winnebago:drive:eagle5")) {
          log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                   "Here are the keys - have fun!");
      } else {
          log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
      }
      
    • 粗粒度权限和细粒度权限的区别:isPermitted()方法中的参数限制不同

  4. 角色Role:角色代表了操作集合,可以理解为权限的集合,一般情况下我们会赋予用户角色而不是权限,即这样用户可以拥有一组权限,赋予权限时比较方便。典型的如:项目经理、技术总监、CTO、开发工程师等都是角色,不同的角色拥有一组不同的权限。

实现

  1. 给页面设置访问的权限,即什么样的用户才能访问该页面;ShiroConfig.java的getShiroFilterFactoryBean()方法下:

    //授权
    //表示用户具有user:add这样的权限才能够访问/user/add页面
    filterChainDefinitionMap.put("/user/add","perms[user:add]");
    filterChainDefinitionMap.put("/user/update","perms[user:update");
    
  2. 如果登录的用户未授权,则设置一个未授权页面供页面跳转;

    //设置未授权登录页面
    filterFactoryBean.setUnauthorizedUrl("/noAuthor");
    
  3. 获取当前登录的用户

    Subject subject = SecurityUtils.getSubject();
    User currentUser = (User) subject.getPrincipal();
    

    在这里插入图片描述

  4. 设置当前用户的权限(根据从数据库中取出的权限赋予当前用户)

    //设置当前用户的权限:从数据库中权限字段获取到
    authorizationInfo.addStringPermission(currentUser.getPerms());
    

    在这里插入图片描述

3.6 整合Thymeleaf

1、导入依赖

<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>

2、在ShiroConfig.java中配置Shiro-Thymeleaf

@Bean
public ShiroDialect getShiroDialect(){
    return new ShiroDialect();
}

3、加入html命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">

4、加入shiro属性(标签)

<!--如果当前登录的用户有user:add权限,就显示如下内容 -->
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">添加</a>
</div>

<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">更新</a>
</div>

5、设置session,方便判断当前用户是否已成功登录

<!--从session中获取值并判断 -->
<div th:if="${session.loginUser==null}">
    <a th:herf="@{/login}">登录</a>
</div>

为当前用户设置session

Subject curSubject = SecurityUtils.getSubject();
Session session = curSubject.getSession();
session.setAttribute("loginUser",user);

【资料来源]

  1. W3Cschool:https://www.w3cschool.cn/shiro/andc1if0.html
  2. Shiro官方文档: https://shiro.apache.org/

标签:Realm,框架,用户,认证,学习,权限,Shiro,Subject
来源: https://blog.csdn.net/weixin_43889825/article/details/114190735

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有