Shiro学习笔记,一篇就够用了

news2024/10/6 12:32:32

目录

 一、Shiro基础

 1.1Shiro定义:

1.2Shiro架构:

1.3快速上手:

二、Spring整合Shiro

2.1导入spring整合shiro的依赖

2.2两个配置类


寻找maven版本号:Maven Repository: org.apache.shiro » shiro-core (mvnrepository.com)

 Shiro官网:Apache Shiro | Simple. Java. Security.

 一、Shiro基础

1.1Shiro定义:

Apache Shiro™ 是一个功能强大且易于使用的 Java 安全框架,用于执行身份验证, 授权、加密和会话管理。使用四郎易于理解的API,您可以 快速轻松地保护任何应用程序 - 从最小的移动应用程序到最大的 Web 和企业应用程序。

1.2Shiro架构:

1.3快速上手:

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */


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 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()) {
            //Token:令牌,没有获取,随机
            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);
    }
}

下面我给出几个shiro的核心代码

1.获取当前的用户 

Subject currentUser = SecurityUtils.getSubject();


2.shiro拥有自己独立的session

Session session = currentUser.getSession();


3.判断当前用户是否被认证

currentUser.isAuthenticated()


4.获得当前用户的认证

currentUser.getPrincipal()


5.判断当前用户是否有对应的角色

currentUser.hasRole("schwartz")


6.获得当前用户的权限,根据参数的不同产生不同的效果

currentUser.isPermitted()


7.注销

currentUser.logout();


8.记住我功能

token.setRememberMe(true);

二、Springboot整合Shiro

2.1导入spring整合shiro的依赖

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

2.2两个配置类

第一个为ShiroConfig类,需要注入三个bean,注意,这三个bean逻辑上有严格的层级关系

package com.example.springbshiro.demos.config;

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.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro 的内置过滤器
        /*
        anon:无需认证就可以访问
        authc:必须认证才能访问
        user:必须拥有记住我功能才能用
        perms:拥有对某个资源的权限才能访问
        role:拥有某个角色权限才能访问
         */
        //拦截
        Map<String,String> filternMap = new LinkedHashMap<>();

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

        //设置访问权限
        filternMap.put("/user/add","authc");
        filternMap.put("/user/update","authc");
        //支持通配符
        filternMap.put("/user/*","authc");

        bean.setFilterChainDefinitionMap(filternMap);

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

        return bean;
    }

    //DafaulWebSecurityManager
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象,需要自定义类
    @Bean(name = "userRealm")  //不写name的话,默认是方法名
    public UserRealm userRealm(){
        return new UserRealm();
    }

}

第二个配置类是实现UserRealm,通过给UserRealm进行授权和认证,来限制用户的访问权限

UserRealm继承于AuthorizingRealm

 

package com.example.springbshiro.demos.config;


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;

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //授权对应的方法
        info.addStringPermission("user:add");

        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
//        User user = (User)subject.getPrincipal();  //拿到User对象
        //设置用户权限,设置用户数据库中的权限
        //info.addStringPermission(user.getPerms());

        return info;
    }

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

        //连接真实数据库的操作
        //User user = userService.queryUserByName(userToken.getUsername())
        //if(user == null){  这个人不存在
        // return null; }

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        if(!userToken.getUsername().equals(name)){
            return null;  //抛出异常(UnknownAccountException  返回空就是返回这个错误)
        }

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

    }
}

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

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

相关文章

C. Trailing Loves (or L‘oeufs?)(求某个质因子在n的阶乘中的个数 + 思维)

Problem - C - Codeforces Aki喜欢数字&#xff0c;尤其是那些带有尾随零的数字。例如&#xff0c;数字9200有两个尾随零。Aki认为数字拥有的尾随零越多&#xff0c;它就越漂亮。 然而&#xff0c;Aki认为&#xff0c;一个数字拥有的尾随零的数量并不是固定的&#xff0c;而是…

