Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

" 常在河边走,哪能不湿鞋。" ——若发现文章内容有误,敬请指正,望不吝赐教,谢谢!

文章目录

参考资料


运行环境


  • Windows10
  • Maven 3.8.3
  • IDEA 2021.1 专业版
  • JDK 8
  • SpringBoot 2.6
  • Shrio 1.8

一、Shiro体系结构


Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

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

1.1 Shiro外部架构

Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例
Subject

Subject是应用代码直接交互的对象,也就是说Shiro的对外API核心就是Subject,Subject代表了当前的用户,这个用户不一定是具体的人,与当前应用交互的任何东西都是Subject,比如网络爬虫,、机器人等,与Subject的所有交互都会委托给SecurityManager;Subject其实是一个门面,SecurityManager才是实际的执行者。

SecurityManager

SecurityManager称为安全管理器,即所有与安全有关的操作都会与SecurityManager交互,并且它管理者所有的Subject,所以它称作为Shiro的核心,它负责与Shiro的其他组件进行交互,相当于SpringMVC框架的DispatcherServlet的角色

Realm

Shiro从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较,来确定用户的身份是否合法,也需要从Realm得到用户相应的角色、权限,进行验证用户的操作是否能够进行,可以把Realm看成DataSource

1.2 Shiro内部架构

Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

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

二、Shiro 快速入门


Shiro 官方-快速入门地址:点击访问

Shiro 1.8 版本下载地址:点击访问
Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例
解压从官方下载的Shiro 1.8.0资源

访问解压后的目录D:\shiro1.8.0\shiro-root-1.8.0\samples\quickstart\src\main\resources

通过官方提供的快速入门Maven项目里的配置文件可以实现简单的应用

接下来的内容,部分是参考官方快速入门文档 ,大部分参考 视频资料

2.1 使用IDEA创建Maven项目,引入依赖

贴一个官方快速入门案例的依赖pom.xml,方便做参考

<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->
<!--suppress osmorcNonOsgiMavenDependency -->
<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 https://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.apache.shiro.samples</groupId>
        <artifactId>shiro-samples</artifactId>
        <version>1.8.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>samples-quickstart</artifactId>
    <name>Apache Shiro :: Samples :: Quick Start</name>
    <packaging>jar</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.6.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <classpathScope>test</classpathScope>
                    <mainClass>Quickstart</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>


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

        <!-- configure logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

</project>

测试Demo的依赖 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>com.uni</groupId>
    <artifactId>shiro1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <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.8.0</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>
</project>

2.2 配置Shiro

这里是参考官方案例里的配置

配置日志文件 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 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]
# '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

2.3 测试运行官方的Quickstart实例

Quickstart.java

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

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.
 *
 * @since 0.9 RC2
 */
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 with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        SecurityUtils.setSecurityManager(securityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        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 roles and 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 ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //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.");
        }

        //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);
    }
}

运行结果:
Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

2.4 官方案例过程梳理

第一步,通过配置文件进行初始化

在官方案例中读取配置文件部分:

Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);

注:根据IDEA提示,IniSecurityManagerFactory类是过时的,说明有了其他更方便的用法,但这里不会影响使用
Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

第二步,获取当前用户对象

Subject currentUser = SecurityUtils.getSubject();

第三步,通过当前用户拿到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 + "]");
}

第四步,进行用户验证

 if (!currentUser.isAuthenticated()) {
    // 生成Token令牌
    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?
    }
}

第五步,输出当前用户登陆信息,判断用户角色

log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

if (currentUser.hasRole("schwartz")) {
    log.info("May the Schwartz be with you!");
} else {
    log.info("Hello, mere mortal.");
}

第六步,判断当前用户是否有wield权限、eagle5权限

//test a typed permission (not instance-level)
// 检测是否有权限 wield: 粗粒度
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:
// 检测权限 eagle5: 细粒度
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!");
}

第七步,注销登陆,结束测试

currentUser.logout();
System.exit(0);

三、Shrio MDK5


MDK5算法作用:加密或者签名
MDK5算法特点:(1)不可逆(2)若内容相同,无论执行多少次算法,生成的结果始终一致

MDK5算法生成结果:始终是一个16进制、32位长度的字符串

