shiro框架学习

发布于 2023-06-30  300 次阅读


什么是shiro?

  • Apache Shiro是一个Java 的安全(权限)框架
  • 主要功能为:用户认证、访问控制、支持会话、单点登录、记住我功能

核心内容

  • Authentication:身份认证、登录,验证用户是否拥有响应的身份。
  • Authorization:授权,也就是权限认证,验证已经认证的用户身份权限,判断用户可以进行哪些操作。
  • Session Manager:会话管理,在用户未退出前,所有的信息都在会话中。
  • Cryptography:加密,保护数据的安全性,如密码加密存储到数据库。
  • Web Support:web支持,使得非常容易集成到web环境。
  • Caching:缓存,比如用户登录后的用户信息、拥有的角色、权限,提高效率。
  • Concurrency:Shiro支持多线程应用的并发验证,也就是在一个线程中开启另一个线程,能把权限自动传播过去。
  • Testing:提供测试支持。
  • RunAs:允许一个用户作为另一个用户(如果允许)的身份进行访问。
  • Remember Me:记住我功能。

详细架构图

从外部来看

image-20230625221149107

  • Subject:代码直接交互对象是subject,代表当前用户。

  • SecurityManager:安全管理器,管理着所有的subject。

  • Realm:Shiro从Realm获取安全数据 (如用户,角色,权限),比较像database。

从内部来看

image-20230625221021410

  • Subject:当前与应用交互的实体。
  • Security Manager:是Shiro API中的核心组件,管理所有的Subject,并且负责进行认证,授权,会话,以及缓存的管理。
  • Authenticator:认证器,负责Subject认证。
  • Authorizer:授权器,权限访问控制,负责确定用户在系统中对哪些资源拥有访问权限。
  • SessionManager:管理Session,用于创建和管理用户会话。
    • SessionDAO:负责Session会话的持久化。
  • CacheManager:缓存管理器,负责创建和管理cache实例的生命周期。
  • Cryptography:加密支持,Shiro提供了一些常见的加密组件用于密码加密,解密等。
  • Realms:领域,充当一个连通Shiro和用户自己安全数据源的桥梁。

登录时身份认证逻辑

login(username,password) {
    1. 参数非空校验
    2. 判断username是否存在,存在则获取该用户的所有信息,包括salt值
    3. 判断密码是否正确
        1. 对password进行加密,使用salt,采用和添加用户时相同的算法进行加密
        2. 将加密后的密钥与user对象中的密码进行比对
}

使用shiro框架的逻辑过程

image-20230625231754181

快速入门

按照官网10min入门教程。

一、创建项目

创建一个新项目,命名为shiro_login。

image-20230626135559075

二、导入依赖

进入github复制pom.xml中的依赖。

https://github.com/apache/shiro/blob/main/samples/quickstart/pom.xml

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

        <!-- configure logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
</dependencies>

三、创建shiro.ini文件

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

[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

四、编写java代码

Quickstart.java

public class Quickstart {

    // 开启日志
    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);

    public static void main() {
        // 使用工厂模式加载配置文件,获取工厂对象
        Factory<SecurityManager> factory = new                    IniSecurityManagerFactory("classpath:shiro.ini");
        // 使用工厂获取securityManager接口对象
        SecurityManager securityManager = factory.getInstance();
        // 给SecurityUtils设置管理器
        SecurityUtils.setSecurityManager(securityManager);

        // 获取当前用户对象 Subject
        Subject currentUser = SecurityUtils.getSubject();
        // 通过用户获取session
        Session session = currentUser.getSession();
        // 给session设置属性,键值对形式
        session.setAttribute("someKey", "aValue");
        // 获取session中的属性值
        String value = (String) session.getAttribute("someKey");
        // if判断,打印日志
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        // 判断当前用户是否被认证
        if (!currentUser.isAuthenticated()) {
            // 通过UsernamePasswordToken生成令牌,正常业务是需要从Realm中读取正确的user信息
            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) {
                //unexpected condition?  error?
            }
        }
        // if判断当前用户的角色
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }
        // if判断当前用户的是否被允许操作(权限)
        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.");
        }

        // 注销
        currentUser.logout();
        // 结束
        System.exit(0);
    }
}

SpringBoot整合Shiro

一、创建项目

image-20230626231049140

二、导入依赖

<!--shiro-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.4.1</version>
</dependency>

三、三大组件配置

ShiroFilterFactoryBean ==》 Subject

DefaultWebSecurityManager   ==》 SecurityManager

创建realm对象   ==》 realm
    Realm需要继承AuthorizingRealm

UserRealm.java

// 自定义的Realm需要继承AuthorizingRealm,并重写方法
public class UserRealm extends AuthorizingRealm {

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权doGetAuthorizationInfo");
        return null;
    }

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

ShiroConfig.java

package cn.ordshine.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;

/**
 * @author: Ordshine
 * @date: 2023 - 06
 * @description:
 * @version: 1.0
 */

@Configuration
public class ShiroConfig {

    // ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        bean.setSecurityManager(securityManager);

        // 添加shiro的内置过滤器
        /*
            anon: 无需认证就可以访问
            authc: 必须认证才可以访问
            user: 必须拥有记住我功能才可以使用
            perms: 拥有对某个资源的权限才能访问
            role: 拥有某个角色权限才能访问
         */

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add", "user");
        filterMap.put("/user/update", "user");
        bean.setFilterChainDefinitionMap(filterMap);

