shiro 整合 springboot 实战

news2024/9/22 22:35:27

序言

前面我们学习了如下内容:

5 分钟入门 shiro 安全框架实战笔记

shiro 整合 spring 实战及源码详解

这一节我们来看下如何将 shiro 与 springboot 进行整合。

spring 整合

maven 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>shiro-inaction-01-springboot</artifactId>
    <description>springboot web 整合</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-web-starter</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

这里主要是 spring-boot-starter-web 和 shiro-spring-boot-web-starter。

我们这里为了演示页面,所以引入了 spring-boot-starter-thymeleaf

application.properties 配置文件

配置文件内容如下:

# 指定服务信息
server.port=7777

# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.content-type=text/html
# spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false

# shiro 相关配置
# 登录地址
shiro.loginUrl = /login.html
# Let Shiro Manage the sessions
shiro.userNativeSessionManager = true
# disable URL session rewriting
shiro.sessionManager.sessionIdUrlRewritingEnabled = false

页面都放在 classpath:/templates/ 目录下,此处不做展开。

可以参见源码:

https://gitee.com/houbinbin/shiro-inaction/tree/master/shiro-inaction-01-springboot

启动类

启动类代码比较简单:

@SpringBootApplication
public class Application { //NOPMD

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

ShiroConfig.java

针对 shiro 的配置内容如下:

package com.github.houbb.shiro.inaction.chap01.springboot.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.TextConfigurationRealm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseStatus;

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

/**
 * @author binbin.hou
 * @since 1.0.0
 */
@Configuration
@ControllerAdvice
public class ShiroConfig {

    @ExceptionHandler(AuthorizationException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public String handleException(AuthorizationException e, Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", HttpStatus.FORBIDDEN.value());
        map.put("message", "No message available");
        model.addAttribute("errors", map);

        return "error";
    }

    @Bean
    public Realm realm() {
        TextConfigurationRealm realm = new TextConfigurationRealm();
        realm.setUserDefinitions("joe.coder=password,user\n" +
                "jill.coder=password,admin");

        realm.setRoleDefinitions("admin=read,write\n" +
                "user=read");
        realm.setCachingEnabled(true);
        return realm;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/login.html", "authc"); // need to accept POSTs from the login form
        chainDefinition.addPathDefinition("/logout", "logout");
        return chainDefinition;
    }

    @ModelAttribute(name = "subject")
    public Subject subject() {
        return SecurityUtils.getSubject();
    }

}

这里主要初始化了一些默认的 Realm 信息,并且指定了对应的过滤器。

这里统一使用了一场处理器处理异常,以便为用户提供更好的体验。

package com.github.houbb.shiro.inaction.chap01.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 */
@Controller
public class RestrictedErrorController implements ErrorController {
    private static final String ERROR_PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    @RequestMapping(ERROR_PATH)
    String error(HttpServletRequest request, Model model) {
        Map<String, Object> errorMap = errorAttributes.getErrorAttributes(new ServletWebRequest(request), false);
        model.addAttribute("errors", errorMap);
        return "error";
    }
}

其他 Controller

我们主要看一下登录和账户信息:

登录

这个直接返回登录页面。

@Controller
public class LoginController {

    @RequestMapping("/login.html")
    public String loginTemplate() {
        return "login";
    }

}

账户信息

这个通过 @RequiresRoles("admin"),要求访问者拥有对应的 admin 角色。

@Controller
public class AccountInfoController {

