权限管理(二)---Shiro整合SpringBoot项目实现认证和授权

目录

Shiro整合SpringBoot项目大致思路

在这里插入图片描述
首先要配置一个Filter去捕获客户端的所有请求并进行拦截,需要在Filter中判断哪些请求是受限资源,需要进行认证授权;哪些请求是公共资源,不需要认证授权,可以直接放行。
如果该请求是受限资源,必须要进行认证授权操作,需要调用SecurityManager中的doGetAuthenticationInfo()doGetAuthorizationInfo()进行校验,在校验时,需要通过Realm获取数据库中的权限数据。

1 环境搭建

1.1 创建SpringBoot项目:springboot_jsp_shiro

(1)新建SpringBoot项目
在这里插入图片描述
在这里插入图片描述
(2)创建如下目录结构,编辑index.jsp
在这里插入图片描述

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    hello world
</body>
</html>

(3)编辑application.yml配置文件

server:
  port: 8888
  servlet:
    context-path: /shiro
spring:
  application:
    name: shiro
  mvc:
    view:
      prefix: /
      suffix: .jsp

(4)编辑pom.xml文件,添加jsp解析依赖等

<!-- 引入jsp解析依赖 -->
<dependency>
	<groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

(5)启动项目测试
访问:http://localhost:8888/shiro/index.jsp
在这里插入图片描述
出现404错误是由于idea和springboot有冲突,需要进行如下配置:
在这里插入图片描述
在这里插入图片描述
再次重启测试:
在这里插入图片描述

1.2 整合shiro

1.2.1 编辑页面

(1)编辑index.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="utf-8" isELIgnored="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>系统主页V1.0</h1>

    <ul>
        <li><a href="">用户管理</a></li>
        <li><a href="">商品管理</a></li>
        <li><a href="">订单管理</a></li>
        <li><a href="">物流管理</a></li>
    </ul>
</body>
</html>

(2)编辑login.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="utf-8" isELIgnored="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>用户登录</h1>
</body>
</html>

(3)访问测试:
在这里插入图片描述
在这里插入图片描述

1.2.2 引入shiro依赖

使用spring整合shiro时,需要在pom.xml中添加如下依赖:

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

1.2.3 配置shiro环境

1)创建配置类
配置ShiroFilterFactoryBean
配置WebSecurityManager
配置自定义realm
package cn.edu.springboot_jsp_shiro.config;

import cn.edu.springboot_jsp_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 用来整合shiro框架相关的配置类
 */
@Configuration
public class ShiroConfig {
    //1.创建shiroFilter--负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        
        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //配置系统受限资源
        //配置系统公共资源
        Map<String,String> map=new HashMap<>();
        map.put("/index.jsp","authc");  //authc:表示请求这个资源需要认证和授权
        
        //shiroFilter中默认认证界面路径
//      shiroFilterFactoryBean.setLoginUrl("/login.jsp"); //不写,默认就是login.jsp

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        
        return shiroFilterFactoryBean;
    }
    //2.创建SecurityManager安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //给安全管理器设置realm
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }
    //3.创建自定义realm
    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }
}

2)创建自定义CustomerRealm
package cn.edu.springboot_jsp_shiro.shiro.realms;

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
public class CustomerRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        return null;
    }
}

3)启动项目测试

访问 http://localhost:8888/shiro/index.jsp
此时,会看到页面自动跳转到了login.jsp页面。

2 shiro实现项目中认证和退出

2.1 shiro中常见过滤器

shiro中提供了多个默认的过滤器可用来配置控制指定url的权限。