接下来通过一个简单的Demo,应用Shiro整合的MD5加密

package com.uni;
import org.apache.shiro.crypto.hash.Md5Hash;

public class TestShiroMD5 {
    public static void main(String[] args) {
        Md5Hash md5Hash1 = new Md5Hash("uni");
        Md5Hash md5Hash2 = new Md5Hash("uni");
        System.out.println(md5Hash1.toHex());
        System.out.println(md5Hash2.toHex());
        // MD5 + salt
    }
}

运行结果:

e52805d8344b67b9b3554d45f1c8958f
e52805d8344b67b9b3554d45f1c8958f

解决MD5算法执行结果一致的问题:设置 salt参数

package com.uni;
import org.apache.shiro.crypto.hash.Md5Hash;

public class TestShiroMD5 {
    public static void main(String[] args) {
        // MD5
        Md5Hash md5Hash1 = new Md5Hash("uni");
        Md5Hash md5Hash2 = new Md5Hash("uni", "haha");
        System.out.println(md5Hash1.toHex());
        System.out.println(md5Hash2.toHex());
        // MD5 + salt
    }
}

运行结果:

e52805d8344b67b9b3554d45f1c8958f
8b2d4072ed1273449708186d568f2ff6

除了加salt参数以外,还有一个参数可以提高安全性,即Hash散列次数

package com.uni;
import org.apache.shiro.crypto.hash.Md5Hash;

public class TestShiroMD5 {
    public static void main(String[] args) {
        // MD5
        Md5Hash md5Hash1 = new Md5Hash("uni");
        // MD5 + salt
        Md5Hash md5Hash2 = new Md5Hash("uni", "haha");
        // MD5 + salt + 多次Hash散列
        Md5Hash md5Hash3 = new Md5Hash("uni", "haha", 21);
        System.out.println(md5Hash1.toHex());
        System.out.println(md5Hash2.toHex());
        System.out.println(md5Hash3.toHex());
    }
}

运行结果:

e52805d8344b67b9b3554d45f1c8958f
8b2d4072ed1273449708186d568f2ff6
16c1bf99d04c5517f1ceac845f3388d5

3.1 Shiro 认证案例

经过之前的测试,已经知道了salt为haha,hash21次后的"uni"字符串对应的MD5加密算法后的内容,现写一个简单的案例应用Shiro实现加密验证,项目配置参考本篇之前的快速入门部分

UserRealm.java 负责授权与认证

package com.uni.md5.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class UserRealm extends AuthorizingRealm {
	// 授权,暂时不做测试
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

	// 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取身份信息
        String principal =(String) token.getPrincipal();
        // 模拟业务层
        if("uni".equals(principal)){
            // 参数1: 数据库用户名
            // 参数2: 数据库 md5 + salt 之后的密码
            // 参数3: 注册时的随机salt
            // 参数4: realm的名称
            return new SimpleAuthenticationInfo(
                    principal,
                    "16c1bf99d04c5517f1ceac845f3388d5",
                    ByteSource.Util.bytes("haha"),
                    this.getName());
        }
        return null;
    }
}

TestUserMd5RealmAuthenicator.java 负责测试Shiro身份认证的结果

package com.uni.md5.test;

import com.uni.md5.realm.UserRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

public class TestUserMd5RealmAuthenicator {
    public static void main(String[] args) {
        // 安全管理器
        DefaultSecurityManager manager = new DefaultSecurityManager();
        // 声明、配置、注入 realm
        UserRealm realm = new UserRealm();
        //    设置realm使用hash凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //          指明md5加密算法
        credentialsMatcher.setHashAlgorithmName("md5");
        //          指明散列次数
        credentialsMatcher.setHashIterations(21);
        realm.setCredentialsMatcher(credentialsMatcher);
        //    注入 realm
        manager.setRealm(realm);
        // 将安全管理器注入安全工具
        SecurityUtils.setSecurityManager(manager);

        // 通过安全工具类获取subject,在web中是从前端传的参数里获取的用户名和密码
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("uni", "uni");
        try {
            subject.login(token);
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }

    }
}

运行结果:

