以前介紹了springboot使用security進行權限管理,這篇文件介紹一下springboot使用shiro進行安全管理。html
簡述本文的場景,本文使用springboot1.5.9+mysql+jpa+thymeleaf+shiro製做一個簡單的驗證,其中有2個角色,分別是admin和user,admin能夠使用select和delete功能,user只能使用select功能。java
新建項目,加入shiro依賴,pom文件以下:mysql
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalaoyang</groupId>
<artifactId>springboot_shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_shiro</name>
<description>springboot_shiro</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.15</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
複製代碼
配置文件以下:git
##端口號
server.port=8888
##數據庫配置
##數據庫地址
spring.datasource.url=jdbc:mysql://localhost:3306/shiro?characterEncoding=utf8&useSSL=false
##數據庫用戶名
spring.datasource.username=root
##數據庫密碼
spring.datasource.password=root
##數據庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
##validate 加載hibernate時,驗證建立數據庫表結構
##create 每次加載hibernate,從新建立數據庫表結構,這就是致使數據庫表數據丟失的緣由。
##create-drop 加載hibernate時建立,退出是刪除表結構
##update 加載hibernate自動更新數據庫結構
##validate 啓動時驗證表的結構,不會建立表
##none 啓動時不作任何操做
spring.jpa.hibernate.ddl-auto=update
##控制檯打印sql
spring.jpa.show-sql=true
# 建議在開發時關閉緩存,否則無法看到實時頁面
spring.thymeleaf.cache=false
##去除thymeleaf的html嚴格校驗
spring.thymeleaf.mode=LEGACYHTML5
複製代碼
建立了三個實體類,分別是 SysUser(用戶表)web
package com.dalaoyang.entity;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.entity
* @email yangyang@dalaoyang.cn
* @date 2018/5/2
*/
@Entity
public class SysUser implements Serializable {
@Id
@GeneratedValue
private Integer userId;
@NotEmpty
private String userName;
@NotEmpty
private String passWord;
//多對多關係
@ManyToMany(fetch= FetchType.EAGER)
//急加載,加載一個實體時,定義急加載的屬性會當即從數據庫中加載
//FetchType.LAZY:懶加載,加載一個實體時,定義懶加載的屬性不會立刻從數據庫中加載
@JoinTable(name = "SysUserRole", joinColumns = { @JoinColumn(name = "userId") },
inverseJoinColumns ={@JoinColumn(name = "roleId") })
private List<SysRole> roleList;// 一個用戶具備多個角色
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public List<SysRole> getRoleList() {
return roleList;
}
public void setRoleList(List<SysRole> roleList) {
this.roleList = roleList;
}
}
複製代碼
SysRole(角色表)spring
package com.dalaoyang.entity;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.entity
* @email yangyang@dalaoyang.cn
* @date 2018/5/2
*/
@Entity
public class SysRole implements Serializable {
@Id
@GeneratedValue
private Integer roleId;
private String roleName;
//多對多關係
@ManyToMany(fetch= FetchType.EAGER)
@JoinTable(name="SysRoleMenu",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="menuId")})
private List<SysMenu> menuList;
//多對多關係
@ManyToMany
@JoinTable(name="SysUserRole",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="userId")})
private List<SysUser> userList;// 一個角色對應多個用戶
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<SysMenu> getMenuList() {
return menuList;
}
public void setMenuList(List<SysMenu> menuList) {
this.menuList = menuList;
}
public List<SysUser> getUserList() {
return userList;
}
public void setUserList(List<SysUser> userList) {
this.userList = userList;
}
}
複製代碼
SysMenu(菜單表)sql
package com.dalaoyang.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.entity
* @email yangyang@dalaoyang.cn
* @date 2018/5/2
*/
@Entity
public class SysMenu implements Serializable {
@Id
@GeneratedValue
private Integer menuId;
private String menuName;
@ManyToMany
@JoinTable(name="SysRoleMenu",joinColumns={@JoinColumn(name="menuId")},inverseJoinColumns={@JoinColumn(name="roleId")})
private List<SysRole> roleList;
public Integer getMenuId() {
return menuId;
}
public void setMenuId(Integer menuId) {
this.menuId = menuId;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public List<SysRole> getRoleList() {
return roleList;
}
public void setRoleList(List<SysRole> roleList) {
this.roleList = roleList;
}
}
複製代碼
建立一個UserRepository用於查詢用戶信息:數據庫
package com.dalaoyang.repository;
import com.dalaoyang.entity.SysUser;
import org.springframework.data.repository.CrudRepository;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.repository
* @email yangyang@dalaoyang.cn
* @date 2018/5/2
*/
public interface UserRepository extends CrudRepository<SysUser,Long> {
SysUser findByUserName(String username);
}
複製代碼
建立幾個前臺頁面進行測試,分別是: login.html:apache
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
錯誤信息:<h4 th:text="${msg}"></h4>
<form action="" method="post">
<p>帳號:<input type="text" name="username" value="dalaoyang"/></p>
<p>密碼:<input type="text" name="password" value="123"/></p>
<p><input type="submit" value="登陸"/></p>
</form>
</body>
</html>
複製代碼
index.html緩存
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
index
<br/>
<form th:action="@{/logout}" method="post">
<p><input type="submit" value="註銷"/></p>
</form>
</body>
</html>
複製代碼
delete.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
delete
</body>
</html>
複製代碼
select.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
select
</body>
</html>
複製代碼
403.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
403
</body>
</html>
複製代碼
建立一個ShiroConfig,代碼以下:
package com.dalaoyang.config;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.config
* @email yangyang@dalaoyang.cn
* @date 2018/5/2
*/
@Configuration
public class ShiroConfig {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
logger.info("啓動shiroFilter--時間是:" + new Date());
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//shiro攔截器
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
//<!-- authc:全部url都必須認證經過才能夠訪問; anon:全部url都均可以匿名訪問-->
//<!-- 過濾鏈定義,從上向下順序執行,通常將/**放在最爲下邊 -->
// 配置不被攔截的資源及連接
filterChainDefinitionMap.put("/static/**", "anon");
// 退出過濾器
filterChainDefinitionMap.put("/logout", "logout");
//配置須要認證權限的
filterChainDefinitionMap.put("/**", "authc");
// 若是不設置默認會自動尋找Web工程根目錄下的"/login"頁面,即本文使用的login.html
shiroFilterFactoryBean.setLoginUrl("/login");
// 登陸成功後要跳轉的連接
shiroFilterFactoryBean.setSuccessUrl("/index");
//未受權界面
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
//自定義身份認證Realm(包含用戶名密碼校驗,權限校驗等)
@Bean
public MyShiroRealm myShiroRealm(){
MyShiroRealm myShiroRealm = new MyShiroRealm();
return myShiroRealm;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
}
//開啓shiro aop註解支持,不開啓的話權限驗證就會失效
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
//配置異常處理,不配置的話沒有權限後臺報錯,前臺不會跳轉到403頁面
@Bean(name="simpleMappingExceptionResolver")
public SimpleMappingExceptionResolver
createSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.setProperty("DatabaseException", "databaseError");//數據庫異常處理
mappings.setProperty("UnauthorizedException","403");
simpleMappingExceptionResolver.setExceptionMappings(mappings); // None by default
simpleMappingExceptionResolver.setDefaultErrorView("error"); // No default
simpleMappingExceptionResolver.setExceptionAttribute("ex"); // Default is "exception"
return simpleMappingExceptionResolver;
}
}
複製代碼
在配置一個MyShiroRealm用於登陸認證和受權認證,代碼以下:
package com.dalaoyang.config;
import com.dalaoyang.entity.SysMenu;
import com.dalaoyang.entity.SysRole;
import com.dalaoyang.entity.SysUser;
import com.dalaoyang.repository.UserRepository;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import javax.annotation.Resource;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.config
* @email yangyang@dalaoyang.cn
* @date 2018/5/2
*/
public class MyShiroRealm extends AuthorizingRealm {
@Resource
private UserRepository userRepository;
//受權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
SysUser userInfo = (SysUser)principals.getPrimaryPrincipal();
for(SysRole role:userInfo.getRoleList()){
authorizationInfo.addRole(role.getRoleName());
for(SysMenu menu:role.getMenuList()){
authorizationInfo.addStringPermission(menu.getMenuName());
}
}
return authorizationInfo;
}
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
//得到當前用戶的用戶名
String username = (String)token.getPrincipal();
System.out.println(token.getCredentials());
//根據用戶名找到對象
//實際項目中,這裏能夠根據實際狀況作緩存,若是不作,Shiro本身也是有時間間隔機制,2分鐘內不會重複執行該方法
SysUser userInfo = userRepository.findByUserName(username);
if(userInfo == null){
return null;
}
//這裏會去校驗密碼是否正確
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
userInfo, //用戶名
userInfo.getPassWord(),//密碼
getName()
);
return authenticationInfo;
}
}
複製代碼
最後新建一個controller,其中本文使用了2種驗證權限的方法,select方法使用@RequiresPermissions("select")來驗證用戶是否具備select權限,delete方法使用@RequiresRoles("admin")來驗證用戶是不是admin,代碼以下:
package com.dalaoyang.controller;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.controller
* @email yangyang@dalaoyang.cn
* @date 2018/5/2
*/
@Controller
public class TestController {
@GetMapping({"/","/index"})
public String index(){
return"index";
}
@GetMapping("/403")
public String unauthorizedRole(){
return "403";
}
@GetMapping("/delete")
//@RequiresPermissions("delete")
@RequiresRoles("admin")
public String delete(){
return "delete";
}
@GetMapping("/select")
@RequiresPermissions("select")
public String select(){
return "select";
}
@RequestMapping("/login")
public String login(HttpServletRequest request, Map<String, Object> map) throws Exception{
System.out.println("HomeController.login()");
// 登陸失敗從request中獲取shiro處理的異常信息。
// shiroLoginFailure:就是shiro異常類的全類名.
String exception = (String) request.getAttribute("shiroLoginFailure");
String msg = "";
//根據異常判斷錯誤類型
if (exception != null) {
if (UnknownAccountException.class.getName().equals(exception)) {
msg = "帳號不存在";
} else if (IncorrectCredentialsException.class.getName().equals(exception)) {
msg = "密碼不正確";
} else {
msg = "else >> "+exception;
}
}
map.put("msg", msg);
// 此方法不處理登陸成功,由shiro進行處理
return "/login";
}
@GetMapping("/logout")
public String logout(){
return "/login";
}
}
複製代碼
爲了方便測試,本人插入了幾條初始數據,sql以下:
INSERT INTO `shiro`.`sys_menu`(`menu_id`, `menu_name`) VALUES (1, 'add');
INSERT INTO `shiro`.`sys_menu`(`menu_id`, `menu_name`) VALUES (2, 'delete');
INSERT INTO `shiro`.`sys_menu`(`menu_id`, `menu_name`) VALUES (3, 'update');
INSERT INTO `shiro`.`sys_menu`(`menu_id`, `menu_name`) VALUES (4, 'select');
INSERT INTO `shiro`.`sys_role`(`role_id`, `role_name`) VALUES (1, 'admin');
INSERT INTO `shiro`.`sys_role`(`role_id`, `role_name`) VALUES (2, 'user');
INSERT INTO `shiro`.`sys_role_menu`(`role_id`, `menu_id`) VALUES (1, 1);
INSERT INTO `shiro`.`sys_role_menu`(`role_id`, `menu_id`) VALUES (1, 2);
INSERT INTO `shiro`.`sys_role_menu`(`role_id`, `menu_id`) VALUES (1, 3);
INSERT INTO `shiro`.`sys_role_menu`(`role_id`, `menu_id`) VALUES (1, 4);
INSERT INTO `shiro`.`sys_role_menu`(`role_id`, `menu_id`) VALUES (2, 4);
INSERT INTO `shiro`.`sys_user`(`user_id`, `pass_word`, `user_name`) VALUES (1, '123', 'dalaoyang');
INSERT INTO `shiro`.`sys_user`(`user_id`, `pass_word`, `user_name`) VALUES (2, '123', 'xiaoli');
INSERT INTO `shiro`.`sys_user_role`(`role_id`, `user_id`) VALUES (1, 1);
INSERT INTO `shiro`.`sys_user_role`(`role_id`, `user_id`) VALUES (2, 2);
複製代碼
啓動項目,我在這裏就不一一截圖了,口述一下,訪問http://localhost:8888/select因爲沒有登陸的緣由,會自動跳轉到http://localhost:8888/login,輸入錯誤的用戶名和密碼會出現對應的提示。輸入角色user的用戶名xiaoli,密碼123。訪問http://localhost:8888/select頁面會正常跳轉,訪問http://localhost:8888/delete會攔截到403頁面。
若是使用角色爲admin的用戶dalaoyang密碼123登陸,以上請求全能夠正常訪問。
源碼下載 :大老楊碼雲
我的網站:dalaoyang.cn