简介:

  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. Ubuntu中部署Django项目的配置与链接MySQL

    Django的简介 MVT模式的介绍创建项目的虚拟环境 本次使用的是pip安装 一.更新 sudo apt update 二.安装pip sudo apt install python3-pip 三. ...

  2. selenium,测试套件的使用

    学习 selenium-webdriver 已经一段时间了,最近学习到,测试用例的批量执行,和测试套件的使用,有点自己的理解,不晓得对不对,希望大家指正!   写一个测试用例 baidu.py   c ...

  3. ios--->上下拉刷新控件MJRefresh

    上下拉刷新控件MJRefresh 一.类结构 MJRefreshComponent.h MJRefreshHeader.h MJRefreshFooter.h MJRefreshAutoFooter. ...

  4. xhsell关闭jupyter仍然运行的命令

    nohup jupyter notebook & nohup 和 &都是linux的命令 1.& 当在前台运行某个作业时,终端被该作业占据:可以在命令后面加上& 实现后 ...

  5. Centos 7 下部署集群式阿波罗

    apollo工作原理 用户通过浏览器登录Portal管理界面 >> 通过Admin server对配置进行修改 >> 应用程序主动向config server配置注意:Port ...

  6. learn more ,study less(三):超越整体性学习

    高效率的学生 成为一名高效率学生或是自学者需 要掌握减少花在书本上时间的艺术,我上学时,除了全日制的上课学习,业余时间经营一家 企业,每周写大约 7000 字,健身以及主持一家演讲俱乐部,尽管如此,我 ...

  7. linux 命令全名

    su:Swith user  切换用户,切换到root用户cat: Concatenate  串联uname: Unix name  系统名称df: Disk free  空余硬盘du: Disk u ...

  8. js中函数this的指向

    this 在面试中,js指向也常常被问到,在开发过程中也是一个需要注意的问题,严格模式下的this指向undefined,这里就不讨论. 普通函数 记住一句话哪个对象调用函数,该函数的this就指向该 ...

  9. <背包>solution_CF366C_Dima and Salad

    Dima and Salad Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. T ...

  10. SSH(三)

    在Spring中引用属性文件:    优点:        1.防止随意更改jdbc的连接        2.给不懂代码的人使用    步骤:        1.数据库连接信息写在属性文件中      ...