1
0
mirror of synced 2026-05-22 21:33:16 +00:00

Add AuthorizationManagerFactory

Signed-off-by: Steve Riesenberg <5248162+sjohnr@users.noreply.github.com>
This commit is contained in:
Steve Riesenberg
2025-09-02 12:47:53 -05:00
committed by Rob Winch
parent a4f813ab29
commit eeb4574bb3
37 changed files with 2719 additions and 178 deletions
@@ -28,6 +28,8 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.authorization.AuthorizationManagerFactory;
import org.springframework.security.authorization.DefaultAuthorizationManagerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
@@ -38,6 +40,7 @@ import org.springframework.util.Assert;
*
* @author Luke Taylor
* @author Evgeniy Cheban
* @author Steve Riesenberg
* @since 3.1
*/
public abstract class AbstractSecurityExpressionHandler<T>
@@ -49,6 +52,8 @@ public abstract class AbstractSecurityExpressionHandler<T>
private @Nullable RoleHierarchy roleHierarchy;
private AuthorizationManagerFactory<T> authorizationManagerFactory = new DefaultAuthorizationManagerFactory<>();
private PermissionEvaluator permissionEvaluator = new DenyAllPermissionEvaluator();
@Override
@@ -106,11 +111,58 @@ public abstract class AbstractSecurityExpressionHandler<T>
protected abstract SecurityExpressionOperations createSecurityExpressionRoot(
@Nullable Authentication authentication, T invocation);
/**
* Sets the {@link AuthorizationManagerFactory} to be used. The default is
* {@link DefaultAuthorizationManagerFactory}.
* @param authorizationManagerFactory the {@link AuthorizationManagerFactory} to use.
* Cannot be null.
* @since 7.0
*/
public final void setAuthorizationManagerFactory(AuthorizationManagerFactory<T> authorizationManagerFactory) {
Assert.notNull(authorizationManagerFactory, "authorizationManagerFactory cannot be null");
this.authorizationManagerFactory = authorizationManagerFactory;
}
protected final AuthorizationManagerFactory<T> getAuthorizationManagerFactory() {
return this.authorizationManagerFactory;
}
/**
* Allows accessing the {@link DefaultAuthorizationManagerFactory} for getting and
* setting defaults. This method will be removed in Spring Security 8.
* @return the {@link DefaultAuthorizationManagerFactory}
* @throws IllegalStateException if a different {@link AuthorizationManagerFactory}
* was already set
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
protected final DefaultAuthorizationManagerFactory<T> getDefaultAuthorizationManagerFactory() {
if (!(this.authorizationManagerFactory instanceof DefaultAuthorizationManagerFactory<T> defaultAuthorizationManagerFactory)) {
throw new IllegalStateException(
"authorizationManagerFactory must be an instance of DefaultAuthorizationManagerFactory");
}
return defaultAuthorizationManagerFactory;
}
/**
* @deprecated Use {@link #getDefaultAuthorizationManagerFactory()} instead
*/
@Deprecated(since = "7.0")
protected @Nullable RoleHierarchy getRoleHierarchy() {
return this.roleHierarchy;
}
public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
/**
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
public void setRoleHierarchy(@Nullable RoleHierarchy roleHierarchy) {
if (roleHierarchy != null) {
getDefaultAuthorizationManagerFactory().setRoleHierarchy(roleHierarchy);
}
this.roleHierarchy = roleHierarchy;
}
@@ -17,8 +17,6 @@
package org.springframework.security.access.expression;
import java.io.Serializable;
import java.util.Collection;
import java.util.Set;
import java.util.function.Supplier;
import org.jspecify.annotations.Nullable;
@@ -26,10 +24,11 @@ import org.jspecify.annotations.Nullable;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.authorization.AuthorizationManagerFactory;
import org.springframework.security.authorization.AuthorizationResult;
import org.springframework.security.authorization.DefaultAuthorizationManagerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.util.Assert;
import org.springframework.util.function.SingletonSupplier;
@@ -38,20 +37,19 @@ import org.springframework.util.function.SingletonSupplier;
*
* @author Luke Taylor
* @author Evgeniy Cheban
* @author Steve Riesenberg
* @since 3.0
*/
public abstract class SecurityExpressionRoot implements SecurityExpressionOperations {
public abstract class SecurityExpressionRoot<T extends @Nullable Object> implements SecurityExpressionOperations {
private final Supplier<Authentication> authentication;
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private @Nullable RoleHierarchy roleHierarchy;
private @Nullable Set<String> roles;
private String defaultRolePrefix = "ROLE_";
private final T object;
private AuthorizationManagerFactory<T> authorizationManagerFactory = new DefaultAuthorizationManagerFactory<>();
/**
* Allows "permitAll" expression
*/
@@ -77,9 +75,12 @@ public abstract class SecurityExpressionRoot implements SecurityExpressionOperat
/**
* Creates a new instance
* @param authentication the {@link Authentication} to use. Cannot be null.
* @deprecated Use {@link #SecurityExpressionRoot(Supplier, Object)} instead
*/
@Deprecated(since = "7.0")
@SuppressWarnings("NullAway")
public SecurityExpressionRoot(@Nullable Authentication authentication) {
this(() -> authentication);
this(() -> authentication, null);
}
/**
@@ -88,44 +89,70 @@ public abstract class SecurityExpressionRoot implements SecurityExpressionOperat
* @param authentication the {@link Supplier} of the {@link Authentication} to use.
* Cannot be null.
* @since 5.8
* @deprecated Use {@link #SecurityExpressionRoot(Supplier, Object)} instead
*/
public SecurityExpressionRoot(Supplier<? extends @Nullable Authentication> authentication) {
@Deprecated(since = "7.0")
@SuppressWarnings("NullAway")
public SecurityExpressionRoot(Supplier<@Nullable Authentication> authentication) {
this(authentication, null);
}
/**
* Creates a new instance that uses lazy initialization of the {@link Authentication}
* object.
* @param authentication the {@link Supplier} of the {@link Authentication} to use.
* Cannot be null.
* @param object the object being authorized
* @since 7.0
*/
public SecurityExpressionRoot(Supplier<? extends @Nullable Authentication> authentication, T object) {
this.authentication = SingletonSupplier.of(() -> {
Authentication value = authentication.get();
Assert.notNull(value, "Authentication object cannot be null");
return value;
});
this.object = object;
}
@Override
public final boolean hasAuthority(String authority) {
return hasAnyAuthority(authority);
return isGranted(this.authorizationManagerFactory.hasAnyAuthority(authority));
}
@Override
public final boolean hasAnyAuthority(String... authorities) {
return hasAnyAuthorityName(null, authorities);
return isGranted(this.authorizationManagerFactory.hasAnyAuthority(authorities));
}
@Override
public final boolean hasRole(String role) {
return hasAnyRole(role);
if (this.authorizationManagerFactory instanceof DefaultAuthorizationManagerFactory<T>) {
// To provide passivity for old behavior where hasRole('ROLE_A') is allowed,
// we strip the role prefix when found.
// TODO: Remove in favor of fixing inconsistent behavior?
String rolePrefix = this.defaultRolePrefix;
if (role.startsWith(rolePrefix)) {
role = role.substring(rolePrefix.length());
}
}
return isGranted(this.authorizationManagerFactory.hasRole(role));
}
@Override
public final boolean hasAnyRole(String... roles) {
return hasAnyAuthorityName(this.defaultRolePrefix, roles);
}
private boolean hasAnyAuthorityName(@Nullable String prefix, String... roles) {
Set<String> roleSet = getAuthoritySet();
for (String role : roles) {
String defaultedRole = getRoleWithDefaultPrefix(prefix, role);
if (roleSet.contains(defaultedRole)) {
return true;
if (this.authorizationManagerFactory instanceof DefaultAuthorizationManagerFactory<T>) {
// To provide passivity for old behavior where hasRole('ROLE_A') is allowed,
// we strip the role prefix when found.
// TODO: Remove in favor of fixing inconsistent behavior?
String rolePrefix = this.defaultRolePrefix;
for (int index = 0; index < roles.length; index++) {
String role = roles[index];
if (role.startsWith(rolePrefix)) {
roles[index] = role.substring(rolePrefix.length());
}
}
}
return false;
return isGranted(this.authorizationManagerFactory.hasAnyRole(roles));
}
@Override
@@ -135,33 +162,37 @@ public abstract class SecurityExpressionRoot implements SecurityExpressionOperat
@Override
public final boolean permitAll() {
return true;
return isGranted(this.authorizationManagerFactory.permitAll());
}
@Override
public final boolean denyAll() {
return false;
return isGranted(this.authorizationManagerFactory.denyAll());
}
@Override
public final boolean isAnonymous() {
return this.trustResolver.isAnonymous(getAuthentication());
return isGranted(this.authorizationManagerFactory.anonymous());
}
@Override
public final boolean isAuthenticated() {
return this.trustResolver.isAuthenticated(getAuthentication());
return isGranted(this.authorizationManagerFactory.authenticated());
}
@Override
public final boolean isRememberMe() {
return this.trustResolver.isRememberMe(getAuthentication());
return isGranted(this.authorizationManagerFactory.rememberMe());
}
@Override
public final boolean isFullyAuthenticated() {
Authentication authentication = getAuthentication();
return this.trustResolver.isFullyAuthenticated(authentication);
return isGranted(this.authorizationManagerFactory.fullyAuthenticated());
}
private boolean isGranted(AuthorizationManager<T> authorizationManager) {
AuthorizationResult authorizationResult = authorizationManager.authorize(this.authentication, this.object);
return (authorizationResult != null && authorizationResult.isGranted());
}
/**
@@ -173,12 +204,24 @@ public abstract class SecurityExpressionRoot implements SecurityExpressionOperat
return getAuthentication().getPrincipal();
}
/**
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
this.trustResolver = trustResolver;
getDefaultAuthorizationManagerFactory().setTrustResolver(trustResolver);
}
/**
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
public void setRoleHierarchy(@Nullable RoleHierarchy roleHierarchy) {
this.roleHierarchy = roleHierarchy;
if (roleHierarchy != null) {
getDefaultAuthorizationManagerFactory().setRoleHierarchy(roleHierarchy);
}
}
/**
@@ -193,20 +236,46 @@ public abstract class SecurityExpressionRoot implements SecurityExpressionOperat
* If null or empty, then no default role prefix is used.
* </p>
* @param defaultRolePrefix the default prefix to add to roles. Default "ROLE_".
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
public void setDefaultRolePrefix(String defaultRolePrefix) {
@Deprecated(since = "7.0")
public void setDefaultRolePrefix(@Nullable String defaultRolePrefix) {
if (defaultRolePrefix == null) {
defaultRolePrefix = "";
}
getDefaultAuthorizationManagerFactory().setRolePrefix(defaultRolePrefix);
this.defaultRolePrefix = defaultRolePrefix;
}
private Set<String> getAuthoritySet() {
if (this.roles == null) {
Collection<? extends GrantedAuthority> userAuthorities = getAuthentication().getAuthorities();
if (this.roleHierarchy != null) {
userAuthorities = this.roleHierarchy.getReachableGrantedAuthorities(userAuthorities);
}
this.roles = AuthorityUtils.authorityListToSet(userAuthorities);
/**
* Sets the {@link AuthorizationManagerFactory} to use for creating instances of
* {@link AuthorizationManager}.
* @param authorizationManagerFactory the {@link AuthorizationManagerFactory} to use
* @since 7.0
*/
public void setAuthorizationManagerFactory(AuthorizationManagerFactory<T> authorizationManagerFactory) {
Assert.notNull(authorizationManagerFactory, "authorizationManagerFactory cannot be null");
this.authorizationManagerFactory = authorizationManagerFactory;
}
/**
* Allows accessing the {@link DefaultAuthorizationManagerFactory} for getting and
* setting defaults. This method will be removed in Spring Security 8.
* @return the {@link DefaultAuthorizationManagerFactory}
* @throws IllegalStateException if a different {@link AuthorizationManagerFactory}
* was already set
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0", forRemoval = true)
private DefaultAuthorizationManagerFactory<T> getDefaultAuthorizationManagerFactory() {
if (!(this.authorizationManagerFactory instanceof DefaultAuthorizationManagerFactory<T> defaultAuthorizationManagerFactory)) {
throw new IllegalStateException(
"authorizationManagerFactory must be an instance of DefaultAuthorizationManagerFactory");
}
return this.roles;
return defaultAuthorizationManagerFactory;
}
@Override
@@ -225,24 +294,4 @@ public abstract class SecurityExpressionRoot implements SecurityExpressionOperat
this.permissionEvaluator = permissionEvaluator;
}
/**
* Prefixes role with defaultRolePrefix if defaultRolePrefix is non-null and if role
* does not already start with defaultRolePrefix.
* @param defaultRolePrefix
* @param role
* @return
*/
private static String getRoleWithDefaultPrefix(@Nullable String defaultRolePrefix, String role) {
if (role == null) {
return role;
}
if (defaultRolePrefix == null || defaultRolePrefix.length() == 0) {
return role;
}
if (role.startsWith(defaultRolePrefix)) {
return role;
}
return defaultRolePrefix + role;
}
}
@@ -43,6 +43,7 @@ import org.springframework.security.access.expression.AbstractSecurityExpression
import org.springframework.security.access.expression.ExpressionUtils;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authorization.AuthorizationManagerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.parameters.DefaultSecurityParameterNameDiscoverer;
import org.springframework.util.Assert;
@@ -56,11 +57,14 @@ import org.springframework.util.Assert;
* @author Luke Taylor
* @author Evgeniy Cheban
* @author Blagoja Stamatovski
* @author Steve Riesenberg
* @since 3.0
*/
public class DefaultMethodSecurityExpressionHandler extends AbstractSecurityExpressionHandler<MethodInvocation>
implements MethodSecurityExpressionHandler {
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
protected final Log logger = LogFactory.getLog(getClass());
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
@@ -69,7 +73,7 @@ public class DefaultMethodSecurityExpressionHandler extends AbstractSecurityExpr
private @Nullable PermissionCacheOptimizer permissionCacheOptimizer = null;
private String defaultRolePrefix = "ROLE_";
private String defaultRolePrefix = DEFAULT_ROLE_PREFIX;
public DefaultMethodSecurityExpressionHandler() {
}
@@ -106,12 +110,14 @@ public class DefaultMethodSecurityExpressionHandler extends AbstractSecurityExpr
private MethodSecurityExpressionOperations createSecurityExpressionRoot(
Supplier<? extends @Nullable Authentication> authentication, MethodInvocation invocation) {
MethodSecurityExpressionRoot root = new MethodSecurityExpressionRoot(authentication);
MethodSecurityExpressionRoot root = new MethodSecurityExpressionRoot(authentication, invocation);
root.setThis(invocation.getThis());
root.setAuthorizationManagerFactory(getAuthorizationManagerFactory());
root.setPermissionEvaluator(getPermissionEvaluator());
root.setTrustResolver(getTrustResolver());
Optional.ofNullable(getRoleHierarchy()).ifPresent(root::setRoleHierarchy);
root.setDefaultRolePrefix(getDefaultRolePrefix());
if (!DEFAULT_ROLE_PREFIX.equals(this.defaultRolePrefix)) {
// Ensure SecurityExpressionRoot can strip the custom role prefix
root.setDefaultRolePrefix(getDefaultRolePrefix());
}
return root;
}
@@ -232,15 +238,22 @@ public class DefaultMethodSecurityExpressionHandler extends AbstractSecurityExpr
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null.
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
getDefaultAuthorizationManagerFactory().setTrustResolver(trustResolver);
this.trustResolver = trustResolver;
}
/**
* @return The current {@link AuthenticationTrustResolver}
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
protected AuthenticationTrustResolver getTrustResolver() {
return this.trustResolver;
}
@@ -289,14 +302,24 @@ public class DefaultMethodSecurityExpressionHandler extends AbstractSecurityExpr
* If null or empty, then no default role prefix is used.
* </p>
* @param defaultRolePrefix the default prefix to add to roles. Default "ROLE_".
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
public void setDefaultRolePrefix(String defaultRolePrefix) {
@Deprecated(since = "7.0")
public void setDefaultRolePrefix(@Nullable String defaultRolePrefix) {
if (defaultRolePrefix == null) {
defaultRolePrefix = "";
}
getDefaultAuthorizationManagerFactory().setRolePrefix(defaultRolePrefix);
this.defaultRolePrefix = defaultRolePrefix;
}
/**
* @return The default role prefix
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
protected String getDefaultRolePrefix() {
return this.defaultRolePrefix;
}
@@ -18,6 +18,7 @@ package org.springframework.security.access.expression.method;
import java.util.function.Supplier;
import org.aopalliance.intercept.MethodInvocation;
import org.jspecify.annotations.Nullable;
import org.springframework.security.access.expression.SecurityExpressionRoot;
@@ -28,9 +29,11 @@ import org.springframework.security.core.Authentication;
*
* @author Luke Taylor
* @author Evgeniy Cheban
* @author Steve Riesenberg
* @since 3.0
*/
class MethodSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {
class MethodSecurityExpressionRoot extends SecurityExpressionRoot<MethodInvocation>
implements MethodSecurityExpressionOperations {
private @Nullable Object filterObject;
@@ -38,12 +41,9 @@ class MethodSecurityExpressionRoot extends SecurityExpressionRoot implements Met
private @Nullable Object target;
MethodSecurityExpressionRoot(@Nullable Authentication a) {
super(a);
}
MethodSecurityExpressionRoot(Supplier<? extends @Nullable Authentication> authentication) {
super(authentication);
MethodSecurityExpressionRoot(Supplier<? extends @Nullable Authentication> authentication,
MethodInvocation methodInvocation) {
super(authentication, methodInvocation);
}
@Override
@@ -0,0 +1,124 @@
/*
* Copyright 2002-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authorization;
import org.jspecify.annotations.Nullable;
/**
* A factory for creating different kinds of {@link AuthorizationManager} instances.
*
* @param <T> the type of object that the authorization check is being done on
* @author Steve Riesenberg
* @since 7.0
*/
public interface AuthorizationManagerFactory<T extends @Nullable Object> {
/**
* Create an {@link AuthorizationManager} that allows anyone.
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> permitAll() {
return SingleResultAuthorizationManager.permitAll();
}
/**
* Creates an {@link AuthorizationManager} that does not allow anyone.
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> denyAll() {
return SingleResultAuthorizationManager.denyAll();
}
/**
* Creates an {@link AuthorizationManager} that requires users to have the specified
* role.
* @param role the role (automatically prepended with ROLE_) that should be required
* to allow access (i.e. USER, ADMIN, etc.)
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> hasRole(String role) {
return AuthorityAuthorizationManager.hasRole(role);
}
/**
* Creates an {@link AuthorizationManager} that requires users to have one of many
* roles.
* @param roles the roles (automatically prepended with ROLE_) that the user should
* have at least one of to allow access (i.e. USER, ADMIN, etc.)
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> hasAnyRole(String... roles) {
return AuthorityAuthorizationManager.hasAnyRole(roles);
}
/**
* Creates an {@link AuthorizationManager} that requires users to have the specified
* authority.
* @param authority the authority that should be required to allow access (i.e.
* ROLE_USER, ROLE_ADMIN, etc.)
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> hasAuthority(String authority) {
return AuthorityAuthorizationManager.hasAuthority(authority);
}
/**
* Creates an {@link AuthorizationManager} that requires users to have one of many
* authorities.
* @param authorities the authorities that the user should have at least one of to
* allow access (i.e. ROLE_USER, ROLE_ADMIN, etc.)
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> hasAnyAuthority(String... authorities) {
return AuthorityAuthorizationManager.hasAnyAuthority(authorities);
}
/**
* Creates an {@link AuthorizationManager} that allows any authenticated user.
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> authenticated() {
return AuthenticatedAuthorizationManager.authenticated();
}
/**
* Creates an {@link AuthorizationManager} that allows users who have authenticated
* and were not remembered.
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> fullyAuthenticated() {
return AuthenticatedAuthorizationManager.fullyAuthenticated();
}
/**
* Creates an {@link AuthorizationManager} that allows users that have been
* remembered.
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> rememberMe() {
return AuthenticatedAuthorizationManager.rememberMe();
}
/**
* Creates an {@link AuthorizationManager} that allows only anonymous users.
* @return A new {@link AuthorizationManager} instance
*/
default AuthorizationManager<T> anonymous() {
return AuthenticatedAuthorizationManager.anonymous();
}
}
@@ -0,0 +1,123 @@
/*
* Copyright 2002-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authorization;
import org.jspecify.annotations.Nullable;
import org.springframework.security.access.hierarchicalroles.NullRoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.util.Assert;
/**
* A factory for creating different kinds of {@link AuthorizationManager} instances.
*
* @param <T> the type of object that the authorization check is being done on
* @author Steve Riesenberg
* @since 7.0
*/
public final class DefaultAuthorizationManagerFactory<T extends @Nullable Object>
implements AuthorizationManagerFactory<T> {
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private RoleHierarchy roleHierarchy = new NullRoleHierarchy();
private String rolePrefix = "ROLE_";
/**
* Sets the {@link AuthenticationTrustResolver} used to check the user's
* authentication.
* @param trustResolver the {@link AuthenticationTrustResolver} to use
*/
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
}
/**
* Sets the {@link RoleHierarchy} used to discover reachable authorities.
* @param roleHierarchy the {@link RoleHierarchy} to use
*/
public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
Assert.notNull(roleHierarchy, "roleHierarchy cannot be null");
this.roleHierarchy = roleHierarchy;
}
/**
* Sets the prefix used to create an authority name from a role name. Can be an empty
* string.
* @param rolePrefix the role prefix to use
*/
public void setRolePrefix(String rolePrefix) {
Assert.notNull(rolePrefix, "rolePrefix cannot be null");
this.rolePrefix = rolePrefix;
}
@Override
public AuthorizationManager<T> hasRole(String role) {
return hasAnyRole(role);
}
@Override
public AuthorizationManager<T> hasAnyRole(String... roles) {
return withRoleHierarchy(AuthorityAuthorizationManager.hasAnyRole(this.rolePrefix, roles));
}
@Override
public AuthorizationManager<T> hasAuthority(String authority) {
return withRoleHierarchy(AuthorityAuthorizationManager.hasAuthority(authority));
}
@Override
public AuthorizationManager<T> hasAnyAuthority(String... authorities) {
return withRoleHierarchy(AuthorityAuthorizationManager.hasAnyAuthority(authorities));
}
@Override
public AuthorizationManager<T> authenticated() {
return withTrustResolver(AuthenticatedAuthorizationManager.authenticated());
}
@Override
public AuthorizationManager<T> fullyAuthenticated() {
return withTrustResolver(AuthenticatedAuthorizationManager.fullyAuthenticated());
}
@Override
public AuthorizationManager<T> rememberMe() {
return withTrustResolver(AuthenticatedAuthorizationManager.rememberMe());
}
@Override
public AuthorizationManager<T> anonymous() {
return withTrustResolver(AuthenticatedAuthorizationManager.anonymous());
}
private AuthorityAuthorizationManager<T> withRoleHierarchy(AuthorityAuthorizationManager<T> authorizationManager) {
authorizationManager.setRoleHierarchy(this.roleHierarchy);
return authorizationManager;
}
private AuthenticatedAuthorizationManager<T> withTrustResolver(
AuthenticatedAuthorizationManager<T> authorizationManager) {
authorizationManager.setTrustResolver(this.trustResolver);
return authorizationManager;
}
}
@@ -16,6 +16,7 @@
package org.springframework.security.access.expression.method;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -53,7 +54,7 @@ public class MethodSecurityExpressionRootTests {
@BeforeEach
public void createContext() {
this.user = mock(Authentication.class);
this.root = new MethodSecurityExpressionRoot(this.user);
this.root = new MethodSecurityExpressionRoot(() -> this.user, mock(MethodInvocation.class));
this.ctx = new StandardEvaluationContext();
this.ctx.setRootObject(this.root);
this.trustResolver = mock(AuthenticationTrustResolver.class);
@@ -0,0 +1,100 @@
/*
* Copyright 2002-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authorization;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link AuthorizationManagerFactory}.
*
* @author Steve Riesenberg
*/
public class AuthorizationManagerFactoryTests {
@Test
public void permitAllReturnsSingleResultAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.permitAll();
assertThat(authorizationManager).isInstanceOf(SingleResultAuthorizationManager.class);
}
@Test
public void denyAllReturnsSingleResultAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.denyAll();
assertThat(authorizationManager).isInstanceOf(SingleResultAuthorizationManager.class);
}
@Test
public void hasRoleReturnsAuthorityAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.hasRole("USER");
assertThat(authorizationManager).isInstanceOf(AuthorityAuthorizationManager.class);
}
@Test
public void hasAnyRoleReturnsAuthorityAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.hasAnyRole("USER", "ADMIN");
assertThat(authorizationManager).isInstanceOf(AuthorityAuthorizationManager.class);
}
@Test
public void hasAuthorityReturnsAuthorityAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.hasAuthority("authority1");
assertThat(authorizationManager).isInstanceOf(AuthorityAuthorizationManager.class);
}
@Test
public void hasAnyAuthorityReturnsAuthorityAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.hasAnyAuthority("authority1", "authority2");
assertThat(authorizationManager).isInstanceOf(AuthorityAuthorizationManager.class);
}
@Test
public void authenticatedReturnsAuthenticatedAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.authenticated();
assertThat(authorizationManager).isInstanceOf(AuthenticatedAuthorizationManager.class);
}
@Test
public void fullyAuthenticatedReturnsAuthenticatedAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.fullyAuthenticated();
assertThat(authorizationManager).isInstanceOf(AuthenticatedAuthorizationManager.class);
}
@Test
public void rememberMeReturnsAuthenticatedAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.rememberMe();
assertThat(authorizationManager).isInstanceOf(AuthenticatedAuthorizationManager.class);
}
@Test
public void anonymousReturnsAuthenticatedAuthorizationManagerByDefault() {
AuthorizationManagerFactory<String> factory = new DefaultAuthorizationManagerFactory<>();
AuthorizationManager<String> authorizationManager = factory.anonymous();
assertThat(authorizationManager).isInstanceOf(AuthenticatedAuthorizationManager.class);
}
}