栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

文章目录

参考资料运行环境一、Shiro体系结构

1.1 Shiro外部架构1.2 Shiro内部架构 二、Shiro 快速入门

2.1 使用IDEA创建Maven项目,引入依赖2.2 配置Shiro2.3 测试运行官方的Quickstart实例2.4 官方案例过程梳理 三、Shrio MDK5

3.1 Shiro 认证案例3.2 Shiro 授权案例 四、SpringBoot整合Shiro + Web + MyBatis + Thymeleaf案例

4.1 引入相关依赖4.2 配置MyBatis4.3 编写SpringMVC控制层 + 前端Thymeleaf页面4.4 配置Shiro4.5 运行测试4.6 小结

参考资料

视频链接1视频链接2 运行环境


Windows10Maven 3.8.3IDEA 2021.1 专业版JDK 8SpringBoot 2.6Shrio 1.8 一、Shiro体系结构


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

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


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内部架构

模块描述
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 1.8.0资源

访问解压后的目录D:shiro1.8.0shiro-root-1.8.0samplesquickstartsrcmainresources

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

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

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

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






    
        org.apache.shiro.samples
        shiro-samples
        1.8.0
        ../pom.xml
    

    4.0.0
    samples-quickstart
    Apache Shiro :: Samples :: Quick Start
    jar

    
        
            
                org.codehaus.mojo
                exec-maven-plugin
                1.6.0
                
                    
                        
                            java
                        
                    
                
                
                    test
                    Quickstart
                
            
        
    


    
        
            org.apache.shiro
            shiro-core
        

        
        
            org.slf4j
            jcl-over-slf4j
            runtime
        
        
            org.slf4j
            slf4j-log4j12
            runtime
        
        
            log4j
            log4j
            runtime
        
    


测试Demo的依赖 pom.xml



    4.0.0

    com.uni
    shiro1
    1.0-SNAPSHOT

    
        8
        8
    

    
        
            org.apache.shiro
            shiro-core
            1.8.0
        
        
            log4j
            log4j
            1.2.17
        

        
            org.slf4j
            jcl-over-slf4j
            1.6.1
        
        
            org.slf4j
            slf4j-log4j12
            1.6.1
        
    

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


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;



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

运行结果:

2.4 官方案例过程梳理

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

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

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

注:根据IDEA提示,IniSecurityManagerFactory类是过时的,说明有了其他更方便的用法,但这里不会影响使用

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

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;


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案例

项目结构:

4.1 引入相关依赖

pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.3
         
    
    com.uni
    springboot-shiro
    0.0.1-SNAPSHOT
    springboot-shiro
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
        
            org.apache.shiro
            shiro-spring
            1.6.0
        

        
        
            com.github.theborakompanioni
            thymeleaf-extras-shiro
            2.0.0
        
        
        
            mysql
            mysql-connector-java
        

        
            com.alibaba
            druid
            1.1.9
        

        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.3
        

        
            org.projectlombok
            lombok
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



4.2 配置MyBatis

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

mybatis.type-aliases-package=com.uni.pojo
mybatis.mapper-locations=classpath:mapper
        Map 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/

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

登陆页面输入密码错误会有错误提示

输入数据库里存在的用户登录后,再次跳转到首页

此时可正常访问add和update

4.6 小结

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/732242.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号