        // 设置登录的请求
        bean.setLoginUrl("/toLogin");
        return bean;
    }

    // DefaultWebSecurityManager
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    // 创建realm对象
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}

四、实现用户认证

登录接口

@RequestMapping("/login")
    public String login(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";
        }
    }

realm认证方法

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

        // 判断用户名,密码
        String name = "root";
        String password = "123456";

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        // 用户名认证
        if (!userToken.getUsername().equals(name)) {
            return null; // 抛出异常 UnknownAccountException
        }

        // 密码认证,shiro自动验证
        return new SimpleAuthenticationInfo("",password,"");

    }

五、整合MyBatis和Druid

创建表

CREATE TABLE `user` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) DEFAULT NULL,
  `password` varchar(30) DEFAULT NULL,
  `perms` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

导入依赖

<!--Log4j-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

<!--mysql驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<!--Druid驱动-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.9</version>
</dependency>

<!--引入mybatis, 则是MyBatis官方提供的适配Spring Boot的jar包-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

配置数据库信息

application.yml

server:
  port: 8080

  # 运行环境
  profiles:
    active: dev
  #  active: prod
  #  active: test

  # 数据库
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    password: root
    username: root
    url: jdbc:mysql://localhost:3306/shiro_test #?serverTimezone=UTC&useUnicode=true&charcterEncoding=UTF-8
    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

User.java

package cn.ordshine.pojo;

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

/**
 * @author: Ordshine
 * @date: 2023 - 06
 * @description:
 * @version: 1.0
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private int id;
    private String username;
    private String password;
    private String perms;

}

UserMapper.java

package cn.ordshine.mapper;

import cn.ordshine.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

/**
 * @author: Ordshine
 * @date: 2023 - 06
 * @description:
 * @version: 1.0
 */

@Mapper
public interface UserMapper {

    @Select("select * from user where username = #{username}")
    public User queryUserByName(String username);
}

UserService.java

package cn.ordshine.service;

import cn.ordshine.pojo.User;

/**
 * @author: Ordshine
 * @date: 2023 - 06
 * @description:
 * @version: 1.0
 */

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

UserServiceImpl.java

package cn.ordshine.service;

import cn.ordshine.mapper.UserMapper;
import cn.ordshine.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: Ordshine
 * @date: 2023 - 06
 * @description:
 * @version: 1.0
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User queryUserByName(String username) {

        return userMapper.queryUserByName(username);
    }
}

UserRelam.java

package cn.ordshine.config;

import cn.ordshine.pojo.User;
import cn.ordshine.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;

/**
 * @author: Ordshine
 * @date: 2023 - 06
 * @description:
 * @version: 1.0
 */

// 自定义的Realm需要继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权doGetAuthorizationInfo");
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
        // 判断用户名,密码
//        String username = "root";
//        String password = "123456";
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        // 连接数据库获取用户信息
        User user = userService.queryUserByName(userToken.getUsername());
        // 用户名认证
        if (user == null) {
            return null; // 抛出异常 UnknownAccountException
        }
        // 密码认证,shiro自动验证
        return new SimpleAuthenticationInfo("",user.getPassword(),"");
    }
}

请求授权实现

授权

数据库中应当添加表示用户权限的字段,如perms字段。

保存格式例如:user:add,update 表示user用户具有add和update权限

ShiroConfig.java

增加拦截,设置访问权限。

// 拦截请求
Map<String, String> filterMap = new LinkedHashMap<>();
// 授权,只有user用户可以进入add页面, 授权是在认证之后的拦截
filterMap.put("/user/add", "perms[user:add]");
filterMap.put("/user/update", "perms[user:update]");

UserRealm.java

在授权方法中,对用户进行授权。

通过SimpleAuthorizationInfo获取info对象,并根据当前用户拥有权限进行设置。

// 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权doGetAuthorizationInfo");
        // SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 从认证方法中获取用户信息
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        System.out.println(user);
        // 设置当前用户的权限
        info.addStringPermission(user.getPerms());
        // 设置授权需要return info
        return info;
    }
// 这里是认证方法的返回值,返回user对象存到principal(身份)
return new SimpleAuthenticationInfo(user,user.getPassword(),"");

登出操作

UserController.java

// 退出登录
    @RequestMapping("/logOut")
    public String logout() {
        // 获取当前用户的 Subject
        Subject currentUser = SecurityUtils.getSubject();
        // 调用 Subject 的 logout 方法执行登出操作
        currentUser.logout();
        return "login";
    }

整合Thymeleaf

目的

实现前端根据用户具有的权限对功能进行隐藏。

导入依赖

<!--shiro整合Thymeleaf-->
<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.1.0</version>
</dependency>

ShiroConfig.java

添加ShiroDialect配置

@Bean
// 整合ShiroDialect:用来整合shiro和thymeleaf
public ShiroDialect getShiroDialect() {
    return new ShiroDialect();
}

前端代码

<!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</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>

<hr>
<div th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登录</a>
</div>
<p th:text="${session.loginUser}"></p>
<a th:href="@{/logOut}" style="float: right;color: red">退出登录</a>
<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>