Shiro 整合 SpringBoot

Shiro 整合 SpringBoot

shiro主要有三大功能模块

  1. Subject:主体,一般指用户。

  2. SecurityManager:安全管理器,管理所有Subject,可以配合内部安全组件。(类似于SpringMVC中的DispatcherServlet)

  3. Realms:用于进行权限信息的验证,一般需要自己实现。

shiro架构图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PkoyMhpN-1610439982383)(C:\Users\郑大人\AppData\Roaming\Typora\typora-user-images\image-20200629142750768.png)]

Subject 用户
SecurityManager 管理所有用户
Realm   连接数据

Shiro入门

Shiro 配置

按步骤:

  1. 先创建一个 Realms 类 继承自 AuthorizingRealm 类 实现它两个方法 授权 doGetAuthorizationInfo 和 认证 doGetAuthenticationInfo

    import com.entity.User;
    import com.service.impl.UserServiceImpl;
    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;//自定义的UserRealm
    public class UserRealm  extends AuthorizingRealm {@AutowiredUserServiceImpl userService;//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了==>  授权");// 创建 简单授权信息类final SimpleAuthorizationInfo  authorizationInfo= new SimpleAuthorizationInfo();//获得当前的用户 当前的用户首先得被存入  简单身份验证信息类 构造函数的第一个参数中final Subject subject = SecurityUtils.getSubject();User currentUser = (User)subject.getPrincipal();//添加当前用户 字符串权限authorizationInfo.addStringPermission(currentUser.getPerms());return authorizationInfo;}//认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("执行了==> 认证 ");UsernamePasswordToken token  =  (UsernamePasswordToken)authenticationToken;// 用户名,密码 从数据库中取User user = userService.qureyUserByName(token.getUsername());if(user == null){return null; //抛出异常 UnknownAccountException 未知账户异常}//密码认证 由 shiro 来完成,加密了//返回 简单身份验证信息类return new SimpleAuthenticationInfo(user,user.getPassword(),"");}
    }
    
  2. 创建一个Shiro的配置类,里面向spring容器注入三个Bean 分别是:

    1. ShiroFilterFactoryBean: 用来设置 过滤器,以及权限,登录页,未授权跳转页等等.(需要给方法传入安全管理器 DefaultWebSecurityManager对象)
    2. DefaultWebSecurityManager: DefaultWebSecurityManager类主要定义了设置subjectDao,获取会话模式,设置会话模式,设置会话管理器,是否是http会话模式等操作,它继承了DefaultSecurityManager类,实现了WebSecurityManager接口。
    3. Realms 自定义的类
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
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.Map;@Configuration
public class ShiroConfig {//ShiroFilterFactoryBean :3@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager")DefaultWebSecurityManager defaultWebSecurityManager){final ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();// 设置安全管理器bean.setSecurityManager(defaultWebSecurityManager);//添加shiro的内置过滤器  拦截/*** anon:无需认证即可访问* authc:必须认证才可以访问* user:必须拥有记住我 功能才可以用* perms:拥有对某个资源的权限才能访问* role:拥有某个角色权限才能访问*///拦截Map<String,String> filterMap = new LinkedHashMap<>();filterMap.put("/add","authc"); //也可支持通配符 *filterMap.put("/update","authc");//授权 perms[a:b] 必须是a ,且有权限bfilterMap.put("/add","perms[user:add]");filterMap.put("/update","perms[user:update]");//设置过滤器链定义图bean.setFilterChainDefinitionMap(filterMap);//设置登录页面,即如果没有权限,就会跳转至登录页面bean.setLoginUrl("/toLogin");//设置未授权跳转页面的urlbean.setUnauthorizedUrl("/unauthorized");return bean;}//DefaultWebSecurityManager:2@Bean(name = "SecurityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){final DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();//关联 UserRealmdefaultWebSecurityManager.setRealm(userRealm);return defaultWebSecurityManager;}//创建 realm 对象 ,需要自定义 :1@Bean(name = "userRealm")public UserRealm getRealm(){return new UserRealm();}}

登录

@RequestMapping("/login")public String login(@RequestParam(name = "username") String username,@RequestParam(name = "password") String password,Model model){//获取当前用户final Subject subject = SecurityUtils.getSubject();//封装用户的登录数据final UsernamePasswordToken token = new UsernamePasswordToken(username, password);try {//执行登录的方法 ,如果没有异常就ok了//执行登录时,会进入Realm中认证subject.login(token);return "index";} catch (AuthenticationException e) {model.addAttribute("msg","用户名或密码错误!");return "login";}}

注销

	/*** 退出用户* @return*/@RequestMapping("/logout")public String logout(){final Subject subject = SecurityUtils.getSubject();//退出用户subject.logout();return "index";}

Shiro整合 Thymeleaf

依赖

<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version>
</dependency>

整合配置

Shiro整合 Thymeleaf 需要在配置类中加入一个Bean 到 spring容器,这个类是 ShiroDialect

@Configuration
public class ShiroConfig {//用来整合 thymeleaf@Beanpublic ShiroDialect getShiroDialect(){return new ShiroDialect();}//ShiroFilterFactoryBean :3@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager")DefaultWebSecurityManager defaultWebSecurityManager){final ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();// 设置安全管理器bean.setSecurityManager(defaultWebSecurityManager);//添加shiro的内置过滤器  拦截/*** anon:无需认证即可访问* authc:必须认证才可以访问* user:必须拥有记住我 功能才可以用* perms:拥有对某个资源的权限才能访问* role:拥有某个角色权限才能访问*///拦截Map<String,String> filterMap = new LinkedHashMap<>();filterMap.put("/add","authc"); //也可支持通配符 *filterMap.put("/update","authc");//授权 perms[a:b] 必须是a ,且有权限bfilterMap.put("/add","perms[user:add]");filterMap.put("/update","perms[user:update]");//设置过滤器链定义图bean.setFilterChainDefinitionMap(filterMap);//设置登录页面,即如果没有权限,就会跳转至登录页面bean.setLoginUrl("/toLogin");//设置未授权跳转页面的urlbean.setUnauthorizedUrl("/unauthorized");return bean;}//DefaultWebSecurityManager:2@Bean(name = "SecurityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){final DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();//关联 UserRealmdefaultWebSecurityManager.setRealm(userRealm);return defaultWebSecurityManager;}//创建 realm 对象 ,需要自定义 :1@Bean(name = "userRealm")public UserRealm getRealm(){return new UserRealm();}}

html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"> <!-- shiro 整合 thymeleaf 的提示-->
<head><meta charset="UTF-8"><title>首页</title>
</head>
<body>
<h1>首页</h1>
<p><a href="/toLogin">登录</a></p>
<p><a href="/logout">退出</a></p>
<hr><div shiro:hasPermission="user:add"> <!--判断权限--><a th:href="@{/add}">add</a>
</div>
<div shiro:hasPermission="user:update"><a th:href="@{/update}">update</a>
</div></body>
</html>

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

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

相关文章

centos安装php7编译

centos7下安装php7 php7 centos7 安装PHP7 首先安装一些必须的依赖&#xff0c;这里就不阐述了&#xff0c;后面文章再细说 yum install -y \ gcc-c autoconf \ yum -y install postgresql-devel\ libjpeg libjpeg-devel libpng \ libpng-devel freetype freetype-devel \ li…

SpringBoot Web 入门

SpringBoot Web 要解决的问题&#xff1a; 导入静态资源首页模板引擎 Thymeleaf装配扩展SpringMVCCRUD拦截器国际化 SpringMVC的自动配置类为WebMvcAutoConfiguration &#xff0c;对应的properties类为WebMvcProperties //WebMvcProperties部分代码 //在application配置文…

CentOS7搭建ftp服务器(vsftpd,亲测成功)

安装vsftpd sudo yum install vsftpd 配置参数 命令行输入 vim /etc/vsftpd.conf 使用如下配置 # Example config file /etc/vsftpd.conf # # The default compiled in settings are fairly paranoid. This sample file # loosens things up a bit, to make the ftp daem…

handler类型的定时器

2019独角兽企业重金招聘Python工程师标准>>> 一、采用Handle与线程的sleep(long)方法 Handler主要用来处理接受到的消息。这只是最主要的方法&#xff0c;当然Handler里还有其他的方法供实现&#xff0c;有兴趣的可以去查API&#xff0c;这里不过多解释。 1. 定义…

Vue路由基本操作

路由index.js import Vue from vue import VueRouter from vue-router import Home from ../views/Home.vue import Me from ../views/me.vue import About from "../views/About.vue" import Centor from "/views/Center.vue" import _404 from "..…

Windows 10 搭建Python3 安装使用 protobuf

Windows 10 搭建Python3 安装使用 protobuf Protobuf对比XML、Json等其他序列化的优势 protobuf 不管是处理时间上&#xff0c;还是空间占用上都优于现有的其他序列化方式。内存暂用是java 序列化的1/9&#xff0c;时间也是差了一个数量级&#xff0c;一次操作在1us左右。缺点…

如何用PS的样式制作图片椭圆形边框

制作过程&#xff1a; 1&#xff09;点击文件→新建&#xff0c;画布尺寸按需&#xff0c;背景白色。 2&#xff09;点击形状工具→椭圆形工具&#xff0c;画一椭圆&#xff0c;位置居中大小按需。 3&#xff09;选择样式&#xff0c;本例如图1 4&#xff09;点击选框工具→椭圆…

Vue + SpringBoot跨域

Vue设置 1、在项目根目录创建文件vue.config.js module.exports {devServer: {proxy: {/api: {target: http://zlf.plus, //对应自己的接口changeOrigin: true,ws: true,pathRewrite: {^/api: }}}}}2、 在main.js中配置 import Vue from vue import App from ./App.vue imp…

Windows10 64位 安装 Postgresql 数据库

Windows10 64位 安装 Postgresql 数据库 1&#xff0c;下载Postgresql 10.7 版本&#xff0c;下载地址 https://www.enterprisedb.com/downloads/postgres-postgresql-downloads 2&#xff0c;打开安装包&#xff0c;傻瓜式默认安装&#xff0c;请谨记 “数据库密码” 和 “…

node.js入门小案例

nodejs 和 Java node.js是运行在服务端的JavaScript。node.js是一个基于chrome JavaScript 运行时建立的一个平台。底层架构 是JavaScript。 node.js是一个事件驱动I/O服务端JavaScript环境&#xff0c;chrome V8引擎执行JavaScript的速度非常快&#xff0c;性能非常好。 可以…

Windows10 64位安装DB2数据库

Windows10 64位安装DB2数据库 安装前准备 &#xff1a; 系统&#xff1a;Windows10 64位 DB2 v9.5下载地址&#xff08;迅雷&#xff09;&#xff1a;http://big3.ddooo.com/db2_93661.rar 选择安装包解压位置&#xff0c;并复制记住&#xff1a; 去到解压的安装目录&#xff…

crossdomain.xml

使用crossdomain.xml让Flash可以跨域传输数据 本文来自http://www.mzwu.com/article.asp?id975 一、概述 位于www.mzwu.com域中的SWF文件要访问www.163.com的文件时&#xff0c;SWF首先会检查163服务器目录下是否有crossdomain.xml文件&#xff0c;如果没有&#xff0c;则访问…

npm包管理器安装模块

使用npm init 初始化目录(npm init -y) 可以省略中间过程 会在项目根目录生成一个文件 package.json&#xff08;类似于Maven 的pom文件&#xff09; {"name": "test","version": "1.0.1","description": "第一次创建…

Git报错: OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

Git报错: OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 在使用Git来克隆仓库报了错误&#xff0c;如下&#xff1a; fatal: unable to access ‘https://github.com/xiaobingchan/machine_learn/‘: OpenSSL SSL_connect: SSL_ERROR_SYSCALL in co…

linux下的redis配置;

2019独角兽企业重金招聘Python工程师标准>>> linux环境下的php和redis的集成&#xff1a;http://blog.csdn.net/21aspnet/article/details/6960757 转载于:https://my.oschina.net/wangfree/blog/115987

Babel入门

Babel简介 Babel 是一个工具链&#xff0c;主要用于将 ECMAScript 2015 版本的代码转换为向后兼容的 JavaScript 语法&#xff0c;以便能够运行在当前和旧版本的浏览器或其他环境中。 中文文档 安装 npm install -g bable-cli 全局安装 babel --version 查看版本 Babel的…

Server 2012使用Windows PowerShell cmdlet安装角色和角色服务功能

Server 2012使用Windows PowerShell cmdlet安装角色和角色服务功能 Server 2012使用Windows PowerShell cmdlet安装角色和角色服务功能 Windows Server 2012 安装 SQL server 2008 出现了如下错误&#xff1a;解决方案1&#xff08;简单&#xff0c;界面操作&#xff09;&…

commonjs 和 es6模块化开发入门

commonjs模块化 首先写一个api&#xff0c;提供给外部调用 //commonjslet sum (a,b)> ab;// 暴露接口 module.exports {sum // sum:sum }导入调用 const m require(./Api.js)console.log(m.sum(10,20));es6模块化 首先写一个api&#xff0c;提供给外部调用 //es6 exp…

黑马程序员_7k面试题交通管理系统

------- android培训、java培训、期待与您交流&#xff01; ---------- //以下知识来在张孝祥老师的讲解总结 项目需求 模仿实现十字路口的交通灯系统逻辑&#xff0c;具体需求如下 1.异步随机生成按照各个线路行驶的车辆 例如&#xff1a; 由南而来去往北向的车辆......直行车…