10.SpringBoot整合Shiro

10.SpringBoot整合Shiro

10.1 Shiro介绍

​ 什么是Shiro?

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

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

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

​ Shiro功能?

10.SpringBoot整合Shiro_第1张图片

  • 三个核心组件: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>
    
    <dependency>
        <groupId>org.apache.shirogroupId>
        <artifactId>shiro-coreartifactId>
        <version>1.5.3version>
    dependency>

    
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>jcl-over-slf4jartifactId>
        <version>1.7.30version>
    dependency>
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-log4j12artifactId>
        <version>1.7.30version>
    dependency>
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.17version>
    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>
    
    <dependency>
        <groupId>com.github.theborakompanionigroupId>
        <artifactId>thymeleaf-extras-shiroartifactId>
        <version>2.0.0version>
    dependency>

    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.18.12version>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>8.0.20version>
    dependency>
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.1.22version>
    dependency>
    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>2.1.3version>
    dependency>
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.17version>
    dependency>
    <dependency>
        <groupId>org.apache.shirogroupId>
        <artifactId>shiro-spring-boot-starterartifactId>
        <version>1.5.3version>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-thymeleafartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintagegroupId>
                <artifactId>junit-vintage-engineartifactId>
            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}">adda><br>

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

@RequestMapping("/user/update")
public String toUpdate(){
    return "user/update";
}
  • add.html 和update.html
<h1>addh1>
<h1>updateh1>
  • 启动主类,可以看到点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链接进行限定 判断是否有特定的权限

<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

<h1 th:text="${msg}">首页h1>
<h1 th:href="@{/toLogin}">h1>
<hr>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">adda><br>
div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">updatea>
div>
body>
html>

你可能感兴趣的:(shiro,SpringBoot,Thymeleaf,Realm,安全框架)