10.SpringBoot整合Shiro

10.SpringBoot整合Shiro

10.1 Shiro介绍

​ 什么是Shiro?

  • shiro官网:https://shiro.apache.org/

  • Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理

  • 使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

​ Shiro功能?

img

  • 三个核心组件:Subject, SecurityManager 和 Realms
  • Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。
  • SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
  • Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。

10.2 官网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.30</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>

​ 第二步:引入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

​ 第四步:引入quickStart

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) {

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

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

​ 第五步:运行quickStart测试 (下面是测试结果)

2020-07-25 13:42:47,366 INFO [Quickstart] - Retrieved the correct value! [aValue] 
2020-07-25 13:42:47,368 INFO [Quickstart] - User [lonestarr] logged in successfully. 
2020-07-25 13:42:47,368 INFO [Quickstart] - May the Schwartz be with you! 
2020-07-25 13:42:47,368 INFO [Quickstart] - You may use a lightsaber ring.  Use it wisely. 
2020-07-25 13:42:47,369 INFO [Quickstart] - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  Here are the keys - have fun! 

​ 基于以上官网快速入门案例就搭建完成了 现在就是我们研究shiro到底如何使用的时候了

  • 首先我们会对QuickStart的代码一点一点榨干
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) {

        /**
         * 这段话主要是我们可以通过读取shiro.ini中的内容(user是用户,role是角色)得到一个工厂对象来实例化SecurityManager
         * 管理shiro内部组件提供安全管理的各种服务,并通过SecurityUtils工具类将securityManager
         * 设置进去
         *
         * shiro.ini文件配置了用户权限以及认证
         */
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //拿到当前用户对象
        Subject currentUser = SecurityUtils.getSubject();

        //通过当前用户拿到Shiro的Session对象
        Session session = currentUser.getSession();

        //通过Session进行存值取值 并将值强转为String类型
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");

        if (value.equals("aValue")) {
            log.info("拿到的Subject对象的Session中value为 [" + value + "]");
        }

        //判断当前用户对象是否已经认证
        if (!currentUser.isAuthenticated()) {

            //根据你的账号密码生成一个令牌(token)  这是与shiro.ini文件相对应的 也就是说可以自己改ini文件进行设置
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            //token令牌设置记住我
            token.setRememberMe(true);

            //下面三个登录异常分别是没有当前对象、密码错误、账户被锁定
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log.info("没有当前用户对象 " + 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 (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.");
        }

        //用户是否被允许有这样的实力级权限(这个权限是属于schwartz用户角色的)
        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.");
        }

        //判断是否拥有实例级权限(这个权限是属于goodguy用户角色的)
        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);
    }
}
  • 深入分析提取出我们需要的信息
Subject currentUser = SecurityUtils.getSubject();//拿到当前用户对象
Session session = currentUser.getSession(); //通过当前用户拿到Shiro的Session对象
UsernamePasswordToken token = new UsernamePasswordToken("账号", "密码");//根据你的账号密码生成一个令牌(token)
token.getPrincipal();//获取当前用户对象
currentUser.isAuthenticated()//判断当前用户对象是否已经认证
currentUser.hasRole("schwartz")//判断用户角色
currentUser.isPermitted("lightsaber:wield")//用户是否被允许有这样的实力级权限
currentUser.logout();//用户注销

10.3 SpringBoot集成Shiro(关键)

​ 首先这个web项目是需要我们连接数据库的,所以需要一下信息

  • 数据库信息(数据库驱动mysql-driver、数据库连接池Druid、数据库依赖mysql)

  • SpringBoot-web场景启动器

  • Mybatis场景启动器

  • Shiro场景启动器

  • thymeleaf场景启动器

  • Shiro整合Thymeleaf

  • log4j日志

​ 第一步:导入相关依赖

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
    <dependency>
        <groupId>com.github.theborakompanioni</groupId>
        <artifactId>thymeleaf-extras-shiro</artifactId>
        <version>2.0.0</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.20</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.22</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.3</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring-boot-starter</artifactId>
        <version>1.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

​ 第二步:编写Shiro配置

三个核心对象对应相应的方法或类来创建

  • Subject当前用户对应:ShiroFilterFactoryBean

  • SecurityManager对应:DefaultWebSecurityManager

  • Realm对象对应继承AuthorizingRealm而创建

  • 这三个对象的创建方式应该由下往上,因为上面一个会调用下面一个,需要通过@Qualifier指定@Bean的值

  • 首先编写UserRealm

