文章目录

  • Shiro框架简介
  • 环境搭建springboot+shiro+mybatis-plus+thymeleaf
    • 1.创建Spring Boot项目,集成Shiro及相关组件
    • 2.准备一个sql表
    • 3.配置yml
    • 4.创建表的实体类
    • 5.创建mybatis-plus的basemapper接口
    • 6.创建UserService接口实现
    • 7.创建UserServiceImpl业务逻辑
    • 8.编写自定义Realm认证授权
    • 9.编写Shiro的配置类
    • 10.编写controller控制器
    • 11.编写controller对应的界面html
    • 12.启动器测试
  • shiro完美解释

Shiro框架简介

Apache Shiro是一个强大且易用的Java安全框架,执行身份认证丶授权丶密码和会话管理。
以用户登录为例-多图参考↓


Shiro主要用来用户认证和用户授权

用户认证 — 用户身份识别。得知道来的人是谁;
用户授权 — 用户权限访问控制。得知道来的人有没有资格进来,又不是“我家大门常打开”;

环境搭建springboot+shiro+mybatis-plus+thymeleaf

springboot+shiro+mybatis-plus+thymeleaf
目录结构

1.创建Spring Boot项目,集成Shiro及相关组件


pom.xml

<!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency>
<!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
<!--shiro--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.7.1</version></dependency>
2.准备一个sql表
创建数据库
create database 数据库名;选择数据库
use 数据库名;

创建数据表

create database shirompdb;use shirompdb;create table account(id int AUTO_INCREMENT,name varchar(30) default null,password varchar(30) default null,perms varchar(30) default null,primary key(id)
)engine=innodb charset=utf8;

mysql连接idea并且添加几个用户

3.配置yml
spring:datasource:url: jdbc:mysql://localhost:3306/shirompdbusername: rootpassword: guohuidriver-class-name: com.mysql.cj.jdbc.Driverthymeleaf:prefix: classpath:/templates
4.创建表的实体类

pojo

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("account")//account 对应数据库的表
public class user {private Integer id;private String name;private String password;private String perms;
}
5.创建mybatis-plus的basemapper接口

mapper

@Repository
public interface UserMapper extends BaseMapper<user> {}
6.创建UserService接口实现

service

@Service
public interface UserService {public user queryUserByName(String name);
}
7.创建UserServiceImpl业务逻辑

service/impl

@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic user queryUserByName(String name) {QueryWrapper wrapper = new QueryWrapper();wrapper.eq("name",name);return userMapper.selectOne(wrapper);}
}
8.编写自定义Realm认证授权

shiro

public class AccountRealm extends AuthorizingRealm {@Autowiredprivate UserService userService;//。1 自定义的Realm@Override//授权protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了授权===》doGetAuthorizationInfo");SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//拿到当前登陆的对象Subject subject = SecurityUtils.getSubject();//拿到account对象user currentUser = (user) subject.getPrincipal();//设置当前用户权限info.addStringPermission(currentUser.getPerms());return info;}@Override//认证protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("执行了认证===》doGetAuthenticationInfo");//连接数据库UsernamePasswordToken Token = (UsernamePasswordToken) authenticationToken;user user = userService.queryUserByName(Token.getUsername());if (user != null) {return new SimpleAuthenticationInfo(user, user.getPassword(), getName());}return null;}
}
9.编写Shiro的配置类

config

@Configuration
public class ShiroConfig {//3. 连接前端  ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();//设置安全管理器bean.setSecurityManager(defaultWebSecurityManager);/* 添加Shiro的内置过滤器anon: 无需认证就可以访问authc: 必须认证了才能访问user:  必须拥有我 记住我 功能才能访问perms: 拥有对莫个资源的权限才能访问role:  拥有莫个角色权限才能访问*/LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();filterMap.put("/user/add", "perms[user:add]");//user,的add anon设置所有人可以访问filterMap.put("/user/update", "perms[user:update]");//user,的update authc设置认证了才能访问bean.setFilterChainDefinitionMap(filterMap);bean.setLoginUrl("/tologin");bean.setUnauthorizedUrl("/noauth");return bean;}//2. 接管对象  DafaultWebSecurityManager@Beanpublic DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") AccountRealm userRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();//关联userReal   接管reaml对象securityManager.setRealm(userRealm);return securityManager;}//1. 创建realm对象 、需要自定义@Beanpublic AccountRealm userRealm() {return new AccountRealm();}
}
10.编写controller控制器

