shiro的一套配置
@[TOC]
1、快速开始(QuickStart)
1.1、通过shiro.ini配置角色和权限
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president,goodguy
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
1.2、pom.xml
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
1.3、Log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
1.4、快速开始注释QuickStart.java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
//加载shiro.ini配置文件,前三行是配置一个简单的shiro环境
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//得到当前正在执行的用户
Subject currentUser = SecurityUtils.getSubject();
//得到当前用户的session(shiro独有的session)
Session session = currentUser.getSession();
//给session里面设置属性和值
session.setAttribute("xiaoqiu", "lulu");
String value = (String) session.getAttribute("xiaoqiu");
if (value.equals("lulu")) {
log.info("当前属性xiaoqiu的值为: [" + value + "]");
}
// 首先判断是否已经登录
if (!currentUser.isAuthenticated()) {
//虚拟一个用户名和密码,根据用户名和密码生成令牌
UsernamePasswordToken token = new UsernamePasswordToken("presidentskroob", "12345");
//设置记住我
token.setRememberMe(true);
try {
//执行登录操作
currentUser.login(token);
} catch (UnknownAccountException uae) {
//未知的用户异常
log.info("这是一个未知的用户: " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("密码错误:" + token.getPrincipal());
} catch (LockedAccountException lae) {
//账号被锁定
log.info("这个账号已经被锁定: " + token.getPrincipal());
}catch (AuthenticationException ae) {
// 最高权限的异常,前面的没有捕获,必定被这个捕获
log.info("认证异常");
}
}
//获得当前用户认证的用户名
log.info("你的用户名是 [" + currentUser.getPrincipal() + "]");
//检测用户的角色
if (currentUser.hasRole("schwartz")) {
log.info("你当前的用户角色是:schwartz");
} else {
log.info("你还没有`schwartz`角色");
}
//检测用户的权限
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("你已经拥有权限lightsaber:wield");
} else {
log.info("你没有lightsaber:wield权限");
}
//检测用户的权限
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("你已经拥有权限winnebago:drive:eagle5");
} else {
log.info("你没有winnebago:drive:eagle5权限");
}
System.exit(0);
}
}
2、springboot-shiro
2.1、application.yml(配置数据库,整合mybatis)
spring:
datasource:
username: root
password: root
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.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:
type-aliases-package: com.yishuai.springbootshiro.pojo
mapper-locations: classpath:mapper/*.xml
2.2、shiroConfig.java(shiro的配置文件)
package com.yishuai.springbootshiro.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @AuThor yishuai
* @description shiro配置文件
* @date 2021/4/9 10:48 上午
*/
@Configuration
public class ShiroConfig {
/**
* 创建 ShiroFilterFactoryBean
* 通过Qualifier方法,获得spring容器中的SecurityManager bean
* @Param defaultWebSecurityManager 通过容器中来获得bean
* @Return 返回Shiro拦截工厂的Bean
*/
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")
DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
/**
* 添加Shiro内置过滤器,常用的有如下过滤器:
* anon: 无需认证就可以访问
* authc: 必须认证才可以访问
* user: 如果使用了记住我功能就可以直接访问
* perms: 拥有某个资源权限才可以访问
* role: 拥有某个角色权限才可以访问
*/
//创建一个map,往里面放权限过滤
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
// filterMap.put("/user/add","anon");
// filterMap.put("/user/update","authc");
//支持通配符
// filterMap.put("/user/*","authc");
//单击退出,退出登录
// filterMap.put("/logout","logout");
//通过shiro过滤工厂bean把存放权限的map设置进去
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
//认证失败,跳到登录页面
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//权限不足,跳到权限不足页面
shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
return shiroFilterFactoryBean;
}
/**
* 创建 DefaultWebSecurityManager,将SecurityManager与userRealm绑定
* 通过Qualifier方法,获得spring容器中的uesrRealm bean
* @param userRealm 通过容器中来获得bean
* @return 返回安全管理器
*/
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//把自定义的realm加入到安全管理器中
securityManager.setRealm(userRealm);
return securityManager;
}
/**
* @return 返回创建的 realm 对象
*/
@Bean(name = "userRealm")
public UserRealm getUserRealm(){
return new UserRealm();
}
/**
* 为了整合thymeleaf和shiro标签的配合使用
* @return
*/
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
2.3、UserRealm(自定义Realm)
package com.yishuai.springbootshiro.config;
import com.yishuai.springbootshiro.pojo.User;
import com.yishuai.springbootshiro.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author yishuai
* @description 自定义realm,需要继承AuthorizingRealm类
* @date 2021/4/9 10:43 上午
*/
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserServiceImpl userService;
/**
* 执行授权的逻辑
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权的==>doGetAuthorizationInfo");
//新建要返回的AuthorizationInfo的子类SimpleAuthorizationInfo
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//授权的权限,因为要通过查询出来的user拿到,所以要把user传递过来
Subject subject = SecurityUtils.getSubject();
//此时principal里面存的就是user
User user =(User) subject.getPrincipal();
//添加对应的权限信息
simpleAuthorizationInfo.addStringPermission(user.getRole());
return simpleAuthorizationInfo;
}
/**
* 执行认证的逻辑
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了认证的==>doGetAuthenticationInfo");
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
//通过数据库查询到用户
User user = userService.getUserByUserName(usernamePasswordToken.getUsername());
System.out.println(user);
if (user == null){
//用户名错误,返回空的,shiro会自动抛出UnknownAccountException异常
return null;
}
//把登录成功的用户加入到session中
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("user",user);
//第一个user是为了让授权的逻辑拿到user的权限
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
2.4 IndexController(一个为了测试的控制器)
package com.yishuai.springbootshiro.controller;
import com.yishuai.springbootshiro.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author yishuai
* @description
* @date 2021/4/8 11:41 下午
*/
@Controller
public class IndexController {
@Autowired
private UserServiceImpl userService;
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello");
return "index";
}
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/login")
public String login(String username,String password,Model model){
//获得subject
Subject subject = SecurityUtils.getSubject();
//通过用户名和密码生成token
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try {
//执行登录操作
subject.login(token);
return "index";
} catch (UnknownAccountException uae) {
//未知的用户异常
model.addAttribute("msg","这是一个未知的用户: " + token.getPrincipal());
return "login";
} catch (IncorrectCredentialsException ice) {
model.addAttribute("msg","密码错误:" + token.getPrincipal());
return "login";
} catch (LockedAccountException lae) {
//账号被锁定
model.addAttribute("msg","这个账号已经被锁定: " + token.getPrincipal());
return "login";
}catch (AuthenticationException ae) {
// 最高权限的异常,前面的没有捕获,必定被这个捕获
model.addAttribute("msg","认证异常");
return "login";
}
}
@RequestMapping("/noAuth")
@ResponseBody
public String noAuth(){
return "权限不足,请更换有权限的账号";
}
@RequestMapping("/logout")
public String logout(Model model){
model.addAttribute("msg","你已经成功退出!");
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "index";
}
}
2.5 index.html(测试shiro整合权限)
<!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>Title</title>
</head>
<body>
<h1>shiro</h1>
<p th:text="${msg}"></p>
<div th:if="${session.user} == null">
<p>
<a th:href="@{/toLogin}">登录</a>
</p>
</div>
<div th:if="${session.user} != null">
<p>
<a th:href="@{/logout}">退出</a>
</p>
</div>
<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>
<div></div>
</body>
</html>