角色继承
用户表user:
角色表role:
中间表user_role:
一般来说,角色之间是有关系的,例如ROLE_admin一般既具有admin的权限,又具有user的权限。
在Spring Security中只需要开发者提供一个RoleHierarchy即可。
假设ROLE_dba是终极大Boss,具有所有的权限,ROLE_admin具有ROLE_user的权限,ROLE_user则是一个公共角色,即ROLE_admin继承ROLE_user、ROLE_dba继承ROLE_admin,要描述这种继承关系,只需要在SpringSecurity的配置类中提供一个RoleHierarchy即可:
@Bean
RoleHierarchy roleHierarchy(){
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
String hierarchy = "ROLE_dba > ROLE_admin ROLE_admin > ROLE_user";
roleHierarchy.setHierarchy(hierarchy);
return roleHierarchy;
}
此时,具有ROLE_dba角色的用户就可以访问所有资源了,具有ROLE_admin角色的用户也可以访问具有ROLE_user角色才能访问的资源。
动态配置权限
1. 数据库设计:
在上文3张表的基础上再增加一张资源表和资源角色关联表。
资源表menu:定义了用户能够访问的URL模式
create table `menu` (
`id` int(11) not null auto_increment,
`pattern` varchar(255),
primary key(`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into menu values(1, '/db/**');
insert into menu values(2, '/admin/**');
insert into menu values(3, '/user/**');
资源角色表menu_role:定义了访问该模式的URL需要什么样的角色:
create table `menu_role` (
`id` int(11) not null auto_increment,
`mid` int(11),
`rid` int(11),
primary key(`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into menu_role values(1, 1, 1);
insert into menu_role values(2, 2, 2);
insert into menu_role values(3, 3, 3);
创建对应的pojo:
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;
}
}
2. 自定义FilterInvocationSecurityMetadataSource:
要实现动态配置权限,首先要自定义FilterInvocationSecurityMetadataSource,Spring Security中通过FilterInvocationSecurityMetadataSource接口中的getAttributes方法来确定一个请求需要哪些角色,FilterInvocationSecurityMetadataSource接口的默认实现类是DefaultFilterInvocationSecurityMetadataSource,参考DefaultFilterInvocationSecurityMetadataSource的实现,开发者可以定义自己的FilterInvocationSecurityMetadataSource:
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
//用于实现ant风格的URL匹配
AntPathMatcher antPathMatcher = new AntPathMatcher();
@Autowired
MenuMapper menuMapper;
//Collection<ConfigAttribute>表示当前请求URL所需的角色
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
//获取当前请求的URL
String requestUrl = ((FilterInvocation) o).getRequestUrl();
//获取数据库中的资源信息,一般放在Redis缓存中
List<Menu> allMenus = menuMapper.getAllMenus();
//遍历信息,遍历过程中获取当前请求的URL所需要的角色信息并返回
for (Menu menu : allMenus){
if(antPathMatcher.match(menu.getPattern(), requestUrl)){
List<Role> roles = menu.getRoles();
String[] roleArr = new String[roles.size()];
for (int i = 0; i < roleArr.length; i++){
roleArr[i] = roles.get(i).getName();
}
return SecurityConfig.createList(roleArr);
}
}
//如果当前请求的URL在资源表中不存在响应的模式,就假设该请求登录后即可访问,直接返回ROLE_LOGIN
return SecurityConfig.createList("ROLE_LOGIN");
}
//getAllConfigAttributes()方法用来返回所有定义好的权限资源,SpringSecurity在启动时会校验相关配置是否正确
//如果不需要校验,直接返回null即可
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
//supports方法返回类对象是否支持校验
@Override
public boolean supports(Class<?> aClass) {
return FilterInvocation.class.isAssignableFrom(aClass);
}
}
3. 自定义AccessDecisionManager:
当一个请求走完FilterInvocationSecurityMetadataSource中的getAttributes方法后,接下来就会来到AccessDecisionManager类中进行角色信息的对比,自定义AccessDecisionManager如下:
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {
//在该方法中判断当前登录的用户是否具有当前请求URL所需要的角色信息,如果不具备,就抛出AccessDeniedException异常,否则不做任何事情
/*
参数:
1. Authentication: 包含当前登录用户的信息
2. Object: 是一个FilterInvocation对象,可以获取当前请求对象
3. Collection<ConfigAttribute>: FilterInvocationSecurityMetadataSource中的getAttributes方法的返回值,即当前请求URL所需要的角色
*/
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
Collection<? extends GrantedAuthority> auths = authentication.getAuthorities();
for (ConfigAttribute configAttribute : collection){
if("ROLE_LOGIN".equals(configAttribute.getAttribute()) && authentication instanceof UsernamePasswordAuthenticationToken){
//如果角色是"ROLE_LOGIN",说明当前请求的URL用户登录后即可访问
//如果auth是UsernamePasswordAuthenticationToken的实例,那么说明当前用户已登录,该方法到此结束,否则进入正常判断流程
return;
}
for (GrantedAuthority authority : auths){//如果当前用户具备当前请求需的角色,方法结束。
if (configAttribute.getAttribute().equals(authority.getAuthority())){
return;
}
}
}
throw new AccessDeniedException("权限不足!");
}
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
4. MenuMapper和MenuMapper.xml:
@Mapper
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="pers.zhang.demo.mapper.MenuMapper">
<resultMap id="BaseResultMap" type="pers.zhang.demo.pojo.Menu">
<id property="id" column="id"/>
<result property="pattern" column="pattern"/>
<collection property="roles" ofType="pers.zhang.demo.pojo.Role">
<id property="id" column="rid"/>
<result property="name" column="rname"/>
<result property="nameZh" column="rnameZh"/>
</collection>
</resultMap>
<select id="getAllMenus" resultMap="BaseResultMap">
SELECT m.*,r.id AS rid,r.name AS rname,r.nameZh AS rnameZh
FROM menu m
LEFT JOIN menu_role mr ON m.`id`=mr.`mid`
LEFT JOIN role r ON mr.`rid`=r.`id`
</select>
</mapper>
== 5. 配置:==
@Configuration
public class WebSecurityConfig3 extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O o) {
o.setSecurityMetadataSource(cfisms());
o.setAccessDecisionManager(cadm());
return o;
}
})
.and()
.formLogin()
.loginProcessingUrl("/login").permitAll()
.and()
.csrf().disable();
}
@Bean
CustomFilterInvocationSecurityMetadataSource cfisms(){
return new CustomFilterInvocationSecurityMetadataSource();
}
@Bean
CustomAccessDecisionManager cadm(){
return new CustomAccessDecisionManager();
}
// @Bean
// RoleHierarchy roleHierarchy(){
// RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
// String hierarchy = "ROLE_dba > ROLE_admin ROLE_admin > ROLE_user";
// roleHierarchy.setHierarchy(hierarchy);
// return roleHierarchy;
// }
}