controller

@Controller
public class MyController {@RequestMapping("/index")public String toIndex(Model model) {model.addAttribute("msgTest", "hello,shiro");return "index";}@RequestMapping("user/add")public String add() {return "user/add";}@RequestMapping("user/update")public String update() {return "user/update";}@RequestMapping("/tologin")public String toLonin() {return "login";}@RequestMapping("/login")public String login(String username, String password, Model model) {//获取当前的用户Subject subject = SecurityUtils.getSubject();//封装用户的登录数据UsernamePasswordToken token = new UsernamePasswordToken(username, password);try {//执行登录的方法subject.login(token);return "index";} catch (UnknownAccountException e) {//用户名不存在model.addAttribute("msg","用户名错误");return "login";}catch (IncorrectCredentialsException e){//密码错误model.addAttribute("msg","密码错误");return "login";}}@RequestMapping("/noauth")@ResponseBodypublic String unauthorized(){return "未授权无法访问此页面";}
}
11.编写controller对应的界面html

templates\index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head><meta charset="UTF-8"><title>shiro学习</title>
</head>
<body>
<H1>首页</H1>
<p th:test="${msgTest}"></p>
<hr>
<div shiro:hasPermission="user:add"></div>
<a th:href="@{/user/add}">add</a>
<div shiro:hasPermission="user:update"></div>
<a th:href="@{/user/update}">update</a>
</body>
</html>

templates\login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>shiro登录</title>
</head>
<body>
<div><p th:text="${msg}" style="color: #ff0000"></p><form method="get" th:action="@{/login}"><p>用户名:<input type="text" name="username"></p><p>密  码:<input type="text" name="password"></p><p><input type="submit" value="登录"></p></form>
</div>
</body>
</html>

templates\user\add.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>加一个用户</title>
</head>
<body>
<h1>add</h1>
</body>
</html>

templates\user\update.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>修改一个用户</title>
</head>
<body>
<h1>update</h1>
</body>
</html>
12.启动器测试

启动类上添加@MapperScan(“com.guohui.mapper”) 扫描你自己mapper

@SpringBootApplication
@MapperScan("com.guohui.mapper")
public class SpringbootShirotestApplication {public static void main(String[] args) {SpringApplication.run(SpringbootShirotestApplication.class, args);}
}

启动测试
用户认证 — 用户身份识别

用户授权 — 用户权限访问控制。

shiro完美解释

让 Apache Shiro 保护你的应用

springboot整合shiro+mybatis-plus相关推荐

  1. SpringBoot整合Shiro实现登录认证和授权CHCache

    文章目录 一. springboot实现普通登录 1 添加依赖 2 编写配置文件 3 新建实体类和mapper 4 编写业务层代码 5 编写控制器 6 编写启动类 7 编写登录页面和主页面 二. sp ...

  2. SpringBoot整合Shiro搭建登录注册认证授权权限项目模板

    主要内容: 1 SpringBoot整合Shiro安全框架; 2 Shiro主要学习内容总结;(执行流程.主要对象接口.注意事项等) 3 Redis实现对权限信息缓存; ! 温馨提示: 想要快速搭Sh ...

  3. SpringBoot整合Shiro学习(上)

    SpringBoot整合Shiro(上) 基于[编程不良人]2020最新版Shiro教程,整合SpringBoot项目实战教程 哔哩哔哩链接:https://www.bilibili.com/vide ...

  4. 降龙十八掌之 springboot整合shiro(含MD5加密)

