springboot整合shiro

预览地址:https://www.ixigua.com/7026306880414679588?logTag=f7052a9353889cecc2d9
gitee:https://gitee.com/caohanzong/springboot-shiro

文章目录

1、环境搭建

1、新建一个springboot项目,勾选Spring Web和Thymeleaf依赖

<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>
        </dependency>

2、测试环境是否正常

  1. 新建一个controller页面
@Controller
public class MyController {

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

  1. 新建一个index.html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>

<h1>首页</h1>
<p th:text="${msg}"></p>
<hr>

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

</body>
</html>
  1. 新建一个add.html页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>add</h1>

</body>
</html>
  1. 新建一个update.html页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>update</h1>

</body>
</html>
  1. 项目结构
    springboot整合shiro

  2. 运行截图
    springboot整合shiro
    3、导入shiro整合spring的包

<!--
        Subject 用户
        SecurityManager 管理所有用户
        Realm 连接数据
        -->

        <!--shiro整合spring包-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.5.3</version>
        </dependency>

4、编写导入配置类

  1. 编写一个自定义类UserRealm
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
        return null;
    }
}
  1. 编写配置ShiroConfig
    1、创建realm对象,需要自定义类
    2、DefaultWebSecurityManager
    3、ShiroFilterFactoryBean
@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean : 3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaulWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        return bean;
    }

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

        return securityManager;
    }

    //创建realm对象,需要自定义类 : 1
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

2、Shiro实现登录拦截

  • ShiroConfig中的getShiroFilterFactoryBean方法中添加如下配置:
//添加shiro的内置过滤器
        /*
        * anon: 无需认证,就可以访问
        * authc: 必须认证了,才能访问
        * user: 必须拥有‘记住我’功能,才能访问
        * perms: 拥有对某个资源的权限,才能访问
        * role: 拥有某个角色权限,才能访问
        * */
    Map<String, String> filterMap = new LinkedHashMap<>();
	filterMap.put("/user/add","authc");
	filterMap.put("/user/update","authc");
	bean.setFilterChainDefinitionMap(filterMap);

  • 再点击首页的add或者update之后,
    springboot整合shiro
    这是拦截之后的系统默认页面,我们要把这个页面显示一些内容
  • 添加拦截成功页面
    • 登录页面login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<h1>登录</h1>
<hr>

<form action="">
    <p>用户名:<input type="text" name="username"></p>
    <p>密码:<input type="text" name="password"></p>
    <p>密码:<input type="submit"></p>
</form>
</body>
</html>

  • 在MyController中添加toLogin
@RequestMapping("/toLogin")
public String toLogin() {
    return "login";
}

  • ShiroConfig中的getShiroFilterFactoryBean方法中添加如下配置
//设置登录的请求,(如果没有登录,点击了有权限的访问)
bean.setLoginUrl("/toLogin");
  • 拦截成功页面
    springboot整合shiro

3、Shiro实现用户认证

  1. MyController中编写用户提交表单之后处理
@RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //执行登录的方法,如果没有异常就ok
        //subject.login(token);
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {   //用户名错误
            model.addAttribute("msg","用户名错误");
            return "login";
        } catch (IncorrectCredentialsException e){  //密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
    
  1. login.html的修改
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>登录</h1>
<hr>
<p th:text="${msg}" style="color: red;"></p>

<form th:action="@{/login}">
  <p>用户名:<input type="text" name="username"></p>
  <p>密码:<input type="text" name="password"></p>
  <p><input type="submit"></p>
</form>

</body>
</html>

  1. 用户输入登录信息
    页面:
    springboot整合shiro
    控制台:
    springboot整合shiro

  2. 用户认证编写UserRealm中的认证(doGetAuthenticationInfo)

//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    System.out.println("执行了=>认证doGetAuthorizationInfo");
    // 用户名、密码, 数据中取
    String name = "root";
    String password = "123456";

    UsernamePasswordToken userToken = (UsernamePasswordToken) token;

    if (!userToken.getUsername().equals(name)) {
        return null;//抛出异常 UnknownAccountException
    }

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

4、Shiro整合Mybatis

1、导入依赖:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>

<!--引入mybatis,这是MyBatis官方提供的适配spring Boot的,而不是spring Boot自己的-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

2、配置文件application.yml的编写

spring:
  datasource:
    username: root
    password: 123456
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/mybatis?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:
  type-aliases-package: com.chz.pojo
  mapper-locations: classpath:mapper/*.xml

springboot整合shiro
3、User类的编写

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private String perms;
}

4、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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.chz.mapper.UserMapper">

    <select id="queryUserByName" parameterType="String" resultType="User">
        select * from mybatis.user where name=#{name}
    </select>

</mapper>

5、UserService接口实现

public interface UserService {
    public User queryUserByName(String name);
}

6、UserServiceImpl业务逻辑

@Service
public class UserServiceImpl implements  UserService{
    @Autowired
    UserMapper userMapper;

    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

7、UserRealm连接真实数据库 (config-UserRealm)

//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
        UsernamePasswordToken userToken= (UsernamePasswordToken) token;
        //用户名,密码 ————数据库中取,连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());
        //没有这个人
        if(user==null){
            //UnknownAccountException
            return null;
        }
        //密码认证,shiro做
        //可以加密:MD5,MD5演唱、盐值加密
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
    

5、Shiro实现用户授权

1、ShiroConfig中的getShiroFilterFactoryBean方法添加认证代码

//授权,正常情况下,未授权会跳转到未授权页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");

2、登录之后点击add按钮会弹出如下页面
springboot整合shiro
3、添加为授权页面

  1. MyController
@RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面";
    }
  1. ShiroConfig中的getShiroFilterFactoryBean方法中添加
//未授权页面
bean.setUnauthorizedUrl("/noauth");
  1. 再次测试
    springboot整合shiro
    所以需要在UserRealm中为用户进行真正授权

4、UserRealm类的修改

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        //拿到user对象
        User currentUser = (User) subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
        UsernamePasswordToken userToken= (UsernamePasswordToken) token;
        //用户名,密码 ————数据库中取,连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());
        //没有这个人
        if(user==null){
            //UnknownAccountException
            return null;
        }
        //密码认证,shiro做
        //可以加密:MD5,MD5演唱、盐值加密
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}

5、再次测试
springboot整合shiro

6、Shiro整合Thymeleaf

1、shiro-thymeleaf整合包导入

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

2、在ShiroConfig中整合ShiroDialect

// 整合ShiroDialect: 用来整合 Shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect() {
    return new ShiroDialect();
}

3、index.html页面

<!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>
</head>
<body>

<h1>首页</h1>
<div shiro:notAuthenticated>
    <a th:href="@{/toLogin}">登录</a>
</div>
<div shiro:Authenticated>
    <a th:href="@{/logout}">注销</a>
</div>
<p th:text="${msg}"></p>
<hr>

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

</body>
</html>

4、页面显示
springboot整合shiro
没有add,只有update

所有代码

springboot整合shiro

ShiroConfig

package com.chz.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean : 3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaulWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro的内置过滤器
        /*
        * anon: 无需认证,就可以访问
        * authc: 必须认证了,才能访问
        * user: 必须拥有‘记住我’功能,才能访问
        * perms: 拥有对某个资源的权限,才能访问
        * role: 拥有某个角色权限,才能访问
        * */

        //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();
        //user下的add、update,authc
        //filterMap.put("/user/add","authc");
        //filterMap.put("/user/update","authc");

        //授权,正常情况下,未授权会跳转到未授权页面
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");

        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求,(如果没有登录,点击了有权限的访问)
        bean.setLoginUrl("/toLogin");
        //未授权页面
        bean.setUnauthorizedUrl("/noauth");

        return bean;
    }

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

        return securityManager;

    }

    //创建realm对象,需要自定义类 : 1
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //整合ShiroDialect: 用来整合 shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

UserRealm

package com.chz.config;

import com.chz.pojo.User;
import com.chz.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.Authenticator;

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        //拿到user对象
        User currentUser = (User) subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
        UsernamePasswordToken userToken= (UsernamePasswordToken) token;
        //用户名,密码 ————数据库中取,连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());
        //没有这个人
        if(user==null){
            //UnknownAccountException
            return null;
        }
        //密码认证,shiro做
        //可以加密:MD5,MD5演唱、盐值加密
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}

MyController

package com.chz.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
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.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.lang.model.element.NestingKind;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class MyController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,Shiro!");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }

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

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //执行登录的方法,如果没有异常就ok
        //subject.login(token);
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {   //用户名错误
            model.addAttribute("msg","用户名错误");
            return "login";
        } catch (IncorrectCredentialsException e){  //密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }

}

index.html

<!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>
</head>
<body>

<h1>首页</h1>
<div shiro:notAuthenticated>
    <a th:href="@{/toLogin}">登录</a>
</div>
<div shiro:Authenticated>
    <a th:href="@{/logout}">注销</a>
</div>
<p th:text="${msg}"></p>
<hr>

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


</body>
</html>

login.html

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

<h1>登录</h1>
<hr>
<p th:text="${msg}" style="color: red;"></p>

<form th:action="@{/login}">
  <p>用户名:<input type="text" name="username"></p>
  <p>密码:<input type="text" name="password"></p>
  <p><input type="submit"></p>
</form>

</body>
</html>
上一篇:03-shiro中的认证


下一篇:Vue最全面试梳理(二)