shiro初级入门

前言:

Spring Security和Shiro的比较

1.相同点

①认证功能
②授权功能
③加密功能
④会话管理
⑤缓存支持
⑥rememberMe功能
… …

2.不同点

①Spring Security是一个重量级的安全管理框架;Shiro则是一个轻量级的安全管理框架
②Spring Security 基于Spring开发,项目若使用Spring作为基础,配合Spring Security 做权限更便捷,而Shiro需要和Spring 进行整合开发;
③Spring Security 功能比Shiro更加丰富些,例如安全维护方面;
④Spring Security 社区资源相对于Shiro更加丰富;
⑤Shiro 的配置和使用比较简单,Spring Security 上手复杂些;
⑥Shiro 依赖性低,不需要任何框架和容器,可以独立运行, Spring Security依赖Spring容器;
⑦Shiro 不仅仅可以使用在web中,它可以工作在任何应用环境中。在集群会话时Shiro最重要的一个好处或许就是它的会话是独立于容器的;
image-20220312111852929

1 、Shiro简介

1.1、什么是Shiro?

  • [ ]Apache Shiro 是一个Java 的安全(权限)框架。
  • Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。
  • Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等。
  • 下载地址:http://shiro.apache.org/
    image-20220403182821385

1.2、有哪些功能?

image-20220403182901184

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

1.3、Shiro架构(外部)

从外部来看Shiro,即从应用程序角度来观察如何使用shiro完成工作:

image-20220403183315537

shiro的主要工作流程:
  • subject: 应用代码直接交互的对象是Subject,也就是说Shiro的对外API核心就是SubjectSubject代表了当前的用户,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是 Subject,如网络爬虫,机器人等,与Subject的所有交互都会委托给SecurityManager;Subject其 实是一个门面,SecurityManageer 才是实际的执行者
  • SecurityManager:安全管理器,即所有与安全有关的操作都会与SercurityManager交互,并且它 管理着所有的Subject,可以看出它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于 SpringMVC的DispatcherServlet的角色
  • Realm:Shiro从Realm获取安全数据(如用户,角色,权限),就是说SecurityManager 要验证 用户身份,那么它需要从Realm 获取相应的用户进行比较,来确定用户的身份是否合法;也需要从 Realm得到用户相应的角色、权限,进行验证用户的操作是否能够进行,可以把Realm看成 DataSource;