配置缩写对应的过滤器功能
anonAnonymousFilter指定url可以匿名访问
authcFormAuthenticationFilter指定url需要form表单登录- -基于表单的拦截器,默认会从请求中获取 username、password、rememberMe等参数并尝试登录,如果登录不了会跳到LoginUrl配置的路径。主要属性:usernameParam:表单提交的用户名参数名( username); passwordParam:表单提交的密码参数名(password); rememberMeParam:表单提交的密码参数名(rememberMe); loginUrl:登录页面地址(/login.jsp);successUrl:登录成功后的默认重定向地址; failureKeyAttribute:登录失败后错误信息存储key(shiroLoginFailure)。
authcBasicBasicHttpAuthenticationFilterBasic HTTP身份验证拦截器。主要属性: applicationName:弹出登录框显示的信息(application)
logoutLogoutFilter退出拦截器,配置指定url就可以实现退出功能。主要属性:redirectUrl:退出成功后重定向的地址(/)
userUserFilter用户拦截器,需要已登录/记住我的用户才能访问
rolesRolesAuthorizationFilter角色授权拦截器,指定角色才能访问。主要属性: loginUrl:登录页面地址(/login.jsp);unauthorizedUrl:未授权后重定向的地址
permsPermissionsAuthorizationFilter权限授权拦截器,指定权限才能访问。属性和roles一样
portPortFilter端口拦截器,指定端口才能访问。
restHttpMethodPermissionFilterrest风格拦截器,自动根据请求方法构建权限字符串。
sslSslFilterSSL拦截器,需要请求协议是https才能访问。
noSessionCreationNoSessionCreationFilter禁止创建会话。

2.2 认证实现

2.2.1 编辑login.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="utf-8" isELIgnored="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>用户登录</h1>

    <form action="${pageContext.request.contextPath}/user/login" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="text" name="password"><br/>
        <input type="submit" value="登录">
    </form>
</body>
</html>

2.2.2 编辑UserController

package cn.edu.springboot_jsp_shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("user")
public class UserController {
    /**
     * 用来处理身份认证
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("login")
    public String login(String username,String password){

        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            return "redirect:/index.jsp";
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户名错误!");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误!");
        }
        return "redirect:/login.jsp";
    }
}

2.2.3 编辑自定义CustomerRealm

先给一个假数据,不连接数据库

package cn.edu.springboot_jsp_shiro.shiro.realms;

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;
//自定义realm
public class CustomerRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("===========");
        String principal = (String) token.getPrincipal();
        if("xiaochen".equals(principal)){
            return new SimpleAuthenticationInfo(principal,"123",this.getName());
        }
        return null;
    }
}

2.2.4 启动测试

访问:http://localhost:8888/shiro/index.jsp
会跳转到 login.jsp 页面,
在这里插入图片描述
输入错误信息后,会再次跳回到登录页,且控制台会输出提示信息:
在这里插入图片描述
输入正确信息后,会进入index.jsp系统主页:
在这里插入图片描述

2.3 退出实现

2.3.1 编辑index.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="utf-8" isELIgnored="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>系统主页V1.0</h1>
    <a href="${pageContext.request.contextPath}/user/logout">退出系统</a>

    <ul>
        <li><a href="">用户管理</a></li>
        <li><a href="">商品管理</a></li>
        <li><a href="">订单管理</a></li>
        <li><a href="">物流管理</a></li>
    </ul>
</body>
</html>

2.3.2 编辑UserController

package cn.edu.springboot_jsp_shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("user")
public class UserController {
    /**
     * 退出登录
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }

    /**
     * 用来处理身份认证
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("login")
    public String login(String username,String password){

        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            return "redirect:/index.jsp";
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户名错误!");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误!");
        }
        return "redirect:/login.jsp";
    }
}

重启测试,可以退出系统,回到登录页。

2.3.3 编辑ShiroConfig配置类

注意:因为我们系统中会有很多受限资源,所以使用通配符"/**";此时,无论访问什么路径,都会回到登陆页面,登陆无法成功进入系统,所以我们要把系统允许匿名访问的公共资源设置在受限资源前。

package cn.edu.springboot_jsp_shiro.config;

import cn.edu.springboot_jsp_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 用来整合shiro框架相关的配置类
 */
@Configuration
public class ShiroConfig {
    //1.创建shiroFilter--负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //配置系统受限资源
        //配置系统公共资源
        Map<String,String> map=new HashMap<>();
        map.put("/user/login","anon");  //anon:设置为公共资源
        map.put("/**","authc");  //authc:表示请求这个资源需要认证和授权

//        shiroFilterFactoryBean.setLoginUrl("/login.jsp"); //shiroFilter中默认认证界面路径
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }
    //2.创建SecurityManager安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //给安全管理器设置realm
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }
    //3.创建自定义realm
    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }
}

3 shiro连接数据库完成基于MD5+Salt的注册功能

3.1 准备数据表

在这里插入图片描述

3.2 准备注册页register.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="utf-8" isELIgnored="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>用户注册</h1>

    <form action="${pageContext.request.contextPath}/user/register" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="text" name="password"><br/>
        <input type="submit" value="立即注册">
    </form>
