Custom AccessDecisionVoters in Spring Security – 在Spring Security中自定义访问决策程序(AccessDecisionVoters

最后修改: 2016年 10月 28日

1. Introduction


Most of the time when securing a Spring Web application or a REST API, the tools provided by Spring Security are more than enough, but sometimes we are looking for a more specific behavior.

在确保Spring Web应用或REST API的安全时,大多数时候Spring Security提供的工具是绰绰有余的,但有时我们要寻找更具体的行为。

In this tutorial, we’ll write a custom AccessDecisionVoter and show how it can be used to abstract away the authorization logic of a web application and separate it from the business logic of the application.


2. Scenario


To demonstrate how the AccessDecisionVoter works, we’ll implement a scenario with two user types, USER and ADMIN, in which a USER may access the system only on even-numbered minutes, while an ADMIN will always be granted access.


3. AccessDecisionVoter Implementations


First, we’ll describe a few of the implementations provided by Spring that will participate alongside our custom voter in making the final decision on the authorization. Then we’ll take a look at how to implement a custom voter.


3.1. The Default AccessDecisionVoter Implementations


Spring Security provides several AccessDecisionVoter implementations. We will use a few of them as part of our security solution here.

Spring Security提供了几个AccessDecisionVoter的实现。我们将在这里使用其中的几个作为我们安全解决方案的一部分。

Let’s take a look at how and when these default voters implementations vote.


The AuthenticatedVoter will cast a vote based on the Authentication object’s level of authentication – specifically looking for either a fully authenticated pricipal, one authenticated with remember-me or, finally, anonymous.


The RoleVoter votes if any of the configuration attributes starts with the String “ROLE_”. If so, it will search for the role in the GrantedAuthority list of the Authentication object.


The WebExpressionVoter enables us to use SpEL (Spring Expression Language) to authorize the requests using the @PreAuthorize annotation.

WebExpressionVoter使我们能够使用SpEL(Spring Expression Language)来授权使用@PreAuthorize注释的请求。

For example, if we’re using Java config:


public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

Or using an XML configuration – we can use SpEL inside an intercept-url tag, in the http tag:


<http use-expressions="true">
    <intercept-url pattern="/"

3.2. Custom AccessDecisionVoter Implementation


Now let’s create a custom voter – by implementing the AccessDecisionVoter interface:


public class MinuteBasedVoter implements AccessDecisionVoter {

The first of three methods we must provide is the vote method. The vote method is the most important part of the custom voter and is where our authorization logic goes.


The vote method can return three possible values:


  • ACCESS_GRANTED – the voter gives an affirmative answer
  • ACCESS_DENIED – the voter gives a negative answer
  • ACCESS_ABSTAIN – the voter abstains from voting

Let’s now implement the vote method:


public int vote(
  Authentication authentication, Object object, Collection collection) {
    return authentication.getAuthorities().stream()
      .filter(r -> "ROLE_USER".equals(r) 
        && % 2 != 0)
      .map(s -> ACCESS_DENIED)
      .orElseGet(() -> ACCESS_ABSTAIN);

In our vote method, we check if the request comes from a USER. If so, we return ACCESS_GRANTED if it’s an even-numbered minute, otherwise, we return ACCESS_DENIED. If the request does not come from a USER, we abstain from the vote and return ACCESS_ABSTAIN.


The second method returns whether the voter supports a particular configuration attribute. In our example, the voter does not need any custom configuration attribute, so we return true:


public boolean supports(ConfigAttribute attribute) {
    return true;

The third method returns whether the voter can vote for the secured object type or not. Since our voter is not concerned with the secured object type, we return true:


public boolean supports(Class clazz) {
    return true;

4. The AccessDecisionManager

4.The AccessDecisionManager

The final authorization decision is handled by the AccessDecisionManager.


The AbstractAccessDecisionManager contains a list of AccessDecisionVoters – which are responsible for casting their votes independent of each other.


There are three implementations for processing the votes to cover the most common use cases:


  • AffirmativeBased – grants access if any of the AccessDecisionVoters return an affirmative vote
  • ConsensusBased – grants access if there are more affirmative votes than negative (ignoring users who abstain)
  • UnanimousBased – grants access if every voter either abstains or returns an affirmative vote

Of course, you can implement your own AccessDecisionManager with your custom decision-making logic.


5. Configuration


In this part of the tutorial, we will take a look at Java-based and XML-based methods for configuring our custom AccessDecisionVoter with an AccessDecisionManager.


5.1. Java Configuration


Let’s create a configuration class for Spring Web Security:

让我们为Spring Web Security创建一个配置类。

public class WebSecurityConfig {

And let’s define an AccessDecisionManager bean that uses a UnanimousBased manager with our customized list of voters:


public AccessDecisionManager accessDecisionManager() {
    List<AccessDecisionVoter<? extends Object>> decisionVoters 
      = Arrays.asList(
        new WebExpressionVoter(),
        new RoleVoter(),
        new AuthenticatedVoter(),
        new MinuteBasedVoter());
    return new UnanimousBased(decisionVoters);

Finally, let’s configure Spring Security to use the previously defined bean as the default AccessDecisionManager:

最后,让我们将Spring Security配置为使用之前定义的Bean作为默认的AccessDecisionManager

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

5.2. XML Configuration


If using XML configuration, you’ll need to modify your spring-security.xml file (or whichever file contains your security settings).


First, you’ll need to modify the <http> tag:


<http access-decision-manager-ref="accessDecisionManager">
    access="hasAnyRole('ROLE_ADMIN', 'ROLE_USER')"/>

Next, add a bean for the custom voter:



Then add a bean for the AccessDecisionManager:


            <beans:bean class=
            <beans:bean class=
            <beans:bean class=
            <beans:bean class=

Here’s a sample <authentication-manager> tag supporting our scenario:


            <user name="user" password="pass" authorities="ROLE_USER"/>
            <user name="admin" password="pass" authorities="ROLE_ADMIN"/>

If you are using a combination of Java and XML configuration, you can import the XML into a configuration class:


public class XmlSecurityConfig {
    public XmlSecurityConfig() {

6. Conclusion


In this tutorial, we looked at a way to customize security for a Spring Web application by using AccessDecisionVoters. We saw some voters provided by Spring Security that contributed to our solution. Then we discussed how to implement a custom AccessDecisionVoter.

在本教程中,我们看了一种通过使用AccessDecisionVoters为Spring Web应用程序定制安全的方法。我们看到了一些由Spring Security提供的投票者,它们对我们的解决方案做出了贡献。然后我们讨论了如何实现一个自定义的AccessDecisionVoter

Then we discussed how the AccessDecisionManager makes the final authorization decision, and we showed how to use the implementations provided by Spring to make this decision after all the voters cast their votes.


Then we configured a list of AccessDecisionVoters with an AccessDecisionManager through Java and XML.


The implementation can be found in the Github project.


When the project runs locally the login page can be accessed at:



The credentials for the USER are “user” and “pass, and credentials for the ADMIN are “admin” and “pass”.

USER的凭证是 “user “和 “pass”,而ADMIN的凭证是 “admin “和 “pass”。