springboot 与shiro整合

shiro~

    • shiro快速入门
    • springboot 整合shiro
      • 核心目标
      • 清爽pom
      • 用户认证授权认证,与数据库交互
      • shiro configuration
      • 核心controller 获取shiro 中的token
      • 页面控制功能的隐藏和显示

https://github.com/sevenyoungairye/spring-boot-study/tree/main/springboot-shiro-07

shiro快速入门

  1. 什么是shiro
  • apache shiro 是一个java的安全(权限)框架。
  • shiro可以非常容易的开发出足够好的应用,可以在javase环境,也可用在javaee环境
  • shiro可以完成 认证,授权,加密,会话管理,web继承,缓存等。
  • 下载地址:http://shiro.apache.org
  1. shiro快速入门代码简单分析~
    git来拿来的
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;public class QuickStart {// 日志对象private static final transient Logger log = LoggerFactory.getLogger(QuickStart.class);public static void main(String[] args) {// 创建shiro环境Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");SecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);// 获取当前的用户对象Subject currentUser = SecurityUtils.getSubject();// 获取当前sessionSession session = currentUser.getSession();// 设置keysession.setAttribute("someKey", "aValue");// 获取valueString 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);}
}

springboot 整合shiro

核心目标

  • springboot 整合shiro shiro-spring

  • subject 用户

  • SecurityManager 管理所有用户

  • Realm 连接数据

  • 认证 数据库匹配账号密码

  • 授权 用户的角色匹配 [user:add], [user:update]用户修改和新增的权限

  • shiro与thymeleaf的整合

清爽pom

  • shiro-core
 <!-- shiro config.. --><dependencies><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.6.0</version></dependency><!-- configure logging --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.30</version><scope>runtime</scope></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version><scope>runtime</scope></dependency></dependencies>
  • spring 与shiro整合
<!-- thymeleaf & shiro --><dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version></dependency><!-- shiro & springboot --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.6.0</version></dependency>

用户认证授权认证,与数据库交互

package cn.bitqian.config;import cn.bitqian.entity.Users;
import cn.bitqian.mapper.UsersMapper;
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;/*** 用户认证* @author echo lovely* @date 2020/10/27 15:58*/
public class UserRealm extends AuthorizingRealm {@Autowiredprivate UsersMapper usersMapper;// 授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("授权认证=> PrincipalCollection");SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();// 对user:add授权// authorizationInfo.addStringPermission("user:add");// 获取当前用户Subject subject = SecurityUtils.getSubject();Users users = (Users) subject.getPrincipal();// 进行身份认证 设置当前用户的权限authorizationInfo.addStringPermission(users.getPermission());return authorizationInfo;}// 认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("登录认证=> AuthenticationToken");// 用户名 密码认证UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;// 页面用户名String tokenUsername = userToken.getUsername();// 数据库中是否存在该用户Users users = usersMapper.findUsersByUsersName(tokenUsername);if (users == null) {return null;}SecurityUtils.getSubject().getSession().setAttribute("loginUser", users);// principal 用户认证 用户里面存在权限return new SimpleAuthenticationInfo(users, users.getUserPassword(), ""); // 密码自动验证}
}

shiro configuration

package cn.bitqian.config;import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
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;/*** shiro的配置类* @author echo lovely* @date 2020/10/27 16:03*/
@Configuration
public class ShiroConfig {// 1. 自定义realm对象@Bean(name = "authorizingRealm")public AuthorizingRealm authorizingRealm() {return new UserRealm();}// 2. DefaultWebSecurityManager@Bean(name = "securityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("authorizingRealm") AuthorizingRealm authorizingRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();// 关联UserRealmsecurityManager.setRealm(authorizingRealm);return securityManager;}// 3. ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();// 设置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);/*** anon 无需认证就可访问* authc 必须认证了才能访问* user 必须拥有 记住我 功能* perms 拥有对某个资源的权限* roles 角色权限*/Map<String, String> filterMap = new LinkedHashMap<>();shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);// filterMap.put("/*", "authc");// 必须认证 才可用filterMap.put("/update", "authc");filterMap.put("/add", "authc");// 必须有某个资源的权限 授权 正常的情况下,没有授权会跳转到未授权页面// user:add 和 user:update 的权限filterMap.put("/add", "perms[user:add]");filterMap.put("/update", "perms[user:update]");// 设置登录请求shiroFilterFactoryBean.setLoginUrl("login");// 没有权限 跳转到提示到页面shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");return shiroFilterFactoryBean;}@Bean // 用来整合thymeleafpublic ShiroDialect getShiroDialect() {return new ShiroDialect();}}

核心controller 获取shiro 中的token

