一、引入依赖

 <!-- Spring Boot SpringMVC 框架 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok-->
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version>
</dependency>
<!-- 热部署 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional><scope>true</scope>
</dependency>
<!-- MySQL 连接驱动依赖 -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.39</version>
</dependency>
<!--Mybatis-Plus依赖-->
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version>
</dependency>
<!-- thymeleaf依赖 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- shiro依赖 -->
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.4.0</version>
</dependency>
<!-- 配置数据源 -->
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version>
</dependency>
<!-- thymeleaf-shiro依赖 -->
<dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version>
</dependency>

二、配置application.yml配置文件

# 配置端口号
server:port: 8888
spring:# 配置数据源datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/study?useSSL=falseusername: rootpassword: admin# 配置数据库连接池type: com.alibaba.druid.pool.DruidDataSource#配置MyBatis-Plus
mybatis-plus:# 配置别名type-aliases-package: com.wx.springboot_shiro.entity# 配置xxxMapper.xml文件地址mapper-locations:classpath: mapper/*.xml

三、编写实体类 User

  数据库表中的字段与实体类字段相同

  直接使用lombok注解来进行有参无参构造和Getter/Setter方法

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private Long id;private String name;private String password;}

四、编写dao层user的mapper接口

  在接口上加上@Mapper注解,或在启动类上添加@MapperScan("mapper接口所在路径")

  因为使用的是MyBatis-Plus,所以直接继承BaseMapper<实体类名>即可

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

五、编写业务层接口以及实现业务层接口

public interface UserService {User getUserByName(String name);}
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.springboot_shiro.dao.UserMapper;
import com.wx.springboot_shiro.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @author iuxin* @date create in 20:33 2022/4/16* @apiNote*/
@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic User getUserByName(String name) {QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();userQueryWrapper.eq("name",name);return userMapper.selectOne(userQueryWrapper);}
}

六、Controller表现层

@Controller
public class UserController {@RequestMapping("/testThymeleaf")public String testThymeleaf(Model model){model.addAttribute("name","Hello");return "test";}@RequestMapping("/login")public String login(String name,String password,Model model){// 使用Shiro编写认证操作// 1、获取SubjectSubject subject = SecurityUtils.getSubject();// 2、封装用户数据UsernamePasswordToken token = new UsernamePasswordToken(name, password);// 3、执行登录方法try {subject.login(token);// 登录成功跳转到test.htmlreturn "redirect:/testThymeleaf";}catch (UnknownAccountException e) {// 登录失败,用户不存在model.addAttribute("msg","用户不存在");return "login";}catch (IncorrectCredentialsException e) {//登录失败:密码错误model.addAttribute("msg", "密码错误");return "login";}}@RequestMapping("/toLogin")public String toLogin(Model model){return "login";}}

七、shiro包

ShiroConfig类可以进行过滤

@Configuration
public class ShiroConfig {/*** 配置ShiroDialect,用于thymeleaf和shiro标签配合使用* @return*/@Beanpublic ShiroDialect getShiroDialect(){return new ShiroDialect();}@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();// 设置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);// 添加Shiro内置过滤器/*** Shiro内置过滤器,可以实现权限相关的拦截器* 常用的过滤器* anon::无需认证(登录)可以访问* authc:必须认证才可以访问* user:如果使用rememberMe的功能可以直接访问* perms:该资源必须得到资源权限才可以访问* role:该资源必须得到角色权限才可以访问*/Map<String,String> filterMap = new LinkedHashMap<String, String>();filterMap.put("/testThymeleaf","anon");filterMap.put("/login","anon");// 过滤器的授权filterMap.put("/add","perms[user:add]");filterMap.put("/**","authc");// 修改调整的登录页面shiroFilterFactoryBean.setLoginUrl("/toLogin");// 设置未授权提示页面shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);return shiroFilterFactoryBean;}@Bean(name = "securityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();// 关联realmsecurityManager.setRealm(userRealm);return securityManager;}@Bean(name = "userRealm")public UserRealm getRealm(){return new UserRealm();}}

UserRealm类继承AuthorizingRealm 并重写它的两个方法,一个是授权逻辑,一个是认证逻辑。

再将Servive业务层注入。

public class UserRealm extends AuthorizingRealm {@Autowiredprivate UserService userRealm;@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行授权逻辑");// 给资源进行授权SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();// 添加资源的授权字符串info.addStringPermission("user:add");return info;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("执行认证逻辑");// 填写Shiro判断逻辑 判断用户名和密码// 1、判断用户名UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;User userByName = userRealm.getUserByName(token.getUsername());if(userByName == null){// 用户名不存在return null; // Shiro底层会抛出UNKnowAccountException}// 2、判断密码return new SimpleAuthenticationInfo("",userByName.getPassword(),"");}
}

八、在recources包下的templates包内创建两个HTML页面

整个项目结构

login.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>登录页面</title>
</head>
<body>
<h3>登录</h3>
<form method="post" action="login">用户名:<input type="text" name="name" /><br/>密码:<input type="password" name="password" /><br/><input type="submit" value="登录" />
</form>
</body>
</html>

test.html

<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head><meta charset="UTF-8"><title>thymeleaf</title>
</head>
<body>
<h1 th:text="${name}"></h1><hr/>
<div shiro:hasPermission="user:add">进入用户添加功能:<a href="add">用户添加</a>
</div><a href="toLogin">登录</a>
</body>
</html>

完整项目与数据库下载地址:

https://wwm.lanzoul.com/i6t3e03bjv2h
密码:Shiro

end.

SpringBoot + MyBatis-Plus + Shiro授权认证相关推荐

