简介:

  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. mysql使用唯一索引避免插入重复数据

    使用MySQL 索引防止一个表中的一列或者多列产生重复值 一:介绍MYSQL唯一索引 如果要强烈使一列或多列具有唯一性,通常使用PRIMARY KEY约束. 但是,每个表只能有一个主键. 因此,如果使 ...

  2. pta 6-7 统计某类完全平方数 (20分)

    6-7 统计某类完全平方数 (20分) 本题要求实现一个函数,判断任一给定整数N是否满足条件:它是完全平方数,又至少有两位数字相同,如144.676等. 函数接口定义: int IsTheNumber ...

  3. Docker安装之路

    从3月初到现在,一直在安装docker 的路上越走越远,大概就在1个小时前,我终于成功了,那一刻,我觉得我拥有了整个世界,于是乎,拥有了整个世界的我决定草率的并粗略的记录一下安装过程中遇到的我能记住的 ...

  4. ASP.NET MVC4 使用UEditor富文本

    原帖:http://user.qzone.qq.com/369175376/infocenter?ptlang=2052     第一步:先到http://ueditor.baidu.com/webs ...

  5. Java程序员学习Go指南(二)

    摘抄:https://www.luozhiyun.com/archives/211 Go中的结构体 构建结构体 如下: type AnimalCategory struct { kingdom str ...

  6. [NOI2005]维护数列(区间splay)

    [NOI2005]维护数列(luogu) 打这玩意儿真是要了我的老命 Description 请写一个程序,要求维护一个数列,支持以下 6 种操作:(请注意,格式栏 中的下划线‘ _ ’表示实际输入文 ...

  7. Liunx(centos8)下的yum的基本用法和实例

    yum 命令 Yum(全称为 Yellow dog Updater, Modified)是一个在Fedora和RedHat以及CentOS中的Shell前端软件包管理器.基于RPM包管理,能够从指定的 ...

  8. php--->使用callable强制指定回调类型

    php 使用callable强制指定回调类型 如果一个方法需要接受一个回调方法作为参数,我们可以这样写 <?php function dosth($callback){ call_user_fu ...

  9. qt creator源码全方面分析(0)

    本人主攻C++和Qt. 上两天刚研究完Qt install framework(IFW)应用程序安装框架. google没发现有正儿八经的官方文档的翻译,我就进行了翻译哈!! 系列文章具体见:http ...

  10. 记一次golang的内存泄露

    程序功能 此程序的主要功能是将文件中数据导入到clickhouse数据库中. [问题描述] 服务器内存每隔一段时间会耗尽 [问题分析] 由于使用的是go语言开发的,所以采用了业界流行的工具pprof. ...