    @PostMapping(value = "/login")public String login(String username, String password, Model model) {// 设置用户名 跟 密码UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);// 获取当前用户对象Subject subject = SecurityUtils.getSubject();try {// 执行了登录操作subject.login(usernamePasswordToken);return "index";} catch (UnknownAccountException uae) { // 账号不存在model.addAttribute("msg", "账号错误");return "login";} catch (IncorrectCredentialsException ice) { // 密码错误model.addAttribute("msg", "密码错误");return "login";}}@RequestMapping(value = "/unauthorized")@ResponseBodypublic String toUnauthorized() {return "未经授权,不许访问!";}

页面控制功能的隐藏和显示

<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org"xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro.com">
<head><meta charset="UTF-8"><title>index shiro</title>
</head>
<body><p th:text="${msg}"></p><hr/><div th:if="${session.loginUser==null}"><a href="/login">login</a></div><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>

更多代码git clone

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

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

相关文章

jvm内存设置

摘抄自&#xff1a;http://www.cnblogs.com/fyj218/archive/2011/07/19/2110570.html 在eclipse根目录下打开eclipse.ini&#xff0c;默认内容为&#xff08;这里设置的是运行当前开发工具的JVM内存分配&#xff09;&#xff1a;-vmargs-Xms40m-Xmx256m-vmargs表示以下为虚拟机…

swagger接口文档使用

swagger接口文档一&#xff0c;swagger简介前后端分离swagger 诞生二&#xff0c;springboot集成swagger依赖编写helloworld接口配置swagger > config 配置类测试运行三&#xff0c;配置swaggerswagger 配置扫描接口如何做到只在生产环境中启动swagger&#xff1f;配置api文…

异步任务,邮箱任务,定时任务

task~异步任务邮箱任务定时任务源码下载异步任务 开启多线程&#xff0c;我飞了。 package cn.bitqian.service;import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service;/*** 异步任务 目的 多线程&#xff0c;交给spring托…

iframe在ipad safari的显示

今 天要在web中嵌套一个网址或本地HTML&#xff0c;用到了iframe&#xff0c;在电脑上设置scrolling‘auto’&#xff0c;宽度高度&#xff0c;会有滚动条出现。而在 ipad上会全部显示整个网页的宽度高度。scrolling属性无效。原来在html5中的iframe已经只有剩下src的属性。 但…

IOS 开发中 Whose view is not in the window hierarchy 错误的解决办法

在 IOS 开发当中经常碰到 whose view is not in the window hierarchy 的错误&#xff0c;该错误简单的说&#xff0c;是由于 "ViewController" 还没有被加载&#xff0c;就调用该 ViewController 或者 ViewController 内的方法时&#xff0c;就会报这个错误。在不同…

maven传递依赖

目录1. 依赖传递2. 什么是依赖冲突3. 怎么解决4. 项目聚合maven是一个项目管理的工具&#xff0c;从项目的构建到项目开发&#xff0c;再到项目的测试&#xff0c;项目上线&#xff0c;都可一键管理。1. 那么&#xff0c;还有maven是如何管理项目中所用到的jar版本冲突&#xf…

使用apache FileUtils下载文件

目录工具代码实现测试工具 <dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency>或者 https://mvnrepository.com/artifact/commons-io/commons-io/2.7 然后放…

二分图多重匹配

在二分图的最大匹配中&#xff0c;每个点&#xff08;不管是X集合还是Y集合&#xff09;最多只能与一条匹配边相关联&#xff0c; 然而&#xff0c;经常有这种问题&#xff0c;即二分图的一个点可以和多条匹配边相关联&#xff0c;但有上限&#xff0c;即cap[i]表示点i最多能和…

springmvc,spring,hibernate5.0整合

目录1. pom依赖2. web.xml3. spring核心配置文件3.1 jdbc配置信息3.2 sping 配置文件4. 实体映射5. 项目结构5.1 curd5.2 页面6. 测试1. spring版本 5.1.5 RELEASE 2. hibernate版本 5.3.9.Final 3. 数据源使用c3p0项目使用eclipse2017 maven构建, 完成学生的新增&#xff0c;…

MYSQL 查看表上索引的 1 方法

前期准备&#xff1a; create table T9(A int ,B text,C text,fulltext index fix_test_for_T8_B(B));#在定义表的时候加索引 create unique index ix_test_for_T8_A on T9(A);#加朴素索引 create fulltext index fix_test_for_T8_C on T9(C);#加全文索引 --------------------…

springmvc 结合ajax批量新增

目录1. 需要注意的问题2. 页面代码3. controller定义参数接收1. 需要注意的问题 mvc框架的处理日期问题ResponseBody响应对象是自定义对象&#xff0c;响应不是jsonResopnseBody响应自定义对象时&#xff0c;日期为是long类型的数结束数据方法的参数&#xff0c;该如何定义&am…

吐槽一下Activiti的用户手册和一本书

业余没事的时候&#xff0c;看了点Java的资料&#xff0c;无意之中发现了Activiti&#xff0c;就打算自己跑几个例子看看到底是怎么回事。一直搞底层&#xff0c;也得偶尔关心下上层到底发展到什么程度了不是。悲惨的过程就是这么开始的&#xff0c;首先是Activiti的用户手册&a…

手写简单的启动器

starter1. target2. 手写启动器~2.1 自动装配&#xff0c;自定义属性2.2 启动器&#xff0c;引用自动装配模块3. 在自己的项目引用上面的starter1. target 1. 启动器只用来做依赖导入(导入配置模块)2. 专门来写一个自动配置模块3. 启动器依赖自动配置&#xff1b;别人只需要引入…

Android 颜色渲染(九) PorterDuff及Xfermode详解

Android 颜色渲染(九) PorterDuff及Xfermode详解之前已经讲过了除ComposeShader之外Shader的全部子类, 在讲ComposeShader(组合渲染)之前, 由于构造ComposeShader需要 PorterDuffXfermode或者PorterDuff.Mode作为参数,所以在此先详细地了解下这两个类的作用,这对之后的绘图会…

拦截器(二)

只拦截controller的请求, 基于aop&#xff0c;横切。 Spring MVC的拦截器类似于Servlet开发中的过滤器Filter&#xff0c; 用于对处理器进行预处理和后处理。 将拦截器按一定的顺序联结成一条链&#xff0c; 这条链称为拦截器链&#xff08;InterceptorChain&#xff09;。 在访…

nodejsmongoangularjs

http://www.ibm.com/developerworks/cn/web/wa-nodejs-polling-app/转载于:https://www.cnblogs.com/xixifusigao/p/4037928.html

每次新建Android项目都报样式找不到的错误?

问题描述如图再网上找了下说改为<style name"AppBaseTheme" parent"android:Theme.Light">这样就行了的确改为这样就ok了但是如果每次都要这么改&#xff0c;不是很烦&#xff1f;有没有彻底解决这个问题的方法&#xff1f;谢谢 解决方案1新建的时候…

spring mvc全局异常处理,注解实现

ssm框架中的异常处理&#xff0c;可以是dao, service, controller 一直抛出异常&#xff0c;抛出就完事了。最终由全局异常类捕获&#xff0c;进行日志记录&#xff0c;页面跳转。… 核心注解 // 方法级别 ExceptionHandler // 全局异常类上 ControllerAdvice // ControllerA…

Qt多线程学习:创建多线程

【为什么要用多线程&#xff1f;】 传统的图形用户界面应用程序都仅仅有一个运行线程&#xff0c;而且一次仅仅运行一个操作。假设用户从用户界面中调用一个比較耗时的操作&#xff0c;当该操作正在运行时&#xff0c;用户界面一般会冻结而不再响应。这个问题能够用事件处理和多…