</body>
</html>

3.3 编辑ShiroConfig

需要放行register.jsp和注册路径:

package cn.edu.springboot_jsp_shiro.config;

import cn.edu.springboot_jsp_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 用来整合shiro框架相关的配置类
 */
@Configuration
public class ShiroConfig {
    //1.创建shiroFilter--负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //配置系统受限资源
        //配置系统公共资源
        Map<String,String> map=new HashMap<>();
        map.put("/user/login","anon");  //anon:设置为公共资源
        map.put("/user/register","anon");
        map.put("/register.jsp","anon");
        map.put("/**","authc");  //authc:表示请求这个资源需要认证和授权

//        shiroFilterFactoryBean.setLoginUrl("/login.jsp"); //shiroFilter中默认认证界面路径
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }
    //2.创建SecurityManager安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //给安全管理器设置realm
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }
    //3.创建自定义realm
    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }
}

3.4 连接数据库

3.4.1 添加依赖

<!-- mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

<!-- mysql -->
<dependency>
	<groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>

<!-- druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.19</version>
</dependency>

3.4.2 编辑.yml文件

server:
  port: 8888
  servlet:
    context-path: /shiro
spring:
  application:
    name: shiro
  mvc:
    view:
      prefix: /
      suffix: .jsp
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/shiro?characterEncoding=UTF-8
    username: root
    password: root

mybatis:
  type-aliases-package: cn.edu.springboot_jsp_shiro.entity
  mapper-locations: classpath:cn/edu/mapper/*.xml

此时,项目目录结构如下:
在这里插入图片描述

3.4.3 编辑User实体

package cn.edu.springboot_jsp_shiro.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String id;
    private String username;
    private String password;
    private String salt;
}

3.4.4 编辑UserDao接口

package cn.edu.springboot_jsp_shiro.dao;

import cn.edu.springboot_jsp_shiro.entity.User;
@Mapper
public interface UserDao {
    void save(User users);
}

3.4.5 编辑UserDaoMapper.xml

在resources的

<?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="cn.edu.springboot_jsp_shiro.dao.UserDao">

    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into  t_user values(#{id},#{username},#{password},#{salt})
    </insert>

</mapper>

注意:建此文件需要 new–>Mapper 。当新建没有Mapper选项时,参考以下链接的解决办法。
在这里插入图片描述
解决方案:https://blog.csdn.net/showLo1120/article/details/107846480

3.4.6 编辑UserService接口及其实现类

package cn.edu.springboot_jsp_shiro.service;

import cn.edu.springboot_jsp_shiro.entity.User;

public interface UserService {
    //用户注册
    void register(User user);
}

package cn.edu.springboot_jsp_shiro.service;

import cn.edu.springboot_jsp_shiro.dao.UserDao;
import cn.edu.springboot_jsp_shiro.entity.User;
import cn.edu.springboot_jsp_shiro.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Override
    public void register(User user) {
        //1.生成随机盐
        String salt = SaltUtils.getSalt(8);
        //2.将随机盐保存到数据库中
        user.setSalt(salt);
        //3.明文密码 MD5 +salt +hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
        user.setPassword(md5Hash.toHex());
        userDao.save(user);
    }
}

3.4.7 编辑SaltUtils生成随机盐的工具类

package cn.edu.springboot_jsp_shiro.utils;

import java.util.Random;

public class SaltUtils {
    /**
     * 生成salt的静态方法
     * @param n
     * @return
     */
    public static String getSalt(int n){//ctrl+shift+u:将大写字母转小写
        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890!@#$%^&*()".toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            stringBuilder.append(aChar);
        }
        return stringBuilder.toString();
    }

    //测试
    public static void main(String[] args){
        String salt = getSalt(8);
        System.out.println(salt);//@%h*E0BL
    }
}

3.4.8 编辑UserController

package cn.edu.springboot_jsp_shiro.controller;

import cn.edu.springboot_jsp_shiro.entity.User;
import cn.edu.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("user")
public class UserController {
    
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping("register")
    public String register(User user){
        try {
            userService.register(user);
            return "redirect:/login.jsp";
        }catch (Exception e){
            e.printStackTrace();
            return "redirect:/register.jsp";
        }
    }
    
