Move spring-security-webflux into spring-security-web
Fixes gh-4662
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.test.web.reactive.server;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.web.server.SecurityWebFilterChain;
|
||||
import org.springframework.security.web.server.WebFilterChainProxy;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient.Builder;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.WebFilter;
|
||||
|
||||
/**
|
||||
* Provides a convenient mechanism for running {@link WebTestClient} against
|
||||
* {@link WebFilter}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*
|
||||
*/
|
||||
public class WebTestClientBuilder {
|
||||
|
||||
public static Builder bindToWebFilters(WebFilter... webFilters) {
|
||||
return WebTestClient.bindToController(new Http200RestController()).webFilter(webFilters).configureClient();
|
||||
}
|
||||
|
||||
public static Builder bindToWebFilters(SecurityWebFilterChain securityWebFilterChain) {
|
||||
return bindToWebFilters(WebFilterChainProxy.fromSecurityWebFilterChains(securityWebFilterChain));
|
||||
}
|
||||
|
||||
@RestController
|
||||
public static class Http200RestController {
|
||||
@RequestMapping("/**")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public String ok() {
|
||||
return "ok";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.test.web.reactive.server;
|
||||
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest.BaseBuilder;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.WebFilter;
|
||||
import org.springframework.web.server.WebHandler;
|
||||
import org.springframework.web.server.handler.FilteringWebHandler;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class WebTestHandler {
|
||||
private final MockWebHandler webHandler = new MockWebHandler();
|
||||
private final WebHandler handler;
|
||||
|
||||
private WebTestHandler(WebFilter... filters) {
|
||||
this.handler = new FilteringWebHandler(webHandler, Arrays.asList(filters));
|
||||
}
|
||||
|
||||
public WebHandlerResult exchange(BaseBuilder<?> baseBuilder) {
|
||||
ServerWebExchange exchange = MockServerWebExchange.from(baseBuilder.build());
|
||||
return exchange(exchange);
|
||||
}
|
||||
|
||||
public WebHandlerResult exchange(ServerWebExchange exchange) {
|
||||
handler.handle(exchange).block();
|
||||
return new WebHandlerResult(webHandler.exchange);
|
||||
}
|
||||
|
||||
public static class WebHandlerResult {
|
||||
private final ServerWebExchange exchange;
|
||||
|
||||
private WebHandlerResult(ServerWebExchange exchange) {
|
||||
this.exchange = exchange;
|
||||
}
|
||||
|
||||
public ServerWebExchange getExchange() {
|
||||
return exchange;
|
||||
}
|
||||
}
|
||||
|
||||
public static WebTestHandler bindToWebFilters(WebFilter... filters) {
|
||||
return new WebTestHandler(filters);
|
||||
}
|
||||
|
||||
static class MockWebHandler implements WebHandler {
|
||||
private ServerWebExchange exchange;
|
||||
|
||||
@Override
|
||||
public Mono<Void> handle(ServerWebExchange exchange) {
|
||||
this.exchange = exchange;
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.method;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Parameter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.aopalliance.intercept.MethodInterceptor;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.aop.target.EmptyTargetSource;
|
||||
import org.springframework.cglib.core.SpringNamingPolicy;
|
||||
import org.springframework.cglib.proxy.Callback;
|
||||
import org.springframework.cglib.proxy.Enhancer;
|
||||
import org.springframework.cglib.proxy.Factory;
|
||||
import org.springframework.cglib.proxy.MethodProxy;
|
||||
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
|
||||
import org.springframework.core.MethodIntrospector;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.core.ParameterNameDiscoverer;
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.core.annotation.AnnotatedElementUtils;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.core.annotation.SynthesizingMethodParameter;
|
||||
import org.springframework.objenesis.ObjenesisException;
|
||||
import org.springframework.objenesis.SpringObjenesis;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.web.bind.annotation.ValueConstants;
|
||||
|
||||
import static java.util.stream.Collectors.joining;
|
||||
|
||||
/**
|
||||
* Convenience class to resolve method parameters from hints.
|
||||
*
|
||||
* <h1>Background</h1>
|
||||
*
|
||||
* <p>When testing annotated methods we create test classes such as
|
||||
* "TestController" with a diverse range of method signatures representing
|
||||
* supported annotations and argument types. It becomes challenging to use
|
||||
* naming strategies to keep track of methods and arguments especially in
|
||||
* combination with variables for reflection metadata.
|
||||
*
|
||||
* <p>The idea with {@link ResolvableMethod} is NOT to rely on naming techniques
|
||||
* but to use hints to zero in on method parameters. Such hints can be strongly
|
||||
* typed and explicit about what is being tested.
|
||||
*
|
||||
* <h2>1. Declared Return Type</h2>
|
||||
*
|
||||
* When testing return types it's likely to have many methods with a unique
|
||||
* return type, possibly with or without an annotation.
|
||||
*
|
||||
* <pre>
|
||||
*
|
||||
* import static org.springframework.web.method.ResolvableMethod.on;
|
||||
* import static org.springframework.web.method.MvcAnnotationPredicates.requestMapping;
|
||||
*
|
||||
* // Return type
|
||||
* on(TestController.class).resolveReturnType(Foo.class);
|
||||
* on(TestController.class).resolveReturnType(List.class, Foo.class);
|
||||
* on(TestController.class).resolveReturnType(Mono.class, responseEntity(Foo.class));
|
||||
*
|
||||
* // Annotation + return type
|
||||
* on(TestController.class).annotPresent(RequestMapping.class).resolveReturnType(Bar.class);
|
||||
*
|
||||
* // Annotation not present
|
||||
* on(TestController.class).annotNotPresent(RequestMapping.class).resolveReturnType();
|
||||
*
|
||||
* // Annotation with attributes
|
||||
* on(TestController.class).annot(requestMapping("/foo").params("p")).resolveReturnType();
|
||||
* </pre>
|
||||
*
|
||||
* <h2>2. Method Arguments</h2>
|
||||
*
|
||||
* When testing method arguments it's more likely to have one or a small number
|
||||
* of methods with a wide array of argument types and parameter annotations.
|
||||
*
|
||||
* <pre>
|
||||
*
|
||||
* import static org.springframework.web.method.MvcAnnotationPredicates.requestParam;
|
||||
*
|
||||
* ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build();
|
||||
*
|
||||
* testMethod.arg(Foo.class);
|
||||
* testMethod.annotPresent(RequestParam.class).arg(Integer.class);
|
||||
* testMethod.annotNotPresent(RequestParam.class)).arg(Integer.class);
|
||||
* testMethod.annot(requestParam().name("c").notRequired()).arg(Integer.class);
|
||||
* </pre>
|
||||
*
|
||||
* <h3>3. Mock Handler Method Invocation</h3>
|
||||
*
|
||||
* Locate a method by invoking it through a proxy of the target handler:
|
||||
*
|
||||
* <pre>
|
||||
*
|
||||
* ResolvableMethod.on(TestController.class).mockCall(o -> o.handle(null)).method();
|
||||
* </pre>
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
* @since 5.0
|
||||
*/
|
||||
public class ResolvableMethod {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(ResolvableMethod.class);
|
||||
|
||||
private static final SpringObjenesis objenesis = new SpringObjenesis();
|
||||
|
||||
private static final ParameterNameDiscoverer nameDiscoverer =
|
||||
new LocalVariableTableParameterNameDiscoverer();
|
||||
|
||||
|
||||
private final Method method;
|
||||
|
||||
|
||||
private ResolvableMethod(Method method) {
|
||||
Assert.notNull(method, "method is required");
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return the resolved method.
|
||||
*/
|
||||
public Method method() {
|
||||
return this.method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the declared return type of the resolved method.
|
||||
*/
|
||||
public MethodParameter returnType() {
|
||||
return new SynthesizingMethodParameter(this.method, -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a unique argument matching the given type.
|
||||
* @param type the expected type
|
||||
* @param generics optional array of generic types
|
||||
*/
|
||||
public MethodParameter arg(Class<?> type, Class<?>... generics) {
|
||||
return new ArgResolver().arg(type, generics);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a unique argument matching the given type.
|
||||
* @param type the expected type
|
||||
* @param generic at least one generic type
|
||||
* @param generics optional array of generic types
|
||||
*/
|
||||
public MethodParameter arg(Class<?> type, ResolvableType generic, ResolvableType... generics) {
|
||||
return new ArgResolver().arg(type, generic, generics);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a unique argument matching the given type.
|
||||
* @param type the expected type
|
||||
*/
|
||||
public MethodParameter arg(ResolvableType type) {
|
||||
return new ArgResolver().arg(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on method arguments with annotation.
|
||||
* See {@link MvcAnnotationPredicates}.
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final ArgResolver annot(Predicate<MethodParameter>... filter) {
|
||||
return new ArgResolver(filter);
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) {
|
||||
return new ArgResolver().annotPresent(annotationTypes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on method arguments that don't have the given annotation type(s).
|
||||
* @param annotationTypes the annotation types
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final ArgResolver annotNotPresent(Class<? extends Annotation>... annotationTypes) {
|
||||
return new ArgResolver().annotNotPresent(annotationTypes);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ResolvableMethod=" + formatMethod();
|
||||
}
|
||||
|
||||
private String formatMethod() {
|
||||
return this.method().getName() +
|
||||
Arrays.stream(this.method.getParameters())
|
||||
.map(this::formatParameter)
|
||||
.collect(joining(",\n\t", "(\n\t", "\n)"));
|
||||
}
|
||||
|
||||
private String formatParameter(Parameter param) {
|
||||
Annotation[] annot = param.getAnnotations();
|
||||
return annot.length > 0 ?
|
||||
Arrays.stream(annot).map(this::formatAnnotation).collect(joining(",", "[", "]")) + " " + param :
|
||||
param.toString();
|
||||
}
|
||||
|
||||
private String formatAnnotation(Annotation annotation) {
|
||||
Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation);
|
||||
map.forEach((key, value) -> {
|
||||
if (value.equals(ValueConstants.DEFAULT_NONE)) {
|
||||
map.put(key, "NONE");
|
||||
}
|
||||
});
|
||||
return annotation.annotationType().getName() + map;
|
||||
}
|
||||
|
||||
private static ResolvableType toResolvableType(Class<?> type, Class<?>... generics) {
|
||||
return ObjectUtils.isEmpty(generics) ?
|
||||
ResolvableType.forClass(type) :
|
||||
ResolvableType.forClassWithGenerics(type, generics);
|
||||
}
|
||||
|
||||
private static ResolvableType toResolvableType(Class<?> type, ResolvableType generic, ResolvableType... generics) {
|
||||
ResolvableType[] genericTypes = new ResolvableType[generics.length + 1];
|
||||
genericTypes[0] = generic;
|
||||
System.arraycopy(generics, 0, genericTypes, 1, generics.length);
|
||||
return ResolvableType.forClassWithGenerics(type, genericTypes);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Main entry point providing access to a {@code ResolvableMethod} builder.
|
||||
*/
|
||||
public static <T> Builder<T> on(Class<T> objectClass) {
|
||||
return new Builder<>(objectClass);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Builder for {@code ResolvableMethod}.
|
||||
*/
|
||||
public static class Builder<T> {
|
||||
|
||||
private final Class<?> objectClass;
|
||||
|
||||
private final List<Predicate<Method>> filters = new ArrayList<>(4);
|
||||
|
||||
|
||||
private Builder(Class<?> objectClass) {
|
||||
Assert.notNull(objectClass, "Class must not be null");
|
||||
this.objectClass = objectClass;
|
||||
}
|
||||
|
||||
|
||||
private void addFilter(String message, Predicate<Method> filter) {
|
||||
this.filters.add(new LabeledPredicate<>(message, filter));
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on methods with the given name.
|
||||
*/
|
||||
public Builder<T> named(String methodName) {
|
||||
addFilter("methodName=" + methodName, m -> m.getName().equals(methodName));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on annotated methods.
|
||||
* See {@link MvcAnnotationPredicates}.
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final Builder<T> annot(Predicate<Method>... filters) {
|
||||
this.filters.addAll(Arrays.asList(filters));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on methods annotated with the given annotation type.
|
||||
* @see #annot(Predicate[])
|
||||
* @see MvcAnnotationPredicates
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final Builder<T> annotPresent(Class<? extends Annotation>... annotationTypes) {
|
||||
String message = "annotationPresent=" + Arrays.toString(annotationTypes);
|
||||
addFilter(message, method ->
|
||||
Arrays.stream(annotationTypes).allMatch(annotType ->
|
||||
AnnotatedElementUtils.findMergedAnnotation(method, annotType) != null));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on methods not annotated with the given annotation type.
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final Builder<T> annotNotPresent(Class<? extends Annotation>... annotationTypes) {
|
||||
String message = "annotationNotPresent=" + Arrays.toString(annotationTypes);
|
||||
addFilter(message, method -> {
|
||||
if (annotationTypes.length != 0) {
|
||||
return Arrays.stream(annotationTypes).noneMatch(annotType ->
|
||||
AnnotatedElementUtils.findMergedAnnotation(method, annotType) != null);
|
||||
}
|
||||
else {
|
||||
return method.getAnnotations().length == 0;
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on methods returning the given type.
|
||||
* @param returnType the return type
|
||||
* @param generics optional array of generic types
|
||||
*/
|
||||
public Builder<T> returning(Class<?> returnType, Class<?>... generics) {
|
||||
return returning(toResolvableType(returnType, generics));
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on methods returning the given type with generics.
|
||||
* @param returnType the return type
|
||||
* @param generic at least one generic type
|
||||
* @param generics optional extra generic types
|
||||
*/
|
||||
public Builder<T> returning(Class<?> returnType, ResolvableType generic, ResolvableType... generics) {
|
||||
return returning(toResolvableType(returnType, generic, generics));
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on methods returning the given type.
|
||||
* @param returnType the return type
|
||||
*/
|
||||
public Builder<T> returning(ResolvableType returnType) {
|
||||
String expected = returnType.toString();
|
||||
String message = "returnType=" + expected;
|
||||
addFilter(message, m -> expected.equals(ResolvableType.forMethodReturnType(m).toString()));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a {@code ResolvableMethod} from the provided filters which must
|
||||
* resolve to a unique, single method.
|
||||
*
|
||||
* <p>See additional resolveXxx shortcut methods going directly to
|
||||
* {@link Method} or return type parameter.
|
||||
*
|
||||
* @throws IllegalStateException for no match or multiple matches
|
||||
*/
|
||||
public ResolvableMethod build() {
|
||||
Set<Method> methods = MethodIntrospector.selectMethods(this.objectClass, this::isMatch);
|
||||
Assert.state(!methods.isEmpty(), "No matching method: " + this);
|
||||
Assert.state(methods.size() == 1, "Multiple matching methods: " + this + formatMethods(methods));
|
||||
return new ResolvableMethod(methods.iterator().next());
|
||||
}
|
||||
|
||||
private boolean isMatch(Method method) {
|
||||
return this.filters.stream().allMatch(p -> p.test(method));
|
||||
}
|
||||
|
||||
private String formatMethods(Set<Method> methods) {
|
||||
return "\nMatched:\n" + methods.stream()
|
||||
.map(Method::toGenericString).collect(joining(",\n\t", "[\n\t", "\n]"));
|
||||
}
|
||||
|
||||
public ResolvableMethod mockCall(Consumer<T> invoker) {
|
||||
MethodInvocationInterceptor interceptor = new MethodInvocationInterceptor();
|
||||
T proxy = initProxy(this.objectClass, interceptor);
|
||||
invoker.accept(proxy);
|
||||
Method method = interceptor.getInvokedMethod();
|
||||
return new ResolvableMethod(method);
|
||||
}
|
||||
|
||||
|
||||
// Build & resolve shortcuts...
|
||||
|
||||
/**
|
||||
* Resolve and return the {@code Method} equivalent to:
|
||||
* <p>{@code build().method()}
|
||||
*/
|
||||
public final Method resolveMethod() {
|
||||
return build().method();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and return the {@code Method} equivalent to:
|
||||
* <p>{@code named(methodName).build().method()}
|
||||
*/
|
||||
public Method resolveMethod(String methodName) {
|
||||
return named(methodName).build().method();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and return the declared return type equivalent to:
|
||||
* <p>{@code build().returnType()}
|
||||
*/
|
||||
public final MethodParameter resolveReturnType() {
|
||||
return build().returnType();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortcut to the unique return type equivalent to:
|
||||
* <p>{@code returning(returnType).build().returnType()}
|
||||
* @param returnType the return type
|
||||
* @param generics optional array of generic types
|
||||
*/
|
||||
public MethodParameter resolveReturnType(Class<?> returnType, Class<?>... generics) {
|
||||
return returning(returnType, generics).build().returnType();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortcut to the unique return type equivalent to:
|
||||
* <p>{@code returning(returnType).build().returnType()}
|
||||
* @param returnType the return type
|
||||
* @param generic at least one generic type
|
||||
* @param generics optional extra generic types
|
||||
*/
|
||||
public MethodParameter resolveReturnType(Class<?> returnType, ResolvableType generic,
|
||||
ResolvableType... generics) {
|
||||
|
||||
return returning(returnType, generic, generics).build().returnType();
|
||||
}
|
||||
|
||||
public MethodParameter resolveReturnType(ResolvableType returnType) {
|
||||
return returning(returnType).build().returnType();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ResolvableMethod.Builder[\n" +
|
||||
"\tobjectClass = " + this.objectClass.getName() + ",\n" +
|
||||
"\tfilters = " + formatFilters() + "\n]";
|
||||
}
|
||||
|
||||
private String formatFilters() {
|
||||
return this.filters.stream().map(Object::toString)
|
||||
.collect(joining(",\n\t\t", "[\n\t\t", "\n\t]"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Predicate with a descriptive label.
|
||||
*/
|
||||
private static class LabeledPredicate<T> implements Predicate<T> {
|
||||
|
||||
private final String label;
|
||||
|
||||
private final Predicate<T> delegate;
|
||||
|
||||
|
||||
private LabeledPredicate(String label, Predicate<T> delegate) {
|
||||
this.label = label;
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean test(T method) {
|
||||
return this.delegate.test(method);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Predicate<T> and(Predicate<? super T> other) {
|
||||
return this.delegate.and(other);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Predicate<T> negate() {
|
||||
return this.delegate.negate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Predicate<T> or(Predicate<? super T> other) {
|
||||
return this.delegate.or(other);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.label;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolver for method arguments.
|
||||
*/
|
||||
public class ArgResolver {
|
||||
|
||||
private final List<Predicate<MethodParameter>> filters = new ArrayList<>(4);
|
||||
|
||||
|
||||
@SafeVarargs
|
||||
private ArgResolver(Predicate<MethodParameter>... filter) {
|
||||
this.filters.addAll(Arrays.asList(filter));
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on method arguments with annotations.
|
||||
* See {@link MvcAnnotationPredicates}.
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final ArgResolver annot(Predicate<MethodParameter>... filters) {
|
||||
this.filters.addAll(Arrays.asList(filters));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on method arguments that have the given annotations.
|
||||
* @param annotationTypes the annotation types
|
||||
* @see #annot(Predicate[])
|
||||
* @see MvcAnnotationPredicates
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) {
|
||||
this.filters.add(param -> Arrays.stream(annotationTypes).allMatch(param::hasParameterAnnotation));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter on method arguments that don't have the given annotations.
|
||||
* @param annotationTypes the annotation types
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final ArgResolver annotNotPresent(Class<? extends Annotation>... annotationTypes) {
|
||||
this.filters.add(param ->
|
||||
(annotationTypes.length != 0) ?
|
||||
Arrays.stream(annotationTypes).noneMatch(param::hasParameterAnnotation) :
|
||||
param.getParameterAnnotations().length == 0);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the argument also matching to the given type.
|
||||
* @param type the expected type
|
||||
*/
|
||||
public MethodParameter arg(Class<?> type, Class<?>... generics) {
|
||||
return arg(toResolvableType(type, generics));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the argument also matching to the given type.
|
||||
* @param type the expected type
|
||||
*/
|
||||
public MethodParameter arg(Class<?> type, ResolvableType generic, ResolvableType... generics) {
|
||||
return arg(toResolvableType(type, generic, generics));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the argument also matching to the given type.
|
||||
* @param type the expected type
|
||||
*/
|
||||
public MethodParameter arg(ResolvableType type) {
|
||||
this.filters.add(p -> type.toString().equals(ResolvableType.forMethodParameter(p).toString()));
|
||||
return arg();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the argument.
|
||||
*/
|
||||
public final MethodParameter arg() {
|
||||
List<MethodParameter> matches = applyFilters();
|
||||
Assert.state(!matches.isEmpty(), () ->
|
||||
"No matching arg in method\n" + formatMethod());
|
||||
Assert.state(matches.size() == 1, () ->
|
||||
"Multiple matching args in method\n" + formatMethod() + "\nMatches:\n\t" + matches);
|
||||
return matches.get(0);
|
||||
}
|
||||
|
||||
|
||||
private List<MethodParameter> applyFilters() {
|
||||
List<MethodParameter> matches = new ArrayList<>();
|
||||
for (int i = 0; i < method.getParameterCount(); i++) {
|
||||
MethodParameter param = new SynthesizingMethodParameter(method, i);
|
||||
param.initParameterNameDiscovery(nameDiscoverer);
|
||||
if (this.filters.stream().allMatch(p -> p.test(param))) {
|
||||
matches.add(param);
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
}
|
||||
|
||||
private static class MethodInvocationInterceptor
|
||||
implements org.springframework.cglib.proxy.MethodInterceptor, MethodInterceptor {
|
||||
|
||||
private Method invokedMethod;
|
||||
|
||||
|
||||
Method getInvokedMethod() {
|
||||
return this.invokedMethod;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) {
|
||||
if (ReflectionUtils.isObjectMethod(method)) {
|
||||
return ReflectionUtils.invokeMethod(method, object, args);
|
||||
}
|
||||
else {
|
||||
this.invokedMethod = method;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(org.aopalliance.intercept.MethodInvocation inv) throws Throwable {
|
||||
return intercept(inv.getThis(), inv.getMethod(), inv.getArguments(), null);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> T initProxy(Class<?> type, MethodInvocationInterceptor interceptor) {
|
||||
Assert.notNull(type, "'type' must not be null");
|
||||
if (type.isInterface()) {
|
||||
ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE);
|
||||
factory.addInterface(type);
|
||||
factory.addInterface(Supplier.class);
|
||||
factory.addAdvice(interceptor);
|
||||
return (T) factory.getProxy();
|
||||
}
|
||||
|
||||
else {
|
||||
Enhancer enhancer = new Enhancer();
|
||||
enhancer.setSuperclass(type);
|
||||
enhancer.setInterfaces(new Class<?>[] {Supplier.class});
|
||||
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
|
||||
enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);
|
||||
|
||||
Class<?> proxyClass = enhancer.createClass();
|
||||
Object proxy = null;
|
||||
|
||||
if (objenesis.isWorthTrying()) {
|
||||
try {
|
||||
proxy = objenesis.newInstance(proxyClass, enhancer.getUseCache());
|
||||
}
|
||||
catch (ObjenesisException ex) {
|
||||
logger.debug("Objenesis failed, falling back to default constructor", ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (proxy == null) {
|
||||
try {
|
||||
proxy = ReflectionUtils.accessibleConstructor(proxyClass).newInstance();
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
throw new IllegalStateException("Unable to instantiate proxy " +
|
||||
"via both Objenesis and default constructor fails as well", ex);
|
||||
}
|
||||
}
|
||||
|
||||
((Factory) proxy).setCallbacks(new Callback[] {interceptor});
|
||||
return (T) proxy;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.reactive.result.method.annotation;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.core.ReactiveAdapterRegistry;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.web.method.ResolvableMethod;
|
||||
import org.springframework.web.reactive.BindingContext;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AuthenticationPrincipalArgumentResolverTests {
|
||||
@Mock
|
||||
ServerWebExchange exchange;
|
||||
@Mock
|
||||
BindingContext bindingContext;
|
||||
@Mock
|
||||
Authentication authentication;
|
||||
|
||||
ResolvableMethod authenticationPrincipal = ResolvableMethod.on(getClass()).named("authenticationPrincipal").build();
|
||||
ResolvableMethod spel = ResolvableMethod.on(getClass()).named("spel").build();
|
||||
ResolvableMethod meta = ResolvableMethod.on(getClass()).named("meta").build();
|
||||
|
||||
AuthenticationPrincipalArgumentResolver resolver;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
resolver = new AuthenticationPrincipalArgumentResolver(new ReactiveAdapterRegistry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsParameterAuthenticationPrincipal() throws Exception {
|
||||
assertThat(resolver.supportsParameter(this.authenticationPrincipal.arg(String.class))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsParameterCurrentUser() throws Exception {
|
||||
assertThat(resolver.supportsParameter(this.meta.arg(String.class))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveArgumentWhenIsAuthenticationThenObtainsPrincipal() throws Exception {
|
||||
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
|
||||
when(authentication.getPrincipal()).thenReturn("user");
|
||||
when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));
|
||||
|
||||
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
|
||||
|
||||
assertThat(argument.block()).isEqualTo(authentication.getPrincipal());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveArgumentWhenIsNotAuthenticationThenMonoEmpty() throws Exception {
|
||||
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
|
||||
when(exchange.getPrincipal()).thenReturn(Mono.just(() -> ""));
|
||||
|
||||
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
|
||||
|
||||
assertThat(argument).isNotNull();
|
||||
assertThat(argument.block()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveArgumentWhenIsEmptyThenMonoEmpty() throws Exception {
|
||||
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
|
||||
when(exchange.getPrincipal()).thenReturn(Mono.empty());
|
||||
|
||||
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
|
||||
|
||||
assertThat(argument).isNotNull();
|
||||
assertThat(argument.block()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveArgumentWhenMonoIsAuthenticationThenObtainsPrincipal() throws Exception {
|
||||
MethodParameter parameter = this.authenticationPrincipal.arg(Mono.class, String.class);
|
||||
when(authentication.getPrincipal()).thenReturn("user");
|
||||
when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));
|
||||
|
||||
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
|
||||
|
||||
assertThat(argument.cast(Mono.class).block().block()).isEqualTo(authentication.getPrincipal());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveArgumentWhenSpelThenObtainsPrincipal() throws Exception {
|
||||
MyUser user = new MyUser(3L);
|
||||
MethodParameter parameter = this.spel.arg(Long.class);
|
||||
when(authentication.getPrincipal()).thenReturn(user);
|
||||
when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));
|
||||
|
||||
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
|
||||
|
||||
assertThat(argument.block()).isEqualTo(user.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveArgumentWhenMetaThenObtainsPrincipal() throws Exception {
|
||||
MethodParameter parameter = this.meta.arg(String.class);
|
||||
when(authentication.getPrincipal()).thenReturn("user");
|
||||
when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));
|
||||
|
||||
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
|
||||
|
||||
assertThat(argument.block()).isEqualTo("user");
|
||||
}
|
||||
|
||||
|
||||
void authenticationPrincipal(@AuthenticationPrincipal String principal, @AuthenticationPrincipal Mono<String> monoPrincipal) {}
|
||||
|
||||
void spel(@AuthenticationPrincipal(expression = "id") Long id) {}
|
||||
|
||||
void meta(@CurrentUser String principal) {}
|
||||
|
||||
static class MyUser {
|
||||
private final Long id;
|
||||
|
||||
MyUser(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
@Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@AuthenticationPrincipal
|
||||
public @interface CurrentUser {}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultServerRedirectStrategyTests {
|
||||
|
||||
@Mock
|
||||
private ServerWebExchange exchange;
|
||||
|
||||
private URI location = URI.create("/login");
|
||||
|
||||
private DefaultServerRedirectStrategy strategy =
|
||||
new DefaultServerRedirectStrategy();
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void sendRedirectWhenLocationNullThenException() {
|
||||
this.strategy.sendRedirect(this.exchange, (URI) null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void sendRedirectWhenExchangeNullThenException() {
|
||||
this.strategy.sendRedirect((ServerWebExchange) null, this.location);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectWhenNoSubscribersThenNoActions() {
|
||||
this.strategy.sendRedirect(this.exchange, this.location);
|
||||
|
||||
verifyZeroInteractions(this.exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectWhenNoContextPathThenStatusAndLocationSet() {
|
||||
this.exchange = exchange(MockServerHttpRequest.get("/"));
|
||||
|
||||
this.strategy.sendRedirect(this.exchange, this.location).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(
|
||||
HttpStatus.FOUND);
|
||||
assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectWhenContextPathSetThenStatusAndLocationSet() {
|
||||
this.exchange = exchange(MockServerHttpRequest.get("/context/foo").contextPath("/context"));
|
||||
|
||||
this.strategy.sendRedirect(this.exchange, this.location).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||
assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath("/context" + this.location.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectWhenContextPathSetAndAbsoluteURLThenStatusAndLocationSet() {
|
||||
this.location = URI.create("https://example.com/foo/bar");
|
||||
this.exchange = exchange(MockServerHttpRequest.get("/context/foo").contextPath("/context"));
|
||||
|
||||
this.strategy.sendRedirect(this.exchange, this.location).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||
assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectWhenContextPathSetAndDisabledThenStatusAndLocationSet() {
|
||||
this.strategy.setContextRelative(false);
|
||||
this.exchange = exchange(MockServerHttpRequest.get("/context/foo").contextPath("/context"));
|
||||
|
||||
this.strategy.sendRedirect(this.exchange, this.location).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||
assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectWhenCustomStatusThenStatusSet() {
|
||||
HttpStatus status = HttpStatus.MOVED_PERMANENTLY;
|
||||
this.strategy.setHttpStatus(status);
|
||||
this.exchange = exchange(MockServerHttpRequest.get("/"));
|
||||
|
||||
this.strategy.sendRedirect(this.exchange, this.location).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(status);
|
||||
assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location.getPath());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setHttpStatusWhenNullThenException() {
|
||||
this.strategy.setHttpStatus(null);
|
||||
}
|
||||
|
||||
private static MockServerWebExchange exchange(MockServerHttpRequest.BaseBuilder<?> request) {
|
||||
return MockServerWebExchange.from(request.build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.security.web.server.DelegatingServerAuthenticationEntryPoint.*;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DelegatingServerAuthenticationEntryPointTests {
|
||||
private ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
@Mock
|
||||
private ServerWebExchangeMatcher matcher1;
|
||||
@Mock
|
||||
private ServerWebExchangeMatcher matcher2;
|
||||
@Mock
|
||||
private ServerAuthenticationEntryPoint delegate1;
|
||||
@Mock
|
||||
private ServerAuthenticationEntryPoint delegate2;
|
||||
|
||||
private AuthenticationException e = new AuthenticationCredentialsNotFoundException("Log In");
|
||||
private DelegatingServerAuthenticationEntryPoint entryPoint;
|
||||
|
||||
@Test
|
||||
public void commenceWhenNotMatchThenMatchThenOnlySecondDelegateInvoked() {
|
||||
Mono<Void> expectedResult = Mono.empty();
|
||||
when(this.matcher1.matches(this.exchange)).thenReturn(
|
||||
ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
when(this.matcher2.matches(this.exchange)).thenReturn(
|
||||
ServerWebExchangeMatcher.MatchResult.match());
|
||||
when(this.delegate2.commence(this.exchange, this.e)).thenReturn(expectedResult);
|
||||
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(
|
||||
new DelegateEntry(this.matcher1, this.delegate1),
|
||||
new DelegateEntry(this.matcher2, this.delegate2));
|
||||
|
||||
Mono<Void> actualResult = this.entryPoint.commence(this.exchange, this.e);
|
||||
actualResult.block();
|
||||
|
||||
verifyZeroInteractions(this.delegate1);
|
||||
verify(this.delegate2).commence(this.exchange, this.e);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commenceWhenNotMatchThenDefault() {
|
||||
when(this.matcher1.matches(this.exchange)).thenReturn(
|
||||
ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(
|
||||
new DelegateEntry(this.matcher1, this.delegate1));
|
||||
|
||||
this.entryPoint.commence(this.exchange, this.e).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(
|
||||
HttpStatus.UNAUTHORIZED);
|
||||
verifyZeroInteractions(this.delegate1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ServerFormLoginAuthenticationConverterTests {
|
||||
@Mock
|
||||
private ServerWebExchange exchange;
|
||||
|
||||
private MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
|
||||
|
||||
private ServerFormLoginAuthenticationConverter converter = new ServerFormLoginAuthenticationConverter();
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
when(this.exchange.getFormData()).thenReturn(Mono.just(this.data));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyWhenUsernameAndPasswordThenCreatesTokenSuccess() {
|
||||
String username = "username";
|
||||
String password = "password";
|
||||
this.data.add("username", username);
|
||||
this.data.add("password", password);
|
||||
|
||||
Authentication authentication = this.converter.apply(this.exchange).block();
|
||||
|
||||
assertThat(authentication.getName()).isEqualTo(username);
|
||||
assertThat(authentication.getCredentials()).isEqualTo(password);
|
||||
assertThat(authentication.getAuthorities()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyWhenCustomParametersAndUsernameAndPasswordThenCreatesTokenSuccess() {
|
||||
String usernameParameter = "j_username";
|
||||
String passwordParameter = "j_password";
|
||||
String username = "username";
|
||||
String password = "password";
|
||||
this.converter.setUsernameParameter(usernameParameter);
|
||||
this.converter.setPasswordParameter(passwordParameter);
|
||||
this.data.add(usernameParameter, username);
|
||||
this.data.add(passwordParameter, password);
|
||||
|
||||
Authentication authentication = this.converter.apply(this.exchange).block();
|
||||
|
||||
assertThat(authentication.getName()).isEqualTo(username);
|
||||
assertThat(authentication.getCredentials()).isEqualTo(password);
|
||||
assertThat(authentication.getAuthorities()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyWhenNoDataThenCreatesTokenSuccess() {
|
||||
Authentication authentication = this.converter.apply(this.exchange).block();
|
||||
|
||||
assertThat(authentication.getName()).isNullOrEmpty();
|
||||
assertThat(authentication.getCredentials()).isNull();
|
||||
assertThat(authentication.getAuthorities()).isEmpty();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setUsernameParameterWhenNullThenIllegalArgumentException() {
|
||||
this.converter.setUsernameParameter(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setPasswordParameterWhenNullThenIllegalArgumentException() {
|
||||
this.converter.setPasswordParameter(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class ServerHttpBasicAuthenticationConverterTests {
|
||||
|
||||
ServerHttpBasicAuthenticationConverter converter = new ServerHttpBasicAuthenticationConverter();
|
||||
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/");
|
||||
|
||||
@Test
|
||||
public void applyWhenNoAuthorizationHeaderThenEmpty() {
|
||||
Mono<Authentication> result = apply(this.request);
|
||||
|
||||
assertThat(result.block()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyWhenEmptyAuthorizationHeaderThenEmpty() {
|
||||
Mono<Authentication> result = apply(this.request.header(HttpHeaders.AUTHORIZATION, ""));
|
||||
|
||||
assertThat(result.block()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyWhenOnlyBasicAuthorizationHeaderThenEmpty() {
|
||||
Mono<Authentication> result = apply(this.request.header(HttpHeaders.AUTHORIZATION, "Basic "));
|
||||
|
||||
assertThat(result.block()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyWhenNotBase64ThenEmpty() {
|
||||
Mono<Authentication> result = apply(this.request.header(HttpHeaders.AUTHORIZATION, "Basic z"));
|
||||
|
||||
assertThat(result.block()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyWhenNoSemicolonThenEmpty() {
|
||||
Mono<Authentication> result = apply(this.request.header(HttpHeaders.AUTHORIZATION, "Basic dXNlcg=="));
|
||||
|
||||
assertThat(result.block()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyWhenUserPasswordThenAuthentication() {
|
||||
Mono<Authentication> result = apply(this.request.header(HttpHeaders.AUTHORIZATION, "Basic dXNlcjpwYXNzd29yZA=="));
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication = result.cast(UsernamePasswordAuthenticationToken.class).block();
|
||||
assertThat(authentication.getPrincipal()).isEqualTo("user");
|
||||
assertThat(authentication.getCredentials()).isEqualTo("password");
|
||||
}
|
||||
|
||||
private Mono<Authentication> apply(MockServerHttpRequest.BaseBuilder<?> request) {
|
||||
return this.converter.apply(MockServerWebExchange.from(this.request.build()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.WebFilterChain;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class WebFilterExchangeTests {
|
||||
@Mock
|
||||
private ServerWebExchange exchange;
|
||||
@Mock
|
||||
private WebFilterChain chain;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorServerWebExchangeWebFilterChainWhenExchangeNullThenException() {
|
||||
this. exchange = null;
|
||||
new WebFilterExchange(this.exchange, this.chain);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorServerWebExchangeWebFilterChainWhenChainNullThenException() {
|
||||
this. chain = null;
|
||||
new WebFilterExchange(this.exchange, this.chain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getExchange() {
|
||||
WebFilterExchange filterExchange = new WebFilterExchange(this.exchange, this.chain);
|
||||
|
||||
assertThat(filterExchange.getExchange()).isEqualTo(this.exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getChain() {
|
||||
WebFilterExchange filterExchange = new WebFilterExchange(this.exchange, this.chain);
|
||||
|
||||
assertThat(filterExchange.getChain()).isEqualTo(this.chain);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.authentication;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.ReactiveAuthenticationManager;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
|
||||
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
|
||||
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
|
||||
import org.springframework.test.web.reactive.server.EntityExchangeResult;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;
|
||||
import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.Credentials.basicAuthenticationCredentials;
|
||||
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AuthenticationWebFilterTests {
|
||||
@Mock
|
||||
private ServerAuthenticationSuccessHandler successHandler;
|
||||
@Mock
|
||||
private Function<ServerWebExchange,Mono<Authentication>> authenticationConverter;
|
||||
@Mock
|
||||
private ReactiveAuthenticationManager authenticationManager;
|
||||
@Mock
|
||||
private ServerAuthenticationFailureHandler failureHandler;
|
||||
@Mock
|
||||
private ServerSecurityContextRepository serverSecurityContextRepository;
|
||||
|
||||
private AuthenticationWebFilter filter;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.filter = new AuthenticationWebFilter(this.authenticationManager);
|
||||
this.filter.setServerAuthenticationSuccessHandler(this.successHandler);
|
||||
this.filter.setAuthenticationConverter(this.authenticationConverter);
|
||||
this.filter.setServerSecurityContextRepository(this.serverSecurityContextRepository);
|
||||
this.filter.setServerAuthenticationFailureHandler(this.failureHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenDefaultsAndNoAuthenticationThenContinues() {
|
||||
this.filter = new AuthenticationWebFilter(this.authenticationManager);
|
||||
|
||||
WebTestClient client = WebTestClientBuilder
|
||||
.bindToWebFilters(this.filter)
|
||||
.build();
|
||||
|
||||
EntityExchangeResult<String> result = client.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).consumeWith(b -> assertThat(b.getResponseBody()).isEqualTo("ok"))
|
||||
.returnResult();
|
||||
|
||||
verifyZeroInteractions(this.authenticationManager);
|
||||
assertThat(result.getResponseCookies()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() {
|
||||
when(this.authenticationManager.authenticate(any())).thenReturn(Mono.just(new TestingAuthenticationToken("test","this", "ROLE")));
|
||||
this.filter = new AuthenticationWebFilter(this.authenticationManager);
|
||||
|
||||
WebTestClient client = WebTestClientBuilder
|
||||
.bindToWebFilters(this.filter)
|
||||
.filter(basicAuthentication())
|
||||
.build();
|
||||
|
||||
EntityExchangeResult<String> result = client
|
||||
.get()
|
||||
.uri("/")
|
||||
.attributes(basicAuthenticationCredentials("test", "this"))
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).consumeWith(b -> assertThat(b.getResponseBody()).isEqualTo("ok"))
|
||||
.returnResult();
|
||||
|
||||
assertThat(result.getResponseCookies()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() {
|
||||
when(this.authenticationManager.authenticate(any())).thenReturn(Mono.error(new BadCredentialsException("failed")));
|
||||
this.filter = new AuthenticationWebFilter(this.authenticationManager);
|
||||
|
||||
WebTestClient client = WebTestClientBuilder
|
||||
.bindToWebFilters(this.filter)
|
||||
.filter(basicAuthentication())
|
||||
.build();
|
||||
|
||||
EntityExchangeResult<Void> result = client
|
||||
.get()
|
||||
.uri("/")
|
||||
.attributes(basicAuthenticationCredentials("test", "this"))
|
||||
.exchange()
|
||||
.expectStatus().isUnauthorized()
|
||||
.expectHeader().valueMatches("WWW-Authenticate", "Basic realm=\"Realm\"")
|
||||
.expectBody().isEmpty();
|
||||
|
||||
assertThat(result.getResponseCookies()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenConvertEmptyThenOk() {
|
||||
when(this.authenticationConverter.apply(any())).thenReturn(Mono.empty());
|
||||
|
||||
WebTestClient client = WebTestClientBuilder
|
||||
.bindToWebFilters(this.filter)
|
||||
.build();
|
||||
|
||||
client
|
||||
.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).consumeWith(b -> assertThat(b.getResponseBody()).isEqualTo("ok"))
|
||||
.returnResult();
|
||||
|
||||
verify(this.serverSecurityContextRepository, never()).save(any(), any());
|
||||
verifyZeroInteractions(this.authenticationManager, this.successHandler,
|
||||
this.failureHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenConvertErrorThenServerError() {
|
||||
when(this.authenticationConverter.apply(any())).thenReturn(Mono.error(new RuntimeException("Unexpected")));
|
||||
|
||||
WebTestClient client = WebTestClientBuilder
|
||||
.bindToWebFilters(this.filter)
|
||||
.build();
|
||||
|
||||
client
|
||||
.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus().is5xxServerError()
|
||||
.expectBody().isEmpty();
|
||||
|
||||
verify(this.serverSecurityContextRepository, never()).save(any(), any());
|
||||
verifyZeroInteractions(this.authenticationManager, this.successHandler,
|
||||
this.failureHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenConvertAndAuthenticationSuccessThenSuccess() {
|
||||
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
|
||||
when(this.authenticationConverter.apply(any())).thenReturn(authentication);
|
||||
when(this.authenticationManager.authenticate(any())).thenReturn(authentication);
|
||||
when(this.successHandler.onAuthenticationSuccess(any(), any())).thenReturn(Mono.empty());
|
||||
when(this.serverSecurityContextRepository.save(any(),any())).thenAnswer( a -> Mono.just(a.getArguments()[0]));
|
||||
|
||||
WebTestClient client = WebTestClientBuilder
|
||||
.bindToWebFilters(this.filter)
|
||||
.build();
|
||||
|
||||
client
|
||||
.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody().isEmpty();
|
||||
|
||||
verify(this.successHandler).onAuthenticationSuccess(any(),
|
||||
eq(authentication.block()));
|
||||
verify(this.serverSecurityContextRepository).save(any(), any());
|
||||
verifyZeroInteractions(this.failureHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues() {
|
||||
this.filter.setRequiresAuthenticationMatcher(e -> ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
|
||||
WebTestClient client = WebTestClientBuilder
|
||||
.bindToWebFilters(this.filter)
|
||||
.filter(basicAuthentication())
|
||||
.build();
|
||||
|
||||
EntityExchangeResult<String> result = client
|
||||
.get()
|
||||
.uri("/")
|
||||
.attributes(basicAuthenticationCredentials("test", "this"))
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).consumeWith(b -> assertThat(b.getResponseBody()).isEqualTo("ok"))
|
||||
.returnResult();
|
||||
|
||||
assertThat(result.getResponseCookies()).isEmpty();
|
||||
verifyZeroInteractions(this.authenticationConverter, this.authenticationManager, this.successHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenConvertAndAuthenticationFailThenEntryPoint() {
|
||||
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
|
||||
when(this.authenticationConverter.apply(any())).thenReturn(authentication);
|
||||
when(this.authenticationManager.authenticate(any())).thenReturn(Mono.error(new BadCredentialsException("Failed")));
|
||||
when(this.failureHandler.onAuthenticationFailure(any(),any())).thenReturn(Mono.empty());
|
||||
|
||||
WebTestClient client = WebTestClientBuilder
|
||||
.bindToWebFilters(this.filter)
|
||||
.build();
|
||||
|
||||
client
|
||||
.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody().isEmpty();
|
||||
|
||||
verify(this.failureHandler).onAuthenticationFailure(any(),any());
|
||||
verify(this.serverSecurityContextRepository, never()).save(any(), any());
|
||||
verifyZeroInteractions(this.successHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenConvertAndAuthenticationExceptionThenServerError() {
|
||||
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
|
||||
when(this.authenticationConverter.apply(any())).thenReturn(authentication);
|
||||
when(this.authenticationManager.authenticate(any())).thenReturn(Mono.error(new RuntimeException("Failed")));
|
||||
|
||||
WebTestClient client = WebTestClientBuilder
|
||||
.bindToWebFilters(this.filter)
|
||||
.build();
|
||||
|
||||
client
|
||||
.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus().is5xxServerError()
|
||||
.expectBody().isEmpty();
|
||||
|
||||
verify(this.serverSecurityContextRepository, never()).save(any(), any());
|
||||
verifyZeroInteractions(this.successHandler, this.failureHandler);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setRequiresAuthenticationMatcherWhenNullThenException() {
|
||||
this.filter.setRequiresAuthenticationMatcher(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.authentication;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class HttpBasicServerAuthenticationEntryPointTests {
|
||||
@Mock
|
||||
private ServerWebExchange exchange;
|
||||
private HttpBasicServerAuthenticationEntryPoint entryPoint = new HttpBasicServerAuthenticationEntryPoint();
|
||||
|
||||
private AuthenticationException exception = new AuthenticationCredentialsNotFoundException("Authenticate");
|
||||
|
||||
@Test
|
||||
public void commenceWhenNoSubscribersThenNoActions() {
|
||||
this.entryPoint.commence(this.exchange,
|
||||
this.exception);
|
||||
|
||||
verifyZeroInteractions(this.exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commenceWhenSubscribeThenStatusAndHeaderSet() {
|
||||
this.exchange = exchange(MockServerHttpRequest.get("/"));
|
||||
|
||||
this.entryPoint.commence(this.exchange, this.exception).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(
|
||||
HttpStatus.UNAUTHORIZED);
|
||||
assertThat(this.exchange.getResponse().getHeaders().get("WWW-Authenticate")).containsOnly(
|
||||
"Basic realm=\"Realm\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commenceWhenCustomRealmThenStatusAndHeaderSet() {
|
||||
this.entryPoint.setRealm("Custom");
|
||||
this.exchange = exchange(MockServerHttpRequest.get("/"));
|
||||
|
||||
this.entryPoint.commence(this.exchange, this.exception).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(
|
||||
HttpStatus.UNAUTHORIZED);
|
||||
assertThat(this.exchange.getResponse().getHeaders().get("WWW-Authenticate")).containsOnly(
|
||||
"Basic realm=\"Custom\"");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setRealmWhenNullThenException() {
|
||||
this.entryPoint.setRealm(null);
|
||||
}
|
||||
|
||||
|
||||
private static MockServerWebExchange exchange(MockServerHttpRequest.BaseBuilder<?> request) {
|
||||
return MockServerWebExchange.from(request.build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.authentication;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.server.ServerRedirectStrategy;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RedirectServerAuthenticationEntryPointTests {
|
||||
|
||||
@Mock
|
||||
private ServerWebExchange exchange;
|
||||
@Mock
|
||||
private ServerRedirectStrategy serverRedirectStrategy;
|
||||
|
||||
private String location = "/login";
|
||||
|
||||
private RedirectServerAuthenticationEntryPoint entryPoint =
|
||||
new RedirectServerAuthenticationEntryPoint(this.location);
|
||||
|
||||
private AuthenticationException exception = new AuthenticationCredentialsNotFoundException("Authentication Required");
|
||||
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorStringWhenNullLocationThenException() {
|
||||
new RedirectServerAuthenticationEntryPoint((String) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commenceWhenNoSubscribersThenNoActions() {
|
||||
this.entryPoint.commence(this.exchange,
|
||||
this.exception);
|
||||
|
||||
verifyZeroInteractions(this.exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commenceWhenSubscribeThenStatusAndLocationSet() {
|
||||
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
this.entryPoint.commence(this.exchange, this.exception).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(
|
||||
HttpStatus.FOUND);
|
||||
assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() {
|
||||
Mono<Void> result = Mono.empty();
|
||||
when(this.serverRedirectStrategy.sendRedirect(any(), any())).thenReturn(result);
|
||||
this.entryPoint.setServerRedirectStrategy(this.serverRedirectStrategy);
|
||||
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
assertThat(this.entryPoint.commence(this.exchange, this.exception)).isEqualTo(result);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setRedirectStrategyWhenNullThenException() {
|
||||
this.entryPoint.setServerRedirectStrategy(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.authentication;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.server.ServerRedirectStrategy;
|
||||
import org.springframework.security.web.server.WebFilterExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.WebFilterChain;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RedirectServerAuthenticationSuccessHandlerTests {
|
||||
|
||||
@Mock
|
||||
private ServerWebExchange exchange;
|
||||
@Mock
|
||||
private WebFilterChain chain;
|
||||
@Mock
|
||||
private ServerRedirectStrategy serverRedirectStrategy;
|
||||
@Mock
|
||||
private Authentication authentication;
|
||||
|
||||
private URI location = URI.create("/");
|
||||
|
||||
private RedirectServerAuthenticationSuccessHandler handler =
|
||||
new RedirectServerAuthenticationSuccessHandler();
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorStringWhenNullLocationThenException() {
|
||||
new RedirectServerAuthenticationEntryPoint(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successWhenNoSubscribersThenNoActions() {
|
||||
this.handler.onAuthenticationSuccess(new WebFilterExchange(this.exchange,
|
||||
this.chain), this.authentication);
|
||||
|
||||
verifyZeroInteractions(this.exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successWhenSubscribeThenStatusAndLocationSet() {
|
||||
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
this.handler.onAuthenticationSuccess(new WebFilterExchange(this.exchange,
|
||||
this.chain), this.authentication).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(
|
||||
HttpStatus.FOUND);
|
||||
assertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(this.location);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successWhenCustomLocationThenCustomLocationUsed() {
|
||||
Mono<Void> result = Mono.empty();
|
||||
when(this.serverRedirectStrategy.sendRedirect(any(), any())).thenReturn(result);
|
||||
this.handler.setServerRedirectStrategy(this.serverRedirectStrategy);
|
||||
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
assertThat(this.handler.onAuthenticationSuccess(new WebFilterExchange(this.exchange,
|
||||
this.chain), this.authentication)).isEqualTo(result);
|
||||
verify(this.serverRedirectStrategy).sendRedirect(any(), eq(this.location));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setRedirectStrategyWhenNullThenException() {
|
||||
this.handler.setServerRedirectStrategy(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setLocationWhenNullThenException() {
|
||||
this.handler.setLocation(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.authentication;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.server.WebFilterExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.WebFilterChain;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ServerAuthenticationEntryPointFailureHandlerTests {
|
||||
@Mock
|
||||
private ServerAuthenticationEntryPoint serverAuthenticationEntryPoint;
|
||||
@Mock
|
||||
private ServerWebExchange exchange;
|
||||
@Mock
|
||||
private WebFilterChain chain;
|
||||
|
||||
@InjectMocks
|
||||
private WebFilterExchange filterExchange;
|
||||
|
||||
@InjectMocks
|
||||
private ServerAuthenticationEntryPointFailureHandler handler;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorWhenNullEntryPointThenException() {
|
||||
this.serverAuthenticationEntryPoint = null;
|
||||
new ServerAuthenticationEntryPointFailureHandler(this.serverAuthenticationEntryPoint);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void onAuthenticationFailureWhenInvokedThenDelegatesToEntryPoint() {
|
||||
Mono<Void> result = Mono.empty();
|
||||
BadCredentialsException e = new BadCredentialsException("Failed");
|
||||
when(this.serverAuthenticationEntryPoint.commence(this.exchange, e)).thenReturn(result);
|
||||
|
||||
assertThat(this.handler.onAuthenticationFailure(this.filterExchange, e)).isEqualTo(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.authorization;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.security.authorization.AuthorityReactiveAuthorizationManager;
|
||||
import org.springframework.security.authorization.AuthorizationDecision;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
|
||||
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcherEntry;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DelegatingReactiveAuthorizationManagerTests {
|
||||
@Mock
|
||||
ServerWebExchangeMatcher match1;
|
||||
@Mock
|
||||
ServerWebExchangeMatcher match2;
|
||||
@Mock AuthorityReactiveAuthorizationManager<AuthorizationContext> delegate1;
|
||||
@Mock AuthorityReactiveAuthorizationManager<AuthorizationContext> delegate2;
|
||||
@Mock
|
||||
ServerWebExchange exchange;
|
||||
@Mock
|
||||
Mono<Authentication> authentication;
|
||||
@Mock
|
||||
AuthorizationDecision decision;
|
||||
|
||||
DelegatingReactiveAuthorizationManager manager;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
manager = DelegatingReactiveAuthorizationManager.builder()
|
||||
.add(new ServerWebExchangeMatcherEntry<>(match1, delegate1))
|
||||
.add(new ServerWebExchangeMatcherEntry<>(match2, delegate2))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
|
||||
when(match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
|
||||
when(delegate1.check(eq(authentication), any(AuthorizationContext.class))).thenReturn(Mono.just(decision));
|
||||
|
||||
assertThat(manager.check(authentication, exchange).block()).isEqualTo(decision);
|
||||
|
||||
verifyZeroInteractions(match2, delegate2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
|
||||
when(match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
when(match2.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
|
||||
when(delegate2.check(eq(authentication), any(AuthorizationContext.class))).thenReturn(Mono.just(decision));
|
||||
|
||||
assertThat(manager.check(authentication, exchange).block()).isEqualTo(decision);
|
||||
|
||||
verifyZeroInteractions(delegate1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.authorization;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
import reactor.test.publisher.PublisherProbe;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.WebFilterChain;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ExceptionTranslationWebFilterTests {
|
||||
@Mock
|
||||
private Principal principal;
|
||||
@Mock
|
||||
private ServerWebExchange exchange;
|
||||
@Mock
|
||||
private WebFilterChain chain;
|
||||
@Mock
|
||||
private ServerAccessDeniedHandler deniedHandler;
|
||||
@Mock
|
||||
private ServerAuthenticationEntryPoint entryPoint;
|
||||
|
||||
private PublisherProbe<Void> deniedPublisher = PublisherProbe.empty();
|
||||
private PublisherProbe<Void> entryPointPublisher = PublisherProbe.empty();
|
||||
|
||||
private ExceptionTranslationWebFilter filter = new ExceptionTranslationWebFilter();
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
when(this.exchange.getResponse()).thenReturn(new MockServerHttpResponse());
|
||||
when(this.deniedHandler.handle(any(), any())).thenReturn(this.deniedPublisher.mono());
|
||||
when(this.entryPoint.commence(any(), any())).thenReturn(this.entryPointPublisher.mono());
|
||||
|
||||
this.filter.setServerAuthenticationEntryPoint(this.entryPoint);
|
||||
this.filter.setServerAccessDeniedHandler(this.deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenNoExceptionThenNotHandled() {
|
||||
when(this.chain.filter(this.exchange)).thenReturn(Mono.empty());
|
||||
|
||||
StepVerifier.create(this.filter.filter(this.exchange, this.chain))
|
||||
.expectComplete()
|
||||
.verify();
|
||||
|
||||
this.deniedPublisher.assertWasNotSubscribed();
|
||||
this.entryPointPublisher.assertWasNotSubscribed();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenNotAccessDeniedExceptionThenNotHandled() {
|
||||
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new IllegalArgumentException("oops")));
|
||||
|
||||
StepVerifier.create(this.filter.filter(this.exchange, this.chain))
|
||||
.expectError(IllegalArgumentException.class)
|
||||
.verify();
|
||||
|
||||
this.deniedPublisher.assertWasNotSubscribed();
|
||||
this.entryPointPublisher.assertWasNotSubscribed();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenAccessDeniedExceptionAndNotAuthenticatedThenHandled() {
|
||||
when(this.exchange.getPrincipal()).thenReturn(Mono.empty());
|
||||
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized")));
|
||||
|
||||
StepVerifier.create(this.filter.filter(this.exchange, this.chain))
|
||||
.verifyComplete();
|
||||
|
||||
this.deniedPublisher.assertWasNotSubscribed();
|
||||
this.entryPointPublisher.assertWasSubscribed();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void filterWhenDefaultsAndAccessDeniedExceptionAndAuthenticatedThenForbidden() {
|
||||
this.filter = new ExceptionTranslationWebFilter();
|
||||
when(this.exchange.getPrincipal()).thenReturn(Mono.just(this.principal));
|
||||
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized")));
|
||||
|
||||
StepVerifier.create(this.filter.filter(this.exchange, this.chain))
|
||||
.expectComplete()
|
||||
.verify();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(
|
||||
HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenDefaultsAndAccessDeniedExceptionAndNotAuthenticatedThenUnauthorized() {
|
||||
this.filter = new ExceptionTranslationWebFilter();
|
||||
when(this.exchange.getPrincipal()).thenReturn(Mono.empty());
|
||||
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized")));
|
||||
|
||||
StepVerifier.create(this.filter.filter(this.exchange, this.chain))
|
||||
.expectComplete()
|
||||
.verify();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(
|
||||
HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenAccessDeniedExceptionAndAuthenticatedThenHandled() {
|
||||
when(this.exchange.getPrincipal()).thenReturn(Mono.just(this.principal));
|
||||
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized")));
|
||||
|
||||
StepVerifier.create(this.filter.filter(this.exchange, this.chain))
|
||||
.expectComplete()
|
||||
.verify();
|
||||
|
||||
this.deniedPublisher.assertWasSubscribed();
|
||||
this.entryPointPublisher.assertWasNotSubscribed();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setAccessDeniedHandlerWhenNullThenException() {
|
||||
this.filter.setServerAccessDeniedHandler(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setAuthenticationEntryPointWhenNullThenException() {
|
||||
this.filter.setServerAuthenticationEntryPoint(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.authorization;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class HttpStatusServerAccessDeniedHandlerTests {
|
||||
@Mock
|
||||
private ServerWebExchange exchange;
|
||||
private final HttpStatus httpStatus = HttpStatus.FORBIDDEN;
|
||||
private HttpStatusServerAccessDeniedHandler handler = new HttpStatusServerAccessDeniedHandler(this.httpStatus);
|
||||
|
||||
private AccessDeniedException exception = new AccessDeniedException("Forbidden");
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorHttpStatusWhenNullThenException() {
|
||||
new HttpStatusServerAccessDeniedHandler((HttpStatus) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commenceWhenNoSubscribersThenNoActions() {
|
||||
this.handler.handle(this.exchange, this.exception);
|
||||
|
||||
verifyZeroInteractions(this.exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commenceWhenSubscribeThenStatusSet() {
|
||||
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
this.handler.handle(this.exchange, this.exception).block();
|
||||
|
||||
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(this.httpStatus);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.context;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.handler.DefaultWebFilterChain;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
import reactor.util.context.Context;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class AuthenticationReactorContextWebFilterTests {
|
||||
AuthenticationReactorContextWebFilter filter = new AuthenticationReactorContextWebFilter();
|
||||
|
||||
Principal principal = new TestingAuthenticationToken("user","password", "ROLE_USER");
|
||||
|
||||
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
@Test
|
||||
public void filterWhenExistingContextAndPrincipalNotNullThenContextPopulated() {
|
||||
exchange = exchange.mutate().principal(Mono.just(principal)).build();
|
||||
StepVerifier.create(filter.filter(exchange,
|
||||
new DefaultWebFilterChain( e ->
|
||||
Mono.subscriberContext().doOnSuccess( context -> {
|
||||
Principal contextPrincipal = context.<Mono<Principal>>get(Authentication.class).block();
|
||||
assertThat(contextPrincipal).isEqualTo(principal);
|
||||
assertThat(context.<String>get("foo")).isEqualTo("bar");
|
||||
})
|
||||
.then()
|
||||
)
|
||||
)
|
||||
.subscriberContext( context -> context.put("foo", "bar")))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenPrincipalNotNullThenContextPopulated() {
|
||||
exchange = exchange.mutate().principal(Mono.just(principal)).build();
|
||||
StepVerifier.create(filter.filter(exchange,
|
||||
new DefaultWebFilterChain( e ->
|
||||
Mono.subscriberContext().doOnSuccess( context -> {
|
||||
Principal contextPrincipal = context.<Mono<Principal>>get(Authentication.class).block();
|
||||
assertThat(contextPrincipal).isEqualTo(principal);
|
||||
})
|
||||
.then()
|
||||
)
|
||||
))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenPrincipalNullThenContextEmpty() {
|
||||
Context defaultContext = Context.empty();
|
||||
StepVerifier.create(filter.filter(exchange,
|
||||
new DefaultWebFilterChain( e ->
|
||||
Mono.subscriberContext()
|
||||
.defaultIfEmpty(defaultContext)
|
||||
.doOnSuccess( context -> {
|
||||
Principal contextPrincipal = context.<Mono<Principal>>get(Authentication.class).block();
|
||||
assertThat(contextPrincipal).isNull();
|
||||
})
|
||||
.then()
|
||||
)
|
||||
))
|
||||
.verifyComplete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.context;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextImpl;
|
||||
import org.springframework.security.test.web.reactive.server.WebTestHandler;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ServerSecurityContextRepositoryWebFilterTests {
|
||||
@Mock
|
||||
Authentication principal;
|
||||
|
||||
@Mock ServerSecurityContextRepository repository;
|
||||
|
||||
MockServerHttpRequest.BaseBuilder<?> exchange = MockServerHttpRequest.get("/");
|
||||
|
||||
SecurityContextRepositoryWebFilter filter;
|
||||
|
||||
WebTestHandler filters;
|
||||
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
filter = new SecurityContextRepositoryWebFilter(repository);
|
||||
filters = WebTestHandler.bindToWebFilters(filter);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullSecurityContextRepository() {
|
||||
ServerSecurityContextRepository repository = null;
|
||||
new SecurityContextRepositoryWebFilter(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenNoPrincipalAccessThenNoInteractions() {
|
||||
filters.exchange(exchange);
|
||||
|
||||
verifyZeroInteractions(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenGetPrincipalMonoThenNoInteractions() {
|
||||
filters = WebTestHandler.bindToWebFilters(filter, (e,c) -> {
|
||||
Mono<Principal> p = e.getPrincipal();
|
||||
return c.filter(e);
|
||||
});
|
||||
|
||||
filters.exchange(exchange);
|
||||
|
||||
verifyZeroInteractions(repository);
|
||||
}
|
||||
|
||||
// We must use the original principal if the result is empty for test support to work
|
||||
@Test
|
||||
public void filterWhenEmptyAndGetPrincipalThenInteractAndUseOriginalPrincipal() {
|
||||
when(repository.load(any())).thenReturn(Mono.empty());
|
||||
filters = WebTestHandler.bindToWebFilters(filter, (e,c) -> e.getPrincipal().flatMap( p-> c.filter(e))) ;
|
||||
|
||||
ServerWebExchange exchangeWithPrincipal = MockServerWebExchange.from(exchange.build()).mutate().principal(Mono.just(principal)).build();
|
||||
WebTestHandler.WebHandlerResult result = filters.exchange(exchangeWithPrincipal);
|
||||
|
||||
verify(repository).load(any());
|
||||
assertThat(result.getExchange().getPrincipal().block()).isSameAs(principal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenPrincipalAndGetPrincipalThenInteractAndUseOriginalPrincipal() {
|
||||
SecurityContextImpl context = new SecurityContextImpl();
|
||||
context.setAuthentication(principal);
|
||||
when(repository.load(any())).thenReturn(Mono.just(context));
|
||||
filters = WebTestHandler.bindToWebFilters(filter, (e,c) -> e.getPrincipal().flatMap( p-> c.filter(e))) ;
|
||||
|
||||
WebTestHandler.WebHandlerResult result = filters.exchange(exchange);
|
||||
|
||||
verify(repository).load(any());
|
||||
assertThat(result.getExchange().getPrincipal().block()).isSameAs(principal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.context;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextImpl;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class ServerWebExchangeAttributeServerSecurityContextRepositoryTests {
|
||||
ServerWebExchangeAttributeServerSecurityContextRepository repository = new ServerWebExchangeAttributeServerSecurityContextRepository();
|
||||
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
@Test
|
||||
public void saveAndLoad() {
|
||||
SecurityContext context = new SecurityContextImpl();
|
||||
this.repository.save(this.exchange, context).block();
|
||||
|
||||
Mono<SecurityContext> loaded = this.repository.load(this.exchange);
|
||||
|
||||
assertThat(context).isSameAs(loaded.block());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.header;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*
|
||||
*/
|
||||
public class CacheControlServerHttpHeadersWriterTests {
|
||||
CacheControlServerHttpHeadersWriter writer = new CacheControlServerHttpHeadersWriter();
|
||||
|
||||
ServerWebExchange exchange = MockServerWebExchange
|
||||
.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenCacheHeadersThenWritesAllCacheControl() {
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(3);
|
||||
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(
|
||||
CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE);
|
||||
assertThat(headers.get(HttpHeaders.EXPIRES)).containsOnly(
|
||||
CacheControlServerHttpHeadersWriter.EXPIRES_VALUE);
|
||||
assertThat(headers.get(HttpHeaders.PRAGMA)).containsOnly(
|
||||
CacheControlServerHttpHeadersWriter.PRAGMA_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenCacheControlThenNoCacheControlHeaders() {
|
||||
String cacheControl = "max-age=1234";
|
||||
|
||||
headers.set(HttpHeaders.CACHE_CONTROL, cacheControl);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(cacheControl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenPragmaThenNoCacheControlHeaders() {
|
||||
String pragma = "1";
|
||||
headers.set(HttpHeaders.PRAGMA, pragma);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(HttpHeaders.PRAGMA)).containsOnly(pragma);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenExpiresThenNoCacheControlHeaders() {
|
||||
String expires = "1";
|
||||
headers.set(HttpHeaders.EXPIRES, expires);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(HttpHeaders.EXPIRES)).containsOnly(expires);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.header;
|
||||
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CompositeServerHttpHeadersWriterTests {
|
||||
@Mock ServerHttpHeadersWriter writer1;
|
||||
|
||||
@Mock ServerHttpHeadersWriter writer2;
|
||||
|
||||
CompositeServerHttpHeadersWriter writer;
|
||||
|
||||
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
writer = new CompositeServerHttpHeadersWriter(Arrays.asList(writer1, writer2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHttpHeadersWhenErrorNoErrorThenError() {
|
||||
when(writer1.writeHttpHeaders(exchange)).thenReturn(Mono.error(new RuntimeException()));
|
||||
when(writer2.writeHttpHeaders(exchange)).thenReturn(Mono.empty());
|
||||
|
||||
Mono<Void> result = writer.writeHttpHeaders(exchange);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError()
|
||||
.verify();
|
||||
|
||||
verify(writer1).writeHttpHeaders(exchange);
|
||||
verify(writer2).writeHttpHeaders(exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHttpHeadersWhenErrorErrorThenError() {
|
||||
when(writer1.writeHttpHeaders(exchange)).thenReturn(Mono.error(new RuntimeException()));
|
||||
when(writer2.writeHttpHeaders(exchange)).thenReturn(Mono.error(new RuntimeException()));
|
||||
|
||||
Mono<Void> result = writer.writeHttpHeaders(exchange);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError()
|
||||
.verify();
|
||||
|
||||
verify(writer1).writeHttpHeaders(exchange);
|
||||
verify(writer2).writeHttpHeaders(exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHttpHeadersWhenNoErrorThenNoError() {
|
||||
when(writer1.writeHttpHeaders(exchange)).thenReturn(Mono.empty());
|
||||
when(writer2.writeHttpHeaders(exchange)).thenReturn(Mono.empty());
|
||||
|
||||
Mono<Void> result = writer.writeHttpHeaders(exchange);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectComplete()
|
||||
.verify();
|
||||
|
||||
verify(writer1).writeHttpHeaders(exchange);
|
||||
verify(writer2).writeHttpHeaders(exchange);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.header;
|
||||
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.security.test.web.reactive.server.WebTestHandler;
|
||||
import org.springframework.security.test.web.reactive.server.WebTestHandler.WebHandlerResult;
|
||||
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class HttpHeaderWriterWebFilterTests {
|
||||
@Mock ServerHttpHeadersWriter writer;
|
||||
|
||||
HttpHeaderWriterWebFilter filter;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
when(writer.writeHttpHeaders(any())).thenReturn(Mono.empty());
|
||||
filter = new HttpHeaderWriterWebFilter(writer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenCompleteThenWritten() {
|
||||
WebTestClient rest = WebTestClientBuilder.bindToWebFilters(filter).build();
|
||||
|
||||
rest.get().uri("/foo").exchange();
|
||||
|
||||
verify(writer).writeHttpHeaders(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterWhenNotCompleteThenNotWritten() {
|
||||
WebTestHandler handler = WebTestHandler.bindToWebFilters(filter);
|
||||
|
||||
WebHandlerResult result = handler.exchange(MockServerHttpRequest.get("/foo"));
|
||||
|
||||
verify(writer, never()).writeHttpHeaders(any());
|
||||
|
||||
result.getExchange().getResponse().setComplete();
|
||||
|
||||
verify(writer).writeHttpHeaders(any());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.header;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class StaticServerHttpHeadersWriterTests {
|
||||
|
||||
StaticServerHttpHeadersWriter writer = StaticServerHttpHeadersWriter.builder()
|
||||
.header(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, ContentTypeOptionsServerHttpHeadersWriter.NOSNIFF)
|
||||
.build();
|
||||
|
||||
ServerWebExchange exchange = MockServerWebExchange
|
||||
.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenSingleHeaderThenWritesHeader() {
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(
|
||||
ContentTypeOptionsServerHttpHeadersWriter.NOSNIFF);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenSingleHeaderAndHeaderWrittenThenSuccess() {
|
||||
String headerValue = "other";
|
||||
headers.set(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(headerValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenMultiHeaderThenWritesAllHeaders() {
|
||||
writer = StaticServerHttpHeadersWriter.builder()
|
||||
.header(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE)
|
||||
.header(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE)
|
||||
.header(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE)
|
||||
.build();
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(
|
||||
CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE);
|
||||
assertThat(headers.get(HttpHeaders.PRAGMA)).containsOnly(
|
||||
CacheControlServerHttpHeadersWriter.PRAGMA_VALUE);
|
||||
assertThat(headers.get(HttpHeaders.EXPIRES)).containsOnly(
|
||||
CacheControlServerHttpHeadersWriter.EXPIRES_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenMultiHeaderAndSingleWrittenThenNoHeadersOverridden() {
|
||||
String headerValue = "other";
|
||||
headers.set(HttpHeaders.CACHE_CONTROL, headerValue);
|
||||
|
||||
writer = StaticServerHttpHeadersWriter.builder()
|
||||
.header(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE)
|
||||
.header(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE)
|
||||
.header(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE)
|
||||
.build();
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(headerValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.header;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class StrictTransportSecurityServerHttpHeadersWriterTests {
|
||||
StrictTransportSecurityServerHttpHeadersWriter hsts = new StrictTransportSecurityServerHttpHeadersWriter();
|
||||
|
||||
ServerWebExchange exchange;
|
||||
|
||||
@Test
|
||||
public void writeHttpHeadersWhenHttpsThenWrites() {
|
||||
exchange = exchange(MockServerHttpRequest.get("https://example.com/"));
|
||||
|
||||
hsts.writeHttpHeaders(exchange);
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers).containsEntry(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
|
||||
Arrays.asList("max-age=31536000 ; includeSubDomains"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHttpHeadersWhenCustomMaxAgeThenWrites() {
|
||||
Duration maxAge = Duration.ofDays(1);
|
||||
hsts.setMaxAge(maxAge);
|
||||
exchange = exchange(MockServerHttpRequest.get("https://example.com/"));
|
||||
|
||||
hsts.writeHttpHeaders(exchange);
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers).containsEntry(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
|
||||
Arrays.asList("max-age=" + maxAge.getSeconds() + " ; includeSubDomains"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHttpHeadersWhenCustomIncludeSubDomainsThenWrites() {
|
||||
hsts.setIncludeSubDomains(false);
|
||||
exchange = exchange(MockServerHttpRequest.get("https://example.com/"));
|
||||
|
||||
hsts.writeHttpHeaders(exchange);
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers).containsEntry(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
|
||||
Arrays.asList("max-age=31536000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHttpHeadersWhenNullSchemeThenNoHeaders() {
|
||||
exchange = exchange(MockServerHttpRequest.get("/"));
|
||||
|
||||
hsts.writeHttpHeaders(exchange);
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
assertThat(headers).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHttpHeadersWhenHttpThenNoHeaders() {
|
||||
exchange = exchange(MockServerHttpRequest.get("http://example.com/"));
|
||||
|
||||
hsts.writeHttpHeaders(exchange);
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
assertThat(headers).isEmpty();
|
||||
}
|
||||
|
||||
private static MockServerWebExchange exchange(MockServerHttpRequest.BaseBuilder<?> request) {
|
||||
return MockServerWebExchange.from(request.build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.header;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class XContentTypeOptionsServerHttpHeadersWriterTests {
|
||||
|
||||
ContentTypeOptionsServerHttpHeadersWriter writer = new ContentTypeOptionsServerHttpHeadersWriter();
|
||||
|
||||
ServerWebExchange exchange = MockServerWebExchange
|
||||
.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenNoHeadersThenWriteHeaders() {
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(
|
||||
ContentTypeOptionsServerHttpHeadersWriter.NOSNIFF);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenHeaderWrittenThenDoesNotOverrride() {
|
||||
String headerValue = "value";
|
||||
headers.set(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(headerValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.header;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class XFrameOptionsServerHttpHeadersWriterTests {
|
||||
|
||||
ServerWebExchange exchange = exchange(MockServerHttpRequest.get("/"));
|
||||
|
||||
XFrameOptionsServerHttpHeadersWriter writer;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
writer = new XFrameOptionsServerHttpHeadersWriter();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenUsingDefaultsThenWritesDeny() {
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenUsingExplicitDenyThenWritesDeny() {
|
||||
writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.DENY);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenUsingSameOriginThenWritesSameOrigin() {
|
||||
writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("SAMEORIGIN");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenAlreadyWrittenThenWritesHeader() {
|
||||
String headerValue = "other";
|
||||
exchange.getResponse().getHeaders().set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, headerValue);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly(headerValue);
|
||||
}
|
||||
|
||||
private static MockServerWebExchange exchange(MockServerHttpRequest.BaseBuilder<?> request) {
|
||||
return MockServerWebExchange.from(request.build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.header;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class XXssProtectionServerHttpHeadersWriterTests {
|
||||
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
HttpHeaders headers = exchange.getResponse().getHeaders();
|
||||
|
||||
XXssProtectionServerHttpHeadersWriter writer = new XXssProtectionServerHttpHeadersWriter();
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenNoHeadersThenWriteHeaders() {
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1 ; mode=block");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenBlockFalseThenWriteHeaders() {
|
||||
writer.setBlock(false);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenEnabledFalseThenWriteHeaders() {
|
||||
writer.setEnabled(false);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersWhenHeaderWrittenThenDoesNotOverrride() {
|
||||
String headerValue = "value";
|
||||
headers.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, headerValue);
|
||||
|
||||
writer.writeHttpHeaders(exchange);
|
||||
|
||||
assertThat(headers).hasSize(1);
|
||||
assertThat(headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly(headerValue);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.util.matcher;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AndServerWebExchangeMatcherTests {
|
||||
@Mock
|
||||
ServerWebExchange exchange;
|
||||
@Mock
|
||||
ServerWebExchangeMatcher matcher1;
|
||||
@Mock
|
||||
ServerWebExchangeMatcher matcher2;
|
||||
|
||||
AndServerWebExchangeMatcher matcher;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
matcher = new AndServerWebExchangeMatcher(matcher1, matcher2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenTrueTrueThenTrue() throws Exception {
|
||||
Map<String, Object> params1 = Collections.singletonMap("foo", "bar");
|
||||
Map<String, Object> params2 = Collections.singletonMap("x", "y");
|
||||
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
|
||||
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
|
||||
|
||||
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
|
||||
|
||||
assertThat(matches.isMatch()).isTrue();
|
||||
assertThat(matches.getVariables()).hasSize(2);
|
||||
assertThat(matches.getVariables()).containsAllEntriesOf(params1);
|
||||
assertThat(matches.getVariables()).containsAllEntriesOf(params2);
|
||||
|
||||
verify(matcher1).matches(exchange);
|
||||
verify(matcher2).matches(exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenFalseFalseThenFalseAndMatcher2NotInvoked() throws Exception {
|
||||
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
|
||||
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
|
||||
|
||||
assertThat(matches.isMatch()).isFalse();
|
||||
assertThat(matches.getVariables()).isEmpty();
|
||||
|
||||
verify(matcher1).matches(exchange);
|
||||
verify(matcher2, never()).matches(exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenTrueFalseThenFalse() throws Exception {
|
||||
Map<String, Object> params = Collections.singletonMap("foo", "bar");
|
||||
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
|
||||
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
|
||||
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
|
||||
|
||||
assertThat(matches.isMatch()).isFalse();
|
||||
assertThat(matches.getVariables()).isEmpty();
|
||||
|
||||
verify(matcher1).matches(exchange);
|
||||
verify(matcher2).matches(exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenFalseTrueThenFalse() throws Exception {
|
||||
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
|
||||
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
|
||||
|
||||
assertThat(matches.isMatch()).isFalse();
|
||||
assertThat(matches.getVariables()).isEmpty();
|
||||
|
||||
verify(matcher1).matches(exchange);
|
||||
verify(matcher2, never()).matches(exchange);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.util.matcher;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class MediaTypeServerWebExchangeMatcherTests {
|
||||
private MediaTypeServerWebExchangeMatcher matcher;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorMediaTypeArrayWhenNullThenThrowsIllegalArgumentException() {
|
||||
MediaType[] types = null;
|
||||
new MediaTypeServerWebExchangeMatcher(types);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorMediaTypeArrayWhenContainsNullThenThrowsIllegalArgumentException() {
|
||||
MediaType[] types = { null };
|
||||
new MediaTypeServerWebExchangeMatcher(types);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorMediaTypeListWhenNullThenThrowsIllegalArgumentException() {
|
||||
List<MediaType> types = null;
|
||||
new MediaTypeServerWebExchangeMatcher(types);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorMediaTypeListWhenContainsNullThenThrowsIllegalArgumentException() {
|
||||
List<MediaType> types = Collections.singletonList(null);
|
||||
new MediaTypeServerWebExchangeMatcher(types);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchWhenDefaultResolverAndAcceptEqualThenMatch() {
|
||||
MediaType acceptType = MediaType.TEXT_HTML;
|
||||
MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher(acceptType);
|
||||
|
||||
assertThat(matcher.matches(exchange(acceptType)).block().isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchWhenDefaultResolverAndAcceptEqualAndIgnoreThenMatch() {
|
||||
MediaType acceptType = MediaType.TEXT_HTML;
|
||||
MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher(acceptType);
|
||||
matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
|
||||
|
||||
assertThat(matcher.matches(exchange(acceptType)).block().isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchWhenDefaultResolverAndAcceptEqualAndIgnoreThenNotMatch() {
|
||||
MediaType acceptType = MediaType.TEXT_HTML;
|
||||
MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher(acceptType);
|
||||
matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
|
||||
|
||||
assertThat(matcher.matches(exchange(MediaType.ALL)).block().isMatch()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchWhenDefaultResolverAndAcceptImpliedThenMatch() {
|
||||
MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher(MediaType.parseMediaTypes("text/*"));
|
||||
|
||||
assertThat(matcher.matches(exchange(MediaType.TEXT_HTML)).block().isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchWhenDefaultResolverAndAcceptImpliedAndUseEqualsThenNotMatch() {
|
||||
MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher(MediaType.ALL);
|
||||
matcher.setUseEquals(true);
|
||||
|
||||
assertThat(matcher.matches(exchange(MediaType.TEXT_HTML)).block().isMatch()).isFalse();
|
||||
}
|
||||
|
||||
private static ServerWebExchange exchange(MediaType... accept) {
|
||||
return MockServerWebExchange.from(MockServerHttpRequest.get("/").accept(accept).build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.util.matcher;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class OrServerWebExchangeMatcherTests {
|
||||
@Mock
|
||||
ServerWebExchange exchange;
|
||||
@Mock
|
||||
ServerWebExchangeMatcher matcher1;
|
||||
@Mock
|
||||
ServerWebExchangeMatcher matcher2;
|
||||
|
||||
OrServerWebExchangeMatcher matcher;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
matcher = new OrServerWebExchangeMatcher(matcher1, matcher2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenFalseFalseThenFalse() throws Exception {
|
||||
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
|
||||
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
|
||||
|
||||
assertThat(matches.isMatch()).isFalse();
|
||||
assertThat(matches.getVariables()).isEmpty();
|
||||
|
||||
verify(matcher1).matches(exchange);
|
||||
verify(matcher2).matches(exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenTrueFalseThenTrueAndMatcher2NotInvoked() throws Exception {
|
||||
Map<String, Object> params = Collections.singletonMap("foo", "bar");
|
||||
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
|
||||
|
||||
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
|
||||
|
||||
assertThat(matches.isMatch()).isTrue();
|
||||
assertThat(matches.getVariables()).isEqualTo(params);
|
||||
|
||||
verify(matcher1).matches(exchange);
|
||||
verify(matcher2, never()).matches(exchange);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenFalseTrueThenTrue() throws Exception {
|
||||
Map<String, Object> params = Collections.singletonMap("foo", "bar");
|
||||
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
|
||||
|
||||
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
|
||||
|
||||
assertThat(matches.isMatch()).isTrue();
|
||||
assertThat(matches.getVariables()).isEqualTo(params);
|
||||
|
||||
verify(matcher1).matches(exchange);
|
||||
verify(matcher2).matches(exchange);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.util.matcher;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.session.DefaultWebSessionManager;
|
||||
import org.springframework.web.util.pattern.PathPattern;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class PathMatcherServerWebExchangeMatcherTests {
|
||||
@Mock
|
||||
PathPattern pattern;
|
||||
@Mock
|
||||
PathPattern.PathMatchInfo pathMatchInfo;
|
||||
MockServerWebExchange exchange;
|
||||
PathPatternParserServerWebExchangeMatcher matcher;
|
||||
String path;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
MockServerHttpRequest request = MockServerHttpRequest.post("/path").build();
|
||||
MockServerHttpResponse response = new MockServerHttpResponse();
|
||||
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
|
||||
exchange = MockServerWebExchange.from(request);
|
||||
path = "/path";
|
||||
|
||||
matcher = new PathPatternParserServerWebExchangeMatcher(pattern);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorPatternWhenPatternNullThenThrowsException() {
|
||||
new PathPatternParserServerWebExchangeMatcher((PathPattern) null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorPatternAndMethodWhenPatternNullThenThrowsException() {
|
||||
new PathPatternParserServerWebExchangeMatcher((PathPattern) null, HttpMethod.GET);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenPathMatcherTrueThenReturnTrue() {
|
||||
when(pattern.matches(any())).thenReturn(true);
|
||||
when(pattern.matchAndExtract(any())).thenReturn(pathMatchInfo);
|
||||
when(pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>());
|
||||
|
||||
assertThat(matcher.matches(exchange).block().isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenPathMatcherFalseThenReturnFalse() {
|
||||
when(pattern.matches(any())).thenReturn(false);
|
||||
|
||||
assertThat(matcher.matches(exchange).block().isMatch()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenPathMatcherTrueAndMethodTrueThenReturnTrue() {
|
||||
matcher = new PathPatternParserServerWebExchangeMatcher(pattern, exchange.getRequest().getMethod());
|
||||
when(pattern.matches(any())).thenReturn(true);
|
||||
when(pattern.matchAndExtract(any())).thenReturn(pathMatchInfo);
|
||||
when(pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>());
|
||||
|
||||
assertThat(matcher.matches(exchange).block().isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWhenPathMatcherTrueAndMethodFalseThenReturnFalse() {
|
||||
HttpMethod method = HttpMethod.OPTIONS;
|
||||
assertThat(exchange.getRequest().getMethod()).isNotEqualTo(method);
|
||||
matcher = new PathPatternParserServerWebExchangeMatcher(pattern, method);
|
||||
|
||||
assertThat(matcher.matches(exchange).block().isMatch()).isFalse();
|
||||
|
||||
verifyZeroInteractions(pattern);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright 2002-2017 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
|
||||
*
|
||||
* http://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.web.server.util.matcher;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.pathMatchers;
|
||||
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.anyExchange;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
public class ServerWebExchangeMatchersTests {
|
||||
ServerWebExchange exchange = MockServerWebExchange
|
||||
.from(MockServerHttpRequest.get("/").build());
|
||||
|
||||
@Test
|
||||
public void pathMatchersWhenSingleAndSamePatternThenMatches() throws Exception {
|
||||
assertThat(pathMatchers("/").matches(exchange).block().isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pathMatchersWhenSingleAndSamePatternAndMethodThenMatches() throws Exception {
|
||||
assertThat(ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/").matches(exchange).block().isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pathMatchersWhenSingleAndSamePatternAndDiffMethodThenDoesNotMatch() throws Exception {
|
||||
assertThat(ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/").matches(exchange).block().isMatch()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pathMatchersWhenSingleAndDifferentPatternThenDoesNotMatch() throws Exception {
|
||||
assertThat(pathMatchers("/foobar").matches(exchange).block().isMatch()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pathMatchersWhenMultiThenMatches() throws Exception {
|
||||
assertThat(pathMatchers("/foobar", "/").matches(exchange).block().isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void anyExchangeWhenMockThenMatches() {
|
||||
ServerWebExchange mockExchange = mock(ServerWebExchange.class);
|
||||
|
||||
assertThat(anyExchange().matches(mockExchange).block().isMatch()).isTrue();
|
||||
|
||||
verifyZeroInteractions(mockExchange);
|
||||
}
|
||||
|
||||
/**
|
||||
* If a LinkedMap is used and anyRequest equals anyRequest then the following is added:
|
||||
* anyRequest() -> authenticated()
|
||||
* pathMatchers("/admin/**") -> hasRole("ADMIN")
|
||||
* anyRequest() -> permitAll
|
||||
*
|
||||
* will result in the first entry being overridden
|
||||
*/
|
||||
@Test
|
||||
public void anyExchangeWhenTwoCreatedThenDifferentToPreventIssuesInMap() {
|
||||
assertThat(anyExchange()).isNotEqualTo(anyExchange());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user