1.4、Shiro架构(内部)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Qvhi3eHW-1649061537719)(https://cdn.jsdelivr.net/gh/ladidol/figurebed@main/img/image-20220403183757756.png)]

  • Subject:任何可以与应用交互的 ‘用户’;
  • Security Manager:相当于SpringMVC中的DispatcherServlet;是Shiro的心脏,所有具体的交互 都通过Security Manager进行控制,它管理者所有的Subject,且负责进行认证,授权,会话,及 缓存的管理。
  • Authenticator(认证员):负责Subject认证,**是一个扩展点,**可以自定义实现;可以使用认证策略 (Authentication Strategy),即什么情况下算用户认证通过了;
  • Authorizer(授权者):授权器,即访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能 访问应用中的那些功能;
  • Realm:可以有一个或者多个的realm,可以认为是安全实体数据源,即用于获取安全实体的,可以用JDBC实现,也可以是内存实现等等,由用户提供;所以一般在应用中都需要实现自己的realm
  • SessionManager:管理Session生命周期的组件,而Shiro并不仅仅可以用在Web环境,也可以用 在普通的JavaSE环境中
  • CacheManager:缓存控制器,来管理如用户,角色,权限等缓存的;因为这些数据基本上很少改 变,放到缓存中后可以提高访问的性能;
  • Cryptography:密码模块,Shiro 提高了一些常见的加密组件用于密码加密,解密等

2 、HelloWorld

2.1、快速实践

查看官网文档:http://shiro.apache.org/tutorial.html

官方的quickstart:https://github.com/apache/shiro/tree/master/samples/quickstart/

  1. 创建一个maven父工程,用于学习Shiro,删掉不必要的东西

  2. 创建一个普通的Maven子工程:shiro-01-helloworld

  3. 根据官方文档,我们来导入Shiro的依赖

pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>shirofeng</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>shiro-01-helloworld</module>
    </modules>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>


    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.1</version>
        </dependency>


        <dependency>
              
            <groupId>org.slf4j</groupId>
              
            <artifactId>slf4j-simple</artifactId>
              
            <version>1.7.25</version>
              
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.21</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        

    </dependencies>

</project>
  1. 编写Shiro配置

resources目录下:

log4j.properties配置文件

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

shiro.ini(如果是用的idea的话,可能需要安装ini配置文件插件,注意格式不要写错啦,key-value键值对)

[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
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

# -----------------------------------------------------------------------------
# Roles with assigned permissions
# 
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[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
  1. 编写我们的QuickStrat(主要步骤有中文备注提示)
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple Quickstart application showing how to use Shiro's API.
 */
public class Quickstart {
    private static final transient Logger log =
            LoggerFactory.getLogger(Quickstart.class);

    public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager withconfigured
// realms, users, roles and permissions is to use the simpleINI config.
// We'll do that by using a factory that can ingest a .inifile and
// return a SecurityManager instance:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urlsrespectively):
        Factory<SecurityManager> factory = new
                IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make theSecurityManager
// accessible as a JVM singleton. Most applications wouldn'tdo this
// and instead rely on their container configuration orweb.xml for
// webapps. That is outside the scope of this simplequickstart, so
// we'll just do the bare minimum so you can continue to get afeel
// for things.
        SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's seewhat you can do:
// get the currently executing user:

        //获取当前用户对象subject
        Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJBcontainer!!!)
        //通过当前用户拿到session
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }
// let's login the current user so we can check against rolesand permissions:

        //判断当前的用户是否被认证,
        if (!currentUser.isAuthenticated()) {
            //令牌
            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 onesspecific to your application?
            catch (AuthenticationException ae) {
//unexpected condition? error?
            }
        }
//say who they are:
//print their identifying principal (in this case, ausername):
        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.");
        }

        //粗粒度
//test a typed permission (not instance-level)
        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.");
        }

        //细粒度
//a (very powerful) Instance Level permission:
        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!");
        }
//all done - log out!
        //注销
        currentUser.logout();
        //结束系统
        System.exit(0);
    }
}

  1. 运行程序
[main] INFO org.apache.shiro.session.mgt.AbstractValidatingSessionManager - Enabling session validation scheduler...
[main] INFO Quickstart - Retrieved the correct value! [aValue]
[main] INFO Quickstart - User [lonestarr] logged in successfully.
[main] INFO Quickstart - May the Schwartz be with you!
[main] INFO Quickstart - You may use a lightsaber ring. Use it wisely.
[main] INFO Quickstart - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun!

2.2、阅读代码

详情请看上面代码的注解

OK,一个简单的Shiro程序体验,我们就在官方的带领下初步认识了!

3 、SpringBoot集成

3.1、准备工作

  1. 搭建一个SpringBoot项目、选中web模块即可!

pom.xml,新加点东西

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--thymeleaf模板-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
  1. 导入Maven依赖 thymeleaf

  2. 编写一个页面 index.html templates

<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>shiro首页</h1>
<p th:text="${msg}"></p>
</body>
</html>

  1. 编写controller进行访问测试
package com.feng.springbootshiro.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
    //一般首页不止一个,所以就这样写
    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "hello,Shiro");
        return "index";
    }
}

  1. 测试访问首页!
    image-20220403203140214

3.2、整合Shiro

  1. Subject:用户主体

  2. SecurityManager:安全管理器

  3. Realm:Shiro 连接数据

步骤:

  1. 导入shiro依赖
<dependency>
	<groupId>org.apache.shiro</groupId>
	<artifactId>shiro-spring</artifactId>
	<version>1.4.1</version>
</dependency>
  1. 编写Shiro 配置类 config包
package com.feng.springbootshiro.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

