Shiro框架入门
一、Shiro概述
1.1 什么是Shiro
.
Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能。
对于任何一个应用程序,Shiro都可以提供全面的安全管理服务。其不仅可以用在JavaSE环境,也可以用在JavaEE环境。
1.2 shiro特性
- Authentication:身份认证 / 登录,验证用户是不是拥有相应的身份;
- Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限。如:验证某个用户是否拥有某个角色,或者细粒度的验证某个用户对某个资源是否具有某个权限。
- Session Management:会话管理。用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中。会话可以是普通 JavaSE 环境,也可以是 Web 环境。
- Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
- Web Support:Web 支持,可以非常容易的集成到 Web 环境;
- Caching:缓存,比如用户登录后,其用户信息、拥有的角色 / 权限不必每次去查,这样可以提高效率;
- Concurrency:多线程应用的并发验证,如在一个线程中开启另一个线程,能把权限自动传播过去;
- Testing:提供测试支持;
- Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
- Remember Me:记住我,即一次登录后,下次再来的话不用登录了。
1.3 shiro三层架构
Subject:当前用户;SecurityManager:管理所有用户; Realm:连接数据。
- Subject:主体,代表了当前 “用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是 Subject,如网络爬虫,机器人等;即一个抽象概念;所有 Subject 都绑定到 SecurityManager,与 Subject 的所有交互都会委托给 SecurityManager;可以把 - Subject 认为是一个门面;SecurityManager 才是实际的执行者;
- SecurityManager:安全管理器;即所有与安全有关的操作都会与 SecurityManager 交互;且它管理着所有 Subject;可以看出它是 Shiro 的核心,它负责与后边介绍的其他组件进行交互,如果学习过 SpringMVC,你可以把它看成 DispatcherServlet 前端控制器;
- Realm:域,Shiro 从 Realm 获取安全数据(如用户、角色、权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定用户身份是否合法;也需要从 Realm 得到用户相应的角色 / 权限进行验证用户是否能进行操作;可以把 Realm 看成 DataSource,即安全数据源。
二、Shiro快速开始
1.添加依赖
2.配置resources
3.配置Java类:Quickstart.java
// 获取当前用户对象Subject
Subject currentUser = SecurityUtils.getSubject();
// 通过当前用户获取Sessiion
Session session = currentUser.getSession();
currentUser.isAuthenticated() // 判断当前的用户是否被认证
currentUser.getPrincipal() // 获取当前用户角色
currentUser.hasRole("schwartz") //判断当前用户是否有"schwartz"角色
currentUser.isPermitted("lightsaber:wield") //判断是否有"lightsaber:wield"权限,粗粒度
currentUser.isPermitted("winnebago:drive:eagle5") //判断是否有"lightsaber:wield"权限,细粒度
currentUser.logout() //注销
三、SpringBoot整合Shiro
- 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- 1.SpringBoot整合MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- 2.SpringBoot整合Shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.11.0</version>
</dependency>
<!-- 3.Thymeleaf整合Shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.1.0</version>
</dependency>
- MyBatis配置文件
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/oa?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource #使用Druid连接池
#Druid数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
mybatis:
type-aliases-package: com.myapps.springdata.pojo
mapper-locations: classpath:mapper/*.xml
- MyBatis数据层(pojo、dao=mapper、service)
//1.pojo类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String username;
private String password;
private String right;
}
//2.mapper接口(dao层)
@Repository
@Mapper
public interface IUserMapper {
User findByName(String username);
}
//3.mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--映射IUserMapper接口中的方法-->
<mapper namespace="com.myapps.shirospringboot.mapper.IUserMapper">
<!--调用IUserMapper接口中的findByName()方法,返回结果集为User类-->
<select id="findByName" parameterType = "String" resultType="com.myapps.shirospringboot.pojo.User">
select * from USER_INFO where USERNAME = #{username}
</select>
</mapper>
//4.service层
public interface IUserService {
User findByName(String username);
}
@Service
public class UserService implements IUserService{
@Resource
private IUserMapper userMapper;
@Override
public User findByName(String username) {
return userMapper.findByName(username);
}
}
- controller层
@Controller
public class IndexController {
@RequestMapping({"/","/index","index.html"})
public String toIndex(Model model){
model.addAttribute("msg","Springboot整合shiro");
return "index";
}
@RequestMapping("/add")
public String toAdd(){
return "user/add";
}
@RequestMapping("/update")
public String toUpdate(){
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/login")
public String login(String username,String password,Model model){
Subject currentUser = SecurityUtils.getSubject(); //获取当前用户
UsernamePasswordToken token = new UsernamePasswordToken(username,password);//封装用户登录数据
try {
currentUser.login(token); //执行了登录
return "index";
} catch (UnknownAccountException e) {
model.addAttribute("msg","用户名不存在!");
return "login";
} catch (IncorrectCredentialsException e) {
model.addAttribute("msg","密码不正确!");
return "login";
}
}
@RequestMapping("/unAuth")
@ResponseBody
public String unAuth(){
return "对不起,您无权访问,请先开通会员!";
}
}
- 登录拦截ShiroConfig
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean:Subject 登录拦截
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("manager") DefaultWebSecurityManager manager){
ShiroFilterFactoryBean been = new ShiroFilterFactoryBean();
been.setSecurityManager(manager);//设置SecurityManager
//添加Shiro内置过滤器 anno:无需认证 authc:必须认证 user:必须有“记住我”功能 perms[]:拥有某个资源的权限 roles:拥有某个角色权限
Map<String, String> filterMap = new LinkedHashMap<>();
//有权限时正常打开页面,无权限时跳到未授权页面
filterMap.put("/add", "perms[user:add]");
filterMap.put("/update", "perms[user:update]");
been.setFilterChainDefinitionMap(filterMap);
been.setLoginUrl("/toLogin"); //认证失败跳转到登录页
been.setLoginUrl("/unAuth"); //无权限时跳到未授权页面
return been;
}
//DefaultWebSecurityManager:SecurityManager
@Bean(name="manager")
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("realm") UserRealm realm){
DefaultWebSecurityManager manager= new DefaultWebSecurityManager();
manager.setRealm(realm); //关联Realm
return manager;
}
//创建realm对象:Realm
@Bean(name="realm")
public UserRealm userRealm(){
return new UserRealm();
}
//Thymeleaf整合Shiro
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
- 登录认证与用户授权
public class UserRealm extends AuthorizingRealm {
@Resource
private IUserService userService;
//登录认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("正在登录认证...");
UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken; //将参数中的authenticationToken转换为封装的Token类型
//获取数据库用户(service层)
User user = userService.findByName(userToken.getUsername());
if(user == null){
return null;
}
//登录成功后将用户保存在Shiro Session中,供html使用
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("loginUser", user);
//参数:1.将user传递给用户授权使用(可为“”) 2.将密码传递给Shiro底层做验证 3.为“”
return new SimpleAuthenticationInfo(user,user.getPassword(),"");
}
//用户授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("正在授权...");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //授权对象
Subject subject = SecurityUtils.getSubject(); //获取Subject
User currentUser = (User) subject.getPrincipal();//获取登录认证中传入的参数user
info.addStringPermission(currentUser.getRight());//获取当前用户的权限给授权对象
return info;
}
}
- 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>Index</title>
</head>
<body>
<h2>首页</h2>
<div th:text="${msg}"></div>
<hr>
<div th:if="${session.loginUser == null}"> //未登录显示登录按钮
<a th:href="@{/toLogin}">登录</a>
</div>
<div shiro:hasPermission="user:add"> //有user:add权限才会显示
<a th:href="@{/add}">add</a>
</div>
<div shiro:hasPermission="user:update"> //有user:update权限才会显示
<a th:href="@{/update}">update</a>
</div>
</body>
</html>
<!-- 登录页 -->
<div th:text="${msg}" style="color: red"></div>
<form th:action="@{/login}">
<div>用户名:<input type="text" name="username"></div>
<div>密码:<input type="text" name="password"></div>
<div><input type="submit"></div>
</form>