  1. springboot+mybatis整合shiro——登录认证和权限控制

    引依赖 shiro-all包含shiro所有的包.shiro-core是核心包.shiro-web是与web整合.shiro-spring是与spring整合.shiro-ehcache是与EHCac ...

  2. 使用Redis缓存Shiro授权认证信息,搭建集群权限系统

    应用如果做负载均衡,集群间session需要共享,如果session没有共享,用户登录系统以后session保存在登录的应用里面,其他应用里面没有session,没有登陆状态,访问会失败.下面介绍一个 ...

  3. Java项目学校教务教学管理系统源码,基于springboot+mybatis+layui+shiro+jquery开发

    Java学校教务管理系统源码 技术:springboot+mybatis+layui+shiro+jquery 运行环境:jdk8+mysql5.7+IntelliJ IDEA+maven  源码类型 ...

  4. authc过滤器 shiro_使用Shiro实现认证和授权(基于SpringBoot)

    Apache Shiro是一个功能强大且易于使用的Java安全框架,它为开发人员提供了一种直观,全面的身份验证,授权,加密和会话管理解决方案.下面是在SpringBoot中使用Shiro进行认证和授权 ...

  5. 【Vue+SpringBoot】超详细!一周开发一个SpringBoot + Vue+MybatisPlus+Shiro+JWT+Redis前后端分离个人博客项目!!!【项目完结】

    项目目录 资源准备 前后端分离项目 技术栈 Java后端接口开发 1.前言 2.新建Springboot项目 3.整合mybatis plus 3.统一结果封装 4.整合shiro+jwt,并会话共享 ...

  6. Shiro+springboot+mybatis+EhCache(md5+salt+散列)认证与授权-03

    从上文:Shiro+springboot+mybatis(md5+salt+散列)认证与授权-02 当每次进行刷新时,都会从数据库重新查询数据进行授权操作,这样无疑给数据库造成很大的压力,所以需要引入 ...

  7. Shiro+springboot+mybatis(md5+salt+散列)认证与授权-02

    代码延续地址:Shiro+springboot+mybatis(md5+salt+散列)认证与授权-01 1.创建t_role角色表(比如管理员admin,普通用户user等),创建t_pers权限表 ...

  8. Shiro+springboot+mybatis(md5+salt+散列)认证与授权-01

    这个小项目包含了注册与登录,使用了springboot+mybatis+shiro的技术栈:当用户在浏览器登录时发起请求时,首先这一系列的请求会被拦截器进行拦截(ShiroFilter),然后拦截器根 ...

  9. Springboot整合shiro基于url身份认证和授权认证

    你还不会shiro吗? 前奏 shiro核心配置文件(rolesFilter可选). 身份认证 多表登录源如何操作? 授权管理 如何解决界面多角色/资源问题 访问效果 权限管理在日常开发中很重要,所以 ...

最新文章

  1. Android之了解ThreadLocal
  2. 防止Stack smash的技术
  3. 多媒体技术生态未来的三个关键要素
  4. 《孩子,你如此优美:一位作家母亲的家教笔记》
  5. mysql5.5怎么删除字段_Linux 上 Mysql5.5 只能新建表中的字段不能删除表,权限root...
  6. 即时配送的ETA问题之亿级样本特征构造实践
  7. 日常视频一秒变游戏,人物可以随意操控:全靠Facebook的实时算法
  8. ftp挂载分区上去后无法识别的问题
  9. 从硬件竞争到软实力PK——电视媒体竞争观察
  10. cad二次开发程序的绿色安装
  11. IDEA配置-无法读取src/java/main下hbm.xml等资源文件
  12. vs2015完全卸载+重装 成功解决 未能加载xx包、未能安装编译器等问题
  13. html设计判断闰年,判断是否是闰年_JavaScript判断是否闰年 闰年计算方法
  14. 安装multisim后汉化过程中,无法创建文件夹拒绝访问怎么办
  15. 企业自动运行系统——定价策略
  16. 阿尔法贝塔阀原理_阿尔法(α)和贝塔(β)的通俗解释
  17. 彩色二维码生成器,带logo文字和中心文字
  18. mysql count判断_【MySQL】COUNT
  19. Excel快速下拉填充序列至10000行
  20. Java高级特性 - 多线程练习题

热门文章

  1. 基于pytorch的segnet实现,使用camvid数据集训练
  2. Brain:临床前和早期阿尔茨海默病的睡眠和纵向认知表现
  3. 小甲鱼零基础入门学习Python(绝对干货,值得学习)
  4. MATLAB 3D玫瑰花绘制(内附旋转版本)
  5. 2022 CCF BDCI 返乡发展人群预测 [0.9117+]
  6. 数据可视化如何实现?4大基本流程了解一下
  7. 比搞笑诺奖还离谱,看完国产AIGC最新创作,把我给整不会了
  8. 7-12 编程实现两个分数相加
  9. unity编辑器扩展--Inspector自定义编辑
  10. 动态规划算法学习(一)爬楼梯和凑金额