Search in sources :

Example 31 with MethodInvocation

use of org.aopalliance.intercept.MethodInvocation in project spring-security by spring-projects.

the class MethodInvocationUtilsTests method createFromClassReturnsMethodIfGivenArgInfoForMethodWithArgs.

@Test
public void createFromClassReturnsMethodIfGivenArgInfoForMethodWithArgs() {
    MethodInvocation mi = MethodInvocationUtils.createFromClass(null, String.class, "compareTo", new Class<?>[] { String.class }, new Object[] { "" });
    assertThat(mi).isNotNull();
}
Also used : MethodInvocation(org.aopalliance.intercept.MethodInvocation) Test(org.junit.jupiter.api.Test)

Example 32 with MethodInvocation

use of org.aopalliance.intercept.MethodInvocation in project spring-security by spring-projects.

the class MethodInvocationUtilsTests method createFromObjectLocatesExistingMethods.

@Test
public void createFromObjectLocatesExistingMethods() {
    AdvisedTarget t = new AdvisedTarget();
    // Just lie about interfaces
    t.setInterfaces(new Class[] { Serializable.class, MethodInvocation.class, Blah.class });
    MethodInvocation mi = MethodInvocationUtils.create(t, "blah");
    assertThat(mi).isNotNull();
    t.setProxyTargetClass(true);
    mi = MethodInvocationUtils.create(t, "blah");
    assertThat(mi).isNotNull();
    assertThat(MethodInvocationUtils.create(t, "blah", "non-existent arg")).isNull();
}
Also used : MethodInvocation(org.aopalliance.intercept.MethodInvocation) Test(org.junit.jupiter.api.Test)

Example 33 with MethodInvocation

use of org.aopalliance.intercept.MethodInvocation in project spring-security by spring-projects.

the class MethodInvocationUtils method createFromClass.

/**
 * Generates a <code>MethodInvocation</code> for the specified <code>methodName</code>
 * on the passed class.
 *
 * If a method with this name, taking no arguments does not exist, it will check
 * through the declared methods on the class, until one is found matching the supplied
 * name. If more than one method name matches, an <tt>IllegalArgumentException</tt>
 * will be raised.
 * @param clazz the class of object that will be used to find the relevant
 * <code>Method</code>
 * @param methodName the name of the method to find
 * @return a <code>MethodInvocation</code>, or <code>null</code> if there was a
 * problem
 */
public static MethodInvocation createFromClass(Class<?> clazz, String methodName) {
    MethodInvocation invocation = createFromClass(null, clazz, methodName, null, null);
    if (invocation == null) {
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                Assert.isTrue(invocation == null, () -> "The class " + clazz + " has more than one method named" + " '" + methodName + "'");
                invocation = new SimpleMethodInvocation(null, method);
            }
        }
    }
    return invocation;
}
Also used : MethodInvocation(org.aopalliance.intercept.MethodInvocation) Method(java.lang.reflect.Method)

Example 34 with MethodInvocation

use of org.aopalliance.intercept.MethodInvocation in project spring-security by spring-projects.

the class PrePostAdviceReactiveMethodInterceptor method invoke.

