---
title: "Spring security 访问权限控制"
author: "确实比较男"
date: "2015-05-26T10:47:45Z"
tags: ["Spring Security"]
categories: ["编程语言"]
slug: "spring-security"
draft: false
lastmod: "2015-05-26T10:48:16Z"
id: 2214324
url: "https://silentwu.iteye.com/blog/2214324"
---

![](http://dl2.iteye.com/upload/attachment/0108/9170/16052b31-4330-3afc-af10-466284d1e91a.png)

## GrantedAuthority

用户在认证成功后查询处理用户拥有的所有权限，Authentication中存储了用户的所有权限，spring-security的权限接口GrantedAuthority

```
public interface GrantedAuthority extends Serializable {
	//字符串代表一个权限
    String getAuthority();
}
```

 

## AccessDecisionManager

权限校验器Manager，判断用户是否用权限

```
public interface AccessDecisionManager {
	//authentication  : 用户认证后的对象
	//object : 受保护的资源对象
	// configAttributes : 访问资源需要的权限
   	void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException;
 	boolean supports(ConfigAttribute attribute);
    boolean supports(Class<?> clazz);
}
```

 

decide : 判断用户是否具有权限，最终的是让AccessDecisionVoter实现校验，可以配置多个AccessDecisionVoter；若用户没有权限，抛出AccessDeniedException

 

supports(ConfigAttribute): 在启动的时候被AbstractSecurityInterceptor调用，判断AccessDecisionManager是否支持所有的ConfigAttribute

 

supports(Class) : 被FilterSecurityInterceptor调用，判断AccessDecisionManager是否支持受保护的对象

 

## AccessDecisionVoter

 

```
public interface AccessDecisionVoter<S> {
    int ACCESS_GRANTED = 1;
    int ACCESS_ABSTAIN = 0;
int ACCESS_DENIED = -1;

    boolean supports(ConfigAttribute attribute);
    boolean supports(Class<?> clazz);
    int vote(Authentication authentication, S object, Collection<ConfigAttribute> attributes);
}
```

  vote: 返回一个int, AccessDecisionVoter中定义的三个静态变量ACCESS\_ABSTAIN, ACCESS\_DENIED ,ACCESS\_GRANTED 。

 

## 分层的角色权限

 Spring-security 支持把权限划分层次，高层次包含低层次的权限，比如ROLE\_AMDIN,ROLE\_USER两个权限，若用户拥有了ROLE\_AMDIN权限，那么相当于有了ROLE\_USER权限。

例子：

这个一个权限结构：ROLE\_ADMIN =&gt; ROLE\_STAFF =&gt; ROLE\_USER =&gt; ROLE\_GUEST

 

```
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_STAFF
            ROLE_STAFF > ROLE_USER
            ROLE_USER > ROLE_GUEST
        </value>
    </property>
</bean>
```

  

若用户被授权了ADMIN，那么就相当于有其他所有的权限