Selaa lähdekoodia

SEC-2328: Add hasAnyRole to ExpressionUrlAuthorizationConfiguration

Rob Winch 12 vuotta sitten
vanhempi
commit
28fb6ba14b

+ 21 - 0
config/src/main/java/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurer.java

@@ -157,6 +157,11 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
         return expressionHandler;
     }
 
+    private static String hasAnyRole(String... authorities) {
+        String anyAuthorities = StringUtils.arrayToDelimitedString(authorities, "','ROLE_");
+        return "hasAnyRole('ROLE_" + anyAuthorities + "')";
+    }
+
     private static String hasRole(String role) {
         Assert.notNull(role, "role cannot be null");
         if (role.startsWith("ROLE_")) {
@@ -215,6 +220,22 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
             return access(ExpressionUrlAuthorizationConfigurer.hasRole(role));
         }
 
+        /**
+         * Shortcut for specifying URLs require any of a number of roles. If you
+         * do not want to have "ROLE_" automatically inserted see
+         * {@link #hasAnyAuthority(String...)}
+         *
+         * @param roles
+         *            the roles to require (i.e. USER, ADMIN, etc). Note, it
+         *            should not start with "ROLE_" as this is automatically
+         *            inserted.
+         * @return the {@link ExpressionUrlAuthorizationConfigurer} for further
+         *         customization
+         */
+        public ExpressionUrlAuthorizationConfigurer<H> hasAnyRole(String... roles) {
+            return access(ExpressionUrlAuthorizationConfigurer.hasAnyRole(roles));
+        }
+
         /**
          * Specify that URLs require a particular authority.
          *

+ 14 - 0
config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationsTests.groovy

@@ -46,6 +46,20 @@ public class ExpressionUrlAuthorizationConfigurerTests extends BaseSpringSpec {
             expression == "hasAnyAuthority('ROLE_USER','ROLE_ADMIN')"
     }
 
+    def "hasAnyRole('USER')"() {
+        when:
+            def expression = ExpressionUrlAuthorizationConfigurer.hasAnyRole("USER")
+        then:
+            expression == "hasAnyRole('ROLE_USER')"
+    }
+
+    def "hasAnyRole('USER','ADMIN')"() {
+        when:
+            def expression = ExpressionUrlAuthorizationConfigurer.hasAnyRole("USER","ADMIN")
+        then:
+            expression == "hasAnyRole('ROLE_USER','ROLE_ADMIN')"
+    }
+
     def "hasRole('ROLE_USER') is rejected due to starting with ROLE_"() {
         when:
             def expression = ExpressionUrlAuthorizationConfigurer.hasRole("ROLE_USER")