快速入门Shiro - 整合SpringBoot

1. Shiro简介

1.1 什么是Shiro?

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

1.2 有哪些功能?

在这里插入图片描述

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

1.3 Shiro架构(外部)

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

在这里插入图片描述

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

1.4 Shiro架构(内部)

在这里插入图片描述


2. HelloWorld

2.1 快速实践

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

  2. 创建一个普通的maven子工程,demo01

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

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.5.3</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>
    
  4. 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
    
  5. 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
    
  6. Quickstart.java快速开始测试类

    public class Quickstart {
    
        private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
    
    
        public static void main(String[] args) {
    
            Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
            SecurityManager securityManager = factory.getInstance();
            SecurityUtils.setSecurityManager(securityManager);
    
            // 获取当前的用户对象 Subject
            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("Subject ----> session [" + value + "]");
            }
    
            // let's login the current user so we can check against roles and permissions:
            // 判断当前的用户是否被认证
            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?
                }
            }
    
            //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);
        }
    }
    

    其实就是这几个方法:

    Subject currentUser = SecurityUtils.getSubject();// 获取当前的用户对象 Subject
    Session session = currentUser.getSession();// 通过当前用户拿到session
    currentUser.isAuthenticated();  //用户是否被认证
    currentUser.getPrincipal();   // 获取用户的角色
    currentUser.hasRole("schwartz");   // 用户是否有某种权限
    currentUser.isPermitted("lightsaber:wield");
    currentUser.logout();   // 注销
    

3. Springboot整合Shiro

Shiro的三大对象:Subject,SecurityManager,Realm

首先导入Shiro整合spring的包:

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

第一步:创建一个类,自定义Realm

// 自定义的Realm
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

shiroFilterFactoryBean

DefaultWebSecurityManager

创建Realm对象,需要我们自定义,第一步中我们已经自定义了Realm

  1. 将我们自定义的Realm放入IOC中
  2. 创建DefaultWebSecurityManager对象,绑定Realm,放入IOC中
  3. 创建ShiroFilterFactoryBean对象,绑定DefaultWebSecurityManager,放入IOC中
@Configuration
public class ShiroConfig {

    @Bean
    // ShiroFilterFactoryBean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultWebSecurityManager);
        return bean;
    }


    // DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联 UserRealm
        securityManager.setRealm(userRealm);

        return securityManager;
    }

    // 创建Realm对象,需要自定义  ,  第一步
    @Bean  // 将UserRealm放入IOC中
    public UserRealm userRealm(){
        return new UserRealm();
    }
}

这些代码都是定死的

3.1 Shiro实现登录拦截

在ShiroConfig中的getShiroFilterFactoryBean方法中进行配置,添加shiro的内置过滤器

anno:无需认证就可以访问
authc:必须认证了才能访问
user:必须拥有记住我功能才能使用
perms:拥有对某个资源的权限才能访问
role:拥有某个角色权限才能访问
Map<String,String> filterMap = new LinkedHashMap<>();

filterMap.put("/user/add","authc");   // add页面登录后才能访问
filterMap.put("/user/*","authc");      // user下的所有路径 只有登录后才能访问

bean.setFilterChainDefinitionMap(filterMap);

bean.setLoginUrl("/toLogin");  //如果没有权限,则跳转到登录页面

3.2 Shiro实现用户认证

首先我们写一个Controller来获取前端数据,封装token

@RequestMapping("/login")
public String login(String username, String password, Model model){
    // 获取当前的用户
    Subject subject = SecurityUtils.getSubject();

    // 封装用户的登录数据,token封装的数据相当于是全局的
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try{
        subject.login(token);  // 执行登录方法,调用Realm,如果没有异常,则说明ok了
        return "index";
    }catch (UnknownAccountException e){
        // 用户名不存在
        model.addAttribute("msg","用户名错误!");
        return "user/login";
    }catch (IncorrectCredentialsException e){
        // 密码错误
        model.addAttribute("msg","密码错误");
        return "user/login";
    }
}

然后在Realm中的认证方法doGetAuthenticationInfo中进行认证

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

    // 用户名 密码  数据库中取
    String name = "root";
    String password = "shw123zxc";

    UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken;
    if(!userToken.getUsername().equals(name)){  // 从token中取出数据进行比对
        return null;  // 抛出异常UnknownAccountException  用户名不存在
    }
    // 密码认证,shiro做
    return new SimpleAuthenticationInfo("",password,"");
}

3.3 Shiro整合Mybatis

再配置完数据源和Mybatis后,写完Mapper和Service后,在我们自定义的Realm中,在认证方法doGetAuthenticationInfo中,进行获取数据

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

    UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken;

    // 连接真实的数据库
    User user = userService.queryUserByName(userToken.getUsername());
    if (user==null){
        // 用户名不存在
        return null;   // 返回null,就是用户名不存在异常,在controller接收
    }

    // 密码认证,shiro做
    return new SimpleAuthenticationInfo("",user.getPassword(),"");
}

