Shiro - Springboot 入门整合案例

  • 整合了Druid数据源、Springboot、Mybatis、Mysql、Thymeleaf

Shiro

  • 单独使用步骤

    1-导入依赖 2-导入ini配置文件 3-导入log4j.properties 4-创建类

  • 整合 springboot 步骤

    1-导入shiro-spring依赖 2-创建javaConfiguration配置类

Shiro 三大对象

Subject 用户

SecurityManager 管理所有用户

Realm 连接数据

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 中的 Subject

package com.hey;

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.
 * @author Hey
 * @since 0.9 RC2
 */
public class QuickStart {

    //日志门面,后面可以通过log输出一些日志信息 使用了log4j日志框架
    private static final transient Logger log = LoggerFactory.getLogger(QuickStart.class);

    public static void main(String[] args) {

        // 通过工厂模式读取配置文件,使用shiro.ini配置文件
        // 这里的三行代码是死代码
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        // 一下是重点代码
        // 获取当前用户对象
        Subject currentUser = SecurityUtils.getSubject();

        // 一些session操作
        // 通过当前用户获取session
        Session session = currentUser.getSession();
        // 设置了一个值
        session.setAttribute("someKey", "aValue");
        // 从session获取值
        // 这里相当于告诉你如何通过session存值取值
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        // 登录以及一些权限角色认证的操作
        // 判断当前用户是否已经认证
        if (!currentUser.isAuthenticated()) {
            // 生成一个令牌
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            // 设置记住我
            token.setRememberMe(true);
            try {
                // 登录操作,这里会和Realm对象联动完成账号的授权和认证的操作
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                // 用户名不存在会报 UnknownAccountException 错
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                // 密码不正确会报 IncorrectCredentialsException 错
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                // 用户账户被锁定了,比如说可以设置密码输入5次不正确就锁定用户
                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?
            }
        }

        //一个日志输出
        //print their identifying principal (in this case, a username):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //测试角色
        if (currentUser.hasRole("schwartz")) {
            // 当前用户有 schwartz 角色
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }

        // 以下两个都是权限认证 但是是有区别的,在 shiro.ini 中配置给角色的权限可以通过 : 来分级
        // 比如说 A 角色有 user:vip1   B 角色有 user:vip2 C角色有 user:*
        // *号是通配符,表示user下的所有动作
        // 这样就能通过粗粒度或细粒度的划分,来认证vip的等级如何
        // 粗粒度
        // 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!");
        }

        // 注销
        currentUser.logout();
        // 程序结束
        System.exit(0);
    }
}

环境搭建

HTML页面

  • 主页
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<a th:href="@{/user/add}">add</a> |
<a th:href="@{/user/update}">update</a>
</body>
</html>
  • /user/add
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
  • /user/update
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>

pom.xml 依赖

  • springboot
<!-- Shiro整合spring的包 -->
<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-spring</artifactId>
   <version>1.5.1</version>
</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>
   <version>1.2.17</version>
   <scope>runtime</scope>
</dependency>

配置JavaConfig

package com.hey.config;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
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;

/**
 * @author Hey
 */
@Configuration
public class ShiroConfig {
    //3 ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultSecurityManager") DefaultSecurityManager defaultSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);
        //添加shiro内置过滤器
        /*
         * anon: 无需认证就可以访问
         * authc: 必须认证了才可以访问
         * user: 必须拥有 记住我 功能才可以访问
         * perms: 拥有对某个资源的权限才能访问
         * role: 拥有某个角色权限才可以访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add","anon");
        filterMap.put("/user/update","authc");
        //把map放入过滤器chain链中
        bean.setFilterChainDefinitionMap(filterMap);
        return bean;
    }

    //2 DefaultWebSecurityManager
    // 用注解传入realmzhege Bean
    // Qualifier相当于形参上的Autowired
    @Bean(name = "defaultSecurityManager")
    public DefaultSecurityManager getDefaultSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    //1 创建Realm对象 需要自定义类
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }
}

配置自定义Realm

package com.hey.config;

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

/**
 * 自定义的Realm
 * @author Hey
 */
public class UserRealm extends AuthorizingRealm {
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权");
        return null;
    }

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

配置Controller

package com.hey.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Hey
 */
@Controller
public class MyController {

    @RequestMapping("/")
    public String toIndex(Model model){
        model.addAttribute("msg","hello world");
        return "main";
    }
    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }
    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }
}

