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

news2024/10/5 8:37:10

序言

大家好,我是老马。

前面我们学习了 web 安全之 Spring Security 入门教程

这次我们来一起学习下另一款 java 安全框架 shiro。

什么是Apache Shiro?

Apache Shiro是一个功能强大且易于使用的Java安全框架,它为开发人员提供了一种直观而全面的解决方案,用于身份验证,授权,加密和会话管理。

实际上,它可以管理应用程序安全性的所有方面,同时尽可能避免干扰。它建立在可靠的界面驱动设计和OO原则的基础上,可在您可以想象的任何地方实现自定义行为。

但是,只要对所有内容都使用合理的默认值,就可以像应用程序安全性一样“轻松”。至少这就是我们所追求的。

Apache Shiro可以做什么?

很多,但是我们不想夸大快速入门。

如果您想了解其功能,请查看我们的功能页面。另外,如果您对我们的起步方式以及我们为什么存在感到好奇,请参阅Shiro历史和任务页面。

好。现在让我们实际做些事情!

Shiro可以在任何环境中运行,从最简单的命令行应用程序到最大的企业Web和集群应用程序,但是对于此QuickStart,我们将在简单的main方法中使用最简单的示例,以便您对 API 有点感觉。

快速开始

官方的例子是让下载源文件,老马是直接从 github 下载的 mater 源码。

我们把核心的地方直接贴出来即可。

maven 依赖

最基础的 shiro 演示,只需要引入下面的依赖即可。

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.2.2</version>
</dependency>

入门例子

内容看起来很多,主要是因为有很多注释,实际上还是比较简单的。

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

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        SecurityUtils.setSecurityManager(securityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        // let's login the current user so we can check against roles and permissions:
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }

        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:wield")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //a (very powerful) Instance Level permission:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //all done - log out!
        currentUser.logout();

        System.exit(0);
    }
}

代码分析

下面我们针对这段代码做一下简单的分析。

构建安全管理器

核心代码如下:

Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();

实际上就是通过 shiro.ini 文件中的配置,来创建一个 SecurityManager 实例。

然后通过 SecurityUtils.setSecurityManager(securityManager); 设置对应的安全管理器。

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

当前主题

主题是一个相对更大的概念,我们也可以简单的理解为当前用户。

Subject currentUser = SecurityUtils.getSubject();

这个工具方法,实际上是通过 ThreadLocal 维护了当前的用户信息,如果不存在,会创建默认的主题信息。

当获取到当前用户之后,我们就可以进行相关的操作了。

session 操作

写过 web 的同学对 HttpSession 肯定非常熟悉。

shiro 设计非常巧妙的一点,就是有一套独立的 session API,让 session 的管理脱离 web 也可以使用,这是非常棒的设计。

Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
    log.info("Retrieved the correct value! [" + value + "]");
}

我们设置对应的值,并且取出来进行判断。

此时日志也会输出:

2020-12-27 18:59:47,288 INFO [Quickstart] - Retrieved the correct value! [aValue]

用户登录

我们在设计 web 应用的时候,最关心的肯定还是用户的角色权限等信息。

我们前面的 currentUser 就代表这当前的用户,当然默认用户实际上是匿名的。

需要我们进行一次登录:

if (!currentUser.isAuthenticated()) {
    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
    token.setRememberMe(true);
    try {
        currentUser.login(token);
    } catch (UnknownAccountException uae) {
        // 省略后续的各种异常
    }
}

这个登录的账户密码,是前面我们配置在 shiro.ini 文件中的:

# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

当然,这里的 shiro 提供的异常是非常详细的,这可以方便我们更好的定位问题。

但是当用户登录的时候,我们提示应该避免这么详细,为什么呢?

主要是避免有用户恶意撞库,提示一般都是【用户名或者密码错误】。不让恶意用户知道对应的用户名信息。

登录成功之后,可以输出对应的用户名信息:

log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

对应的日志如下:

2020-12-27 18:59:47,289 INFO [Quickstart] - User [lonestarr] logged in successfully. 

权限校验

用户成功登陆之后,我们就可以获取到用户 lonestarr 对应的角色 goodguy 和 schwartz。

这样,就可以判断当前用户是否有具体的权限,比如菜单权限,操作权限等。这也是我们一般最常用的功能。

测试角色

测试当前用户是否拥有指定的角色:

if (currentUser.hasRole("schwartz")) {
    log.info("May the Schwartz be with you!");
} else {
    log.info("Hello, mere mortal.");
}

日志如下:

2020-12-27 18:59:47,290 INFO [Quickstart] - May the Schwartz be with you!

测试权限

测试当前用户是否拥有指定的权限:

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.");
}

我们在 shiro.ini 中配置了对应的操作权限:

# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*

所以可以针对 lightsaber 为所欲为~

日志如下:

2020-12-27 18:59:47,290 INFO [Quickstart] - You may use a lightsaber ring.  Use it wisely.

另外一个方法也是类似的,此处不再赘述。

用户登出

当我们全部操作完成以后,可以执行用户的登出操作。

//all done - log out!
currentUser.logout();

小结

shiro 设计的非常简洁,功能也非常的强大,可以满足我们大部分权限开发功能。

个人感觉这个框架肯定是有多年登录经验的大佬设计的,api 和背后的理念非常值得学习。

当然这里作为入门的例子,整体比较简单。我们日常开发一般都是使用数据库进行账户信息持久化,密码也会进行对应的加密处理。

这些 shiro 都已经考虑到了,我们后续会进行讲解。

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

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

参考资料

10 Minute Tutorial on Apache Shiro

在这里插入图片描述

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

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

相关文章

【深度学习笔记】深度学习训练技巧——处理过拟合

处理过拟合 过拟合 定义&#xff1a;对训练集拟合得很好&#xff0c;但在验证集表现较差 神经网络 通常含有大量参数 (数百万甚至数十亿), 容易过拟合 处理策略&#xff1a;参数正则化、早停、随机失活、数据增强 早停 当发现训练损失逐渐下降&#xff0c;但验证集损失逐渐…

【项目管理】CMMI-项目监督和控制

项目监督和控制&#xff08;Monitoring and Control, MC&#xff09;的目的是通过周期性地跟踪项目计划的各种性能参数如工作产品的规模、工作量、成本、进度、风险等&#xff0c;不断地了解项目的进展情况&#xff0c;以便当项目实际进展状况显著偏离项目计划时能够及时采取纠…

Apache Flink连载(二十八):Flink细粒度资源管理(1)-适用场景和原理

🏡 个人主页:IT贫道-CSDN博客 🚩 私聊博主:私聊博主加WX好友,获取更多资料哦~ 🔔 博主个人B栈地址:豹哥教你学编程的个人空间-豹哥教你学编程个人主页-哔哩哔哩视频 目录

Hack The Box-Office

端口扫描&信息收集 使用nmap对靶机进行扫描 nmap -sC -sV 10.10.11.3开放了80端口&#xff0c;并且注意到该ip对应的域名为office.htb&#xff0c;将其加入到hosts文件中访问之 注意到扫描出来的还有robots文件&#xff0c;经过尝试后只有administrator界面是可以访问的 …

程序员的自我修养笔记

导读 本书将详细描述现在流行的Windows和Linux操作系统下各自的可执行文件、 目标文件格式&#xff1b; 普通C/C程序代码如何被编译成目标文件及程序在目标文件中如何存储&#xff1b; 目标文件如何被链接器链接到一起&#xff0c; 并且形成可执行文件&#xff1b; 目标文件在…

大白话说说redux

redux的3个重要概念 store 就是用来存放应用的各种状态的action 就是用来描述应用发生了什么动作的&#xff0c;注意理解他是对动作的描述reducer 就是用来处理应用的动作&#xff0c;并且决定怎么去更新应用存放在store里面的状态。 redux的3个原则 应用的所有状态存储为re…

消息中间件之RocketMQ源码分析(十)

Namesrv启动流程 第一步:脚本和启动参数配置。 启动命令 nohup ./bin/mqnamesrv -c ./conf/namesrv.conf > dev/null 2>&1 & 通过脚本配置启动基本参数&#xff0c;比如配置文件路径、JVM参数&#xff0c;调用NamesrvStartup.main()方法&#xff0c;解析命令行的…

Vue24 收集表单数据 实例

实例 <!DOCTYPE html> <html><head><meta charset"UTF-8" /><title>收集表单数据</title><script type"text/javascript" src"../js/vue.js"></script></head><body><!-- 收集…

Spring Security基础学习

