SpringBoot安全管理--(三)整合shiro
简介:
Apache Shiro 是一一个开源的轻量级的Java安全框架,它提供身份验证、授权、密码管理以及会话管理等功能。
相对于Spring Security, Shiro框架更加直观、易用,同时也能提供健壮的安全性。在传统的SSM框架中,手动整合Shiro的配置步骤还是比较多的,针对Spring Boot, Shiro 官方提供了shiro-spring-boot-web-starter 用来简化Shiro 在Spring Boot 中的配置。
pom.xml
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId> //已经依赖spring-boot-web-starter
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
application.properties
#开启shiro
shiro.enabled=true
#开启shiro web
shiro.web.enabled=true
#登陆地址,默认/login.jsp
shiro.loginUrl=/login
#登陆成功地址
shiro.successUrl=/index
#未获授权跳转地址
shiro.unauthorizedUrl=/unauthorized
#是否允许通过url进行会话跟踪,默认true
shiro.sessionManager.sessionIdUrlRewritingEnabled=true
#是否允许通过Cookie实现会话跟踪
shiro.sessionManager.sessionIdCookieEnabled=true
配置shiro
@Configuration
public class ShiroConfig {
@Bean
public Realm realm() {//添加用户
TextConfigurationRealm realm = new TextConfigurationRealm();
realm.setUserDefinitions("sang=123,user\n admin=123,admin"); //添加用户名+密码+角色
realm.setRoleDefinitions("admin=read,write\n user=read"); //添加权限
return realm;
}
@Bean #添加过滤规则
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition chainDefinition =
new DefaultShiroFilterChainDefinition();
chainDefinition.addPathDefinition("/login", "anon"); //可以匿名访问
chainDefinition.addPathDefinition("/doLogin", "anon"); //同上
chainDefinition.addPathDefinition("/logout", "logout"); //注销登陆
chainDefinition.addPathDefinition("/**", "authc"); //其余请求都需要认证后擦可以访问
return chainDefinition;
}
@Bean
public ShiroDialect shiroDialect() { //可以在Thymeleaf中使用shiro标签
return new ShiroDialect();
}
}
controller:
@Controller
public class UserController {
@GetMapping("/hello")
public String hello() {
return "hello shiro!";
}
@PostMapping("/doLogin")
public String doLogin(String username, String password, Model model) {
UsernamePasswordToken token =
new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token); //登陆
} catch (AuthenticationException e) {
model.addAttribute("error", "用户名或密码输入错误!");
return "login";
}
return "redirect:/index";
}
@RequiresRoles("admin") //admin角色
@GetMapping("/admin")
public String admin() {
return "admin";
}
@RequiresRoles(value = {"admin","user"},logical = Logical.OR) //admin或者user任意一个都可以
@GetMapping("/user")
public String user() {
return "user";
}
}
对于不需要角色就可以访问的页面
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/unauthorized").setViewName("unauthorized");
}
}
全局异常处理:
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(AuthorizationException.class)
public ModelAndView error(AuthorizationException e) {
ModelAndView mv = new ModelAndView("unauthorized");
mv.addObject("error", e.getMessage());
return mv;
}
}
新建5个页面:

admin.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>管理员页面</h1>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>Hello, <shiro:principal/></h3>
<h3><a href="/logout">注销登录</a></h3>
<h3><a shiro:hasRole="admin" href="/admin">管理员页面</a></h3>
<h3><a shiro:hasAnyRoles="admin,user" href="/user">普通用户页面</a></h3>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form action="/doLogin" method="post">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<div th:text="${error}"></div>
<input type="submit" value="登录">
</form>
</div>
</body>
</html>
unauthorized.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<h3>未获授权,非法访问</h3>
<h3 th:text="${error}"></h3>
</div>
</body>
</html>
user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>普通用户页面</h1>
</body>
</html>
访问http://localhost:8080/login

由于上面的shiro配置,可以匿名访问
输入我们在shiro配置的2用户

sang/123

admin/123

