说明

最近打算打造一个简易的权限管理系统,打算用shiro做认证和授权。本篇作为springboot集成shiro的入门实战案例记录下来,希望也可以帮到大家,代码整理自网络。

  • 技术栈
    springboot+shiro+thymeleaf+mysql

添加pom依赖

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>

定义用户权限模型

@Data
public class Account {
private Integer id;
private String username;
private String password;
// 权限
private String perms;
// 角色
private String role;
}
  • 对应表中数据:

自定义realm

public class AccoutRealm extends AuthorizingRealm {

    @Autowired
private AccountService accountService; /**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取当前登录的用户信息
Subject subject = SecurityUtils.getSubject();
Account account = (Account) subject.getPrincipal(); //设置角色
Set<String> roles = new HashSet<>();
roles.add(account.getRole());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles); //设置权限
info.addStringPermission(account.getPerms());
return info;
} /**
* 认证
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
Account account = accountService.findByUsername(token.getUsername());
if(account != null){
return new SimpleAuthenticationInfo(account,account.getPassword(),getName());
}
return null;
}
}

自定义shiro-config

@Configuration
public class ShiroConfig { @Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
factoryBean.setSecurityManager(securityManager);
//权限设置
Map<String,String> map = new Hashtable<>();
map.put("/main","authc");
map.put("/manage","perms[manage]");
map.put("/administrator","roles[administrator]");
factoryBean.setFilterChainDefinitionMap(map);
//设置登录页面
factoryBean.setLoginUrl("/login");
//设置未授权页面
factoryBean.setUnauthorizedUrl("/unauth");
return factoryBean;
} @Bean
public DefaultWebSecurityManager securityManager(@Qualifier("accoutRealm") AccoutRealm accoutRealm){
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
manager.setRealm(accoutRealm);
return manager;
} @Bean
public AccoutRealm accoutRealm(){
return new AccoutRealm();
} @Bean
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
}

创建登录控制器

@Controller
public class AccountController { @GetMapping("/{url}")
public String redirect(@PathVariable("url") String url){
return url;
} @PostMapping("/login")
public String login(String username, String password, Model model){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try {
subject.login(token);
Account account = (Account) subject.getPrincipal();
subject.getSession().setAttribute("account",account);
return "index";
} catch (UnknownAccountException e) {
e.printStackTrace();
model.addAttribute("msg","用户名错误!");
return "login";
} catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误!");
e.printStackTrace();
return "login";
}
} @GetMapping("/unauth")
@ResponseBody
public String unauth(){
return "未授权,无法访问!";
} @GetMapping("/logout")
public String logout(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "login";
}
}

创建页面

  • 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>Title</title>
<link rel="shortcut icon" href="#"/>
</head>
<body>
<h1>index</h1>
<div th:if="${session.account != null}">
<span th:text="${session.account.username}+'欢迎回来!'"></span><a href="/logout">退出</a>
</div>
<a href="/main">main</a> <br/>
<div shiro:hasPermission="manage">
<a href="manage">manage</a> <br/>
</div>
<div shiro:hasRole="administrator">
<a href="/administrator">administrator</a>
</div>
</body>
</html>
  • login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="shortcut icon" href="#"/>
</head>
<body>
<form action="/login" method="post">
<table>
<span th:text="${msg}" style="color: red"></span>
<tr>
<td>用户名:</td>
<td>
<input type="text" name="username"/>
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="password"/>
</td>
</tr>
<tr>
<td>
<input type="submit" value="登录"/>
</td>
</tr>
</table>
</form>
</body>
</html>

测试

实现的效果

1.访问根路径跳转到index.html
2.访问main页面跳转到登录页
3.登录成功后跳转到首页,根据用户拥有的角色和权限展示不通功能模块

源码

https://gitee.com/indexman/springboot-shiro

Shiro实战2-Springboot集成Shiro实战的更多相关文章

  1. SpringBoot集成Shiro并用MongoDB做Session存储

    之前项目鉴权一直使用的Shiro,那是在Spring MVC里面使用的比较多,而且都是用XML来配置,用Shiro来做权限控制相对比较简单而且成熟,而且我一直都把Shiro的session放在mong ...

  2. springboot集成shiro实现权限认证

    github:https://github.com/peterowang/shiro 基于上一篇:springboot集成shiro实现身份认证 1.加入UserController package ...

  3. SpringBoot集成Shiro 实现动态加载权限

    一.前言 本文小编将基于 SpringBoot 集成 Shiro 实现动态uri权限,由前端vue在页面配置uri,Java后端动态刷新权限,不用重启项目,以及在页面分配给用户 角色 . 按钮 .ur ...

  4. SpringBoot学习笔记(五):SpringBoot集成lombok工具、SpringBoot集成Shiro安全框架

    SpringBoot集成lombok工具 什么是lombok? 自动生成setget方法,构造函数,打印日志 官网:http://projectlombok.org/features/index. 平 ...

  5. SpringBoot集成Shiro安全框架

    跟着我的步骤:先运行起来再说 Spring集成Shiro的GitHub:https://github.com/yueshutong/shiro-imooc 一:导包 <!-- Shiro安全框架 ...

  6. springboot集成shiro 实现权限控制(转)

    shiro apache shiro 是一个轻量级的身份验证与授权框架,与spring security 相比较,简单易用,灵活性高,springboot本身是提供了对security的支持,毕竟是自 ...

  7. 【Shiro】SpringBoot集成Shiro

    项目版本: springboot2.x shiro:1.3.2 Maven配置: <dependency> <groupId>org.apache.shiro</grou ...

  8. SpringBoot集成Shiro实现权限控制

    Shiro简介 Apache Shiro是一个功能强大且易于使用的Java安全框架,用于执行身份验证,授权,加密和会话管理.使用Shiro易于理解的API,您可以快速轻松地保护任何应用程序-从最小的移 ...

  9. springboot 集成shiro

    首先看下shiro configuration 的配置,重要部分用红色标出了 package cn.xiaojf.today.shiro.configuration; import at.pollux ...

  10. SpringBoot集成Shiro

    Shiro是一个安全框架,控制登陆,角色权限管理(身份认证.授权.回话管理.加密) Shiro不会去维护用户,维护权限:这些需要通过realm让开发人员自己注入 1.在pom.xml中引入shiro的 ...

随机推荐

  1. 如何查看centos对于 TIME_WAIT 状态的 Socket 回收时间

    要查看系统对于 TIME_WAIT 状态的 Socket 回收时间,可以通过以下方式查询 TCP 数据结构中的相关字段值: cat /proc/sys/net/ipv4/tcp_fin_timeout ...

  2. Shell-全局变量-export

  3. [转帖]InfluxDB 修改数据存储路径

    1.创建数据存储目录 mkdir -p /home/data/influxdb 说明:目录可以根据实际情况进行修改. 2.设置目录访问权限 sudo chown influxdb.influxdb / ...

  4. [转帖]TiDB的使用限制

    https://docs.pingcap.com/zh/tidb/stable/tidb-limitations 本文会将详细描述 TiDB 中常见的使用限制,包括:标识符长度,最大支持的数据库.表. ...

  5. [转帖]Kafka故障之磁盘打满

    https://www.jianshu.com/p/095e820361ae 问:磁盘打满扩容后能正常重启吗?答:不一定 要看文件格式是否损坏(log.index等).如果损坏会报错:index fi ...

  6. [转帖]resin的安装与配置

    1.安装jdk 之前装过了,就不做演示了 vim /etc/profile   //注意java的配置文件 JAVA_HOME=/usr/local/jdk1.8/ JAVA_BIN=/usr/loc ...

  7. [转帖]nacos开启强鉴权

    注意 Nacos是一个内部微服务组件,需要在可信的内部网络中运行,不可暴露在公网环境,防止带来安全风险. Nacos提供简单的鉴权实现,为防止业务错用的弱鉴权体系,不是防止恶意攻击的强鉴权体系. 如果 ...

  8. Nginx 系列 | (转)Nginx 上传文件:client_max_body_size 、client_body_buffer_size

    原文:http://php-note.com/article/detail/488 client_max_body_size client_max_body_size 默认 1M,表示 客户端请求服务 ...

  9. 神经网络优化篇:详解超参数调试的实践:Pandas VS Caviar(Hyperparameters tuning in practice: Pandas vs. Caviar)

    超参数调试的实践 如今的深度学习已经应用到许多不同的领域,某个应用领域的超参数设定,有可能通用于另一领域,不同的应用领域出现相互交融.比如,曾经看到过计算机视觉领域中涌现的巧妙方法,比如说Confon ...

  10. VictoriaMetrics 1.73.1 值得关注的新特性

    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu 公众号:一本正经的瞎扯 VictoriaMetrics 1.73.1 的changelog: h ...