//声明为配置类
@Configuration
public class ShiroConfig {
    //创建 ShiroFilterFactoryBean( 步骤三
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
            /*
                添加Shiro内置过滤器,常用的有如下过滤器:
                anon: 无需认证就可以访问
                authc: 必须认证才可以访问
                user: 如果使用了记住我功能就可以直接访问
                perms: 拥有某个资源权限才可以访问
                role: 拥有某个角色权限才可以访问
                */
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add", "authc");
        filterMap.put("/user/update", "authc");


        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        //修改到要跳转的login页面;
        shiroFilterFactoryBean.setLoginUrl("/toLogin");

        return shiroFilterFactoryBean;
    }


    //创建 DefaultWebSecurityManager( 步骤二
    @Bean(name = "securityManager")
    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();
    }


}

  1. 我们倒着来,先想办法创建一个 realm 对象
  2. 我们需要自定义一个 realm 的类,用来编写一些查询的方法,或者认证与授权的逻辑
package com.feng.springbootshiro.config;
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 UserRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=>授权逻辑PrincipalCollection");
        return null;
    }

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

3.3、页面拦截实现

  1. 编写两个页面、在templates目录下新建一个 user 目录 新建两个页面

add.html

<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>add</title>
</head>
<body>

<h1>小小的add</h1>

</body>
</html>

update.html

<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>update</title>
</head>
<body>

<h1>小小的update</h1>

</body>
</html>

在template下新建一个首页

nihao.html(这里充当首页的意思)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<h1>登录页面</h1>
<hr>
<form action="">
    <p>
        用户名: <input type="text" name="username">
    </p>
    <p>
        密码: <input type="text" name="password">
    </p>
    <p>
        <input type="submit">
    </p>
</form>
</body>
</html>

  1. 编写跳转到页面的controller
 @RequestMapping("/user/add")
    public String toAdd(){
        return "user/add";
    }
    @RequestMapping("/user/update")
    public String toUpdate(){
        return "user/update";
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "nihao";
    }
  1. 测试,完全OK!

image-20220403214420469

点击两个连接都会跳转到登录界面

image-20220403214441478

3.4、登录认证操作

结果:

当用户名不存在的时候

image-20220404142928230

密码错误:

image-20220404143244141

每一次提交账号和密码都会执行认证逻辑

image-20220404143447875

成功就会跳转到首页:

image-20220404143304742

两个链接也都可以访问了

image-20220404143310795

3.5、整合数据库,来执行登录认证操作

  1. 导入Mybatis的相关依赖:
        <!--整合数据库,来查询用户信息-->
        <!-- 引入 myBatis,这是 MyBatis官方提供的适配 Spring Boot 的,而不是Spring
Boot自己的-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
  1. 编写配置文件,的数据库连接配置application.yaml文件
spring:
  datasource:
    username: root
    password: nihao123
  #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/shiro_feng?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    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,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错 java.lang.ClassNotFoundException:org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