一、SpringSecurity框架简介 二、SpringSecurity入门案例 三、SpringSecurity Web权限方案 四、SpringSecurity微服务权限方案 五、SpringSecurity原理总结

Eclipse - Expressions Add Watch Expression

Eclipse - Expressions & Add Watch Expression References Window -> Show View -> Other… Show View -> Debug -> Expressions -> Open Debug 模式下出现 Expressions 窗口 Debug 模式下&#xff0c;如果需要查看指定变量或者返回函数的值&#xff0c;直…

千分位分隔?一个vue指令搞定

说在前面 &#x1f388;对数字进行千分位分隔后展示应该是大部分同学都做过的功能了吧&#xff0c;常规的做法通常是编写一个工具函数来对数据进行转换&#xff0c;那么我们可不可以通过vue指令来实现这一功能呢&#xff1f; 效果展示 实现原理 非输入框 非输入框我们只需要对…

力扣题目训练(16)

2024年2月9日力扣题目训练 2024年2月9日力扣题目训练530. 二叉搜索树的最小绝对差541. 反转字符串 II543. 二叉树的直径238. 除自身以外数组的乘积240. 搜索二维矩阵 II124. 二叉树中的最大路径和 2024年2月9日力扣题目训练 2024年2月9日第十六天编程训练&#xff0c;今天主要…

【白嫖8k买的机构vip教程】python(2):python_re模块

python之re模块 一、正则表达式   re模块是python独有的匹配字符串的模块&#xff0c;该模块中提供的很多功能是基于正则表达式实现的&#xff0c;而正则表达式是对字符串进行模糊匹配&#xff0c;提取自己需要的字符串部分&#xff0c;他对所有的语言都通用。注意&#xf…

程序员必看的几部电影

目录 《我是谁&#xff1a;没有绝对安全的系统》 《模仿游戏》 《硅谷传奇》 《代码 The Code》 作为程序员&#xff0c;除了在工作中不断学习和提升技术外&#xff0c;适当地放松也是必不可少的 看电影可以是一个很好的放松方式&#xff0c;而对于程序员来说&#xff0c;…

GO框架基础 (一)、MySQL数据库

什么是数据库 数据库是一个组织化的数据集合&#xff0c;它被设计为方便存储、管理和检索数据。数据库通常以表格的形式组织数据&#xff0c;其中每一行代表一个数据记录&#xff0c;每一列代表一个数据字段。数据库系统提供了一种结构化的方法来存储和管理数据&#xff0c;以…

Android 基础技术——Binder 机制

笔者希望做一个系列&#xff0c;整理 Android 基础技术&#xff0c;本章是关于Binder 机制 什么是Binder 机制&#xff1a;Binder 是一种进程间通信机制 驱动&#xff1a;Binder 是一个虚拟物理设备驱动 应用层&#xff1a;Binder 是一个能发起通信的 Java 类 为什么要使用Bind…

Springboot返回给前端的日期变成时间戳问题处理

问题&#xff1a; 解决方案 在对应的Entity类中&#xff0c;给对应属性添加JsonFormat​注解 ​JsonFormat​注解用于将Date日期格式化为指定格式的字符串。由于在序列化时间时是按照国际标准时间GMT进行格式化的&#xff0c;最后接受到的数据会早8个小时&#xff0c;所以应该…

力扣 188. 买卖股票的最佳时机 IV

题目来源&#xff1a;https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/description/ C题解&#xff1a;动态规划 思路同力扣 123. 买卖股票的最佳时机 III-CSDN博客&#xff0c;只是把最高2次换成k次。如果思路不清晰&#xff0c;可以将k从0写到4等找找规律…

FPGA转行ISP的探索之一:行业概览

ISP的行业位置 最近看到一个分析&#xff0c;说FPGA的从业者将来转向ISP&#xff08;Image Signal Process图像信号处理&#xff09;是个不错的选择&#xff0c;可以适应智能汽车、AI等领域。故而我查了一下ISP&#xff0c;对它大致有个概念。 传统的ISP对应的是相机公司&…

phaseDNN文章解读

文章DOI: https://doi.org/10.48550/arXiv.1905.01389 作者是 Southern Methodist University 的Wei Cai 教授 A Parallel Phase Shift Deep Neural Network for Adaptive Wideband Learning 一种并行移相深度神经网络来自适应学习宽带频率信号 20190514 核心思想&#xff1a;…