    /**
     * 退出登录
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }

    /**
     * 用来处理身份认证
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("login")
    public String login(String username,String password){

        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            return "redirect:/index.jsp";
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户名错误!");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误!");
        }
        return "redirect:/login.jsp";
    }
}

3.4.9 启动测试

访问:http://localhost:8888/shiro/register.jsp,输入用户名密码后注册成功会跳转到登录页。
在这里插入图片描述
从数据库中可以看到密码已经进行加密处理:
在这里插入图片描述

4 shiro连接数据库完成基于MD5+Salt的认证功能

4.1 编辑UserDao

package cn.edu.springboot_jsp_shiro.dao;

import cn.edu.springboot_jsp_shiro.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserDao {
    void save(User users);
    User findByUsername(String username);
}

4.2 编辑UserDaoMapper.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="cn.edu.springboot_jsp_shiro.dao.UserDao">

    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into  t_user values(#{id},#{username},#{password},#{salt})
    </insert>

    <select id="findByUsername" parameterType="String" resultType="User">
        select id,username,password,salt from t_user
        where username=#{username}
    </select>
</mapper>

4.3 编辑UserService及实现类

package cn.edu.springboot_jsp_shiro.service;

import cn.edu.springboot_jsp_shiro.entity.User;

public interface UserService {
    //用户注册
    void register(User user);

    //根据用户名查询
    User findByUsername(String username);

}

package cn.edu.springboot_jsp_shiro.service;

import cn.edu.springboot_jsp_shiro.dao.UserDao;
import cn.edu.springboot_jsp_shiro.entity.User;
import cn.edu.springboot_jsp_shiro.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public void register(User user) {
        //1.生成随机盐
        String salt = SaltUtils.getSalt(8);
        //2.将随机盐保存到数据库中
        user.setSalt(salt);
        //3.明文密码 MD5 +salt +hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
        user.setPassword(md5Hash.toHex());
        userDao.save(user);
    }


}

4.4 编辑ApplicationContextUtils工具类

自定义realm需要调用业务方法去做实现,自定义realm需要一个业务对象,业务对象是交给工厂管理的,怎么给自定义realm注入业务对象呢?
由于CustomerRealm并没有交给工厂管理,所以不能直接注入userService对象,需要定义一个工具类,用来获取springboot中创建好工厂的工具类。

package cn.edu.springboot_jsp_shiro.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext context;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context=applicationContext;    
    }
    
    //根据bean名字获取工厂中指定bean 对象
    public static Object getBean(String beanName){
        return context.getBean(beanName);
    }
}

4.5 编辑CustomerRealm

package cn.edu.springboot_jsp_shiro.shiro.realms;

import cn.edu.springboot_jsp_shiro.entity.User;
import cn.edu.springboot_jsp_shiro.service.UserService;
import cn.edu.springboot_jsp_shiro.utils.ApplicationContextUtils;
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;
import org.springframework.util.ObjectUtils;

//自定义realm
public class CustomerRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("===========");
        //获取身份信息
        String principal = (String) token.getPrincipal();
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userServiceImpl");

        User user = userService.findByUsername(principal);

        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        
        return null;
    }
}

4.6 编辑ShiroConfig

package cn.edu.springboot_jsp_shiro.config;

import cn.edu.springboot_jsp_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 用来整合shiro框架相关的配置类
 */
@Configuration
public class ShiroConfig {
    //1.创建shiroFilter--负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //配置系统受限资源
        //配置系统公共资源
        Map<String,String> map=new HashMap<>();
        map.put("/user/login","anon");  //anon:设置为公共资源
        map.put("/user/register","anon");
        map.put("/register.jsp","anon");
        map.put("/**","authc");  //authc:表示请求这个资源需要认证和授权

//        shiroFilterFactoryBean.setLoginUrl("/login.jsp"); //shiroFilter中默认认证界面路径
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }
    //2.创建SecurityManager安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //给安全管理器设置realm
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }
    //3.创建自定义realm
    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法为md5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);

        return customerRealm;
    }
}

4.7 启动测试

访问:http://localhost:8888/shiro/login.jsp
输入正确的用户名密码后,即可进入系统主页。
在这里插入图片描述

5 授权的基本使用

5.1 通过页面标签实现对页面资源的授权过程

5.1.1 在页面引入shiro标签

<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

