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

最后修改: 2016年 10月 28日

1. Introduction

1.介绍

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.

在本教程中,我们将编写一个自定义的AccessDecisionVoter,并展示如何使用它来抽象出Web应用程序的授权逻辑,并将其与应用程序的业务逻辑分开。

2. Scenario

2.情景</strong

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.

为了演示AccessDecisionVoter如何工作,我们将实现一个有两种用户类型的场景,USERADMIN,,其中USER只能在偶数分钟内访问系统,而ADMIN将始终被授予访问权。

3. AccessDecisionVoter Implementations

3.AccessDecisionVoter实施

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.

首先,我们将描述Spring提供的一些实现,它们将与我们的自定义投票器一起参与对授权的最终决定。然后,我们将看看如何实现一个自定义投票器。

3.1. The Default AccessDecisionVoter Implementations

3.1.默认的AccessDecisionVoter实现

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.

AuthenticatedVoter将根据Authentication对象的认证级别进行投票–特别是寻找一个完全认证的市镇,一个通过remember-me认证的市镇,或者最后是匿名。

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.

如果任何配置属性以字符串“ROLLE_”开头,它将在Authentication对象的GrantedAuthority列表中搜索该角色。

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:

例如,如果我们使用Java配置。

@Bean
public SecurityFilterChain filterChain(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:

或者使用XML配置–我们可以在intercept-url标签内,在http标签中使用SpEL。

<http use-expressions="true">
    <intercept-url pattern="/"
      access="hasAuthority('ROLE_USER')"/>
    ...
</http>

3.2. Custom AccessDecisionVoter Implementation

3.2.自定义AccessDecisionVoter实现

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

现在让我们创建一个自定义投票者–通过实现AccessDecisionVoter接口。

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.

我们必须提供的三个方法中的第一个是votemethod。vote方法是自定义投票器最重要的部分,也是我们的授权逻辑所在。

The vote method can return three possible values:

vote方法可以返回三个可能的值。

  • 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:

现在我们来实现vote方法。

@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.

在我们的vote方法中,我们检查该请求是否来自USER。如果是,如果是偶数分钟,我们就返回ACCESS_GRANTED,否则,我们就返回ACCESS_DENIED。如果请求不是来自用户,我们就投弃权票并返回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:

第二个方法返回投票者是否支持某个特定的配置属性。在我们的例子中,投票者不需要任何自定义配置属性,所以我们返回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:

第三个方法返回投票者是否可以投票给安全对象类型。由于我们的投票者不关心安全对象类型,我们返回true

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

4. The AccessDecisionManager

4.The AccessDecisionManager

The final authorization decision is handled by the AccessDecisionManager.

最后的授权决定是由AccessDecisionManager处理的。

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

AbstractAccessDecisionManager包含一个AccessDecisionVoters的列表–它们负责独立投票。

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.

当然,你可以用你自定义的决策逻辑实现你自己的AccessDecisionManager

5. Configuration

5.配置

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.

在这部分教程中,我们将看看基于Java和基于XML的方法,以配置我们的自定义AccessDecisionVoterAccessDecisionManager

5.1. Java Configuration

5.1.Java配置[/strong]。

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

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

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

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

让我们定义一个AccessDecisionManagerbean,它使用UnanimousBased管理器和我们定制的选民列表。

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

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

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
    ...
    .anyRequest()
    .authenticated()
    .accessDecisionManager(accessDecisionManager());
}

5.2. XML Configuration

5.2.XML配置

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

如果使用XML配置,你将需要修改你的spring-security.xml文件(或包含你的安全设置的任何文件)。

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

首先,你需要修改<http>标签。

<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="com.baeldung.voter.MinuteBasedVoter"/>

Then add a bean for the AccessDecisionManager:

然后为AccessDecisionManager添加一个bean。

<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=
              "com.baeldung.voter.MinuteBasedVoter"/>
        </beans:list>
    </beans:constructor-arg>
</beans:bean>

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

下面是一个支持我们方案的<authentication-manager>标签样本。

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

如果你使用Java和XML的组合配置,你可以把XML导入到一个配置类中。

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

6. Conclusion

6.结论

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.

然后我们讨论了AccessDecisionManager如何做出最终的授权决定,我们展示了如何使用Spring提供的实现来在所有投票者投票后做出这一决定。

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

然后我们通过Java和XML配置了一个AccessDecisionVotersAccessDecisionManager的列表。

The implementation can be found in the Github project.

该实现可以在Github项目中找到。

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

当项目在本地运行时,可以访问登录页面。

http://localhost:8082/login

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

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