public class UserRealm extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        
    }
}
  • 接着编写ShiroConfig
@Configuration
public class ShiroConfig {

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

    @Bean("defaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    @Bean("userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }

}
  • 测试一下
<h1 >首页</h1>
<h1 th:href="@{/toLogin}"></h1>
<hr>

<a th:href="@{/user/add}">add</a><br>

<a th:href="@{/user/update}">update</a>
@RequestMapping("/user/add")
public String toAdd(){
    return "user/add";
}

@RequestMapping("/user/update")
public String toUpdate(){
    return "user/update";
}
  • add.html 和update.html
<h1>add</h1>
<h1>update</h1>
  • 启动主类,可以看到点update连接跳到update页面点add连接跳到add页面

​ 第三步:shiro实现登录拦截

  • 写一个登录页面
<form th:action="@{/login}">
    <p>用户名:<input type="text" name="username"></p>
    <p>密 码:<input type="password" name="password"></p>
     <input type="submit" value="提交">
</form>
  • 写controller接口
@RequestMapping("/toLogin")
public String toLogin(){
    return "login";
}
  • 在ShiroConfig中设置登录拦截 (也就是说如果你直接通过首页是进不去的,需要先登录 这个与SpringSecurity原理一致)
//设置登录页面
factoryBean.setLoginUrl("/toLogin");

​ 第四步:shiro实现用户认证

  • controller调用数据库拿到用户名密码进行判断 抛各种异常以及在model存异常提示
  • 拿到当前用户,判断当前用户状态,跳转页面有token令牌才能跳转到首页
@RequestMapping("/login")
public String login(String username,
                    String password,
                    Model model){
    //获取当前用户
    Subject currentUser = SecurityUtils.getSubject();
    //封装用户数据
    UsernamePasswordToken token = new UsernamePasswordToken(username,password);
    try {
        currentUser.login(token);
        return "index";
    } catch (UnknownAccountException uae) {
        model.addAttribute("errormsg","用户名错误!");
        return "login";
    } catch (IncorrectCredentialsException ice) {
        model.addAttribute("errormsg","密码错误!");
        return "login";
    }
}
  • 写UserRealm的认证 你一旦点了提交按钮,就会自动执行UserRealm中的认证方法
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    System.out.println("执行了认证doGetAuthenticationInfo方法!");
    UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
    //将参数token强转为我们需要的UsernamePasswordToken
    User user= userService.findByUsername(token.getUsername());
    if (user==null){
        return null;
    }
	//SimpleAuthenticationInfo是AuthenticationInfo的子类 返回时需要注意三个参数,一个是User对象通过username获取的
    //一个是password密码数据库获得,最后的是realmName
    return new SimpleAuthenticationInfo(user,user.getPassword(),"");
}
  • 接着在登录页共享一下错误数据
<div th:text="${errormsg}" style="color: red"></div>

​ 第五步:shiro授权功能实现

  • 首先需要数据库有perms字段 然后在配置中添加授权
  • 关键认证必须放在授权下面 不然授权是无法成功的
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
    ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
    //设置安全管理器
    factoryBean.setSecurityManager(defaultWebSecurityManager);

    //添加shiro的内置过滤器
    /*
    anno    无需认证就可以访问
    authc   必须认证才能访问
    user    必须拥有记住我功能才能用
    perms   拥有对某个资源权限才能访问
    role    拥有某个角色权限才能访问
     */
    Map<String, String> map = new LinkedHashMap<String, String>();
    //设置授权
    map.put("/user/add","perms[user:add]");
    map.put("/user/update","perms[user:update]");
 	map.put("/user/*", "authc");
    
    factoryBean.setFilterChainDefinitionMap(map);

    factoryBean.setUnauthorizedUrl("/unauthorized");
    //设置登录页面
    factoryBean.setLoginUrl("/toLogin");
    return factoryBean;
}
  • 授权失败跳转页面
//授权
@ResponseBody
@RequestMapping("/unauthorized")
public String unauthorized(){
    return "未授权!请联系管理员!";
}
  • UserRealm与数据库交互查出当前用户的权限
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    System.out.println("执行了doGetAuthorizationInfo授权方法!");
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    //info.addStringPermission("user:add");

    //拿到当前对象
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();

    info.addStringPermission(user.getPerms());
    return info;
}

​ 第六步:Shiro集成Thymeleaf

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值