Shiro
一、简介
Apache Shiro是一个功能强大且易于使用的Java安全框架,它执行身份验证,授权,加密和会话管理。使用Shiro易于理解的API,您可以快速轻松地保护任何应用程序-从最小的移动应用程序到最大的Web和企业应用程序。
github地址:https://github.com/apache/shiro
查看官方文档可以很快上手shiro,和Spring Security不同的是它定制度高一些,但是相对的配置更麻烦一些。
工作原理图:这个很重要!
二、快速上手
1、搭建环境
在github上下载整个zip文件,找到samples文件夹中的quickstart,在这里我用maven新建了一个项目,直接把quickstart的代码拷过去用的。项目结构如下:
2、pom.xml
可以看到shiro-core
和一些日志相关的依赖
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.6.0</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
3、resources
log4j.properties
:配置不用多说,一些日志配置其中有shiro的配置
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
shiro.ini
:shiro的启动配置文件,由四部分组成:
【main】、【users】、【roles】、【urls】 下面给出示例解释
# 内置SecurityManager对象,操作对象时,在[main]里写数据。
[main]
securityManager.属性=值
property=xxx
securityManager.对象属性=$property
[users]
# 定义用户名为xxx,密码为123
xxx=123
# 定义用户名为xxx,密码为123,同时具有a角色和b角色
xxx=123,a,b
[roles]
a=权限1,权限2
b=权限3,权限4
[urls]
# urlpath=内置Filter或自定义Filter
# 访问时出现/login的urlpath必须要验证,支持authc对应的Filter
/login=authc
# 任意的urlpath都不需要进行认证
/**=anno
# 所有的功能都必须保证用户已登录
/**=user
# url xxx访问时必须保证用户拥有角色a和角色b
/xxx=roles["a,b"]
案例:
# 只要是以/login.html开始的路径都放行
/login.html=anon
#所有的路径都放行
/**=anon
# 所有url必须认证通过后才能放行
/**=authc
# 匹配规则:只要满足一个规则就通过,因此如果要是用/**=anon,那么/**=anon要放在最后
4、QuickStart
在简介中提到,Shiro的重要三个部分为:Subject、SecurityManager、Realm
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
//SecurtiyManager工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();//获得实例
SecurityUtils.setSecurityManager(securityManager);//设置属性
//获取当前用户对象
Subject currentUser = SecurityUtils.getSubject();
//通过当前用户得到session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
//判断当前用户是否被认证
if (!currentUser.isAuthenticated()) {
//token令牌
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);//设置记住我
try {
currentUser.login(token);//执行登录操作
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
currentUser.logout();
System.exit(0);
}
}
运行结果如下:
三、Shiro整合Mybatis
1、搭建环境
建立config、controller、mapper、pojo、service包
目录结构如下:
2、pom.xml
整合需要的主要几个包:
- spring-boot-starter-web
- mysql
- druid
- mybatis-spring-boot-starter
- thymeleaf(2个包)
- shiro(2个包,整合Spring,整合themeleaf)
- log4j
- lombok
<dependencies>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
<!--引入mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<!--shiro整合spring包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.6.0</version>
</dependency>
<!--shiro和thymeleaf整合-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>13.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
3、application.yml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3307/mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许空时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.kuang.pojo
4、ShiroConfig
shiro配置,这里又要说起shiro核心3组件:SecurityManager,Subject,Realm
首先建立ShiroConfig.java需要在其中配置几个bean
//配置前台使用shiro
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
1、创建realm对象首先创建realm对象(UserRealm这个类一会再说)当然你也可以命名为MyRealm
//1、创建realm对象
@Bean(name = "userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
2、其次我们需要创建DefaultWebSecurityManager
//2、DefaultWebSecurityManager
//通过传参userRealm将2和1步骤绑定起来,@Qualifier("userRealm") 1的方法名即为默认传过来的参数名
@Bean(name = "defaultWebSecurityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
return securityManager;
}
3、ShiroFilterFactoryBean(这个方法返回的bean实际上是对我们的subject进行装饰的,比如过滤)
//3、ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean =new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//以map的方式添加shiro的内置过滤器
/*
anon:无需认证就可访问
auhtc:必须认证才能访问
user:必须拥有记住我才能用
perms:拥有某个资源的权限才能访问
role:拥有某个角色权限才能访问
// filterMap.put("/user/add", "authc");
// filterMap.put("/user/update", "authc")
*/
//拦截
Map<String, String> filterMap = new LinkedHashMap<>();
//授权:拥有特定权限才能访问,没有会跳转未授权页面
filterMap.put("/user/add", "perms[user:add]");
filterMap.put("/user/update", "perms[user:update]");
//设置登陆了才能访问user下的页面
filterMap.put("/user/*", "authc");
bean.setFilterChainDefinitionMap(filterMap);
//登录请求
bean.setLoginUrl("/toLogin");
bean.setUnauthorizedUrl("/unauthorized");
return bean;
}
这里返回来写UserRealm,就像Spring Security下的认证授权,注意先写认证再写授权!!!
这里注意User实体类中有一个perms字段用来保存用户的权限,比如用户aaa,perms字段值为:user:add 那么 用户aaa将有权访问user/add页面
public class UserRealm extends AuthorizingRealm {
@Autowired
UserServiceImpl userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=》授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//拿到当前登录对象
Subject subject = SecurityUtils.getSubject();
User currUser = (User)subject.getPrincipal();//拿到user对象
info.addStringPermission(currUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=》认证doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//通过userToken获得用户名,再从数据库获得用户
User user = userService.queryUserByName(userToken.getUsername());
if(user==null){
return null;//shiro的自动会报异常
}
Subject currSubject = SecurityUtils.getSubject();
Session session = currSubject.getSession();
session.setAttribute("loginUser", user);
//密码认证 shiro会做
//这里第一个参数放user,在上面重写的授权方法中才能拿到这个user,这是shiro内部已经做了的事情
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
5、Controller
这一层没有什么说的,就是玩一下
@Controller
public class MyController {
@RequestMapping({"/", "/index"})
public String toIndex(Model model){
model.addAttribute("msg", "hello,shiro");
return "index";
}
@RequestMapping("user/add")
public String add(Model model){
return "user/add";
}
@RequestMapping("user/update")
public String update(Model model){
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin(Model model){
return "login";
}
@RequestMapping("/login")
public String login(String username,String password,Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try{
subject.login(token);//执行登录方法
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg", "用户名错误");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg", "密码错误");
return "login";
}
}
//此方法测试用
@RequestMapping("/unauthorized")
@ResponseBody
public String unauthorized(){
return "未经授权无法访问此页面";
}
}
6、resources
主要是index页面和login页面,user/add和user/update就是测试权限新建两个空页面即可
index.html(注意引入shiro和th的命名空间)
<!DOCTYPE html>
<html lang="en"
xmlns:th=“http://www.thymeleaf.org”
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<div th:if="${session.loginUser==null}">
<a th:href="@{/toLogin}">登录</a>
</div>
<p th:text="${msg}"></p>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a>
</div>
</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>
<h1>登录</h1>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}">
<p>用户名:<input type="text" name="username"></p>
<p>密 码:<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>