@Override
public Object invoke(final MethodInvocation invocation) {
    Method method = invocation.getMethod();
    Class<?> returnType = method.getReturnType();
    boolean isSuspendingFunction = KotlinDetector.isSuspendingFunction(method);
    boolean hasFlowReturnType = COROUTINES_FLOW_CLASS_NAME.equals(new MethodParameter(method, RETURN_TYPE_METHOD_PARAMETER_INDEX).getParameterType().getName());
    boolean hasReactiveReturnType = Publisher.class.isAssignableFrom(returnType) || isSuspendingFunction || hasFlowReturnType;
    Assert.state(hasReactiveReturnType, () -> "The returnType " + returnType + " on " + method + " must return an instance of org.reactivestreams.Publisher " + "(i.e. Mono / Flux) or the function must be a Kotlin coroutine " + "function in order to support Reactor Context");
    Class<?> targetClass = invocation.getThis().getClass();
    Collection<ConfigAttribute> attributes = this.attributeSource.getAttributes(method, targetClass);
    PreInvocationAttribute preAttr = findPreInvocationAttribute(attributes);
    // @formatter:off
    Mono<Authentication> toInvoke = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).defaultIfEmpty(this.anonymous).filter((auth) -> this.preInvocationAdvice.before(auth, invocation, preAttr)).switchIfEmpty(Mono.defer(() -> Mono.error(new AccessDeniedException("Denied"))));
    // @formatter:on
    PostInvocationAttribute attr = findPostInvocationAttribute(attributes);
    if (Mono.class.isAssignableFrom(returnType)) {
        return toInvoke.flatMap((auth) -> PrePostAdviceReactiveMethodInterceptor.<Mono<?>>proceed(invocation).map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
    }
    if (Flux.class.isAssignableFrom(returnType)) {
        return toInvoke.flatMapMany((auth) -> PrePostAdviceReactiveMethodInterceptor.<Flux<?>>proceed(invocation).map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
    }
    if (hasFlowReturnType) {
        Flux<?> response;
        if (isSuspendingFunction) {
            response = toInvoke.flatMapMany((auth) -> Flux.from(CoroutinesUtils.invokeSuspendingFunction(invocation.getMethod(), invocation.getThis(), invocation.getArguments())).map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
        } else {
            ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(returnType);
            Assert.state(adapter != null, () -> "The returnType " + returnType + " on " + method + " must have a org.springframework.core.ReactiveAdapter registered");
            response = toInvoke.flatMapMany((auth) -> Flux.from(adapter.toPublisher(PrePostAdviceReactiveMethodInterceptor.flowProceed(invocation))).map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
        }
        return KotlinDelegate.asFlow(response);
    }
    if (isSuspendingFunction) {
        Mono<?> response = toInvoke.flatMap((auth) -> Mono.from(CoroutinesUtils.invokeSuspendingFunction(invocation.getMethod(), invocation.getThis(), invocation.getArguments())).map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
        return KotlinDelegate.awaitSingleOrNull(response, invocation.getArguments()[invocation.getArguments().length - 1]);
    }
    return toInvoke.flatMapMany((auth) -> Flux.from(PrePostAdviceReactiveMethodInterceptor.<Publisher<?>>proceed(invocation)).map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
}
Also used : Continuation(kotlin.coroutines.Continuation) AwaitKt(kotlinx.coroutines.reactive.AwaitKt) MethodSecurityMetadataSource(org.springframework.security.access.method.MethodSecurityMetadataSource) KotlinDetector(org.springframework.core.KotlinDetector) MethodInvocation(org.aopalliance.intercept.MethodInvocation) ReactiveSecurityContextHolder(org.springframework.security.core.context.ReactiveSecurityContextHolder) MethodParameter(org.springframework.core.MethodParameter) Method(java.lang.reflect.Method) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) ConfigAttribute(org.springframework.security.access.ConfigAttribute) ReactiveFlowKt(kotlinx.coroutines.reactive.ReactiveFlowKt) CoroutinesUtils(org.springframework.core.CoroutinesUtils) ReactiveAdapter(org.springframework.core.ReactiveAdapter) Collection(java.util.Collection) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) AccessDeniedException(org.springframework.security.access.AccessDeniedException) MethodInterceptor(org.aopalliance.intercept.MethodInterceptor) Flux(reactor.core.publisher.Flux) SecurityContext(org.springframework.security.core.context.SecurityContext) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) Exceptions(reactor.core.Exceptions) Authentication(org.springframework.security.core.Authentication) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) Assert(org.springframework.util.Assert) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ConfigAttribute(org.springframework.security.access.ConfigAttribute) Mono(reactor.core.publisher.Mono) Flux(reactor.core.publisher.Flux) Method(java.lang.reflect.Method) Authentication(org.springframework.security.core.Authentication) MethodParameter(org.springframework.core.MethodParameter) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 35 with MethodInvocation

use of org.aopalliance.intercept.MethodInvocation in project spring-security by spring-projects.

the class AbstractMethodSecurityMetadataSource method getAttributes.

@Override
public final Collection<ConfigAttribute> getAttributes(Object object) {
    if (object instanceof MethodInvocation) {
        MethodInvocation mi = (MethodInvocation) object;
        Object target = mi.getThis();
        Class<?> targetClass = null;
        if (target != null) {
            targetClass = (target instanceof Class<?>) ? (Class<?>) target : AopProxyUtils.ultimateTargetClass(target);
        }
        Collection<ConfigAttribute> attrs = getAttributes(mi.getMethod(), targetClass);
        if (attrs != null && !attrs.isEmpty()) {
            return attrs;
        }
        if (target != null && !(target instanceof Class<?>)) {
            attrs = getAttributes(mi.getMethod(), target.getClass());
        }
        return attrs;
    }
    throw new IllegalArgumentException("Object must be a non-null MethodInvocation");
}
Also used : ConfigAttribute(org.springframework.security.access.ConfigAttribute) MethodInvocation(org.aopalliance.intercept.MethodInvocation)

Aggregations

MethodInvocation (org.aopalliance.intercept.MethodInvocation)117 Test (org.junit.jupiter.api.Test)50 Test (org.junit.Test)35 MethodInterceptor (org.aopalliance.intercept.MethodInterceptor)25 SimpleMethodInvocation (org.springframework.security.util.SimpleMethodInvocation)22 Method (java.lang.reflect.Method)21 ArrayList (java.util.ArrayList)11 Log (org.apache.commons.logging.Log)11 Authentication (org.springframework.security.core.Authentication)10 EvaluationContext (org.springframework.expression.EvaluationContext)9 Expression (org.springframework.expression.Expression)9 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)9 List (java.util.List)7 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)7 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)7 MyThrowsHandler (org.springframework.aop.testfixture.advice.MyThrowsHandler)7 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)7 RemoteInvocation (org.springframework.remoting.support.RemoteInvocation)6 ITestBean (org.springframework.beans.testfixture.beans.ITestBean)5 Promise (ratpack.exec.Promise)5