    @RequiresRoles("admin")
    @RequestMapping("/account-info")
    public String home(Model model) {

        String name = "World";

        Subject subject = SecurityUtils.getSubject();

        PrincipalCollection principalCollection = subject.getPrincipals();

        if (principalCollection != null && !principalCollection.isEmpty()) {
            name = principalCollection.getPrimaryPrincipal().toString();
        }

        model.addAttribute("name", name);
        return "account-info";
    }

}

页面访问

直接访问 http://localhost:7777/login.html,页面如下:

输入图片说明

我们可以分别登录两个不同的账户,访问对应的用户信息。

会发现只有 admin 账户可以访问。

小结

这一节我们讲解了如何整合 springboot 与 shiro,可以发现使用起来非常的便捷。

后续准备自己动手实现一个简易版本的 shiro。

为了便于大家学习,所有源码都已开源:

https://gitee.com/houbinbin/shiro-inaction/tree/master/shiro-inaction-01-springboot

希望本文对你有所帮助,如果喜欢,欢迎点赞收藏转发一波。

我是老马,期待与你的下次相遇。

参考资料

10 Minute Tutorial on Apache Shiro

https://shiro.apache.org/reference.html

https://shiro.apache.org/session-management.html

本文由博客一文多发平台 OpenWrite 发布!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1464047.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

思考:如何写出让同事难以维护的代码?

本文从【程序命名&注释】【数据类型&类&对象】【控制执行流程】和【程序/结构设计】四个方面梳理了一些真实案例&#xff0c;相信通过这些案例你能迅速get技能&#xff1a;如何写出让同事难以维护的代码doge。 比起什么程序员删库跑路&#xff0c;我更喜欢「写出让…

2024最佳住宅代理IP服务商有哪些?

跨境出海已成为了近几年的最热趋势&#xff0c;大批量的企业开始开拓海外市场&#xff0c;而海外电商领域则是最受欢迎的切入口。新兴的tiktok、Temu&#xff0c;老牌的Amazon、Ebay&#xff0c;热门的Etsy、Mecari等等都是蓝海一片。跨境入门并不难&#xff0c;前期的准备中不…

压缩感知常用的重建算法

重建算法的基本概念 在压缩感知&#xff08;Compressed Sensing, CS&#xff09;框架中&#xff0c;重建算法是指将从原始信号中以低于奈奎斯特率采集得到的压缩测量值恢复成完整信号的数学和计算过程。由于信号在采集过程中被压缩&#xff0c;因此重建算法的目标是找到最符合…

施华洛世奇 Swarovski EDI需求分析

施华洛世奇为全球首屈一指的光学器材及精确切割仿水晶制造商&#xff0c;为时尚服饰、首饰、灯饰、建筑及室内设计提供仿水晶元素。施华洛世奇有两个主要业务&#xff0c;分别负责制造及销售仿水晶元素&#xff0c;以及设计制造成品。 EDI传输协议 施华洛世奇 Swarovski 与合作…

《租车 App:畅享自由出行的新选择》

在现代社会&#xff0c;人们对于出行的需求越来越多样化。为了满足这些需求&#xff0c;租车行业应运而生。而随着智能手机的普及&#xff0c;租车 App 的开发成为了提升用户体验、提高租车效率的重要途径。 一、市场需求与发展趋势 随着人们生活水平的提高和出行观念的变化&am…

一文吃透计算机网络面试八股文

面试网站&#xff1a;topjavaer.cn 目录&#xff1a; 网络分层结构三次握手两次握手可以吗&#xff1f;四次挥手第四次挥手为什么要等待2MSL&#xff1f;为什么是四次挥手&#xff1f;TCP有哪些特点&#xff1f;说说TCP报文首部有哪些字段&#xff0c;其作用又分别是什么&…

DataGrip安装

文章目录 数据库dataGrip安装手册1. 解压2. 运行2.1 创建桌面快捷方式2.2 运行dataGrip 3. 优化4. 配置4.1 配置主题颜色4.2 连接MySQL4.3 展示所有数据库 数据库 dataGrip安装手册 1. 解压 &#xff0c;解压出来的目录如下&#xff1a; 2. 运行 2.1 创建桌面快捷方式 进入…

基于springboot+vue的智能推荐的卫生健康系统(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、阿里云专家博主、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战&#xff0c;欢迎高校老师\讲师\同行交流合作 ​主要内容&#xff1a;毕业设计(Javaweb项目|小程序|Pyt…

SpringBoot集成Mqtt发送消息

1. MQTT简介 MQTT是一种物联网消息协议&#xff0c;为Message Queuing Telemetry Transport的缩写&#xff0c;即消息队列传输探测&#xff0c;协议基于发布订阅模式进行通信&#xff0c;有开销低、带宽小、轻量的特点&#xff0c;通常应用在物联网数据采集、移动应用、智能硬…

程序员必备技能----删库跑路大总结

删库跑路大总结&#xff0c;各个都是大杀器&#xff0c;破坏性太大&#xff0c;轻易不要尝试。 删除linux根目录&#xff0c;用户目录&#xff0c;其实还可以增加一个删除/etc。删除&#xff08;清除&#xff09;数据库。删除redis缓存和持久化文件。删除mongodb库。git push …

大蟒蛇(Python)笔记(总结,摘要,概括)——第9章 类

目录 9.1 创建和使用类 9.1.1 创建Dog类 9.1.2 根据类创建实例 9.2 使用类和实例 9.2.1 Car类 9.2.2 给属性指定默认值 9.2.3 修改属性的值 9.3 继承 9.3.1 子类的_init_()方法 9.3.2 给子类定义属性和方法 9.3.3 重写父类中的方法 9.3.4 将实例用作属性 9.3.5 模拟实物 9.…

JavaWeb——003Axios Vue组件库(Element)

目录 一、Ajax 1、同步与异步​编辑 2、原生Ajax&#xff08;繁琐&#xff09;​编辑 2.1、写一个简易的Ajax 3、Axios&#xff08;推荐使用&#xff09;​编辑 3.1、Axios入门 3.2、Axios请求方式别名 3.3、案例&#xff1a;基于Vue及Axios完成数据的动态加载展示​编…

HarmonyOS—使用预览器查看应用/服务效果

DevEco Studio为开发者提供了UI界面预览功能&#xff0c;可以查看应用/服务的UI界面效果&#xff0c;方便开发者随时调整界面UI布局。预览器支持布局代码的实时预览&#xff0c;只需要将开发的源代码进行保存&#xff0c;就可以通过预览器实时查看应用/服务运行效果&#xff0c…

六、回归与聚类算法 - 逻辑回归与二分类

线性回归欠拟合与过拟合线性回归的改进 - 岭回归分类算法&#xff1a;逻辑回归模型保存与加载无监督学习&#xff1a;K-means算法 1、应用场景 2、原理 2.1 输入 2.2 激活函数 3、损失以及优化 3.1 损失 3.2 优化 4、逻辑回归API 5、分类的评估方法 5.1 精确率和召回率 5.2…

滚雪球学Java(68):全面了解Java中常用的集合类:LinkedHashMap的应用与实践

咦咦咦&#xff0c;各位小可爱&#xff0c;我是你们的好伙伴——bug菌&#xff0c;今天又来给大家普及Java SE相关知识点了&#xff0c;别躲起来啊&#xff0c;听我讲干货还不快点赞&#xff0c;赞多了我就有动力讲得更嗨啦&#xff01;所以呀&#xff0c;养成先点赞后阅读的好…

操作系统虚拟内存(下)

操作系统虚拟内存&#xff08;上&#xff09;-CSDN博客 TLB 多级页表虽然解决了空间上的问题&#xff0c;但是虚拟地址到物理地址的转换就多了几道转换的工序&#xff0c;这显然就降低了这俩地址转换的速度&#xff0c;也就是带来了时间上的开销。 程序是有局部性的&#xff…

使用备份工具xtrabackup完成数据库的备份与恢复

安装备份工具xtrabackup 简介 它是开源免费的支持MySQL 数据库热备份的软件&#xff0c;它能对InnoDB和XtraDB存储引擎的数据库非阻塞地备份。它不暂停服务创建Innodb热备份&#xff1b; 为mysql做增量备份&#xff1b;在mysql服务器之间做在线表迁移&#xff1b;使创建replica…

跟着pink老师前端入门教程(JavaScript)-day05

六、语句 &#xff08;一&#xff09;表达式和语句 1、表达式 表达式是可以被求值的代码&#xff0c;JavaScript 引擎会将其计算出一个结果。 2、语句 语句是一段可以执行的代码。 比如&#xff1a; prompt() 可以弹出一个输入框&#xff0c;还有 if语句 for 循环语句等…

华为OD机试真题-用连续自然数之和来表达整数-2023年OD统一考试(C卷)---python代码免费

题目&#xff1a; 代码 """ 题目分析&#xff1a; 一个整数 连续的自然数之和表示(非负整数&#xff09;输入&#xff1a; 一个整数T[1,1000] 输出&#xff1a; 输出多个表达式&#xff0c;自然数个数最少优先输出 最后一行&#xff0c; 输出“Result : 个数…

【监督学习之线性回归】

曾梦想执剑走天涯&#xff0c;我是程序猿【AK】 目录 简述概要知识图谱 简述概要 了解什么是线性回归 知识图谱 监督学习中的线性回归是一种预测模型&#xff0c;它试图通过拟合一个线性方程来建立输入变量&#xff08;特征&#xff09;和输出变量&#xff08;目标值&#x…