微搭低代码调用第三方API

目录 1 创建项目2 获取实时天气API3 创建APIs4 小程序中调用总结 应粉丝要求&#xff0c;我们本篇介绍一下微搭中如何调用第三方API。我们的应用开发中比较常见的一类需求是开发一个天气的功能&#xff0c;方便用户访问应用的时候实时的看到今天最新的天气情况。 第三方的天气…

虚拟机安装使用经验

1 VMware 跟 VirtualBox 在网络上可以看到很多对比的资料&#xff0c;比如这篇: VirtualBox 和 VMware的区别 VMware 分商业版跟非商业版&#xff0c;我们这里仅讨论非商业版&#xff0c;也就是 VMware Workstation Player&#xff0c;支持在 Linux、Windows、Mac OS 等系统上…

docker容器:Docker consul的容器服务更新与发现

目录 一、Docker consul 1、什么是服务注册与发现 2、什么是consul 3、consul部署 ①实验目的 ②实验环境及拓扑 ③consul配置 ④registrator后端配置 ⑤测试发现功能是否正常 4、consul-template部署 ①准备template nginx模板文件 ②编译安装nginx ③安装templa…

LVS-keepalived

文章目录 一、keepalived1、KEEPALIVED作用2、KEEPALIVED原理3、KEEPALIVED工作模式4、KEEPLIVED问题及优化 二、实验1.LVSKeepalived 高可用群集 总结 一、keepalived 1、KEEPALIVED作用 保证负载均衡的高可用性&#xff0c;完美解决了LVS所有问题&#xff0c;可以检查后端服…

【随笔】转发/转向(服务器重定向,服务器转发,服务器跳转)和重定向(客户端重定向,客户端转发,客户端跳转)

文章目录 1.转发&#xff08;转向&#xff09;和重定向图解2.例子3.区别 1.转发&#xff08;转向&#xff09;和重定向图解 图&#xff1a;转发&#xff08;转向&#xff09; 图&#xff1a;重定向 2.例子 转发&#xff1a;A找B要钱&#xff0c;B没钱&#xff0c;于是B向C…

OSPF路由协议解释

目录 OSPF路由协议OSPF数据包类型OSPF邻区状态OSPF的邻接关系建立过程 路由名词解释OSPF开源项目 OSPF路由协议 OSPF简介 1、&#xff08;Open Shortest Path First&#xff09;&#xff0c;开放式最短路径优先&#xff0c;它属于链路状态路由协议&#xff0c;大部分路由将由O…

ChatGPT进化的过程简介

Chat GPT可以做什么&#xff1f; 分点列条的回答问题 写代码或SQL 翻译 语法检查 ChatGPT官方还未公开论文&#xff0c;ChatGPT有一个“孪生兄弟”InstructGPT&#xff0c;InstructGPT有论文&#xff0c;可以根据InstructGPT论文推导ChatGPT的训练过程&#xff1a; ChatGPT的…

React函数组件语法(N)

文章目录 react学习的说明新的官网全力投入现代React与Hooks React简介概述官网特点生态 React脚手架create-react-app官网创建和启动项目项目结构sass支持 Vite创建和启动项目项目结构常见配置 虚拟DOM什么是虚拟DOM虚拟DOM优缺点优点&#xff1a;缺点&#xff1a; 虚拟DOM实现…

MySQL死锁的原因和处理方法

MySQL死锁的原因和处理方法 表的死锁产生原因解决方案 行级锁死锁产生原因1解决方案1产生原因2产生原因3解决方案 表的死锁 产生原因 用户A访问表A(锁住了表A),然后又访问表B&#xff1b;另一个用户B访问表B(锁住了表B),然后企图访问表A;这时用户A由于用户B已经锁住表B,它必须…

LeetCode349. 两个数组的交集