不同角色,权限不一样,页面也不一样
SpringBoot安全管理--(三)整合shiro的更多相关文章
- SpringBoot 优雅的整合 Shiro
Apache Shiro是一个功能强大且易于使用的Java安全框架,可执行身份验证,授权,加密和会话管理.借助Shiro易于理解的API,您可以快速轻松地保护任何应用程序 - 从最小的移动应用程序到最 ...
- 在 springboot 中如何整合 shiro 应用 ?
Shiro是Apache下的一个开源项目,我们称之为Apache Shiro. 它是一个很易用与Java项目的的安全框架,提供了认证.授权.加密.会话管理,与spring Security 一样都是 ...
- SpringBoot学习:整合shiro(身份认证和权限认证),使用EhCache缓存
项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 (一)在pom.xml中添加依赖: <properties> <shi ...
- SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)
首先在shiro配置类中注入rememberMe管理器 /** * cookie对象; * rememberMeCookie()方法是设置Cookie的生成模版,比如cookie的name,cooki ...
- SpringBoot学习:整合shiro(rememberMe记住我后自动登录session失效解决办法)
项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 定义一个拦截器,判断用户是通过记住我登录时,查询数据库后台自动登录,同时把用户放入ses ...
- SpringBoot学习:整合shiro(验证码功能和登录次数限制功能)
项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 (一)验证码 首先login.jsp里增加了获取验证码图片的标签: <body s ...
- SpringBoot学习:整合shiro(rememberMe记住我功能)
项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 首先在shiro配置类中注入rememberMe管理器 /** * cookie对象; ...
- SpringBoot整合Shiro (二)
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码学和会话管理.相比较Spring Security,shiro有小巧.简单.易上手等的优点.所以很多框架都在使用sh ...
- SpringBoot整合Shiro 三:整合Mybatis
搭建环境见: SpringBoot整合Shiro 一:搭建环境 shiro配置类见: SpringBoot整合Shiro 二:Shiro配置类 整合Mybatis 添加Maven依赖 mysql.dr ...
随机推荐
- python+autoit用法
一.自己封装的一些使用到的autoit库 import autoit class MouseControl(object): ''' AutoIt鼠标相关操作 ''' def __init__(sel ...
- Java之函数式接口@FunctionalInterface详解(附源码)
Java之函数式接口@FunctionalInterface详解 函数式接口的定义 在java8中,满足下面任意一个条件的接口都是函数式接口: 1.被@FunctionalInterface注释的接口 ...
- selenium + PhantomJS使用时 PhantomJS报错解决
selenium + PhantomJS使用时 PhantomJS报错解决 在做动态网页爬虫时用到了selenium + PhantomJS,安装好之后运行时报错: UserWarning: Sele ...
- 光流法draw_flow()函数报错
光流法draw_flow()函数报错 import cv2 from scipy import * def draw_flow(im, flow, step=16): ""&quo ...
- SelectiveSearchCodeIJCV遇到First two input arguments should have the same 2D dimension
在windows 10+visual studio环境下运行SelectiveSearchCodeIJCV中的demo.m难免会出现下列错误 ----------------------- if(~e ...
- 设计模式-03工厂方法模式(Factory Method Pattern)
插曲.简单工厂模式(Simple Factory Pattern) 介绍工厂方法模式之前,先来做一个铺垫,了解一下简单工厂模式,它不属于 GoF 的 23 种经典设计模式,它的缺点是增加新产品时会违背 ...
- Hyper-V虚拟机设置外部网络访问
在Hyper-V管理器中新建一个虚拟交换机,类型为 内部 ,修改名称为 nat 在虚拟机的设置页面中,将网络适配器设置为新建的虚拟交换机 nat 打开win10->控制面板->网络和共享中 ...
- 转载: Java虚拟机:运行时内存数据区域、对象内存分配与访问
转载: https://blog.csdn.net/a745233700/article/details/80291694 (虽然大部分内容都其实是深入理解jvm虚拟机这本书里的,不过整理的很牛逼 ...
- 优雅对API进行内部升级改造
优雅对API进行内部升级改造 背景 随着业务的快速发展老的系统将逐渐的无法快速支撑现有业务迭代重构一个必然的过程;然而在底层业务系统重构的过程中,对外提供的API也同时需要进行相应的升级替换;推动外部 ...
- 西门子PLC在自动浇灌系统中的应用
西门子PLC在自动浇灌系统中的应用(鸿控整理) 2020-02-07 22:50:48 1 自动浇灌系统简介 系统采用自行研制的湿度传感器监测土壤的湿度情况,当土壤湿度低于所要求的值后,自动开启水泵电 ...