部分引自 www.javaboy.org
之前的案例權(quán)限都是寫死的像云,但實(shí)際項(xiàng)目中并不是這樣的聚谁,權(quán)限應(yīng)該放在數(shù)據(jù)庫里倦零,數(shù)據(jù)里面定義有哪些權(quán)限笙什,用戶有哪些角色進(jìn)而達(dá)到動(dòng)態(tài)權(quán)限配置
5張表用來解決用戶角色權(quán)限的動(dòng)態(tài)管理
/*
Navicat MySQL Data Transfer
Source Server : neuedu
Source Server Version : 50723
Source Host : localhost:3306
Source Database : security_test
Target Server Type : MYSQL
Target Server Version : 50723
File Encoding : 65001
Date: 2019-09-30 21:15:30
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for menu
-- ----------------------------
DROP TABLE IF EXISTS `menu`;
CREATE TABLE `menu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pattern` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of menu
-- ----------------------------
INSERT INTO `menu` VALUES ('1', '/dba/**');
INSERT INTO `menu` VALUES ('2', '/admin/**');
INSERT INTO `menu` VALUES ('3', '/user/**');
-- ----------------------------
-- Table structure for menu_role
-- ----------------------------
DROP TABLE IF EXISTS `menu_role`;
CREATE TABLE `menu_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`mid` int(11) DEFAULT NULL,
`rid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of menu_role
-- ----------------------------
INSERT INTO `menu_role` VALUES ('1', '1', '1');
INSERT INTO `menu_role` VALUES ('2', '2', '2');
INSERT INTO `menu_role` VALUES ('3', '3', '3');
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`nameZh` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', 'ROLE_dba', '數(shù)據(jù)庫管理員');
INSERT INTO `role` VALUES ('2', 'ROLE_admin', '系統(tǒng)管理員');
INSERT INTO `role` VALUES ('3', 'ROLE_user', '用戶');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`enabled` tinyint(1) DEFAULT NULL,
`locked` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'root', '$2a$10$WuUO9k/3LfTGzMEAKxNtAenttd9ulTq7wTj17ojqbU44Q5rwN/mWu', '1', '0');
INSERT INTO `user` VALUES ('2', 'admin', '$2a$10$WuUO9k/3LfTGzMEAKxNtAenttd9ulTq7wTj17ojqbU44Q5rwN/mWu', '1', '0');
INSERT INTO `user` VALUES ('3', 'sang', '$2a$10$WuUO9k/3LfTGzMEAKxNtAenttd9ulTq7wTj17ojqbU44Q5rwN/mWu', '1', '0');
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) DEFAULT NULL,
`rid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '1', '1');
INSERT INTO `user_role` VALUES ('2', '1', '2');
INSERT INTO `user_role` VALUES ('3', '2', '2');
INSERT INTO `user_role` VALUES ('4', '3', '3');
環(huán)境搭建
新建項(xiàng)目洲炊,依然添加四個(gè)依賴感局,外加連接池
mybatis數(shù)據(jù)庫配置
spring.datasource.url=jdbc:mysql:///security_test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=root
項(xiàng)目包
在之前的案例之上添加Menu實(shí)體類
package org.javaboy.security_db2.bean;
import java.util.List;
public class Menu {
private Integer id;
private String pattern;
// 表示訪問該路徑需要哪些角色
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
service
package org.javaboy.security_db2.service;
import org.javaboy.security_db2.bean.Menu;
import org.javaboy.security_db2.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MenuService {
@Autowired
MenuMapper menuMapper;
public List<Menu> getAllMenus(){
return menuMapper.getAllMenus();
}
}
mapper
package org.javaboy.security_db2.mapper;
import org.javaboy.security_db2.bean.Menu;
import java.util.List;
public interface MenuMapper {
List<Menu> getAllMenus();
}
<?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">
<mapper namespace="org.javaboy.security_db2.mapper.MenuMapper">
<select id="getAllMenus" resultMap="BaseResultMap">
select m.*,r.id rid,r.`name` rname,r.nameZh rnameZh
from menu m
left join menu_role mr
on m.id = mr.mid
left join role r
on mr.rid = r.id
</select>
<resultMap id="BaseResultMap" type="org.javaboy.security_db2.bean.Menu">
<id property="id" column="id"/>
<result property="pattern" column="pattern"/>
<collection property="roles" ofType="org.javaboy.security_db2.bean.Role">
<id property="id" column="rid"/>
<result property="name" column="rname" />
<result property="nameZh" column="rnameZh"/>
</collection>
</resultMap>
</mapper>
新增配置類
package org.javaboy.security_db2.config;
import com.sun.org.apache.xerces.internal.xs.StringList;
import org.javaboy.security_db2.bean.Menu;
import org.javaboy.security_db2.bean.Role;
import org.javaboy.security_db2.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import java.util.Collection;
import java.util.List;
/**
* 這個(gè)類是分析得出 用戶訪問的 url 需要哪些角色
* 核心的方法是第一個(gè)
* 第三個(gè)方法返回true表示支持支持這種方式即可
*
*/
@Component
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
@Autowired
MenuService menuService;
// ant風(fēng)格匹配符
AntPathMatcher antPathMatcher = new AntPathMatcher();
/**
* 在用戶發(fā)出請求時(shí),根據(jù)請求的 url 查出 該 url 需要哪些角色才能訪問暂衡,并返回
* @param o
* @return
* @throws IllegalArgumentException
*/
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
// 獲取 請求 url 地址
String requestUrl = ((FilterInvocation) o).getRequestUrl();
// 得到所有 url 和 角色 的對應(yīng)關(guān)系(這里可以用緩存處理)
List<Menu> allMenus = menuService.getAllMenus();
// 如果和 請求url 匹配上 就把他存入到 Collection<ConfigAttribute> 里
for (Menu menu : allMenus) {
if (antPathMatcher.match(menu.getPattern(), requestUrl)) {
// 如果匹配上就 獲取到 所需的角色列表
List<Role> roles = menu.getRoles();
String[] strList = new String[roles.size()];
for (int i = 0; i < strList.length; i++) {
strList[i] = roles.get(i).getName();
}
return SecurityConfig.createList(strList);
}
}
// 如果都沒有匹配上询微,我們返回默認(rèn)值,這個(gè)值就像一個(gè)特殊的標(biāo)識(shí)符狂巢,自定義
return SecurityConfig.createList("ROLE_LOGIN");
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
package org.javaboy.security_db2.config;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.Collection;
/**
* 獲取登錄用戶的角色撑毛,并與 訪問 所需要的角色進(jìn)行對比,決定是否可以訪問
*/
@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
for (ConfigAttribute attribute : collection) {
// 如果是其他的 url 訪問隧膘,判斷有沒有登錄代态,沒有登錄拋出異常
if ("ROLE_LOGIN".equals(attribute.getAttribute())) {
if (authentication instanceof AnonymousAuthenticationToken) {
throw new AccessDeniedException("非法請求");
}else{
return;
}
}
// 如果 url 與數(shù)據(jù)庫匹配上了寺惫,判斷 當(dāng)前 用戶有沒有能訪問的角色,如果有就 return 蹦疑,沒有拋出異常
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority().equals(attribute.getAttribute())) {
return;
}
}
throw new AccessDeniedException("非法請求");
}
}
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
package org.javaboy.security_db2.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.javaboy.security_db2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Autowired
UrlAccessDecisionManager urlAccessDecisionManager;
@Autowired
UrlFilterInvocationSecurityMetadataSource urlFilterInvocationSecurityMetadataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O o) {
o.setAccessDecisionManager(urlAccessDecisionManager);
o.setSecurityMetadataSource(urlFilterInvocationSecurityMetadataSource);
return o;
}
})
.and()
.formLogin()
.permitAll()
.and()
.csrf().disable();
}
}