题目链接 LeetCode349. 两个数组的交集 题目描述 题解 题解一&#xff08;Java&#xff09; 作者&#xff1a;仲景 因为数据范围和长度都限制在1000&#xff0c;所以直接使用数组即可 因为数据范围和长度都在1000内&#xff0c;所以碰到数字可以直接arr[i] i来表示这个数字…

如何有效的开展接口自动化测试,一篇就行

一、简介 接口自动化测试是指使用自动化测试工具和脚本对软件系统中的接口进行测试的过程。其目的是在软件开发过程中&#xff0c;通过对接口的自动化测试来提高测试效率和测试质量&#xff0c;减少人工测试的工作量和测试成本&#xff0c;并且能够快速发现和修复接口错误&…

手写Spring框架---IOC容器实现

目录 框架具备的最基本功能 实现容器前奏 创建注解 提取标记对象 extractPacakgeClass里面需要完成的事情 获取项目类加载器的目的 为什么不让用户传入绝对路径 类加载器ClassLoader 统一资源定位符URL ClassUtil提取标记类 获取包下类集合 装载目标类的集合 获取…

Git相关使用

私人博客 许小墨のBlog —— 菜鸡博客直通车 系列文章完整版&#xff0c;配图更多&#xff0c;CSDN博文图片需要手动上传&#xff0c;因此文章配图较少&#xff0c;看不懂的可以去菜鸡博客参考一下配图&#xff01; 系列文章目录 前端系列文章——传送门 后端系列文章——传送…

APP UI自动化测试思路总结 ,教你彻底学会APP自动化测试

目录 一&#xff0c;开发语言选择 二&#xff0c;UI测试框架选择 1&#xff0c;Appium 2&#xff0c;Airtest 3&#xff0c;选择框架 三&#xff0c;单元测试框架选择 四&#xff0c;测试环境搭建 1&#xff0c;测试电脑选择 2&#xff0c;测试手机选择 3&#xff0c;…

【Redis】Redis管道

面试题 如何优化频繁命令往返造成的性能瓶颈&#xff1f; Redis是一种基于客户端-服务端模型以及请求/响应协议的TCP服务。一个请求会遵循以下步骤&#xff1a; 客户端向服务端发送命令分四步(发送命令→命令排队→命令执行→返回结果)&#xff0c;并监听Socket返回&#xf…

基于matlab仿真相控天线阵列在波束成形MIMO-OFDM系统中的使用

一、前言 本例显示了相控阵在采用波束成形的MIMO-OFDM通信系统中的使用。它使用通信工具箱和相控阵系统工具箱中的组件&#xff0c;对组成发射器和前端接收器组件的辐射元件进行建模&#xff0c;用于MIMO-OFDM通信系统。使用用户指定的参数&#xff0c;您可以根据不同空间位置和…

Django自动化测试平台搭建落地全过程(附视频教程+源码)

目录 前言 一、平台基础架构设计 二、自动化测试工具选择与集成 三、平台功能开发 四、总结 前言 自动化测试在现代软件开发中扮演着至关重要的角色&#xff0c;它可以显著提高测试效率和准确性&#xff0c;并帮助开发团队更快地发布高质量的软件产品。Django作为一种流行…

Hudi数据湖技术之集成Spark

目录 1 环境准备1.1 安装MySQL 5.7.311.2 安装Hive 2.11.3 安装Zookeeper 3.4.61.4 安装Kafka 2.4.1 2 滴滴运营分析2.1 需求说明2.2 环境准备2.2.1 工具类SparkUtils2.2.2 日期转换星期 2.3 数据ETL保存2.3.1 开发步骤2.3.2 加载CSV数据2.3.3 数据ETL转换2.3.4 保存数据至Hudi…

Flink的DataStreamApi

1.源算子 SourceFunction 并行度只能为1 ParallelSourceFunction 并行度 2.转换算子 &#xff08;1&#xff09;基本类型 所有 Java 基本类型及其包装类&#xff0c;再加上 Void、String、Date、BigDecimal 和 BigInteger。 &#xff08;2&#xff09;数组类型 包括基…