diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.java index 8b559cbd54a..2c6a5b6a28b 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.java +++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.java @@ -25,6 +25,7 @@ import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Import; import org.springframework.core.Ordered; +import org.springframework.security.access.annotation.Secured; import org.springframework.security.authorization.ReactiveAuthorizationManager; /** @@ -76,4 +77,20 @@ */ boolean useAuthorizationManager() default true; + /** + * Determines if Spring Security's {@link Secured} annotation should be enabled. + * Requires {@link #useAuthorizationManager()} to be {@code true}. Default is false. + * @return true if {@link Secured} annotation should be enabled false otherwise + * @since 7.3 + */ + boolean securedEnabled() default false; + + /** + * Determines if JSR-250 annotations should be enabled. Requires + * {@link #useAuthorizationManager()} to be {@code true}. Default is false. + * @return true if JSR-250 should be enabled false otherwise + * @since 7.3 + */ + boolean jsr250Enabled() default false; + } diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveJsr250MethodSecurityConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveJsr250MethodSecurityConfiguration.java new file mode 100644 index 00000000000..0288c7eff64 --- /dev/null +++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveJsr250MethodSecurityConfiguration.java @@ -0,0 +1,83 @@ +/* + * Copyright 2004-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.config.annotation.method.configuration; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.Pointcut; +import org.springframework.aop.framework.AopInfrastructureBean; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Role; +import org.springframework.security.access.hierarchicalroles.RoleHierarchy; +import org.springframework.security.authorization.AuthoritiesAuthorizationManager; +import org.springframework.security.authorization.ReactiveAuthorizationManager; +import org.springframework.security.authorization.method.AuthorizationManagerBeforeReactiveMethodInterceptor; +import org.springframework.security.authorization.method.Jsr250ReactiveAuthorizationManager; +import org.springframework.security.config.ObjectPostProcessor; +import org.springframework.security.config.core.GrantedAuthorityDefaults; + +/** + * {@link Configuration} for enabling JSR-250 Spring Security Reactive Method Security. + * + * @author Rohit Behera + * @since 7.3 + * @see EnableReactiveMethodSecurity + */ +@Configuration(value = "_reactiveJsr250MethodSecurityConfiguration", proxyBeanMethods = false) +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) +final class ReactiveJsr250MethodSecurityConfiguration implements AopInfrastructureBean { + + private static final Pointcut pointcut = AuthorizationManagerBeforeReactiveMethodInterceptor.jsr250().getPointcut(); + + private final Jsr250ReactiveAuthorizationManager authorizationManager = new Jsr250ReactiveAuthorizationManager(); + + private final AuthorizationManagerBeforeReactiveMethodInterceptor methodInterceptor; + + ReactiveJsr250MethodSecurityConfiguration( + ObjectProvider>> postProcessors) { + ReactiveAuthorizationManager manager = postProcessors + .getIfUnique(ObjectPostProcessor::identity) + .postProcess(this.authorizationManager); + this.methodInterceptor = AuthorizationManagerBeforeReactiveMethodInterceptor.jsr250(manager); + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + static MethodInterceptor jsr250AuthorizationMethodInterceptor( + ObjectProvider _reactiveJsr250MethodSecurityConfiguration) { + return new DeferringMethodInterceptor<>(pointcut, + () -> _reactiveJsr250MethodSecurityConfiguration.getObject().methodInterceptor); + } + + @Autowired(required = false) + void setGrantedAuthorityDefaults(GrantedAuthorityDefaults defaults) { + this.authorizationManager.setRolePrefix(defaults.getRolePrefix()); + } + + @Autowired(required = false) + void setRoleHierarchy(RoleHierarchy roleHierarchy) { + AuthoritiesAuthorizationManager authoritiesAuthorizationManager = new AuthoritiesAuthorizationManager(); + authoritiesAuthorizationManager.setRoleHierarchy(roleHierarchy); + this.authorizationManager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager); + } + +} diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecuritySelector.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecuritySelector.java index 47f145a11d5..b0745bef7de 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecuritySelector.java +++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecuritySelector.java @@ -59,8 +59,17 @@ public String[] selectImports(AnnotationMetadata importMetadata) { List imports = new ArrayList<>(Arrays.asList(this.autoProxy.selectImports(importMetadata))); if (annotation.useAuthorizationManager()) { imports.add(ReactiveAuthorizationManagerMethodSecurityConfiguration.class.getName()); + if (annotation.securedEnabled()) { + imports.add(ReactiveSecuredMethodSecurityConfiguration.class.getName()); + } + if (annotation.jsr250Enabled()) { + imports.add(ReactiveJsr250MethodSecurityConfiguration.class.getName()); + } } else { + Assert.state(!annotation.securedEnabled() && !annotation.jsr250Enabled(), + "@EnableReactiveMethodSecurity securedEnabled and jsr250Enabled " + + "require useAuthorizationManager = true"); Assert.state( ClassUtils.isPresent(METHOD_SECURITY_METADATA_SOURCE_ADVISOR, ClassUtils.getDefaultClassLoader()), () -> "@EnableReactiveMethodSecurity(useAuthorizationManager = false) requires the " diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveSecuredMethodSecurityConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveSecuredMethodSecurityConfiguration.java new file mode 100644 index 00000000000..3bdfc2bec3d --- /dev/null +++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveSecuredMethodSecurityConfiguration.java @@ -0,0 +1,79 @@ +/* + * Copyright 2004-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.config.annotation.method.configuration; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.Pointcut; +import org.springframework.aop.framework.AopInfrastructureBean; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Role; +import org.springframework.security.access.hierarchicalroles.RoleHierarchy; +import org.springframework.security.authorization.AuthoritiesAuthorizationManager; +import org.springframework.security.authorization.ReactiveAuthorizationManager; +import org.springframework.security.authorization.method.AuthorizationManagerBeforeReactiveMethodInterceptor; +import org.springframework.security.authorization.method.SecuredReactiveAuthorizationManager; +import org.springframework.security.config.ObjectPostProcessor; + +/** + * {@link Configuration} for enabling {@code @Secured} Spring Security Reactive Method + * Security. + * + * @author Rohit Behera + * @since 7.3 + * @see EnableReactiveMethodSecurity + */ +@Configuration(value = "_reactiveSecuredMethodSecurityConfiguration", proxyBeanMethods = false) +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) +final class ReactiveSecuredMethodSecurityConfiguration implements AopInfrastructureBean { + + private static final Pointcut pointcut = AuthorizationManagerBeforeReactiveMethodInterceptor.secured() + .getPointcut(); + + private final SecuredReactiveAuthorizationManager authorizationManager = new SecuredReactiveAuthorizationManager(); + + private final AuthorizationManagerBeforeReactiveMethodInterceptor methodInterceptor; + + ReactiveSecuredMethodSecurityConfiguration( + ObjectProvider>> postProcessors) { + ReactiveAuthorizationManager manager = postProcessors + .getIfUnique(ObjectPostProcessor::identity) + .postProcess(this.authorizationManager); + this.methodInterceptor = AuthorizationManagerBeforeReactiveMethodInterceptor.secured(manager); + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + static MethodInterceptor securedAuthorizationMethodInterceptor( + ObjectProvider _reactiveSecuredMethodSecurityConfiguration) { + return new DeferringMethodInterceptor<>(pointcut, + () -> _reactiveSecuredMethodSecurityConfiguration.getObject().methodInterceptor); + } + + @Autowired(required = false) + void setRoleHierarchy(RoleHierarchy roleHierarchy) { + AuthoritiesAuthorizationManager authoritiesAuthorizationManager = new AuthoritiesAuthorizationManager(); + authoritiesAuthorizationManager.setRoleHierarchy(roleHierarchy); + this.authorizationManager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager); + } + +} diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/ReactiveSecuredAndJsr250MethodSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/ReactiveSecuredAndJsr250MethodSecurityConfigurationTests.java new file mode 100644 index 00000000000..4672d178e55 --- /dev/null +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/ReactiveSecuredAndJsr250MethodSecurityConfigurationTests.java @@ -0,0 +1,472 @@ +/* + * Copyright 2004-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.config.annotation.method.configuration; + +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationHandler; +import io.micrometer.observation.ObservationRegistry; +import io.micrometer.observation.ObservationTextPublisher; +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.access.annotation.Secured; +import org.springframework.security.access.hierarchicalroles.RoleHierarchy; +import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.config.core.GrantedAuthorityDefaults; +import org.springframework.security.config.test.SpringTestContext; +import org.springframework.security.config.test.SpringTestContextExtension; +import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.assertj.core.api.Assertions.assertThatException; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +/** + * Tests for {@link EnableReactiveMethodSecurity#jsr250Enabled()} and + * {@link EnableReactiveMethodSecurity#securedEnabled()}. + * + * @author Rohit Behera + */ +@ExtendWith({ SpringExtension.class, SpringTestContextExtension.class }) +@SecurityTestExecutionListeners +public class ReactiveSecuredAndJsr250MethodSecurityConfigurationTests { + + public final SpringTestContext spring = new SpringTestContext(this); + + @Test + @WithMockUser(roles = "ADMIN") + void rolesAllowedWhenJsr250EnabledAndRoleAdminThenGranted() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.rolesAllowedAdmin()).expectNext("admin").verifyComplete(); + } + + @Test + @WithMockUser + void rolesAllowedWhenJsr250EnabledAndRoleUserThenDenied() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.rolesAllowedAdmin()).expectError(AccessDeniedException.class).verify(); + } + + @Test + void rolesAllowedWhenJsr250EnabledAndAnonymousThenDenied() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.rolesAllowedAdmin()).expectError(AccessDeniedException.class).verify(); + } + + @Test + @WithMockUser + void rolesAllowedFluxWhenJsr250EnabledAndRoleUserThenDenied() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.rolesAllowedAdminFlux()).expectError(AccessDeniedException.class).verify(); + } + + @Test + @WithMockUser(roles = "ADMIN") + void rolesAllowedFluxWhenJsr250EnabledAndRoleAdminThenGranted() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.rolesAllowedAdminFlux()).expectNext("a", "b").verifyComplete(); + } + + @Test + @WithMockUser(roles = "ADMIN") + void denyAllWhenJsr250EnabledThenDenied() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.denyAll()).expectError(AccessDeniedException.class).verify(); + } + + @Test + void permitAllWhenJsr250EnabledAndAnonymousThenGranted() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.permitAll()).expectNext("permitAll").verifyComplete(); + } + + @Test + @WithMockUser + void classLevelRolesAllowedWhenJsr250EnabledThenAppliesToMethod() { + this.spring.register(Jsr250Config.class).autowire(); + ClassLevelJsr250Service service = this.spring.getContext().getBean(ClassLevelJsr250Service.class); + StepVerifier.create(service.inheritsUser()).expectNext("user").verifyComplete(); + StepVerifier.create(service.overridesAdmin()).expectError(AccessDeniedException.class).verify(); + } + + @Test + @WithMockUser + void rolesAllowedWhenJsr250NotEnabledThenNotEnforced() { + this.spring.register(DefaultConfig.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.rolesAllowedAdmin()).expectNext("admin").verifyComplete(); + StepVerifier.create(service.denyAll()).expectNext("denyAll").verifyComplete(); + } + + @Test + @WithMockUser(authorities = "CUSTOM_ADMIN") + void rolesAllowedWhenGrantedAuthorityDefaultsThenUsesRolePrefix() { + this.spring.register(Jsr250Config.class, CustomRolePrefixConfig.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.rolesAllowedAdmin()).expectNext("admin").verifyComplete(); + } + + @Test + @WithMockUser(roles = "ADMIN") + void rolesAllowedWhenRoleHierarchyThenUsesHierarchy() { + this.spring.register(Jsr250Config.class, RoleHierarchyConfig.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.rolesAllowedUser()).expectNext("user").verifyComplete(); + } + + @Test + @WithMockUser(roles = "ADMIN") + void securedWhenSecuredEnabledAndRoleAdminThenGranted() { + this.spring.register(SecuredConfig.class).autowire(); + SecuredService service = this.spring.getContext().getBean(SecuredService.class); + StepVerifier.create(service.securedAdmin()).expectNext("admin").verifyComplete(); + } + + @Test + @WithMockUser + void securedWhenSecuredEnabledAndRoleUserThenDenied() { + this.spring.register(SecuredConfig.class).autowire(); + SecuredService service = this.spring.getContext().getBean(SecuredService.class); + StepVerifier.create(service.securedAdmin()).expectError(AccessDeniedException.class).verify(); + StepVerifier.create(service.securedAdminFlux()).expectError(AccessDeniedException.class).verify(); + } + + @Test + @WithMockUser(roles = "ADMIN") + void securedWhenRoleHierarchyThenUsesHierarchy() { + this.spring.register(SecuredConfig.class, RoleHierarchyConfig.class).autowire(); + SecuredService service = this.spring.getContext().getBean(SecuredService.class); + StepVerifier.create(service.securedUser()).expectNext("user").verifyComplete(); + } + + @Test + @WithMockUser + void securedWhenSecuredNotEnabledThenNotEnforced() { + this.spring.register(Jsr250Config.class).autowire(); + SecuredService service = this.spring.getContext().getBean(SecuredService.class); + StepVerifier.create(service.securedAdmin()).expectNext("admin").verifyComplete(); + } + + @Test + @WithMockUser + void rolesAllowedWhenOnlySecuredEnabledThenNotEnforced() { + this.spring.register(SecuredConfig.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.rolesAllowedAdmin()).expectNext("admin").verifyComplete(); + } + + @Test + @WithMockUser(roles = "ADMIN") + void interfaceAnnotationsWhenBothEnabledAndRoleAdminThenGranted() { + this.spring.register(BothConfig.class).autowire(); + AnnotatedInterfaceService service = this.spring.getContext().getBean(AnnotatedInterfaceService.class); + StepVerifier.create(service.rolesAllowedAdmin()).expectNext("admin").verifyComplete(); + StepVerifier.create(service.securedAdmin()).expectNext("admin").verifyComplete(); + } + + @Test + @WithMockUser + void interfaceAnnotationsWhenBothEnabledAndRoleUserThenDenied() { + this.spring.register(BothConfig.class).autowire(); + AnnotatedInterfaceService service = this.spring.getContext().getBean(AnnotatedInterfaceService.class); + StepVerifier.create(service.rolesAllowedAdmin()).expectError(AccessDeniedException.class).verify(); + StepVerifier.create(service.securedAdmin()).expectError(AccessDeniedException.class).verify(); + } + + @Test + @WithMockUser(roles = { "USER", "ADMIN" }) + void preAuthorizeAndRolesAllowedWhenBothSatisfiedThenGranted() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.preAuthorizeUserAndRolesAllowedAdmin()).expectNext("both").verifyComplete(); + } + + @Test + @WithMockUser + void preAuthorizeAndRolesAllowedWhenOnlyPreAuthorizeSatisfiedThenDenied() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.preAuthorizeUserAndRolesAllowedAdmin()) + .expectError(AccessDeniedException.class) + .verify(); + } + + @Test + @WithMockUser(roles = "ADMIN") + void preAuthorizeAndRolesAllowedWhenOnlyRolesAllowedSatisfiedThenDenied() { + this.spring.register(Jsr250Config.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + StepVerifier.create(service.preAuthorizeUserAndRolesAllowedAdmin()) + .expectError(AccessDeniedException.class) + .verify(); + } + + @Test + @WithMockUser + void rolesAllowedWhenObservationRegistryThenObserved() { + this.spring.register(Jsr250Config.class, ObservationConfig.class).autowire(); + Jsr250Service service = this.spring.getContext().getBean(Jsr250Service.class); + ObservationHandler handler = this.spring.getContext().getBean(ObservationHandler.class); + StepVerifier.create(service.rolesAllowedUser()).expectNext("user").verifyComplete(); + verify(handler).onStart(any()); + verify(handler).onStop(any()); + StepVerifier.create(service.rolesAllowedAdmin()).expectError(AccessDeniedException.class).verify(); + verify(handler).onError(any()); + } + + @Test + @WithMockUser + void securedWhenObservationRegistryThenObserved() { + this.spring.register(SecuredConfig.class, ObservationConfig.class).autowire(); + SecuredService service = this.spring.getContext().getBean(SecuredService.class); + ObservationHandler handler = this.spring.getContext().getBean(ObservationHandler.class); + StepVerifier.create(service.securedUser()).expectNext("user").verifyComplete(); + verify(handler).onStart(any()); + verify(handler).onStop(any()); + StepVerifier.create(service.securedAdmin()).expectError(AccessDeniedException.class).verify(); + verify(handler).onError(any()); + } + + @Test + void configureWhenJsr250EnabledWithoutAuthorizationManagerThenFails() { + assertThatException().isThrownBy(() -> this.spring.register(LegacyJsr250Config.class).autowire()) + .havingRootCause() + .isInstanceOf(IllegalStateException.class) + .withMessageContaining("require useAuthorizationManager = true"); + } + + @Test + void configureWhenSecuredEnabledWithoutAuthorizationManagerThenFails() { + assertThatException().isThrownBy(() -> this.spring.register(LegacySecuredConfig.class).autowire()) + .havingRootCause() + .isInstanceOf(IllegalStateException.class) + .withMessageContaining("require useAuthorizationManager = true"); + } + + public static class Jsr250Service { + + @RolesAllowed("ADMIN") + public Mono rolesAllowedAdmin() { + return Mono.just("admin"); + } + + @RolesAllowed("ADMIN") + public Flux rolesAllowedAdminFlux() { + return Flux.just("a", "b"); + } + + @RolesAllowed("USER") + public Mono rolesAllowedUser() { + return Mono.just("user"); + } + + @DenyAll + public Mono denyAll() { + return Mono.just("denyAll"); + } + + @PermitAll + public Mono permitAll() { + return Mono.just("permitAll"); + } + + @PreAuthorize("hasRole('USER')") + @RolesAllowed("ADMIN") + public Mono preAuthorizeUserAndRolesAllowedAdmin() { + return Mono.just("both"); + } + + } + + public interface AnnotatedInterfaceService { + + @RolesAllowed("ADMIN") + Mono rolesAllowedAdmin(); + + @Secured("ROLE_ADMIN") + Mono securedAdmin(); + + } + + public static class AnnotatedInterfaceServiceImpl implements AnnotatedInterfaceService { + + @Override + public Mono rolesAllowedAdmin() { + return Mono.just("admin"); + } + + @Override + public Mono securedAdmin() { + return Mono.just("admin"); + } + + } + + @RolesAllowed("USER") + public static class ClassLevelJsr250Service { + + public Mono inheritsUser() { + return Mono.just("user"); + } + + @RolesAllowed("ADMIN") + public Mono overridesAdmin() { + return Mono.just("admin"); + } + + } + + public static class SecuredService { + + @Secured("ROLE_ADMIN") + public Mono securedAdmin() { + return Mono.just("admin"); + } + + @Secured("ROLE_ADMIN") + public Flux securedAdminFlux() { + return Flux.just("a", "b"); + } + + @Secured("ROLE_USER") + public Mono securedUser() { + return Mono.just("user"); + } + + } + + @Configuration + static class ServicesConfig { + + @Bean + Jsr250Service jsr250Service() { + return new Jsr250Service(); + } + + @Bean + ClassLevelJsr250Service classLevelJsr250Service() { + return new ClassLevelJsr250Service(); + } + + @Bean + SecuredService securedService() { + return new SecuredService(); + } + + @Bean + AnnotatedInterfaceService annotatedInterfaceService() { + return new AnnotatedInterfaceServiceImpl(); + } + + } + + @Configuration + @EnableReactiveMethodSecurity(jsr250Enabled = true) + static class Jsr250Config extends ServicesConfig { + + } + + @Configuration + @EnableReactiveMethodSecurity(securedEnabled = true) + static class SecuredConfig extends ServicesConfig { + + } + + @Configuration + @EnableReactiveMethodSecurity(securedEnabled = true, jsr250Enabled = true) + static class BothConfig extends ServicesConfig { + + } + + @Configuration + @EnableReactiveMethodSecurity + static class DefaultConfig extends ServicesConfig { + + } + + @Configuration + @EnableReactiveMethodSecurity(useAuthorizationManager = false, jsr250Enabled = true) + static class LegacyJsr250Config extends ServicesConfig { + + } + + @Configuration + @EnableReactiveMethodSecurity(useAuthorizationManager = false, securedEnabled = true) + static class LegacySecuredConfig extends ServicesConfig { + + } + + @Configuration + static class CustomRolePrefixConfig { + + @Bean + static GrantedAuthorityDefaults grantedAuthorityDefaults() { + return new GrantedAuthorityDefaults("CUSTOM_"); + } + + } + + @Configuration + static class ObservationConfig { + + private final ObservationHandler handler = spy(new ObservationTextPublisher()); + + @Bean + ObservationRegistry observationRegistry() { + ObservationRegistry registry = ObservationRegistry.create(); + registry.observationConfig().observationHandler(this.handler); + return registry; + } + + @Bean + ObservationHandler observationHandler() { + return this.handler; + } + + } + + @Configuration + static class RoleHierarchyConfig { + + @Bean + static RoleHierarchy roleHierarchy() { + return RoleHierarchyImpl.fromHierarchy("ROLE_ADMIN > ROLE_USER"); + } + + } + +} diff --git a/config/src/test/kotlin/org/springframework/security/config/annotation/method/configuration/KotlinReactiveSecuredAndJsr250MethodSecurityTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/method/configuration/KotlinReactiveSecuredAndJsr250MethodSecurityTests.kt new file mode 100644 index 00000000000..ba572b12098 --- /dev/null +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/method/configuration/KotlinReactiveSecuredAndJsr250MethodSecurityTests.kt @@ -0,0 +1,126 @@ +/* + * Copyright 2004-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.config.annotation.method.configuration + +import jakarta.annotation.security.RolesAllowed +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.runBlocking +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatExceptionOfType +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.security.access.AccessDeniedException +import org.springframework.security.access.annotation.Secured +import org.springframework.security.test.context.support.WithMockUser +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit.jupiter.SpringExtension + +/** + * Tests for [EnableReactiveMethodSecurity.jsr250Enabled] and + * [EnableReactiveMethodSecurity.securedEnabled] with Kotlin coroutines. + * + * @author Rohit Behera + */ +@ExtendWith(SpringExtension::class) +@ContextConfiguration +class KotlinReactiveSecuredAndJsr250MethodSecurityTests { + + @Autowired + lateinit var service: CoroutineService + + @Test + @WithMockUser(roles = ["ADMIN"]) + fun `suspending RolesAllowed when user has role then success`() { + runBlocking { + assertThat(service.suspendingRolesAllowedAdmin()).isEqualTo("admin") + } + } + + @Test + @WithMockUser + fun `suspending RolesAllowed when user does not have role then denied`() { + assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy { + runBlocking { + service.suspendingRolesAllowedAdmin() + } + } + } + + @Test + @WithMockUser(roles = ["ADMIN"]) + fun `flow RolesAllowed when user has role then success`() { + runBlocking { + assertThat(service.flowRolesAllowedAdmin().toList()).containsExactly(1, 2) + } + } + + @Test + @WithMockUser + fun `flow RolesAllowed when user does not have role then denied`() { + assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy { + runBlocking { + service.flowRolesAllowedAdmin().toList() + } + } + } + + @Test + @WithMockUser(roles = ["ADMIN"]) + fun `suspending Secured when user has role then success`() { + runBlocking { + assertThat(service.suspendingSecuredAdmin()).isEqualTo("admin") + } + } + + @Test + @WithMockUser + fun `suspending Secured when user does not have role then denied`() { + assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy { + runBlocking { + service.suspendingSecuredAdmin() + } + } + } + + open class CoroutineService { + + @RolesAllowed("ADMIN") + open suspend fun suspendingRolesAllowedAdmin(): String = "admin" + + @RolesAllowed("ADMIN") + open fun flowRolesAllowedAdmin(): Flow = flowOf(1, 2) + + @Secured("ROLE_ADMIN") + open suspend fun suspendingSecuredAdmin(): String = "admin" + + } + + @Configuration + @EnableReactiveMethodSecurity(jsr250Enabled = true, securedEnabled = true) + open class Config { + + @Bean + open fun service(): CoroutineService = CoroutineService() + + } + +} diff --git a/core/src/main/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeReactiveMethodInterceptor.java b/core/src/main/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeReactiveMethodInterceptor.java index 4c5801d8785..796ea764600 100644 --- a/core/src/main/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeReactiveMethodInterceptor.java +++ b/core/src/main/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeReactiveMethodInterceptor.java @@ -18,6 +18,9 @@ import java.lang.reflect.Method; +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; import kotlinx.coroutines.reactive.ReactiveFlowKt; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; @@ -32,6 +35,7 @@ import org.springframework.core.MethodParameter; import org.springframework.core.ReactiveAdapter; import org.springframework.core.ReactiveAdapterRegistry; +import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.AuthorizationDeniedException; @@ -84,6 +88,53 @@ public static AuthorizationManagerBeforeReactiveMethodInterceptor preAuthorize( return interceptor; } + /** + * Creates an instance for the {@link Secured} annotation. + * @return the {@link AuthorizationManagerBeforeReactiveMethodInterceptor} to use + * @since 7.3 + */ + public static AuthorizationManagerBeforeReactiveMethodInterceptor secured() { + return secured(new SecuredReactiveAuthorizationManager()); + } + + /** + * Creates an instance for the {@link Secured} annotation. + * @param authorizationManager the {@link ReactiveAuthorizationManager} to use + * @return the {@link AuthorizationManagerBeforeReactiveMethodInterceptor} to use + * @since 7.3 + */ + public static AuthorizationManagerBeforeReactiveMethodInterceptor secured( + ReactiveAuthorizationManager authorizationManager) { + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor( + AuthorizationMethodPointcuts.forAnnotations(Secured.class), authorizationManager); + interceptor.setOrder(AuthorizationInterceptorsOrder.SECURED.getOrder()); + return interceptor; + } + + /** + * Creates an instance for the JSR-250 annotations. + * @return the {@link AuthorizationManagerBeforeReactiveMethodInterceptor} to use + * @since 7.3 + */ + public static AuthorizationManagerBeforeReactiveMethodInterceptor jsr250() { + return jsr250(new Jsr250ReactiveAuthorizationManager()); + } + + /** + * Creates an instance for the JSR-250 annotations. + * @param authorizationManager the {@link ReactiveAuthorizationManager} to use + * @return the {@link AuthorizationManagerBeforeReactiveMethodInterceptor} to use + * @since 7.3 + */ + public static AuthorizationManagerBeforeReactiveMethodInterceptor jsr250( + ReactiveAuthorizationManager authorizationManager) { + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor( + AuthorizationMethodPointcuts.forAnnotations(RolesAllowed.class, DenyAll.class, PermitAll.class), + authorizationManager); + interceptor.setOrder(AuthorizationInterceptorsOrder.JSR250.getOrder()); + return interceptor; + } + /** * Creates an instance. * @param pointcut the {@link Pointcut} to use diff --git a/core/src/main/java/org/springframework/security/authorization/method/Jsr250ReactiveAuthorizationManager.java b/core/src/main/java/org/springframework/security/authorization/method/Jsr250ReactiveAuthorizationManager.java new file mode 100644 index 00000000000..0413660d220 --- /dev/null +++ b/core/src/main/java/org/springframework/security/authorization/method/Jsr250ReactiveAuthorizationManager.java @@ -0,0 +1,81 @@ +/* + * Copyright 2004-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.method; + +import java.util.Collection; + +import org.aopalliance.intercept.MethodInvocation; +import reactor.core.publisher.Mono; + +import org.springframework.security.authorization.AuthoritiesAuthorizationManager; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.authorization.AuthorizationResult; +import org.springframework.security.authorization.ReactiveAuthorizationManager; +import org.springframework.security.core.Authentication; + +/** + * A {@link ReactiveAuthorizationManager} which can determine if an {@link Authentication} + * may invoke the {@link MethodInvocation} by evaluating if the {@link Authentication} + * contains a specified authority from the JSR-250 security annotations. + *

+ * The annotations are resolved the same way as in {@link Jsr250AuthorizationManager}. + * + * @author Rohit Behera + * @since 7.3 + * @see Jsr250AuthorizationManager + */ +public final class Jsr250ReactiveAuthorizationManager implements ReactiveAuthorizationManager { + + private final Jsr250AuthorizationManager delegate = new Jsr250AuthorizationManager(); + + /** + * Sets an {@link AuthorizationManager} that accepts a collection of authority + * strings. Defaults to {@link AuthoritiesAuthorizationManager}. + * @param authoritiesAuthorizationManager the {@link AuthorizationManager} that + * accepts a collection of authority strings to use + */ + public void setAuthoritiesAuthorizationManager( + AuthorizationManager> authoritiesAuthorizationManager) { + this.delegate.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager); + } + + /** + * Sets the role prefix. Defaults to "ROLE_". + * @param rolePrefix the role prefix to use + */ + public void setRolePrefix(String rolePrefix) { + this.delegate.setRolePrefix(rolePrefix); + } + + /** + * Determines if an {@link Authentication} may invoke the {@link MethodInvocation} + * according to the JSR-250 annotation on the method or its class. + * @param authentication the {@link Mono} of the {@link Authentication} to check + * @param mi the {@link MethodInvocation} to check + * @return a {@link Mono} of the {@link AuthorizationResult} or an empty {@link Mono} + * if no JSR-250 annotation is present + */ + @Override + public Mono authorize(Mono authentication, MethodInvocation mi) { + // An empty authentication still has to grant @PermitAll, as in the servlet stack + // @formatter:off + return authentication.singleOptional() + .mapNotNull((auth) -> this.delegate.authorize(() -> auth.orElse(null), mi)); + // @formatter:on + } + +} diff --git a/core/src/main/java/org/springframework/security/authorization/method/SecuredReactiveAuthorizationManager.java b/core/src/main/java/org/springframework/security/authorization/method/SecuredReactiveAuthorizationManager.java new file mode 100644 index 00000000000..514d7a0648a --- /dev/null +++ b/core/src/main/java/org/springframework/security/authorization/method/SecuredReactiveAuthorizationManager.java @@ -0,0 +1,73 @@ +/* + * Copyright 2004-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.method; + +import java.util.Collection; + +import org.aopalliance.intercept.MethodInvocation; +import reactor.core.publisher.Mono; + +import org.springframework.security.access.annotation.Secured; +import org.springframework.security.authorization.AuthoritiesAuthorizationManager; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.authorization.AuthorizationResult; +import org.springframework.security.authorization.ReactiveAuthorizationManager; +import org.springframework.security.core.Authentication; + +/** + * A {@link ReactiveAuthorizationManager} which can determine if an {@link Authentication} + * may invoke the {@link MethodInvocation} by evaluating if the {@link Authentication} + * contains a specified authority from Spring Security's {@link Secured} annotation. + *

+ * The annotation is resolved the same way as in {@link SecuredAuthorizationManager}. + * + * @author Rohit Behera + * @since 7.3 + * @see SecuredAuthorizationManager + */ +public final class SecuredReactiveAuthorizationManager implements ReactiveAuthorizationManager { + + private final SecuredAuthorizationManager delegate = new SecuredAuthorizationManager(); + + /** + * Sets an {@link AuthorizationManager} that accepts a collection of authority + * strings. Defaults to {@link AuthoritiesAuthorizationManager}. + * @param authoritiesAuthorizationManager the {@link AuthorizationManager} that + * accepts a collection of authority strings to use + */ + public void setAuthoritiesAuthorizationManager( + AuthorizationManager> authoritiesAuthorizationManager) { + this.delegate.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager); + } + + /** + * Determines if an {@link Authentication} may invoke the {@link MethodInvocation} + * according to the {@link Secured} annotation on the method or its class. + * @param authentication the {@link Mono} of the {@link Authentication} to check + * @param mi the {@link MethodInvocation} to check + * @return a {@link Mono} of the {@link AuthorizationResult} or an empty {@link Mono} + * if no {@link Secured} annotation is present + */ + @Override + public Mono authorize(Mono authentication, MethodInvocation mi) { + // @formatter:off + return authentication.singleOptional() + .mapNotNull((auth) -> this.delegate.authorize(() -> auth.orElse(null), mi)); + // @formatter:on + } + +} diff --git a/core/src/test/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeReactiveMethodInterceptorTests.java b/core/src/test/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeReactiveMethodInterceptorTests.java index 09b069302a6..3542c4a1d93 100644 --- a/core/src/test/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeReactiveMethodInterceptorTests.java +++ b/core/src/test/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeReactiveMethodInterceptorTests.java @@ -16,6 +16,9 @@ package org.springframework.security.authorization.method; +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; import org.aopalliance.intercept.MethodInvocation; import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; @@ -23,11 +26,15 @@ import reactor.core.publisher.Mono; import org.springframework.aop.Pointcut; +import org.springframework.aop.support.AopUtils; import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.access.annotation.Secured; +import org.springframework.security.authentication.TestAuthentication; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.AuthorizationDeniedException; import org.springframework.security.authorization.AuthorizationResult; import org.springframework.security.authorization.ReactiveAuthorizationManager; +import org.springframework.security.core.context.ReactiveSecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -225,6 +232,91 @@ public void invokeWhenCustomAuthorizationDeniedExceptionThenThrows() throws Thro .isThrownBy(() -> ((Mono) advice.invoke(mockMethodInvocation)).block()); } + @Test + public void jsr250WhenCreatedThenMatchesJsr250AnnotationsWithJsr250Order() { + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = AuthorizationManagerBeforeReactiveMethodInterceptor + .jsr250(); + assertThat(interceptor.getOrder()).isEqualTo(AuthorizationInterceptorsOrder.JSR250.getOrder()); + assertThat(AopUtils.canApply(interceptor.getPointcut(), Jsr250Sample.class)).isTrue(); + assertThat(AopUtils.canApply(interceptor.getPointcut(), Sample.class)).isFalse(); + } + + @Test + public void jsr250WhenDenyAllThenAccessDeniedException() throws Throwable { + MethodInvocation mockMethodInvocation = spy( + new MockMethodInvocation(new Jsr250Sample(), Jsr250Sample.class.getDeclaredMethod("denyAll"))); + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = AuthorizationManagerBeforeReactiveMethodInterceptor + .jsr250(); + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> ((Mono) interceptor.invoke(mockMethodInvocation)).block()); + } + + @Test + public void jsr250WhenPermitAllThenProceeds() throws Throwable { + MethodInvocation mockMethodInvocation = spy( + new MockMethodInvocation(new Jsr250Sample(), Jsr250Sample.class.getDeclaredMethod("permitAll"))); + given(mockMethodInvocation.proceed()).willReturn(Mono.just("john")); + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = AuthorizationManagerBeforeReactiveMethodInterceptor + .jsr250(); + Object result = interceptor.invoke(mockMethodInvocation); + assertThat(((Mono) result).block()).isEqualTo("john"); + } + + @Test + public void jsr250WhenRolesAllowedAndRoleUserThenProceeds() throws Throwable { + MethodInvocation mockMethodInvocation = spy( + new MockMethodInvocation(new Jsr250Sample(), Jsr250Sample.class.getDeclaredMethod("rolesAllowedUser"))); + given(mockMethodInvocation.proceed()).willReturn(Mono.just("john")); + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = AuthorizationManagerBeforeReactiveMethodInterceptor + .jsr250(); + Object result = ((Mono) interceptor.invoke(mockMethodInvocation)) + .contextWrite(ReactiveSecurityContextHolder.withAuthentication(TestAuthentication.authenticatedUser())) + .block(); + assertThat(result).isEqualTo("john"); + } + + @Test + public void jsr250WhenRolesAllowedAndAnonymousThenAccessDeniedException() throws Throwable { + MethodInvocation mockMethodInvocation = spy( + new MockMethodInvocation(new Jsr250Sample(), Jsr250Sample.class.getDeclaredMethod("rolesAllowedUser"))); + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = AuthorizationManagerBeforeReactiveMethodInterceptor + .jsr250(); + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> ((Mono) interceptor.invoke(mockMethodInvocation)).block()); + } + + @Test + public void securedWhenRoleUserThenProceeds() throws Throwable { + MethodInvocation mockMethodInvocation = spy( + new MockMethodInvocation(new SecuredSample(), SecuredSample.class.getDeclaredMethod("securedUser"))); + given(mockMethodInvocation.proceed()).willReturn(Mono.just("john")); + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = AuthorizationManagerBeforeReactiveMethodInterceptor + .secured(); + Object result = ((Mono) interceptor.invoke(mockMethodInvocation)) + .contextWrite(ReactiveSecurityContextHolder.withAuthentication(TestAuthentication.authenticatedUser())) + .block(); + assertThat(result).isEqualTo("john"); + } + + @Test + public void securedWhenCreatedThenMatchesSecuredAnnotationWithSecuredOrder() { + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = AuthorizationManagerBeforeReactiveMethodInterceptor + .secured(); + assertThat(interceptor.getOrder()).isEqualTo(AuthorizationInterceptorsOrder.SECURED.getOrder()); + assertThat(AopUtils.canApply(interceptor.getPointcut(), SecuredSample.class)).isTrue(); + assertThat(AopUtils.canApply(interceptor.getPointcut(), Sample.class)).isFalse(); + } + + @Test + public void securedWhenAnonymousThenAccessDeniedException() throws Throwable { + MethodInvocation mockMethodInvocation = spy( + new MockMethodInvocation(new SecuredSample(), SecuredSample.class.getDeclaredMethod("securedUser"))); + AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = AuthorizationManagerBeforeReactiveMethodInterceptor + .secured(); + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> ((Mono) interceptor.invoke(mockMethodInvocation)).block()); + } + interface HandlingReactiveAuthorizationManager extends ReactiveAuthorizationManager, MethodAuthorizationDeniedHandler { @@ -242,6 +334,34 @@ Flux flux() { } + static class Jsr250Sample { + + @DenyAll + Mono denyAll() { + return Mono.just("john"); + } + + @PermitAll + Mono permitAll() { + return Mono.just("john"); + } + + @RolesAllowed("USER") + Mono rolesAllowedUser() { + return Mono.just("john"); + } + + } + + static class SecuredSample { + + @Secured("ROLE_USER") + Mono securedUser() { + return Mono.just("john"); + } + + } + static class MyAuthzDeniedException extends AuthorizationDeniedException { MyAuthzDeniedException(String msg, AuthorizationResult authorizationResult) { diff --git a/core/src/test/java/org/springframework/security/authorization/method/Jsr250ReactiveAuthorizationManagerTests.java b/core/src/test/java/org/springframework/security/authorization/method/Jsr250ReactiveAuthorizationManagerTests.java new file mode 100644 index 00000000000..1a420cc1377 --- /dev/null +++ b/core/src/test/java/org/springframework/security/authorization/method/Jsr250ReactiveAuthorizationManagerTests.java @@ -0,0 +1,279 @@ +/* + * Copyright 2004-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.method; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.Collection; +import java.util.Set; + +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import org.springframework.core.annotation.AnnotationConfigurationException; +import org.springframework.security.authentication.TestAuthentication; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.authorization.AuthorizationResult; +import org.springframework.security.core.Authentication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** + * Tests for {@link Jsr250ReactiveAuthorizationManager}. + * + * @author Rohit Behera + */ +public class Jsr250ReactiveAuthorizationManagerTests { + + private final Jsr250ReactiveAuthorizationManager manager = new Jsr250ReactiveAuthorizationManager(); + + @Test + public void setRolePrefixWhenNullThenException() { + assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setRolePrefix(null)) + .withMessage("rolePrefix cannot be null"); + } + + @Test + public void setAuthoritiesAuthorizationManagerWhenNullThenException() { + assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesAuthorizationManager(null)) + .withMessage("authoritiesAuthorizationManager cannot be null"); + } + + @Test + public void authorizeWhenNoJsr250AnnotationsThenEmpty() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "doSomething"); + StepVerifier.create(this.manager.authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation)) + .verifyComplete(); + } + + @Test + public void authorizeWhenPermitAllThenGranted() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, "permitAll"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + } + + @Test + public void authorizeWhenPermitAllAndNoAuthenticationThenGranted() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, "permitAll"); + AuthorizationResult decision = this.manager.authorize(Mono.empty(), methodInvocation).block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + } + + @Test + public void authorizeWhenDenyAllAndRoleAdminThenDenied() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, "denyAll"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedAdmin()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenRolesAllowedUserOrAdminAndRoleUserThenGranted() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "rolesAllowedUserOrAdmin"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + } + + @Test + public void authorizeWhenRolesAllowedUserOrAdminAndRoleAnonymousThenDenied() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "rolesAllowedUserOrAdmin"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.anonymousUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenRolesAllowedAndNoAuthenticationThenDenied() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "rolesAllowedUserOrAdmin"); + AuthorizationResult decision = this.manager.authorize(Mono.empty(), methodInvocation).block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenRolesAllowedAndCustomRolePrefixThenUsesPrefix() throws Exception { + this.manager.setRolePrefix("CUSTOM_"); + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "rolesAllowedAdmin"); + Mono customAdmin = Mono + .just(new TestingAuthenticationToken("user", "password", "CUSTOM_ADMIN")); + AuthorizationResult decision = this.manager.authorize(customAdmin, methodInvocation).block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + decision = this.manager.authorize(Mono.just(TestAuthentication.authenticatedAdmin()), methodInvocation).block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenCustomAuthoritiesAuthorizationManagerThenUsesIt() throws Exception { + AuthorizationManager> authoritiesAuthorizationManager = mock(AuthorizationManager.class); + given(authoritiesAuthorizationManager.authorize(any(), eq(Set.of("ROLE_ADMIN")))) + .willReturn(new AuthorizationDecision(true)); + this.manager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager); + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "rolesAllowedAdmin"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + } + + @Test + public void authorizeWhenClassLevelRolesAllowedThenAppliesToMethod() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new ClassLevelAnnotations(), + ClassLevelAnnotations.class, "rolesAllowedClassLevel"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + decision = this.manager.authorize(Mono.just(TestAuthentication.anonymousUser()), methodInvocation).block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenMethodLevelOverridesClassLevelThenUsesMethodLevel() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new ClassLevelAnnotations(), + ClassLevelAnnotations.class, "rolesAllowedAdmin"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenMultipleJsr250AnnotationsThenErrors() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "multipleAnnotations"); + StepVerifier.create(this.manager.authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation)) + .expectError(AnnotationConfigurationException.class) + .verify(); + } + + @Test + public void authorizeWhenInheritedAnnotationThenGranted() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new RolesAllowedUserImpl(), + RolesAllowedUserImpl.class, "doSomething"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + } + + public static class TestClass { + + public void doSomething() { + + } + + @DenyAll + public void denyAll() { + + } + + @PermitAll + public void permitAll() { + + } + + @RolesAllowed("ADMIN") + public void rolesAllowedAdmin() { + + } + + @RolesAllowed({ "USER", "ADMIN" }) + public void rolesAllowedUserOrAdmin() { + + } + + @RolesAllowed("USER") + @DenyAll + public void multipleAnnotations() { + + } + + } + + @RolesAllowed("USER") + public static class ClassLevelAnnotations { + + public void rolesAllowedClassLevel() { + + } + + @RolesAllowed("ADMIN") + public void rolesAllowedAdmin() { + + } + + } + + @Retention(RetentionPolicy.RUNTIME) + @RolesAllowed("USER") + public @interface MyRolesAllowedUser { + + } + + public interface RolesAllowedUserInterface { + + @MyRolesAllowedUser + void doSomething(); + + } + + public static class RolesAllowedUserImpl implements RolesAllowedUserInterface { + + @Override + public void doSomething() { + + } + + } + +} diff --git a/core/src/test/java/org/springframework/security/authorization/method/SecuredReactiveAuthorizationManagerTests.java b/core/src/test/java/org/springframework/security/authorization/method/SecuredReactiveAuthorizationManagerTests.java new file mode 100644 index 00000000000..48508209d9e --- /dev/null +++ b/core/src/test/java/org/springframework/security/authorization/method/SecuredReactiveAuthorizationManagerTests.java @@ -0,0 +1,173 @@ +/* + * Copyright 2004-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.method; + +import java.util.Collection; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import org.springframework.security.access.annotation.Secured; +import org.springframework.security.authentication.TestAuthentication; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.authorization.AuthorizationResult; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** + * Tests for {@link SecuredReactiveAuthorizationManager}. + * + * @author Rohit Behera + */ +public class SecuredReactiveAuthorizationManagerTests { + + private final SecuredReactiveAuthorizationManager manager = new SecuredReactiveAuthorizationManager(); + + @Test + public void setAuthoritiesAuthorizationManagerWhenNullThenException() { + assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesAuthorizationManager(null)) + .withMessage("authoritiesAuthorizationManager cannot be null"); + } + + @Test + public void authorizeWhenNoSecuredAnnotationThenEmpty() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "doSomething"); + StepVerifier.create(this.manager.authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation)) + .verifyComplete(); + } + + @Test + public void authorizeWhenSecuredUserAndRoleUserThenGranted() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "securedUserOrAdmin"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + } + + @Test + public void authorizeWhenSecuredAdminAndRoleUserThenDenied() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "securedAdmin"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenSecuredAndRoleAnonymousThenDenied() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "securedUserOrAdmin"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.anonymousUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenSecuredAndNoAuthenticationThenDenied() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "securedUserOrAdmin"); + AuthorizationResult decision = this.manager.authorize(Mono.empty(), methodInvocation).block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenClassLevelSecuredThenAppliesToMethod() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new ClassLevelAnnotations(), + ClassLevelAnnotations.class, "securedClassLevel"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + } + + @Test + public void authorizeWhenMethodLevelOverridesClassLevelThenUsesMethodLevel() throws Exception { + MockMethodInvocation methodInvocation = new MockMethodInvocation(new ClassLevelAnnotations(), + ClassLevelAnnotations.class, "securedAdmin"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isFalse(); + } + + @Test + public void authorizeWhenCustomAuthoritiesAuthorizationManagerThenUsesIt() throws Exception { + AuthorizationManager> authoritiesAuthorizationManager = mock(AuthorizationManager.class); + given(authoritiesAuthorizationManager.authorize(any(), eq(Set.of("ROLE_ADMIN")))) + .willReturn(new AuthorizationDecision(true)); + this.manager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager); + MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, + "securedAdmin"); + AuthorizationResult decision = this.manager + .authorize(Mono.just(TestAuthentication.authenticatedUser()), methodInvocation) + .block(); + assertThat(decision).isNotNull(); + assertThat(decision.isGranted()).isTrue(); + } + + public static class TestClass { + + public void doSomething() { + + } + + @Secured("ROLE_ADMIN") + public void securedAdmin() { + + } + + @Secured({ "ROLE_USER", "ROLE_ADMIN" }) + public void securedUserOrAdmin() { + + } + + } + + @Secured("ROLE_USER") + public static class ClassLevelAnnotations { + + public void securedClassLevel() { + + } + + @Secured("ROLE_ADMIN") + public void securedAdmin() { + + } + + } + +} diff --git a/docs/modules/ROOT/pages/reactive/authorization/method.adoc b/docs/modules/ROOT/pages/reactive/authorization/method.adoc index bfb6f9daf8d..621661fcb40 100644 --- a/docs/modules/ROOT/pages/reactive/authorization/method.adoc +++ b/docs/modules/ROOT/pages/reactive/authorization/method.adoc @@ -143,6 +143,61 @@ class MethodSecurityConfig { Notice that Spring Security's method security is built using Spring AOP. +[[reactive-secured-jsr250]] +=== Using `@Secured` and JSR-250 Annotations + +You can also enable Spring Security's `@Secured` annotation and the JSR-250 annotations (`@RolesAllowed`, `@PermitAll`, and `@DenyAll`) for reactive methods: + +.Enabling @Secured and JSR-250 Annotations +[tabs] +====== +Java:: ++ +[source,java,role="primary"] +---- +@EnableReactiveMethodSecurity(securedEnabled = true, jsr250Enabled = true) +public class MethodSecurityConfig { + // ... +} +---- + +Kotlin:: ++ +[source,kotlin,role="secondary"] +---- +@EnableReactiveMethodSecurity(securedEnabled = true, jsr250Enabled = true) +class MethodSecurityConfig { + // ... +} +---- +====== + +As with `@PreAuthorize`, the annotated methods must return a `Publisher`, such as a `Mono` or a `Flux`, or be a Kotlin coroutine: + +.@Secured and JSR-250 Annotation Usage +[tabs] +====== +Java:: ++ +[source,java,role="primary"] +---- +public interface BankService { + @RolesAllowed("USER") + Mono readAccount(Long id); + + @Secured("ROLE_TELLER") + Mono post(Account account, Double amount); + + @DenyAll + Mono closeAllAccounts(); +} +---- +====== + +`@RolesAllowed` adds the role prefix, which is `ROLE_` unless you publish a `GrantedAuthorityDefaults` bean, while `@Secured` compares the authorities as written. +`@RolesAllowed` and `@Secured` also apply a `RoleHierarchy` bean when you publish one. +These annotations need `useAuthorizationManager = true`, which is the default. + === Customizing Authorization Spring Security's `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` ship with rich expression-based support.