简介:

  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的更多相关文章

  1. SpringBoot 优雅的整合 Shiro

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

  2. 在 springboot 中如何整合 shiro 应用 ?

     Shiro是Apache下的一个开源项目,我们称之为Apache Shiro. 它是一个很易用与Java项目的的安全框架,提供了认证.授权.加密.会话管理,与spring Security 一样都是 ...

  3. SpringBoot学习:整合shiro(身份认证和权限认证),使用EhCache缓存

    项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 (一)在pom.xml中添加依赖: <properties> <shi ...

  4. SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)

    首先在shiro配置类中注入rememberMe管理器 /** * cookie对象; * rememberMeCookie()方法是设置Cookie的生成模版,比如cookie的name,cooki ...

  5. SpringBoot学习:整合shiro(rememberMe记住我后自动登录session失效解决办法)

    项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 定义一个拦截器,判断用户是通过记住我登录时,查询数据库后台自动登录,同时把用户放入ses ...

  6. SpringBoot学习:整合shiro(验证码功能和登录次数限制功能)

    项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 (一)验证码 首先login.jsp里增加了获取验证码图片的标签: <body s ...

  7. SpringBoot学习:整合shiro(rememberMe记住我功能)

    项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 首先在shiro配置类中注入rememberMe管理器 /** * cookie对象; ...

  8. SpringBoot整合Shiro (二)

    Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码学和会话管理.相比较Spring Security,shiro有小巧.简单.易上手等的优点.所以很多框架都在使用sh ...

  9. SpringBoot整合Shiro 三:整合Mybatis

    搭建环境见: SpringBoot整合Shiro 一:搭建环境 shiro配置类见: SpringBoot整合Shiro 二:Shiro配置类 整合Mybatis 添加Maven依赖 mysql.dr ...

随机推荐

  1. Elastcisearch.Nest 7.x 系列`伪`官方翻译:通过 NEST 来快捷试用 Elasticsearch

    本系列已经已经全部完成,完整版可见:https://blog.zhuliang.ltd/categories/Elasticsearch/ 本系列博文是"伪"官方文档翻译(更加本土 ...

  2. node js 爬啊爬 记录 向 Scott 致敬 不要问为什么

    更优雅的异步编程: 定向爬取 :http://www.010xww.com/list/travel.htm 上代码: 打印一下http . 嗯 http 模块加载没问题 获取一个 文章列表: 终于把人 ...

  3. Windows玩转Kubernetes系列2-Centos安装Docker

    接上一章,Windows玩转Kubernetes系列1-VirtualBox安装Centos,我们开始学习如何在Centos中安装Docker 准备 关闭防火墙 防火墙一定要提前关闭,否则在后续安装K ...

  4. (初学JS)JS基础——ATM机终端程序编写<1.0>

    初步学习了JS基础,为了更好地将所学知识熟练运用,我进行了银行ATM存取款机的模拟程序编写,主要通过VScode终端实现系列操作. 我的ATM程序包括6个主要功能:1.查询余额 2.存钱 3. 取钱 ...

  5. Linux Centos7 在桌面添加快捷方式

    当时,刚刚安装好centos7,又下载好了jb家的软件,但是每一次都要用命令行才能运 我想要的是下面的效果,那是我后来才研究出来的 我看到了自动生成的为什么可以用,我的打开了源文件研究了一下 第一,先 ...

  6. ajax--->请求异常 jQuery提示parsererror错误解决办法

    ajax请求异常 jQuery提示parsererror错误解决办法 原因:出现这个错误是因为后端返回的数据类型和前端请求中dataType的要求类型不一致导致的. dataType简介:jquery ...

  7. 高阶函数及 map、reduce、filter 的实现

    博客地址:https://ainyi.com/85 2020 开年国家经历了不少困难,最为凶猛的局势就是新型冠状病毒的蔓延,国务院最终决定春节假期延长至==2 月 2 号==:公司决定 3 - 7 号 ...

  8. Spring Cache 抽象(缓存抽象) Redis 缓存

        积少成多 ----  仅以此致敬和我一样在慢慢前进的人儿 相关内容: https://blog.51cto.com/14230003/2369413?source=dra           ...

  9. spring实战第二章小记-装配bean

    时间:2020/02/06 一.思想 1.创建应用对象之间协作关系的行为通常称为装配,这也是依赖注入(DI)的本质. 对于上面这句话的个人理解:当我们在new一个对象时如果传入了别的对象作为参数(这个 ...

  10. 实验2: CDP命令操作

    基本命令 1.获设备的相邻信息:CDP CDP1.不管上层协议 能够获取的信息包括:1.设备名2.对应各协议的地址3.端口名4.角色特征5.平台 全局启用/关闭CDP:cdp run/no cdp r ...