对密码进行MD5加密,在放入Token之前,对密码进行加密

String md5 = new SimpleHash("md5", password).toString();

3.4 Shiro请求授权实现

在ShiroConfig的getShiroFilterBean方法中进行设置权限拦截,如

filterMap.put("/user/add","perms[user:add]");  //只有拥有user:add的权限才能够访问/user/add
bean.setUnauthorizedUrl("/noauth");    // 未授权时,跳转到/noauth

在我们自定义的Realm中的doGetAuthorizationInfo方法中给用户进行授权

SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
return info;

这样写的话,每个人都会拥有user:add的权限

所以,权限我们要从数据库中取出

在Realm类中的认证方法中应该

return new SimpleAuthenticationInfo(user,user.getPassword(),"");  // 返回从数据库中获取的对象user,在授权方法中进行接收

授权方法中,拿到从认证方法中传过来的user对象

// 拿到当前登录的这个对象
Subject subject = SecurityUtils.getSubject();
User currentuser = (User)subject.getPrincipal();
info.addStringPermission(currentuser.getPerms());  // 获取当前对象的权限,进行授权

3.5 其他功能

注销功能

@RequestMapping("/logout")
public String logout(){
    Subject subject = SecurityUtils.getSubject();
    subject.logout();
    return "index";   // 注销后跳转到index页面
}

4. shiro整合thymeleaf

首先导入整合包 thymeleaf-extras-shiro

<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>

然后需要配置!

整合ShiroDialect:用来整合 Shiro 和 thymeleaf

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

就是将ShiroDialect放入IOC中,这样就OK了~

导入命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.org"
                xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<div shiro:hasPermission="user:add">
       ...
       <!--拥有user:add权限时显示-->
   </div>
   <div shiro:hasPermission="user:update" >
       ...
       <!--拥有user:update 权限时显示-->
   </div>

   <!--未登录时显示-->
   <a th:href="@{/toLogin}" shiro:notAuthenticated="">登录</a>  
   <hr>
   <!--已登录时显示-->
   <a th:href="@{/logout}" shiro:authenticated="">注销</a>

=“en” xmlns:th=“http://www.thymeleaf.org”
xmlns:shiro=“http://www.thymeleaf.org/thymeleaf-extras-shiro”>


 ```html
<div shiro:hasPermission="user:add">
        ...
        <!--拥有user:add权限时显示-->
    </div>
    <div shiro:hasPermission="user:update" >
        ...
        <!--拥有user:update 权限时显示-->
    </div>

	<!--未登录时显示-->
    <a th:href="@{/toLogin}" shiro:notAuthenticated="">登录</a>  
    <hr>
	<!--已登录时显示-->
    <a th:href="@{/logout}" shiro:authenticated="">注销</a>
课程简介:历经半个多月的时间,Debug亲自撸的 “企业员工角色权限管理平台” 终于完成了。正如字面意思,本课程讲解的是一个真正意义上的、企业级的项目实战,主要介绍了企业级应用系统中后端应用权限的管理,其中主要涵盖了六大核心业务模块、十几张数据库表。 其中的核心业务模块主要包括用户模块、部门模块、岗位模块、角色模块、菜单模块和系统日志模块;与此同时,Debug还亲自撸了额外的附属模块,包括字典管理模块、商品分类模块以及考勤管理模块等等,主要是为了更好地巩固相应的技术栈以及企业应用系统业务模块的开发流程! 核心技术栈列表: 值得介绍的是,本课程在技术栈层面涵盖了前端和后端的大部分常用技术,包括Spring BootSpring MVC、Mybatis、Mybatis-Plus、Shiro(身份认证与资源授权跟会话等等)、Spring AOP、防止XSS攻击、防止SQL注入攻击、过滤器Filter、验证码Kaptcha、热部署插件Devtools、POI、Vue、LayUI、ElementUI、JQuery、HTML、Bootstrap、Freemarker、一键打包部署运行工具Wagon等等,如下图所示: 课程内容与收益: 总的来说,本课程是一门具有很强实践性质的“项目实战”课程,即“企业应用员工角色权限管理平台”,主要介绍了当前企业级应用系统中员工、部门、岗位、角色、权限、菜单以及其他实体模块的管理;其中,还重点讲解了如何基于Shiro的资源授权实现员工-角色-操作权限、员工-角色-数据权限的管理;在课程的最后,还介绍了如何实现一键打包上传部署运行项目等等。如下图所示为本权限管理平台的数据库设计图: 以下为项目整体的运行效果截图: 值得一提的是,在本课程中,Debug也向各位小伙伴介绍了如何在企业级应用系统业务模块的开发中,前端到后端再到数据库,最后再到服务器的上线部署运行等流程,如下图所示:
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

mango1698

你的鼓励是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值