2022-02-08 18:25:07,728 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] - Enabling session validation scheduler... 
登录成功

3.2 Shiro 授权案例

UserRealm.java

package com.uni.md5.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * Author:      Unirithe/Mr.Chao
 * CSDN:        https://blog.csdn.net/Unirithe
 * CreatedTime:  2022/2/8 17:53
 **/
public class UserRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        // 根据身份信息、用户名,获取当前用户的角色信息,以及权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 将数据库中查询角色信息赋值给权限对象
        info.addRole("admin");
        info.addRole("user");
        // 将数据库中查询权限信息赋值给权限对象
        info.addStringPermission("user:*:01");
        return info;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取身份信息
        String principal =(String) token.getPrincipal();
        // 模拟业务层
        if("uni".equals(principal)){
            // 参数1: 数据库用户名
            // 参数2: 数据库 md5 + salt 之后的密码
            // 参数3: 注册时的随机salt
            // 参数4: realm的名称
            return new SimpleAuthenticationInfo(
                    principal,
                    "16c1bf99d04c5517f1ceac845f3388d5",
                    ByteSource.Util.bytes("haha"),
                    this.getName());
        }
        return null;
    }
}

TestUserMd5RealmAuthenicator.java

package com.uni.md5.test;

import com.uni.md5.realm.UserRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

public class TestUserMd5RealmAuthenicator {
    public static void main(String[] args) {
        // 安全管理器
        DefaultSecurityManager manager = new DefaultSecurityManager();
        // 声明、配置、注入 realm
        UserRealm realm = new UserRealm();
        //    设置realm使用hash凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //          指明md5加密算法
        credentialsMatcher.setHashAlgorithmName("md5");
        //          指明散列次数
        credentialsMatcher.setHashIterations(21);
        realm.setCredentialsMatcher(credentialsMatcher);
        //    注入 realm
        manager.setRealm(realm);
        // 将安全管理器注入安全工具
        SecurityUtils.setSecurityManager(manager);

        // 通过安全工具类获取subject
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("uni", "uni");
        try {
            subject.login(token);
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }

        // 认证用户进行授权
        if(subject.isAuthenticated()){
            // 基于角色进行权限控制
            System.out.println(subject.hasRole("admin"));
            System.out.println(subject.hasRole("user"));
            // 基于多角色权限控制
            System.out.println(subject.hasAllRoles(Arrays.asList("admin", "super")));

            // 是否有其中一个角色
            boolean[] b = subject.hasRoles(Arrays.asList("admin", "super", "user"));
            for (boolean b1 : b) {
                System.out.println(b1);
            }
            System.out.println("========================================");
            // 基于权限字符串的访问控制, 资源标识符,操作: 资源类型
            System.out.println("权限:" + subject.isPermitted("user:update:01"));

            // 分别具有哪些权限
            boolean[] permitted = subject.isPermitted("user:*:01", "commodity:*:*");
            for (boolean b1 : permitted) {
                System.out.println(b1);
            }

            // 同时具有哪些权限
            subject.isPermittedAll("user:*:01", "product:*");
        }
    }
}

四、SpringBoot整合Shiro + Web + MyBatis + Thymeleaf案例


项目结构:
Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

4.1 引入相关依赖

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.uni</groupId>
    <artifactId>springboot-shiro</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-shiro</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

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

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

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

        <!-- shiro整合spring的依赖 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.6.0</version>
        </dependency>

        <!-- shiro整合Thymeleaf的依赖 -->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- MySQL数据库 + Druid数据源依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>

        <!-- MyBatis起步依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

4.2 配置MyBatis

配置mybatis的接口映射文件扫描路径
application.properties

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

配置数据库 + Druid数据源(许多配置都采用默认的,仅做测试)
application.yaml

spring:
  datasource:
    username: root
    password: 数据库密码
    url: jdbc:mysql://localhost:3306/smbms?serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

pojo实体类 User.java

package com.uni.pojo;

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

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

DAO层接口类 UserMapper.java

package com.uni.mapper;

import com.uni.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

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

}

