springboot整合shiro实现前后端分离,兼容最新的jakarta的依赖包(片尾推荐当前最好用的权限框架)

1.简单的用法如下ini realm方式
//1.创建数据源RealmDefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();Ini ini = Ini.fromResourcePath("classpath:shiro.ini");
        defaultSecurityManager.setRealm(new MyRealm());
defaultSecurityManager.setRealm(new IniRealm(ini));//2、安全管理器SecurityUtils.setSecurityManager(defaultSecurityManager);
//        //3.创建主体Subject subject = SecurityUtils.getSubject();
AuthenticationToken userToken = new UsernamePasswordToken("admin", "123456");try {//4.认证subject.login(userToken);
2、整合步骤
1.添加依赖、适配jakarta的依赖包
<!-- 引入适配jakarta的依赖包 --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><classifier>jakarta</classifier><version>1.11.0</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-web</artifactId><classifier>jakarta</classifier><version>1.11.0</version><exclusions><exclusion><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId></exclusion></exclusions></dependency>
2、添加配置类
package com.example.spring_shiro.config;import com.example.spring_shiro.data.MyRealm;
import jakarta.servlet.Filter;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.HashMap;
import java.util.Map;@Configuration
public class ShiroConfig {//1.设置realm@Autowiredprivate  JWTFilter jwtFilter;@Beanpublic MyRealm getRealm(HashedCredentialsMatcher credentialsMatcher) {MyRealm myRealm = new MyRealm();myRealm.setCredentialsMatcher(credentialsMatcher);return myRealm;}//2.管理安全管理器@Beanpublic DefaultWebSecurityManager defaultWebSecurityManager(Realm realm) {DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();defaultWebSecurityManager.setRealm(realm);return defaultWebSecurityManager;}//3.配置shiro 过滤器@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();factoryBean.setSecurityManager(securityManager);Map<String, String> filterChainDefinitionMap = new HashMap<>();Map<String, Filter> filterMap = new HashMap<>();//这个地方其实另外两个filter可以不设置,默认就是//        filterMap.put("jwt", jwtFilter);//        factoryBean.setFilters(filterMap);//        filterChainDefinitionMap.put("/hello", "anon");filterChainDefinitionMap.put("/user/login", "anon");filterChainDefinitionMap.put("/user/logout", "authc");filterChainDefinitionMap.put("/**", "authc");
//
//        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/**", "authc");
//        factoryBean.setLoginUrl("/unauth");factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);return factoryBean;}@Beanpublic HashedCredentialsMatcher getHashedCredentialsMatcher() {HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();credentialsMatcher.setHashAlgorithmName("md5");credentialsMatcher.setHashIterations(1024);return credentialsMatcher;}// 开启shiro注解的支持@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();advisor.setSecurityManager(securityManager);return advisor;}// 开启aop注解支持@Beanpublic DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();defaultAAP.setProxyTargetClass(true);return defaultAAP;}}
3、realm 认证、加密以及数据库逻辑
package com.example.spring_shiro.data;import com.example.spring_shiro.pojo.PermissionData;
import com.example.spring_shiro.pojo.User;
import com.example.spring_shiro.services.UserServices;
import lombok.extern.slf4j.Slf4j;
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.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;@Slf4j
public class MyRealm extends AuthorizingRealm {@Autowiredprivate UserServices userServices;//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {log.info(principals.getPrimaryPrincipal().toString());String userName = principals.getPrimaryPrincipal().toString();PermissionData data = userServices.findUserIdByName(userName);if (data == null) {throw new IllegalArgumentException("无权限");}String[] authorities = data.getAuthorityName().split(",");log.info(data.getAuthorityName());SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();for (int i = 0; i < authorities.length; i++) {log.info(authorities[i]);authorizationInfo.addStringPermission(authorities[i]);}return authorizationInfo;}//认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("token = " + token);//1.获取当前用户的用户名字String userName = (String) token.getPrincipal();User user = userServices.findUserByName(userName);if (user == null) {throw new AccountException("账号不存在");}//        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, user.getPassword(), this.getClass().getSimpleName());SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, user.getPassword(), ByteSource.Util.bytes("jiangnnayizhou110"), this.getClass().getSimpleName());return simpleAuthenticationInfo;}
}
4.services 代码
package com.example.spring_shiro.services;import com.example.spring_shiro.mapper.UserMapper;
import com.example.spring_shiro.pojo.PermissionData;
import com.example.spring_shiro.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserServices implements IUserServices {@Autowiredprivate UserMapper userMapper;@Overridepublic List<User> findUsersAll() {return userMapper.findUsersAll();}@Overridepublic int saveUser(User user) {return userMapper.saveUser(user);}@Overridepublic User findUserByName(String userName) {return userMapper.findUserByName(userName);}@Overridepublic PermissionData findUserIdByName(String userName) {return userMapper.findUserIdByName(userName);}}
5、mapper
package com.example.spring_shiro.mapper;import com.example.spring_shiro.pojo.PermissionData;
import com.example.spring_shiro.pojo.User;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface UserMapper {List<User> findUsersAll();int saveUser(User user);User findUserByName(String userName);PermissionData findUserIdByName(String userName);
}
6、重要的控制器
package com.example.spring_shiro.controller;import com.example.spring_shiro.encrypt.Md5Utils;
import com.example.spring_shiro.pojo.Result;
import com.example.spring_shiro.pojo.User;
import com.example.spring_shiro.services.IUserServices;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {@Autowiredprivate IUserServices userServices;@GetMapping("list")@RequiresUserpublic List<User> findAll() {return userServices.findUsersAll();}//创建用户@PostMapping("addUser")@RequiresPermissions("student:look")public User saveUser(User user) {String password = user.getPassword();password = Md5Utils.md5(password);user.setPassword(password);//密码加密int number = userServices.saveUser(user);if (number > 0) {return user;}return null;}@GetMapping("edit")@RequiresPermissions("student:edit")public Result edit() {return Result.ok("可以编辑");}@GetMapping("delete")@RequiresPermissions("student:delete")public Result deleteInfo() {return Result.ok("可以删除操作");}@PostMapping("/login")public Result login(User user) {String userName = user.getUserName();String password = user.getPassword();Subject subject = SecurityUtils.getSubject();AuthenticationToken userToken = new UsernamePasswordToken(userName, password);try {subject.login(userToken);log.info("成功");return Result.ok(userName);} catch (UnknownAccountException e) {log.info("失败" + "账号没找到" + e.getMessage());return Result.error(-1, "账号为未找到");} catch (IncorrectCredentialsException incorrectCredentialsException) {log.info("失败" + "账号或者密码错误" + incorrectCredentialsException.getMessage());return Result.error(-1, "账号或者密码错误");}}@GetMapping("/logout")public Result logout() {Subject subject = SecurityUtils.getSubject();log.info(String.valueOf(subject.isAuthenticated()));if (subject.isAuthenticated()) {subject.logout();}return Result.ok("退出成功", null);}
}

Sa-Tokenv1.37.0

一个轻量级 java 权限认证框架,让鉴权变得简单、优雅

添加链接描述

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

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

相关文章

微信开发工具修改编译一直报Cannot read property ‘call‘ of undefined?

我个人的解决方法 更新HbuilderX和微信小程序开发者工具到最新版&#xff0c;微信开发者工具-设置-本地设置-调试基础库也换成最新的3.2.4&#xff0c;打开又报错&#xff0c; 把manifest.json文件内的 “mp-weixin” : {“libVersion”: “latest”}配置上就好了 如果不能解…

Axure基础

软件&#xff1a; 简单交互动效 动态面板 显示和隐藏 表单元件 表格设计 内联框架 导航菜单 元件交互样式 滚动屏幕与弹幕

java 4.数组

文章目录 4.数组4.1数组的概念4.2 数组的定义4.3 数组的初始化4.4 数组下标的有效范围与常见异常4.5 数组内存分析4.6 二维数组4.6.1 创建二维数组4.6.2 二维数组的赋值4.6.3 多维数组4.6.4 通过二维数组输出不同版式的古诗 4.7 不规则数组4.8 数组的基本操作4.8.1 数组遍历4.8…

数据结构和算法-平衡二叉树(定义 插入 删除 时间复杂度)

文章目录 平衡二叉树总览平衡二叉树的定义平衡二叉树的插入调整最小不平衡子树在A的左孩子的左子树中插入导致不平衡在A的右孩子的右子树中插入导致不平衡上述两种的代码思路在A的左孩子的右子树中插入导致不平衡在A的右孩子的左子树中插入导致不平衡 填个坑练习查找效率分析小…

锁相放大器(LIA)基本原理

本文介绍锁相放大器(LIA)基本原理。 锁相放大器(LIA)&#xff0c;英文名称&#xff1a;Lock-In Amplifier&#xff0c;在微弱信号检测领域使用非常广泛&#xff0c;比如科研电生理信号测量&#xff0c;传感器信号测量等。本文从理论上分析锁相放大器(LIA)基本原理。 1.基本概…

vivado生成时钟分析

生成的时钟 本节讨论生成的时钟&#xff0c;包括&#xff1a; •关于生成的时钟 •用户定义的生成时钟 •自动衍生时钟 •自动衍生时钟 关于生成的时钟 生成的时钟在设计内部由称为时钟修改块&#xff08;用于例如MMCM&#xff09;&#xff0c;或者通过一些用户逻辑。生…

如何在Linux中查看正在运行的进程以及过滤特定端口和进程名称

在Linux系统中&#xff0c;管理和监控正在运行的进程是非常重要的。以下是一些常用的命令和技巧&#xff0c;帮助你查看、筛选和管理Linux中的进程。 1. 查看所有正在运行的进程 使用ps命令 ps命令是查看进程状态的基本工具。以下是一些常见的用法&#xff1a; 显示当前终端…

NFS搭建

离线环境&#xff0c;提前在有网络的服务器上下载好需要的软件包 yum -y install nfs-utils rpcbind --downloadonly --downloaddir /root/nfs zip -r nfs.zip nfs/ registry.cn-beijing.aliyuncs.com/pylixm/nfs-subdir-external-provisioner:v4.0.0 #nfs 安装 unzip nfs.zi…

mysql 表锁 行锁

目录 表锁&#xff08;Table Lock&#xff09; 行锁&#xff08;Row Lock&#xff09; 进一步通过举例解释 update操作走的是什么锁 表锁示例&#xff1a; 行锁示例&#xff1a; MySQL 中常见的锁类型包括&#xff1a; 表锁&#xff08;Table Lock&#xff09; 是针对整个…

redisson 哨兵模式配置

背景&#xff1a;项目redis由集群改为哨兵模式&#xff0c;漏洞扫描未授权访问漏洞&#xff08;CNVD-2019-21763&#xff09;&#xff0c;要求对redis哨兵也设置密码&#xff0c;redisson依赖版本为3.11.5 spring-boot版本为2.1.13。 redisson依赖升级 <dependency>&l…

[JS设计模式]Command Pattern

文章目录 举例说明优点缺点完整代码 With the Command Pattern, we can decouple objects that execute a certain task from the object that calls the method. 使用命令模式&#xff0c;我们可以将执行特定任务的对象与调用该方法的对象解耦。 怎么理解 执行特定任务的对…

基于Java (spring-boot)的课程管理系统

一、项目介绍 ​近年来&#xff0c;随着网络学校规模的逐渐增大&#xff0c;人工书写数据已经不能够处理如此庞大的数据。为了更好的适应信息时代的高效性&#xff0c;一个利用计算机来实现学生信息管理工作的系统将必然诞生。基于这一点&#xff0c;设计了一个学生信息管理系统…

Mybatis基本操作

目录 准备工作 删除操作 预编译SQL 增加操作 获取返回的主键 更新操作 准备工作 准备数据库表 emp创建一个新的springboot工程&#xff0c;选择引入对应的起步依赖&#xff08;mybatis、mysql驱动、lombok&#xff09;application.properties中引入数据库连接信息创建对应…

html 内外边距区别以及解释

引入&#xff1a; 我们在之前的学习中学习了边框&#xff0c;我们发现只要是页面的标签元素&#xff0c;都可以实现边框的效果&#xff0c;那么接下来我们来讲解一个比较重要的知识点&#xff0c;边距&#xff0c;边距分为内边距和外边距&#xff0c;它们和边框一起是我们后面学…

Mybatis配置-映射器(mappers)

现在&#xff0c;我们已经配置了MyBatis的行为&#xff0c;准备定义我们的映射SQL语句。但首先&#xff0c;我们需要告诉MyBatis在哪里找到它们。在这方面&#xff0c;Java并没有提供很好的自动发现机制&#xff0c;所以最好的方法是直接告诉MyBatis在哪里找到映射文件。 您可以…

【delphi11】delphi基础探索【三、基础组件和事件】

目录 基础组件 1. TButton&#xff08;按钮&#xff09; 2. TLabel&#xff08;标签&#xff09; 3. TEdit&#xff08;编辑框&#xff09; 4. TMemo&#xff08;多行编辑框&#xff09; 5. TComboBox&#xff08;组合框&#xff09; 6. TCheckBox&#xff08;复选框&…

PSP - 蛋白质与蛋白质的扩散对接 DiffDock-PP 算法

欢迎关注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://spike.blog.csdn.net/article/details/135115528 DiffDock-PP is a new approach to rigid-body protein-protein docking that is based on a diffusion generative model that learns…

PHP数据格式化加,加‘‘引号处理

原数据格式: ABC20231217043116afj6J0I6WV ABC20231217043116dlSyOB5Tvx ABC202312170431166EbL7BbYOm ABC20231217043116troQuaKWzw ABC20231217043116o7ZELjjF7E ABC20231217043122FFp1CSPLQ2 ABC20231217043133uJIBKil3bC ABC202312170431337z4bZwGJVS ABC20231217043133fi…

软件工程快速复习(期末急救)

每个同学要假想自己是一个项目经理&#xff0c;去完成一个软件项目&#xff0c;比如医院管理系统&#xff0c;自动设备控制系统等&#xff0c;以面向结构的软件工程方法&#xff0c;说出完成项目的步骤&#xff0c;涉及到的具体技术。初步了解面向对象的方法的与面向结构的方法…

【java】java学习笔记

1. 快速入门 // Hello类 public class Hello {// main方法public static void main(String[] args) {System.out.println("hello world!");} } 在控制台输入以下命令&#xff0c;对.java文件&#xff08;源文件&#xff09;进行编译操作&#xff0c;生成Hello.clas…