Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3522

Custom AccessDecisionVoters in Spring Security

$
0
0

The Master Class of "Learn Spring Security" is out:

>> CHECK OUT THE COURSE

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.

For example, if we’re using Java config:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    ...
    .antMatchers("/").hasAnyAuthority("ROLE_USER")
    ...
}

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="/"
      access="hasAuthority('ROLE_USER')"/>
    ...
</http>

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:

@Override
public int vote(
  Authentication authentication, Object object, Collection collection) {
    return authentication.getAuthorities().stream()
      .map(GrantedAuthority::getAuthority)
      .filter(r -> "ROLE_USER".equals(r) 
        && LocalDateTime.now().getMinute() % 2 != 0)
      .findAny()
      .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:

@Override
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:

@Override
public boolean supports(Class clazz) {
    return true;
}

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:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
}

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

@Bean
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:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    ...
    .anyRequest()
    .authenticated()
    .accessDecisionManager(accessDecisionManager());
}

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">
  <intercept-url
    pattern="/**"
    access="hasAnyRole('ROLE_ADMIN', 'ROLE_USER')"/>
  ...
</http>

Next, add a bean for the custom voter:

<beans:bean
  id="minuteBasedVoter"
  class="org.baeldung.voter.MinuteBasedVoter"/>

Then add a bean for the AccessDecisionManager:

<beans:bean 
  id="accessDecisionManager" 
  class="org.springframework.security.access.vote.UnanimousBased">
    <beans:constructor-arg>
        <beans:list>
            <beans:bean class=
              "org.springframework.security.web.access.expression.WebExpressionVoter"/>
            <beans:bean class=
              "org.springframework.security.access.vote.AuthenticatedVoter"/>
            <beans:bean class=
              "org.springframework.security.access.vote.RoleVoter"/>
            <beans:bean class=
              "org.baeldung.voter.MinuteBasedVoter"/>
        </beans:list>
    </beans:constructor-arg>
</beans:bean>

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

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="user" password="pass" authorities="ROLE_USER"/>
            <user name="admin" password="pass" authorities="ROLE_ADMIN"/>
        </user-service>
    </authentication-provider>
</authentication-manager>

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

@Configuration
@ImportResource({"classpath:spring-security.xml"})
public class XmlSecurityConfig {
    public XmlSecurityConfig() {
        super();
    }
}

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.

The implementation can be found in the Github project.

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

http://localhost:8080/spring-security-custom-permissions/login

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

The Master Class "Learn Spring Security" is out:

>> CHECK OUT THE COURSE


Viewing all articles
Browse latest Browse all 3522

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>