5.1.2 编辑index.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="utf-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>系统主页V1.0</h1>
    <a href="${pageContext.request.contextPath}/user/logout">退出系统</a>

    <ul>
        <shiro:hasAnyRoles name="user,admin">
            <li><a href="">用户管理</a>
                <ul>
                    <shiro:hasPermission name="user:add:*">
                        <li><a href="">添加</a></li>
                    </shiro:hasPermission>
                    <shiro:hasPermission name="user:update:*">
                        <li><a href="">修改</a></li>
                    </shiro:hasPermission>
                    <shiro:hasPermission name="user:delete:*">
                        <li><a href="">删除</a></li>
                    </shiro:hasPermission>
                    <shiro:hasPermission name="user:find:*">
                        <li><a href="">查询</a></li>
                    </shiro:hasPermission>
                </ul>
            </li>
        </shiro:hasAnyRoles>
        <shiro:hasRole name="admin">
            <li><a href="">商品管理</a></li>
            <li><a href="">订单管理</a></li>
            <li><a href="">物流管理</a></li>
        </shiro:hasRole>
    </ul>
</body>
</html>

5.1.3 编辑自定义realm

package cn.edu.springboot_jsp_shiro.shiro.realms;

import cn.edu.springboot_jsp_shiro.entity.User;
import cn.edu.springboot_jsp_shiro.service.UserService;
import cn.edu.springboot_jsp_shiro.utils.ApplicationContextUtils;
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;
import org.springframework.util.ObjectUtils;

//自定义realm
public class CustomerRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("***************************");
        //根据主身份信息获取 角色 和 权限 信息
        if("xiaochen".equals(primaryPrincipal)){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRole("user");//基于角色的权限管理
            simpleAuthorizationInfo.addStringPermission("user:find:*");//基于资源/权限字符串的权限管理
            simpleAuthorizationInfo.addStringPermission("user:update:*");
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("===========");
        //获取身份信息
        String principal = (String) token.getPrincipal();
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userServiceImpl");

        User user = userService.findByUsername(principal);

        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }

        return null;
    }
}

5.1.3 启动测试

访问:http://localhost:8888/shiro/login.jsp
输入 xiaochen 123 进入系统,效果如下:
![在这里插入图片描述]

5.2 通过代码方式进行授权

5.2.1 新建编辑OrderController

package cn.edu.springboot_jsp_shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("order")
public class OrderController {

    @RequestMapping("save")
    public String save(){
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        //代码方式实现--基于角色
        if(subject.hasRole("admin")){
            System.out.println("保存订单");
        }else{
            System.out.println("无权访问");
        }

        return "redirect:/index.jsp";
    }

}

5.2.2 访问测试

http://localhost:8888/shiro/login.jsp
输入用户名密码后进入主页,
再在地址栏上访问 http://localhost:8888/shiro/order/save
虽然页面还是在系统主页,但查看控制台可知该用户无权保存订单。
在这里插入图片描述

5.3 通过注解方式实现权限控制

5.3.1 编辑OrderController

package cn.edu.springboot_jsp_shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("order")
public class OrderController {

    @RequestMapping("save")
    @RequiresRoles("user")//用来判断角色
    //@RequiresPermissions("user:update:01")//用来判断权限字符串
    public String save(){
        System.out.println("可以进行保存订单操作");
//        //获取主体对象
//        Subject subject = SecurityUtils.getSubject();
//        //代码方式实现
//        if(subject.hasRole("admin")){
//            System.out.println("保存订单");
//        }else{
//            System.out.println("无权访问");
//        }

        return "redirect:/index.jsp";
    }

}

5.3.2 访问测试

xiaochen用户登录进系统主页后,可访问 http://localhost:8888/shiro/order/save,由于xiaochen的角色是user,保存订单的方法也需要user角色的用户才能调用,因此效果如下:
在这里插入图片描述

???当修改xiaochen的角色为admin时,当角色不一样,也能保存订单

6 角色信息从数据库获取实现权限控制

6.1 数据库表设计

6.2 编辑实体类

6.2.1 新建Role实体

package cn.edu.springboot_jsp_shiro.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Role {
    private String id;
    private String name;
}

6.2.2 新建Perms实体

package cn.edu.springboot_jsp_shiro.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Perms {
    private String id;
    private String name;
    private String url;

}

6.2.3 编辑User实体