Mapper映射文件 UserMapper.xml(注:位置在resources资源文件夹的新建文件夹mapper里

<?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.uni.mapper.UserMapper">
    <select id="queryUserByName" parameterType="String" resultType="User">
        SELECT * FROM test_user WHERE username = #{username}
    </select>
</mapper>

Service层接口类 UserService.java

package com.uni.Service;

import com.uni.pojo.User;

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

Service层接口实现类 UserServiceImpl.java

package com.uni.Service.impl;

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

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User queryUserByName(String username) {
        return userMapper.queryUserByName(username);
    }
}

4.3 编写SpringMVC控制层 + 前端Thymeleaf页面

唯一测试的控制层类 MyController.java

package com.uni.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

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

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }
    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }
    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, Model model){
        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();
        // 封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
            subject.login(token);   // 执行登录的方法,如果没有异常就OK
            return "index";
        } catch (UnknownAccountException e) {   // 用户名不存在
            model.addAttribute("msg", "用户名错误");
            return "login";
        } catch (IncorrectCredentialsException e){ // 密码不存在
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }

    @GetMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面!";
    }
}

前端页面主要有四个,如下图:
Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

user/add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1>add</h1>
</body>
</html>

user/update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1>update</h1>
</body>
</html>

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>Document</title>
</head>
<body>
    <h1>首页</h1>

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

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

    <div shiro:hasPerrmission="user:add">
        <a th:href="@{user/add}">add</a>
    </div>

    <div shiro:hasPerrmission="user:update">
        <a th:href="@{/user/update}">update</a>
    </div>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
</head>
<body>
<h1>登陆</h1>
<p th:text="${msg}" style="color:red"></p>
<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>

4.4 配置Shiro

ShiroConfig.java SpringBoot集成Shiro框架,可以通过配置类声明几个相关对象的Bean,通过注解注入到Spring容器后就能生效

package com.uni.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
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 {

    // 1. 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/*", "authc");
        bean.setFilterChainDefinitionMap(filterMap);
        // 设置登录的请求
        bean.setLoginUrl("/toLogin");
        // 未授权页面
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }
    // 2. DefaultWebSecurityManager(第二步)
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联 userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    // 3. 创建 Realm 对象,需自定义类。 (第一步)
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

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

UserRealm.java Shiro框架负责认证和授权的重要类,继承于AuthorizingRealm.java

package com.uni.config;

import com.uni.Service.UserService;
import com.uni.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


// 自定义的 UserRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法 => doGetAuthorizationInfo ");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();      // 获取 User 对象

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

        Object principal = token.getPrincipal();
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        // 连接数据库
        User user = userService.queryUserByName("uni");
        if(user == null) {
            return null; // UnknownAccountException
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser", user);
        return new SimpleAuthenticationInfo(principal, user.getPassword(), "");
    }
}

4.5 运行测试

启动项目后,访问 hhttp://localhost:8080/

Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

在未登录状态下,点击add或者update都会直接跳转到登陆页面

登陆页面输入密码错误会有错误提示
Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例
输入数据库里存在的用户登录后,再次跳转到首页Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

此时可正常访问add和update

Shiro身份认证学习笔记(一)Shrio体系结构 | 基于官方文档的快速入门 | MDK5 + salt 加密案例 | SpringBoot整合Shiro+SSM+Thymeleaf案例

4.6 小结

此案例是参考第一个视频资料的,主要实现了多个框架的简单整合,对于Shiro的简单运用,要点如下:

  • Reaml模块负责于数据库交互,通过token进行参数传递,继承于AuthorizingRealm.java类,对用户实现授权与认证
  • SecurityManager模块用于设置权限访问的问题,通过注入ShiroFilterFactoryBean配置安全管理器,通过注入DefaultWebSecurityManager关联传递的形参Reaml,还需注入之前Realm模块编写的类
  • Shrio整合Thymleaf除了要引入依赖以外,还需要在Shiro配置类里注入ShiroDiealect对象的Bean,从而支持在html页面直接使用shiro相关的标签,进行权限判断、角色判断等操作
  • SpringMVC使用Shiro主要在业务层,而案例中是直接写在控制层,其实在Service层会比较清晰明了,因为它的认证和授权有跟DAO层交互的部分。
上一篇:mock插件使用


下一篇:指针和const