mybatis:
  #似乎没起作用
  type-aliases-package: com.feng.springshiro.pojo
  mapper-locations: classpath:mapper/*.xml


  1. 编写试题类:又引入lombok
package com.feng.springbootshiro.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

  1. 编写mybatis那几层:
package com.feng.springbootshiro.mapper;

import com.feng.springbootshiro.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

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

package com.feng.springbootshiro.service;

import com.feng.springbootshiro.pojo.User;

public interface UserService {
    public User queryUserByName(String name);
}

package com.feng.springbootshiro.service.impl;

import com.feng.springbootshiro.mapper.UserMapper;
import com.feng.springbootshiro.pojo.User;
import com.feng.springbootshiro.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

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.feng.springbootshiro.mapper.UserMapper">
    <select id="queryUserByName" parameterType="String" resultType="com.feng.springbootshiro.pojo.User">
        select * from user where name = #{name}
    </select>
</mapper>
  1. 可以先测试一下数据库整合是否成功:
package com.feng.springbootshiro;

import com.feng.springbootshiro.pojo.User;
import com.feng.springbootshiro.service.impl.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class Shiro02SpringbootApplicationTests {
    @Autowired
    UserServiceImpl userService;

    @Test
    void contextLoads() {
        User user = userService.queryUserByName("ladidol");
        System.out.println(user);
    }
}

如果成功的话就,开始进行realm中的认证了

  1. 改造UserRealm,连接到数据库进行真实的操作!
package com.feng.springbootshiro.config;
import com.feng.springbootshiro.pojo.User;
import com.feng.springbootshiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

//自定义Realm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=>授权逻辑PrincipalCollection");
        return null;
    }

    //执行认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证逻辑AuthenticationToken");

;

        //1.判断用户名
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        //真实连接数据库
        User user = userService.queryUserByName(userToken.getUsername());



        if (user==null){
            //数据库中没有找到
            //用户名不存在
            return null; //shiro底层就会抛出 UnknownAccountException
        }
        //2. 验证密码,我们可以使用一个AuthenticationInfo实现类 SimpleAuthenticationInfo
        // shiro会自动帮我们验证!重点是第二个参数就是要验证的密码!
        return new SimpleAuthenticationInfo("", user.getPwd(), "");
    }
}

整合后的项目结构:

image-20220404150420687

结果:

image-20220404150248929

完全OK,成功查询出来了!

3.6、思考:密码比对原理探究

思考?这个Shiro,是怎么帮我们实现密码自动比对的呢?
我们可以去 realm的父类AuthorizingRealm的父类AuthenticatingRealm中找一个方法 核心: getCredentialsMatcher() 翻译过来:获取证书匹配器 我们去看这个接口 CredentialsMatcher 有很多的实现类,MD5盐值加密

image-20220404153012119

我们的密码一般都不能使用明文保存?需要加密处理;思路分析

  1. 如何把一个字符串加密为MD5
  2. 替换当前的Realm 的 CredentialsMatcher 属性,直接使用 Md5CredentialsMatcher 对象, 并设置加密算法

3.7、用户授权操作顺便整合了一下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>
  1. .配置一个shiro的Dialect ,在shiro的配置中增加一个Bean
    //配置ShiroDialect:方言,用于 thymeleaf 和 shiro 标签配合使用
    //这个为了登录者只展示相应链接,这个是前后端不分离的时候
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

  1. 修改index中的前端配置
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>shiro首页</h1>
<p th:text="${msg}"></p>
<!--这里主要判断是不是需要展示登录按钮-->
<p th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登录</a>
</p>
<!--看权限是否够-->
<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>

  1. 在shiroconfig中修改请求访问权限:
//        filterMap.put("/user/add", "authc");
//        filterMap.put("/user/update", "authc");
        //授权过滤器
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");
  1. 数据库表中的修改:

image-20220404160846241

  1. 实体类的修改:
package com.feng.springbootshiro.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private String perms;
}
  1. 在controller中添加一个未授权不能访问的提示页面
@RequestMapping("/noauth")
@ResponseBody
public String noAuth(){
return "未经授权不能访问此页面";
}

这时候也要在config中的然后再 shiroFilterFactoryBean 中配置一个未授权的请求页面!

 shiroFilterFactoryBean.setUnauthorizedUrl("/noauth");

没登录的话,就可以有thymeleaf来, 展示登录按钮

image-20220404160308339

登录小小就可以有add这个权限:

image-20220404154645775

登录ladidol这个用户就有update这个权限了

image-20220404154730263

ladfeng这个用户暂时没弄权限:

image-20220404154808066

用小小直接访问update的话会返回:

image-20220404161314742

3.8、小结:

如果学习了SpringSecurity 和 Shiro 两个安全的框架,其实什么都不用,我们靠拦截器也可以实现这些功能对吧,但是可能需要花费大量的时间和代码, 还有就是Bug多,思考不全,而现在,我们两个框架都会使用了,也给大家对比的进行学习了,当然真 实的工作中,可能代码会更加的复杂,请多加练习,和复习,也可以看一下源码。

4. 后记:

如果想要更深入了解shiro的话,后续我会再把黑马老师的那个项目分析实现一下,那个结合redis的可能更加适合工作的时候使用;

欢迎点赞关注哦!
也欢迎到访我的博客!小小的博客传送门!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兴趣使然的小小

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值