package cn.edu.springboot_jsp_shiro.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.List;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String id;
    private String username;
    private String password;
    private String salt;
    
    //定义角色集合--由于一个用户可能有多个角色
    private List<Role> roles;
}

6.3 编辑UserDao

package cn.edu.springboot_jsp_shiro.dao;

import cn.edu.springboot_jsp_shiro.entity.Role;
import cn.edu.springboot_jsp_shiro.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserDao {
    
    void save(User users);

    User findByUsername(String username);
    
    //根据用户名查询所有角色
    User findRolesByUsername(String username);
    
}

6.3 编辑UserDaoMapper

<?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="cn.edu.springboot_jsp_shiro.dao.UserDao">

    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into  t_user values(#{id},#{username},#{password},#{salt})
    </insert>

    <select id="findByUsername" parameterType="String" resultType="User">
        select id,username,password,salt from t_user
        where username=#{username}
    </select>

    <resultMap id="userMap" type="User">
        <id column="uid" property="id"></id>
        <result column="username" property="username"></result>
        <!-- 角色信息 -->
        <collection property="roles" javaType="list" ofType="Role">
            <id column="id" property="id"></id>
            <result column="rname" property="name"></result>
        </collection>
    </resultMap>
    <select id="findRolesByUsername" parameterType="String" resultMap="userMap">
        select u.id uid,u.username,r.id,r.name rname
        from t_user u
        left join t_user_role ur
        on u.id=ur.userid
        left join t_role r
        on ur.roleid=r.id
        where u.username=#{username}
    </select>

</mapper>

6.4 编辑UserService及实现类

package cn.edu.springboot_jsp_shiro.service;

import cn.edu.springboot_jsp_shiro.entity.Role;
import cn.edu.springboot_jsp_shiro.entity.User;

import java.util.List;

public interface UserService {
    //用户注册
    void register(User user);

    //根据用户名查询
    User findByUsername(String username);

    //根据用户名查询所有角色
    User findRolesByUsername(String username);

}

package cn.edu.springboot_jsp_shiro.service;

import cn.edu.springboot_jsp_shiro.dao.UserDao;
import cn.edu.springboot_jsp_shiro.entity.Role;
import cn.edu.springboot_jsp_shiro.entity.User;
import cn.edu.springboot_jsp_shiro.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public User findRolesByUsername(String username) {
        return userDao.findRolesByUsername(username);
    }

    @Override
    public void register(User user) {
        //1.生成随机盐
        String salt = SaltUtils.getSalt(8);
        //2.将随机盐保存到数据库中
        user.setSalt(salt);
        //3.明文密码 MD5 +salt +hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
        user.setPassword(md5Hash.toHex());
        userDao.save(user);
    }


}

6.5 编辑自定义realm

package cn.edu.springboot_jsp_shiro.shiro.realms;

import cn.edu.springboot_jsp_shiro.entity.Role;
import cn.edu.springboot_jsp_shiro.entity.User;
import cn.edu.springboot_jsp_shiro.service.UserService;
import cn.edu.springboot_jsp_shiro.utils.ApplicationContextUtils;
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;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

//自定义realm
public class CustomerRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("***************************");
        //根据主身份信息获取 角色 和 权限 信息
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userServiceImpl");
        User user= userService.findRolesByUsername(primaryPrincipal);
        // 授权角色信息
        if(!CollectionUtils.isEmpty(user.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("===========");
        //获取身份信息
        String principal = (String) token.getPrincipal();
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userServiceImpl");

        User user = userService.findByUsername(principal);

        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }

        return null;
    }
}

6.6 启动测试

访问:http://localhost:8888/shiro/login.jsp
xiaochen 登陆后可看到所有内容:
在这里插入图片描述
zhangsan登陆后只能看到一个:
在这里插入图片描述

7 权限信息从数据库获取实现权限控制

7.1 编辑Role实体

package cn.edu.springboot_jsp_shiro.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.List;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Role {
    private String id;
    private String name;

    //定义权限集合
    private List<Perms> perms;
}

7.2 编辑UserDao

package cn.edu.springboot_jsp_shiro.dao;

import cn.edu.springboot_jsp_shiro.entity.Perms;
import cn.edu.springboot_jsp_shiro.entity.Role;
import cn.edu.springboot_jsp_shiro.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserDao {

    void save(User users);

    User findByUsername(String username);

    //根据用户名查询所有角色
    User findRolesByUsername(String username);

    //根据角色id查询权限集合
    List<Perms> findPermsByRoleId(String id);


}