Shiro 实现登录拦截

添加登陆页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<h1>登录</h1>
<hr>
<form th:action="@{/login}" method="post">
    <p>用户名: <input type="text" name="username"></p>
    <p>密 码: <input type="password" name="password"></p>
    <p><input type="submit"></p>
</form>
</body>
</html>

设置shiro登录链接

  • ShiroConfiggetShiroFilterFactoryBean中添加登录链接设置
  • 当shiro拦截过后就会自动跳转到设置好的URL
//设置登录请求
bean.setLoginUrl("/toLogin");

添加Controller映射

@RequestMapping("/toLogin")
public String toLogin(){
    return "login";
}
@RequestMapping("/login")
public String login(){
    return "main";
}

Shiro 实现登录认证

  • 认证是在Realm中进行认证
  • config配置类和自定义Realm会联动

在Controller中获得用户名和密码

@RequestMapping("/login")
public String login(String username,String password,Model model){
    //获取当前用户
    Subject subject = SecurityUtils.getSubject();
    //封装用户登陆数据,放为令牌加密
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    //执行登陆方法, 如果没有异常就说明ok了
    try {
        subject.login(token);
        return "main";
    }catch (UnknownAccountException e){
        //用户名不存在
        model.addAttribute("msg","用户名错误");
        return "login";
    }catch (IncorrectCredentialsException e){
        //密码不存在
        model.addAttribute("msg","密码不存在");
        return "login";

    }
}

配置UserRealm的认证方法

//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    System.out.println("执行了=>认证");
    // Controller 中添加了 subject.login() 后就会进入这个方法
    // 认证用户名和密码 从数据库中获取
    String username = "admin";
    String password = "123456";
    //获取登录信息
    //转换Token
    UsernamePasswordToken userToken = (UsernamePasswordToken) token;
    if(userToken.getUsername().equals(username)){
        //返回null值  就会抛出异常 UnknownAccountException
        return null;
    }
    //密码认证 shiro自己做
    return new SimpleAuthenticationInfo("",password,"");
}

Shiro整合Mybatis

导入依赖

  • 整合了Druid数据源,Mysql驱动,Mybatis,log4j日志
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

Druid 数据源 application.yml

  • 一些简介
    • Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控
    • Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池
    • Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验
    • Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控
spring:
  datasource:
    username: root
    password: 123456
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

配置Mybatis数据库

  • 可以先在IDEA中设置DataBase连接方便管理
  • application.yml中配置 Mybatis 别名包(实体包)以及映射文件路径(在resources目录下创建一个mapper文件夹)
