I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

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.

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.

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.

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:

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.

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.