7.3 编辑UserDaoMapper

<?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="cn.edu.springboot_jsp_shiro.dao.UserDao">

    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into  t_user values(#{id},#{username},#{password},#{salt})
    </insert>

    <select id="findByUsername" parameterType="String" resultType="User">
        select id,username,password,salt from t_user
        where username=#{username}
    </select>

    <resultMap id="userMap" type="User">
        <id column="uid" property="id"></id>
        <result column="username" property="username"></result>
        <!-- 角色信息 -->
        <collection property="roles" javaType="list" ofType="Role">
            <id column="id" property="id"></id>
            <result column="rname" property="name"></result>
        </collection>
    </resultMap>
    <select id="findRolesByUsername" parameterType="String" resultMap="userMap">
        select u.id uid,u.username,r.id,r.name rname
        from t_user u
        left join t_user_role ur
        on u.id=ur.userid
        left join t_role r
        on ur.roleid=r.id
        where u.username=#{username}
    </select>

    <select id="findPermsByRoleId" parameterType="String" resultType="Perms">
        select p.id,p.name,p.url,r.name from t_role r
        left join t_role_perms rp
        on r.id=rp.roleid
        left join t_perms p
        on rp.permsid=p.id
        where r.id=#{id}
    </select>

</mapper>

7.4 编辑UserService及实现类

package cn.edu.springboot_jsp_shiro.service;

import cn.edu.springboot_jsp_shiro.entity.Perms;
import cn.edu.springboot_jsp_shiro.entity.Role;
import cn.edu.springboot_jsp_shiro.entity.User;

import java.util.List;

public interface UserService {
    //用户注册
    void register(User user);

    //根据用户名查询
    User findByUsername(String username);

    //根据用户名查询所有角色
    User findRolesByUsername(String username);

    //根据角色id查询权限集合
    List<Perms> findPermsByRoleId(String id);

}

package cn.edu.springboot_jsp_shiro.service;

import cn.edu.springboot_jsp_shiro.dao.UserDao;
import cn.edu.springboot_jsp_shiro.entity.Perms;
import cn.edu.springboot_jsp_shiro.entity.Role;
import cn.edu.springboot_jsp_shiro.entity.User;
import cn.edu.springboot_jsp_shiro.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public User findRolesByUsername(String username) {
        return userDao.findRolesByUsername(username);
    }

    @Override
    public List<Perms> findPermsByRoleId(String id) {
        return userDao.findPermsByRoleId(id);
    }

    @Override
    public void register(User user) {
        //1.生成随机盐
        String salt = SaltUtils.getSalt(8);
        //2.将随机盐保存到数据库中
        user.setSalt(salt);
        //3.明文密码 MD5 +salt +hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
        user.setPassword(md5Hash.toHex());
        userDao.save(user);
    }


}

7.5 编辑自定义realm

package cn.edu.springboot_jsp_shiro.shiro.realms;

import cn.edu.springboot_jsp_shiro.entity.Perms;
import cn.edu.springboot_jsp_shiro.entity.Role;
import cn.edu.springboot_jsp_shiro.entity.User;
import cn.edu.springboot_jsp_shiro.service.UserService;
import cn.edu.springboot_jsp_shiro.utils.ApplicationContextUtils;
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;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

//自定义realm
public class CustomerRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("***************************");
        //根据主身份信息获取 角色 和 权限 信息
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userServiceImpl");
        User user= userService.findRolesByUsername(primaryPrincipal);
        // 授权角色信息
        if(!CollectionUtils.isEmpty(user.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
                //权限信息
                List<Perms> perms = userService.findPermsByRoleId(role.getId());
                if(!CollectionUtils.isEmpty(perms)){
                    perms.forEach(perm -> {
                        simpleAuthorizationInfo.addStringPermission(perm.getName());
                    });
                }
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }
}

7.6

访问 http://localhost:8888/shiro/login.jsp
以xiaochen身份登录可查看所有:
在这里插入图片描述
以zhangsan身份登陆,只能看到用户的:
在这里插入图片描述

  • 修改index.jsp的查询权限:
    在这里插入图片描述
    此时,zhangsan就看不到 查询 这一项了
    在这里插入图片描述
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值