# 数据库配置
mybatis:
  type-aliases-package: com.hey.entity
  mapper-locations: classpath:mapper/*.xml
  • 创建实体类(此处省略,属性为id username password
  • 创建UserMapper接口
//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface UserMapper {

    public User queryUserByName(String username);
}
  • 创建UserMapper.xml
<?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.hey.mapper.UserMapper">

    <select id="queryUserByName" parameterType="String" resultType="User">
       select * from User where name=#{username};
    </select>

</mapper>
  • 完善Service层(此处省略,创建接口UserService和实现类UserServiceImpl

  • 其实如果业务太多,Service层可以省略,实现类可以使用@Autowired装入UserMapper,再通过@Service将实现类装入spring容器中

UserRealm 中连接数据库

//首先注入UserService
@Autowired
UserService userService;
//在认证的方法里面
User user = userService.queryUserByName(userToken.getUsername());
if(user==null){
    //没有这个人
    return null; //返回null会产生UnknownAccountException 异常
}
//密码认证这里修改一下传入user的密码即可
    return new SimpleAuthenticationInfo("",user.getPassword(),"");

Shiro 密码加密

  • credentialsMatcher 里面可以选择密码的加密方式,默认是SimpleCredentialsMatcher,可以自己继承接口自定义实现
UserRealm 继承了 AuthorizingRealm 继承了 AuthenticatingRealm
AuthenticatingRealm 里面有 getCredentialsMatcher() 返回 CredentialsMatcher类型的数据
CredentialsMatcher 是一个接口,有很多的实现类
在没有配置的时候,默认使用 SimpleCredentialsMatcher 
有一个实现类叫 Md5CredentialsMatcher 就是继承了 SimpleCredentialsMatcher
所以可以自己摸索一下,实现一个自己的加密实现方法
  • 可以加密: MD5 MD5盐值加密

Shiro 授权

### 配置 ShiroConfig

  • getShiroFilterFactoryBean()中添加权限认证拦截和未授权请求跳转链接设置
//授权,正常情况下没有授权访问就会直接跳转到未授权的页面
filterMap.put("/user/add","perms[user:add]");
//设置未授权请求跳转链接
bean.setUnauthorizedUrl("/noauth");

Controller 配置跳转链接

  • Controller中配置跳转链接,这里仅返回一个字符串显示在页面上
@RequestMapping("/noauth")
@ResponseBody
public String unauthorized(){
    return "未经授权无法访问";
}

UserRealm中给用户授权

  • 其中有一个问题,就是doGetAuthorizationInfo中没办法获取到当前登录的用户,那么就无法做出比较或者是权限判断
  • 这个时候可以通过设置doGetAuthenticationInfo返回对象来传递参数
//密码认证 shiro自己做
return new SimpleAuthenticationInfo(user,user.getPassword(),"");
  • doGetAuthorizationInfo中就可以获取到数据库中查询出来的对象
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 经过权限拦截的请求就会进入这个方法,就可以在此方法中对用户进行授权
// info.addStringPermission("user:add");
// 授权的条件可以通过数据库表查询结果判断
// 如果数据复杂了可以分三张表,一张用户表,一张角色表,一张权限表 用户与角色一对一  角色与权限一对多
// 拿到当前登录的对象
Subject subject = SecurityUtils.getSubject();
// 拿到User对象
User currentUser = (User) subject.getPrincipal();
// 设置当前用户的权限
// currentUser.getPerms() 即获取数据库中的权限 在user对象中添加权限属性即可
// info.addStringPermission()的参数即filterMap中perms[]中的值
// filterMap.put("/user/add","perms[user:add]");
// "user:add" == currentUser.getPerms()
info.addStringPermission(currentUser.getPerms());
// 不能再返回null了,要将设置了的info返回
return info;

Shiro 整合 Thymeleaf 模板引擎

导入依赖

<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>
<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置ShiroConfig

//整合ShiroDialect: 用来整合Shiro和Thymeleaf
@Bean
public ShiroDialect getShitoDialect(){
    return new ShiroDialect();
}

HTML使用

<!-- 导入命名空间 -->
smlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
<!-- 如果有这个权限就显示某些部件 -->
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">update</a>
</div>

Shiro常用标签

<!--验证当前用户是否拥有指定权限。  -->
<a shiro:hasPermission="user:add" href="#" >add用户</a><!-- 拥有权限 --> 

<!--与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过。-->
<p shiro:lacksPermission="user:del"> 没有权限 </p>

<!--验证当前用户是否拥有以下所有权限。-->
<p shiro:hasAllPermissions="user:view, user:add"> 权限与判断 </p>

<!--验证当前用户是否拥有以下任意一个权限。-->
<p shiro:hasAnyPermissions="user:view, user:del"> 权限或判断 </p>

<!--验证当前用户是否属于该角色。-->
<a shiro:hasRole="admin" href="#">拥有该角色</a>

<!--与hasRole标签逻辑相反,当用户不属于该角色时验证通过。-->
<p shiro:lacksRole="developer"> 没有该角色 </p>

<!--验证当前用户是否属于以下所有角色。-->
<p shiro:hasAllRoles="developer, admin"> 角色与判断 </p>

<!--验证当前用户是否属于以下任意一个角色。-->
<p shiro:hasAnyRoles="admin, vip, developer"> 角色或判断 </p>
 
<!--验证当前用户是否为“访客”,即未认证(包含未记住)的用户。-->
<p shiro:guest="">访客 未认证</a></p>

<!--认证通过或已记住的用户-->
<p shiro:user=""> 认证通过或已记住的用户 </p>

<!--已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在。-->
<p shiro:authenticated=""> <span shiro:principal=""></span> </p>

<!--输出当前用户信息,通常为登录帐号信息-->
<p> <shiro:principal/> </p>

<!--未认证通过用户,与authenticated标签相对应。-->
<!--与guest标签的区别是,该标签包含已记住用户。-->
<p shiro:notAuthenticated=""> 未认证通过用户 </p>

猜你喜欢

转载自blog.csdn.net/Kobe_k/article/details/104987208