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

springboot 与shiro整合相关推荐

  1. 《SpringBoot与Shiro整合-权限管理实战---从构建到模拟数据库登入》

    <SpringBoot与Shiro整合-权限管理实战> ---- 从构建到模拟数据库登入 ---- 点击下载源码 ---- 或者查看? 文章目录 <SpringBoot与Shiro整 ...

  2. SpringBoot与Shiro整合-概述

    主要讲解如何使用Spring Boot与Shiro进行整合使用,实现强大的用户权限管理,其中涉及如何完成用户认证(即用户登录),用户授权,thymeleaf页面整合shiro权限标签等知识点 Spri ...

  3. 【超详细】SpringBoot与Shiro整合-权限管理实战实操(附源码地址)

    一.搭建SpringBoot开发环境 1. 安装好开发软件和Maven等 开发工具:Spring Tool Suite(TST) Maven :3.3.9 jdk:1.8 2. 创建springboo ...

  4. SpringBoot+Mybatis-Plus+Shiro整合的RBAC权限系统

    Maven仓库: dependencies><dependency><groupId>org.springframework.boot</groupId>&l ...

  5. SpringBoot基于Shiro整合OAuth统一认证

    修改配置文件application.yml

  6. Shiro 整合 SpringBoot

    Shiro 整合 SpringBoot shiro主要有三大功能模块 Subject:主体,一般指用户. SecurityManager:安全管理器,管理所有Subject,可以配合内部安全组件.(类 ...

  7. springBoot中shiro与Redis整合的配置文件

                                                                 springBoot中shiro与Redis整合的配置文件 整合依赖: < ...

  8. Springboot -Shiro整合JWT(注解形式)

    Springboot -Shiro整合JWT(注解形式) 在这里只展示核心代码,具体的请访问github 参考timo 依赖导入 <dependencies><dependency& ...

  9. shiro整合springboot,配置mybatis和增加邮箱验证码登录

    目录 config配置 controller层 Mapper(Mybatis配置) pojo Service 工具类 MailUtil 前台页面 配置(application) 相关依赖 config ...

最新文章

  1. OpenGL中的颜色再次讨论
  2. 推荐11个实用Python库
  3. J-LINK不能烧写(错误:JLink Warning: RESET (pin 15) high, but should be low. Please check target)
  4. 作为程序员之正则表达式
  5. 研发团队平稳度过“从小到大”并非易事
  6. 信息学奥赛C++语言:求正方形的面积
  7. python机器学习彩票_Python机器学习及实战kaggle从零到竞赛PDF电子版分享
  8. 腾讯AI加速器三期全球招募开启,打造AI+产业生力军
  9. idea将项目打包(jar包/war包)
  10. MYSQL 取上一条记录,与下一条记录
  11. 第三十七课.宽度学习
  12. Qt Charts入门
  13. python求次幂_python如何求次幂?
  14. Git 版本控制/项目迭代
  15. cvpr2020 人脸检测与识别_就CVPR2020的来看,目前人工智能的研究热点有哪些进展?未来的研究趋势会有什么变化?...
  16. boot版本是什么 cent os_Cent OS 7系统目录结构
  17. ADS学习:统计分析——灵敏度分析、良率优化
  18. JavaWeb - 软件开发的流程,综合案例
  19. Python之freshman05
  20. 学软件开发都要学哪些基础内容?

热门文章

  1. oracle之高级子查询1
  2. 前端学习(1320):同步和异步得区别
  3. 前端学习(565):margin重叠意义
  4. 第十七期:详解大数据处理中的Lambda架构和Kappa架构
  5. jenkins安装(1)
  6. linux mysql数据库定时备份
  7. mounted钩子函数_Vue 探索之路——生命周期和钩子函数的一些理解
  8. bzoj2683bzoj4066
  9. 编译原理预测分析程序
  10. context:component-scan扫描使用的use-default-filters