    java学习爱好者 2019-05-27 16:21:00 开发环境: 1.mysql - 5.7.21 2.navicat(mysql客户端管理工具) 3.idea 2017 4.jdk9 5.to ...

  5. springboot整合shiro(超详细,你想要的都在这了)

    Springboot整合Shiro 文章目录 pom依赖 前端页面(thymeleaf整合shiro) thymeleaf中shiro标签解释 数据库(整合mybatis) 理解shiro的几个组成部 ...

  6. springboot整合shiro使用shiro-spring-boot-web-starter

    此文章仅仅说明在springboot整合shiro时的一些坑,并不是教程 增加依赖 <!-- 集成shiro依赖 --> <dependency><groupId> ...

  7. springboot整合shiro和session的详细过程和自定义登录拦截器

    文章目录 1.shiro依赖 2.shiro配置 shiro过滤器配置: 关联自定义的其他管理器 自定义会话工厂: 3.登陆时记录用户信息 4.shiro一些工具类的学习 5.自定义登录拦截器 shi ...

  8. 补习系列(6)- springboot 整合 shiro 一指禅

    欢迎添加华为云小助手微信(微信号:HWCloud002 或 HWCloud003),输入关键字"加群",加入华为云线上技术讨论群:输入关键字"最新活动",获取华 ...

  9. SpringBoot整合Shiro实现权限控制,验证码

    本文介绍 SpringBoot 整合 shiro,相对于 Spring Security 而言,shiro 更加简单,没有那么复杂. 目前我的需求是一个博客系统,有用户和管理员两种角色.一个用户可能有 ...

  10. SpringBoot 整合Shiro 一指禅

    目标 了解ApacheShiro是什么,能做什么: 通过QuickStart 代码领会 Shiro的关键概念: 能基于SpringBoot 整合Shiro 实现URL安全访问: 掌握基于注解的方法,以 ...

最新文章

  1. 日志服务(Log service)4月控制台更新指南
  2. Kotlin之?和!!最简单的理解
  3. 2016年《大数据》杂志调查问卷
  4. android style 与theme的区别
  5. 空降新书榜,霸占前三甲,还有什么是这些书做不到的?!
  6. 【Python实例第34讲】高斯过程分类:XOR数据集
  7. 我的Android进阶之旅------Android实现音乐示波器、均衡器、重低音和音场功能
  8. JAVA回调函数简单讲解 CallBack
  9. MMORPG大型游戏设计与开发(概述)updated
  10. 四、字符串(7):重复的子字符串
  11. (精华2020年6月2日更新) TypeScript函数详解
  12. 关于前端架构的过去、现在与未来
  13. 在移动网络上创建更稳定的连接
  14. launch计算机上哪个初中,这位妈妈10年夏校经验告诉你:小学初中高中都该如何选择夏校?...
  15. 【Auto.js脚本】淘宝618集喵币列车活动 自动浏览任务
  16. 兄弟Brother PT-9200DX 驱动
  17. c++,给成绩分等级
  18. 转专业考试c语言试题,C语言程序设计实训题目.doc
  19. 【CSS3动画】利用CSS3制作“百度浏览器”官网奔跑的北极熊效果(不含背景移动)
  20. C++Primer——第8章(IO库)

热门文章

  1. python中复制、浅层拷贝、深层拷贝的区别
  2. 常用思科设备图标(JPG+矢量图)
  3. java String长度与varchar长度匹配理解(字符和字节长度理解)
  4. 《中秋书月》月圆之夜,我和德鲁克
  5. 未能加载文件或程序集“System.Data.SQLite, Version=1.0.96.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139...
  6. JavaScript slice() 方法
  7. Resource interpreted as Script but transferred with MIME type text/plain:
  8. ExtJs 实现动态列,动态多表头 在这里添加日志标题
  9. List 在迭代时可能抛出的异常
  10. 华为鸿蒙公测链接,华为鸿蒙系统2.0启动第二轮公测,新增6款nova机型