Move spring-security-webflux into spring-security-web

Fixes gh-4662
This commit is contained in:
Rob Winch
2017-10-12 13:45:23 -05:00
parent d231441cc0
commit b81c1ce2c0
95 changed files with 26 additions and 185 deletions

View File

@@ -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.reactive.result.method.annotation;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.lang.annotation.Annotation;
/**
* Resolves the Authentication
* @author Rob Winch
* @since 5.0
*/
public class AuthenticationPrincipalArgumentResolver extends HandlerMethodArgumentResolverSupport {
private ExpressionParser parser = new SpelExpressionParser();
private BeanResolver beanResolver;
public AuthenticationPrincipalArgumentResolver(ReactiveAdapterRegistry adapterRegistry) {
super(adapterRegistry);
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return findMethodAnnotation(AuthenticationPrincipal.class, parameter) != null;
}
@Override
public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext bindingContext,
ServerWebExchange exchange) {
ReactiveAdapter adapter = getAdapterRegistry().getAdapter(parameter.getParameterType());
return exchange.getPrincipal()
.ofType(Authentication.class)
.flatMap( a -> {
Object p = resolvePrincipal(parameter, a.getPrincipal());
Mono<Object> principal = Mono.justOrEmpty(p);
return adapter == null ? principal : Mono.just(adapter.fromPublisher(principal));
});
}
private Object resolvePrincipal(MethodParameter parameter, Object principal) {
AuthenticationPrincipal authPrincipal = findMethodAnnotation(
AuthenticationPrincipal.class, parameter);
String expressionToParse = authPrincipal.expression();
if (StringUtils.hasLength(expressionToParse)) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(principal);
context.setVariable("this", principal);
context.setBeanResolver(beanResolver);
Expression expression = this.parser.parseExpression(expressionToParse);
principal = expression.getValue(context);
}
return principal;
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
*
* @param annotationClass the class of the {@link Annotation} to find on the
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass,
MethodParameter parameter) {
T annotation = parameter.getParameterAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(),
annotationClass);
if (annotation != null) {
return annotation;
}
}
return null;
}
}

View File

@@ -0,0 +1,71 @@
/*
* 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.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
/**
* @author Rob Winch
* @since 5.0
*/
public class DefaultServerRedirectStrategy implements ServerRedirectStrategy {
private HttpStatus httpStatus = HttpStatus.FOUND;
private boolean contextRelative = true;
public Mono<Void> sendRedirect(ServerWebExchange exchange, URI location) {
Assert.notNull(exchange, "exchange cannot be null");
Assert.notNull(location, "location cannot be null");
return Mono.fromRunnable(() -> {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(this.httpStatus);
response.getHeaders().setLocation(createLocation(exchange, location));
});
}
private URI createLocation(ServerWebExchange exchange, URI location) {
if(!this.contextRelative) {
return location;
}
String url = location.toASCIIString();
if(url.startsWith("/")) {
String context = exchange.getRequest().getPath().contextPath().value();
return URI.create(context + url);
}
return location;
}
public void setHttpStatus(HttpStatus httpStatus) {
Assert.notNull(httpStatus, "httpStatus cannot be null");
this.httpStatus = httpStatus;
}
/**
* Sets if the location is relative to the context.
* @param contextRelative if redirects should be relative to the context.
* Default is true.
*/
public void setContextRelative(boolean contextRelative) {
this.contextRelative = contextRelative;
}
}

View File

@@ -0,0 +1,94 @@
/*
* 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.springframework.http.HttpStatus;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.web.server.ServerWebExchange;
import java.util.Arrays;
import java.util.List;
/**
* @author Rob Winch
* @since 5.0
*/
public class DelegatingServerAuthenticationEntryPoint
implements ServerAuthenticationEntryPoint {
private final Flux<DelegateEntry> entryPoints;
private ServerAuthenticationEntryPoint defaultEntryPoint = (exchange, e) -> {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
};
public DelegatingServerAuthenticationEntryPoint(
DelegateEntry... entryPoints) {
this(Arrays.asList(entryPoints));
}
public DelegatingServerAuthenticationEntryPoint(
List<DelegateEntry> entryPoints) {
this.entryPoints = Flux.fromIterable(entryPoints);
}
public Mono<Void> commence(ServerWebExchange exchange,
AuthenticationException e) {
return this.entryPoints.filterWhen( entry -> isMatch(exchange, entry))
.next()
.map( entry -> entry.getEntryPoint())
.defaultIfEmpty(this.defaultEntryPoint)
.flatMap( entryPoint -> entryPoint.commence(exchange, e));
}
private Mono<Boolean> isMatch(ServerWebExchange exchange, DelegateEntry entry) {
ServerWebExchangeMatcher matcher = entry.getMatcher();
return matcher.matches(exchange)
.map( result -> result.isMatch());
}
/**
* EntryPoint which is used when no RequestMatcher returned true
*/
public void setDefaultEntryPoint(
ServerAuthenticationEntryPoint defaultEntryPoint) {
this.defaultEntryPoint = defaultEntryPoint;
}
public static class DelegateEntry {
private final ServerWebExchangeMatcher matcher;
private final ServerAuthenticationEntryPoint entryPoint;
public DelegateEntry(ServerWebExchangeMatcher matcher,
ServerAuthenticationEntryPoint entryPoint) {
this.matcher = matcher;
this.entryPoint = entryPoint;
}
public ServerWebExchangeMatcher getMatcher() {
return this.matcher;
}
public ServerAuthenticationEntryPoint getEntryPoint() {
return this.entryPoint;
}
}
}

View File

@@ -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.web.server;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
/**
* @author Rob Winch
* @since 5.0
*/
public class MatcherSecurityWebFilterChain implements SecurityWebFilterChain {
private final ServerWebExchangeMatcher matcher;
private final Flux<WebFilter> filters;
public MatcherSecurityWebFilterChain(ServerWebExchangeMatcher matcher, List<WebFilter> filters) {
this(matcher, Flux.fromIterable(filters));
}
public MatcherSecurityWebFilterChain(ServerWebExchangeMatcher matcher, Flux<WebFilter> filters) {
this.matcher = matcher;
this.filters = filters;
}
@Override
public Mono<Boolean> matches(ServerWebExchange exchange) {
return matcher.matches(exchange)
.map( m -> m.isMatch() );
}
@Override
public Flux<WebFilter> getWebFilters() {
return filters;
}
}

View File

@@ -0,0 +1,33 @@
/*
* 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.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public interface SecurityWebFilterChain {
Mono<Boolean> matches(ServerWebExchange exchange);
Flux<WebFilter> getWebFilters();
}

View File

@@ -0,0 +1,31 @@
/*
* 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 reactor.core.publisher.Mono;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.server.ServerWebExchange;
/**
*
* @author Rob Winch
* @since 5.0
*/
public interface ServerAuthenticationEntryPoint {
Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e);
}

View File

@@ -0,0 +1,71 @@
/*
* 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 java.util.function.Function;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
/**
* Converts a ServerWebExchange into a UsernamePasswordAuthenticationToken from the form
* data HTTP parameters.
*
* @author Rob Winch
* @since 5.0
*/
public class ServerFormLoginAuthenticationConverter implements Function<ServerWebExchange,Mono<Authentication>> {
private String usernameParameter = "username";
private String passwordParameter = "password";
@Override
public Mono<Authentication> apply(ServerWebExchange serverWebExchange) {
return serverWebExchange.getFormData()
.map( data -> createAuthentication(data));
}
private UsernamePasswordAuthenticationToken createAuthentication(
MultiValueMap<String, String> data) {
String username = data.getFirst(this.usernameParameter);
String password = data.getFirst(this.passwordParameter);
return new UsernamePasswordAuthenticationToken(username, password);
}
/**
* The parameter name of the form data to extract the username
* @param usernameParameter the username HTTP parameter
*/
public void setUsernameParameter(String usernameParameter) {
Assert.notNull(usernameParameter, "usernameParameter cannot be null");
this.usernameParameter = usernameParameter;
}
/**
* The parameter name of the form data to extract the password
* @param passwordParameter the password HTTP parameter
*/
public void setPasswordParameter(String passwordParameter) {
Assert.notNull(passwordParameter, "passwordParameter cannot be null");
this.passwordParameter = passwordParameter;
}
}

View File

@@ -0,0 +1,71 @@
/*
* 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 java.util.Base64;
import java.util.function.Function;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class ServerHttpBasicAuthenticationConverter implements Function<ServerWebExchange,Mono<Authentication>> {
public static final String BASIC = "Basic ";
@Override
public Mono<Authentication> apply(ServerWebExchange serverWebExchange) {
ServerHttpRequest request = serverWebExchange.getRequest();
String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if(authorization == null) {
return Mono.empty();
}
String credentials = authorization.length() <= BASIC.length() ?
"" : authorization.substring(BASIC.length(), authorization.length());
byte[] decodedCredentials = base64Decode(credentials);
String decodedAuthz = new String(decodedCredentials);
String[] userParts = decodedAuthz.split(":");
if(userParts.length != 2) {
return Mono.empty();
}
String username = userParts[0];
String password = userParts[1];
return Mono.just(new UsernamePasswordAuthenticationToken(username, password));
}
private byte[] base64Decode(String value) {
try {
return Base64.getDecoder().decode(value);
} catch(Exception e) {
return new byte[0];
}
}
}

View File

@@ -0,0 +1,32 @@
/*
* 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 java.net.URI;
import reactor.core.publisher.Mono;
import org.springframework.web.server.ServerWebExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public interface ServerRedirectStrategy {
Mono<Void> sendRedirect(ServerWebExchange exchange, URI location);
}

View File

@@ -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;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.handler.DefaultWebFilterChain;
import org.springframework.web.server.handler.FilteringWebHandler;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class WebFilterChainProxy implements WebFilter {
private final Flux<SecurityWebFilterChain> filters;
public WebFilterChainProxy(Flux<SecurityWebFilterChain> filters) {
this.filters = filters;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return filters
.filterWhen( securityWebFilterChain -> securityWebFilterChain.matches(exchange))
.next()
.flatMap( securityWebFilterChain -> securityWebFilterChain.getWebFilters()
.collectList()
)
.map( filters -> new FilteringWebHandler(webHandler -> chain.filter(webHandler), filters))
.map( handler -> new DefaultWebFilterChain(handler) )
.flatMap( securedChain -> securedChain.filter(exchange));
}
public static WebFilterChainProxy fromWebFiltersList(List<WebFilter> filters) {
return new WebFilterChainProxy(Flux.just(new MatcherSecurityWebFilterChain(ServerWebExchangeMatchers.anyExchange(), filters)));
}
public static WebFilterChainProxy fromSecurityWebFilterChainsList(List<SecurityWebFilterChain> securityWebFilterChains) {
return new WebFilterChainProxy(Flux.fromIterable(securityWebFilterChains));
}
public static WebFilterChainProxy fromSecurityWebFilterChains(SecurityWebFilterChain... securityWebFilterChains) {
return fromSecurityWebFilterChainsList(Arrays.asList(securityWebFilterChains));
}
}

View File

@@ -0,0 +1,53 @@
/*
* 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.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
/**
* @author Rob Winch
* @since 5.0
*/
public class WebFilterExchange {
private final ServerWebExchange exchange;
private final WebFilterChain chain;
public WebFilterExchange(ServerWebExchange exchange, WebFilterChain chain) {
Assert.notNull(exchange, "exchange cannot be null");
Assert.notNull(chain, "chain cannot be null");
this.exchange = exchange;
this.chain = chain;
}
/**
* Get the exchange
* @return the exchange. Cannot be {@code null}
*/
public ServerWebExchange getExchange() {
return this.exchange;
}
/**
* The filter chain
* @return the filter chain. Cannot be {@code null}
*/
public WebFilterChain getChain() {
return this.chain;
}
}

View File

@@ -0,0 +1,119 @@
/*
* 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.springframework.security.core.AuthenticationException;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.ServerHttpBasicAuthenticationConverter;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.security.web.server.context.SecurityContextRepositoryServerWebExchange;
import org.springframework.security.web.server.context.ServerWebExchangeAttributeServerSecurityContextRepository;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class AuthenticationWebFilter implements WebFilter {
private final ReactiveAuthenticationManager authenticationManager;
private ServerAuthenticationSuccessHandler serverAuthenticationSuccessHandler = new WebFilterChainServerAuthenticationSuccessHandler();
private Function<ServerWebExchange,Mono<Authentication>> authenticationConverter = new ServerHttpBasicAuthenticationConverter();
private ServerAuthenticationFailureHandler serverAuthenticationFailureHandler = new ServerAuthenticationEntryPointFailureHandler(new HttpBasicServerAuthenticationEntryPoint());
private ServerSecurityContextRepository serverSecurityContextRepository = new ServerWebExchangeAttributeServerSecurityContextRepository();
private ServerWebExchangeMatcher requiresAuthenticationMatcher = ServerWebExchangeMatchers.anyExchange();
public AuthenticationWebFilter(ReactiveAuthenticationManager authenticationManager) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
this.authenticationManager = authenticationManager;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerWebExchange wrappedExchange = new SecurityContextRepositoryServerWebExchange(exchange, this.serverSecurityContextRepository);
return filterInternal(wrappedExchange, chain);
}
private Mono<Void> filterInternal(ServerWebExchange wrappedExchange, WebFilterChain chain) {
return this.requiresAuthenticationMatcher.matches(wrappedExchange)
.filter( matchResult -> matchResult.isMatch())
.flatMap( matchResult -> this.authenticationConverter.apply(wrappedExchange))
.switchIfEmpty(chain.filter(wrappedExchange).then(Mono.empty()))
.flatMap( token -> authenticate(wrappedExchange, chain, token));
}
private Mono<Void> authenticate(ServerWebExchange wrappedExchange,
WebFilterChain chain, Authentication token) {
WebFilterExchange webFilterExchange = new WebFilterExchange(wrappedExchange, chain);
return this.authenticationManager.authenticate(token)
.flatMap(authentication -> onAuthenticationSuccess(authentication, webFilterExchange))
.onErrorResume(AuthenticationException.class, e -> this.serverAuthenticationFailureHandler
.onAuthenticationFailure(webFilterExchange, e));
}
private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) {
ServerWebExchange exchange = webFilterExchange.getExchange();
SecurityContextImpl securityContext = new SecurityContextImpl();
securityContext.setAuthentication(authentication);
return this.serverSecurityContextRepository.save(exchange, securityContext)
.then(this.serverAuthenticationSuccessHandler
.onAuthenticationSuccess(webFilterExchange, authentication));
}
public void setServerSecurityContextRepository(
ServerSecurityContextRepository serverSecurityContextRepository) {
Assert.notNull(serverSecurityContextRepository, "securityContextRepository cannot be null");
this.serverSecurityContextRepository = serverSecurityContextRepository;
}
public void setServerAuthenticationSuccessHandler(ServerAuthenticationSuccessHandler serverAuthenticationSuccessHandler) {
this.serverAuthenticationSuccessHandler = serverAuthenticationSuccessHandler;
}
public void setAuthenticationConverter(Function<ServerWebExchange,Mono<Authentication>> authenticationConverter) {
this.authenticationConverter = authenticationConverter;
}
public void setServerAuthenticationFailureHandler(
ServerAuthenticationFailureHandler serverAuthenticationFailureHandler) {
Assert.notNull(serverAuthenticationFailureHandler, "authenticationFailureHandler cannot be null");
this.serverAuthenticationFailureHandler = serverAuthenticationFailureHandler;
}
public void setRequiresAuthenticationMatcher(
ServerWebExchangeMatcher requiresAuthenticationMatcher) {
Assert.notNull(requiresAuthenticationMatcher, "requiresAuthenticationMatcher cannot be null");
this.requiresAuthenticationMatcher = requiresAuthenticationMatcher;
}
}

View File

@@ -0,0 +1,61 @@
/*
* 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.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class HttpBasicServerAuthenticationEntryPoint
implements ServerAuthenticationEntryPoint {
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String DEFAULT_REALM = "Realm";
private static String WWW_AUTHENTICATE_FORMAT = "Basic realm=\"%s\"";
private String headerValue = createHeaderValue(DEFAULT_REALM);
@Override
public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
return Mono.fromRunnable(() -> {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().set(WWW_AUTHENTICATE, this.headerValue);
});
}
/**
* Sets the realm to be used
* @param realm the realm. Default is "Realm"
*/
public void setRealm(String realm) {
this.headerValue = createHeaderValue(realm);
}
private static String createHeaderValue(String realm) {
Assert.notNull(realm, "realm cannot be null");
return String.format(WWW_AUTHENTICATE_FORMAT, realm);
}
}

View File

@@ -0,0 +1,60 @@
/*
* 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.net.URI;
import org.springframework.security.web.server.DefaultServerRedirectStrategy;
import org.springframework.security.web.server.ServerRedirectStrategy;
import reactor.core.publisher.Mono;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
/**
* Performs a redirect to a specified location.
*
* @author Rob Winch
* @since 5.0
*/
public class RedirectServerAuthenticationEntryPoint
implements ServerAuthenticationEntryPoint {
private final URI location;
private ServerRedirectStrategy serverRedirectStrategy = new DefaultServerRedirectStrategy();
public RedirectServerAuthenticationEntryPoint(String location) {
Assert.notNull(location, "location cannot be null");
this.location = URI.create(location);
}
@Override
public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
return this.serverRedirectStrategy.sendRedirect(exchange, this.location);
}
/**
* Sets the RedirectStrategy to use.
* @param serverRedirectStrategy the strategy to use. Default is DefaultRedirectStrategy.
*/
public void setServerRedirectStrategy(ServerRedirectStrategy serverRedirectStrategy) {
Assert.notNull(serverRedirectStrategy, "redirectStrategy cannot be null");
this.serverRedirectStrategy = serverRedirectStrategy;
}
}

View File

@@ -0,0 +1,69 @@
/*
* 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.springframework.security.core.Authentication;
import org.springframework.security.web.server.DefaultServerRedirectStrategy;
import org.springframework.security.web.server.ServerRedirectStrategy;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
/**
* @author Rob Winch
* @since 5.0
*/
public class RedirectServerAuthenticationSuccessHandler
implements ServerAuthenticationSuccessHandler {
private URI location = URI.create("/");
private ServerRedirectStrategy serverRedirectStrategy = new DefaultServerRedirectStrategy();
public RedirectServerAuthenticationSuccessHandler() {}
public RedirectServerAuthenticationSuccessHandler(String location) {
this.location = URI.create(location);
}
@Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange,
Authentication authentication) {
ServerWebExchange exchange = webFilterExchange.getExchange();
return this.serverRedirectStrategy.sendRedirect(exchange, this.location);
}
/**
* Where the user is redirected to upon authentication success
* @param location the location to redirect to. The default is "/"
*/
public void setLocation(URI location) {
Assert.notNull(location, "location cannot be null");
this.location = location;
}
/**
* The RedirectStrategy to use.
* @param serverRedirectStrategy the strategy to use. Default is DefaultRedirectStrategy.
*/
public void setServerRedirectStrategy(ServerRedirectStrategy serverRedirectStrategy) {
Assert.notNull(serverRedirectStrategy, "redirectStrategy cannot be null");
this.serverRedirectStrategy = serverRedirectStrategy;
}
}

View File

@@ -0,0 +1,45 @@
/*
* 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.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class ServerAuthenticationEntryPointFailureHandler
implements ServerAuthenticationFailureHandler {
private final ServerAuthenticationEntryPoint serverAuthenticationEntryPoint;
public ServerAuthenticationEntryPointFailureHandler(
ServerAuthenticationEntryPoint serverAuthenticationEntryPoint) {
Assert.notNull(serverAuthenticationEntryPoint, "authenticationEntryPoint cannot be null");
this.serverAuthenticationEntryPoint = serverAuthenticationEntryPoint;
}
@Override
public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange,
AuthenticationException exception) {
return this.serverAuthenticationEntryPoint
.commence(webFilterExchange.getExchange(), exception);
}
}

View File

@@ -0,0 +1,31 @@
/*
* 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.springframework.security.core.AuthenticationException;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public interface ServerAuthenticationFailureHandler {
Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception);
}

View File

@@ -0,0 +1,30 @@
/*
* 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.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public interface ServerAuthenticationSuccessHandler {
Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange,
Authentication authentication);
}

View File

@@ -0,0 +1,36 @@
/*
* 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.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class WebFilterChainServerAuthenticationSuccessHandler
implements ServerAuthenticationSuccessHandler {
@Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange,
Authentication authentication) {
ServerWebExchange exchange = webFilterExchange.getExchange();
return webFilterExchange.getChain().filter(exchange);
}
}

View File

@@ -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.authentication.logout;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
/**
* If the request matches, logs an authenticated user out by delegating to a
* {@link ServerLogoutHandler}.
*
* @author Rob Winch
* @since 5.0
*/
public class LogoutWebFilter implements WebFilter {
private AnonymousAuthenticationToken anonymousAuthenticationToken = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
private ServerLogoutHandler serverLogoutHandler = new SecurityContextServerLogoutHandler();
private ServerLogoutSuccessHandler serverLogoutSuccessHandler = new RedirectServerLogoutSuccessHandler();
private ServerWebExchangeMatcher requiresLogout = ServerWebExchangeMatchers
.pathMatchers("/logout");
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return this.requiresLogout.matches(exchange)
.filter( result -> result.isMatch())
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.map(result -> exchange)
.flatMap(this::flatMapAuthentication)
.flatMap( authentication -> {
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange,chain);
return logout(webFilterExchange, authentication);
});
}
private Mono<Authentication> flatMapAuthentication(ServerWebExchange exchange) {
return exchange.getPrincipal()
.cast(Authentication.class)
.defaultIfEmpty(this.anonymousAuthenticationToken);
}
private Mono<Void> logout(WebFilterExchange webFilterExchange, Authentication authentication) {
return this.serverLogoutHandler.logout(webFilterExchange, authentication)
.then(this.serverLogoutSuccessHandler.onLogoutSuccess(webFilterExchange, authentication));
}
/**
* Sets the {@link ServerLogoutSuccessHandler}. The default is {@link RedirectServerLogoutSuccessHandler}.
* @param serverLogoutSuccessHandler the handler to use
*/
public void setServerLogoutSuccessHandler(
ServerLogoutSuccessHandler serverLogoutSuccessHandler) {
Assert.notNull(serverLogoutSuccessHandler, "serverLogoutSuccessHandler cannot be null");
this.serverLogoutSuccessHandler = serverLogoutSuccessHandler;
}
public void setServerLogoutHandler(ServerLogoutHandler serverLogoutHandler) {
Assert.notNull(serverLogoutHandler, "logoutHandler must not be null");
this.serverLogoutHandler = serverLogoutHandler;
}
public void setRequiresLogout(ServerWebExchangeMatcher serverWebExchangeMatcher) {
Assert.notNull(serverWebExchangeMatcher, "serverWebExchangeMatcher must not be null");
this.requiresLogout = serverWebExchangeMatcher;
}
}

View File

@@ -0,0 +1,53 @@
/*
* 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.logout;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.DefaultServerRedirectStrategy;
import org.springframework.security.web.server.ServerRedirectStrategy;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;
import java.net.URI;
/**
* @author Rob Winch
* @since 5.0
*/
public class RedirectServerLogoutSuccessHandler implements ServerLogoutSuccessHandler {
public static final String DEFAULT_LOGOUT_SUCCESS_URL = "/login?logout";
private URI logoutSuccessUrl = URI.create(DEFAULT_LOGOUT_SUCCESS_URL);
private ServerRedirectStrategy serverRedirectStrategy = new DefaultServerRedirectStrategy();
@Override
public Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication) {
return this.serverRedirectStrategy
.sendRedirect(exchange.getExchange(), this.logoutSuccessUrl);
}
/**
* The URL to redirect to after successfully logging out.
* @param logoutSuccessUrl the url to redirect to. Default is "/login?logout".
*/
public void setLogoutSuccessUrl(URI logoutSuccessUrl) {
Assert.notNull(logoutSuccessUrl, "logoutSuccessUrl cannot be null");
this.logoutSuccessUrl = logoutSuccessUrl;
}
}

View File

@@ -0,0 +1,59 @@
/*
* 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.logout;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.DefaultServerRedirectStrategy;
import org.springframework.security.web.server.ServerRedirectStrategy;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;
import java.net.URI;
/**
* A {@link ServerLogoutHandler} which removes the SecurityContext using the provided
* {@link ServerSecurityContextRepository}
*
* @author Rob Winch
* @since 5.0
*/
public class SecurityContextServerLogoutHandler implements ServerLogoutHandler {
private ServerSecurityContextRepository serverSecurityContextRepository = new WebSessionServerSecurityContextRepository();
@Override
public Mono<Void> logout(WebFilterExchange exchange,
Authentication authentication) {
return this.serverSecurityContextRepository.save(exchange.getExchange(), null);
}
/**
* Sets the {@link ServerSecurityContextRepository} that should be used for logging
* out. Default is {@link WebSessionServerSecurityContextRepository}
*
* @param serverSecurityContextRepository the {@link ServerSecurityContextRepository}
* to use.
*/
public void setServerSecurityContextRepository(
ServerSecurityContextRepository serverSecurityContextRepository) {
Assert.notNull(serverSecurityContextRepository,
"serverSecurityContextRepository cannot be null");
this.serverSecurityContextRepository = serverSecurityContextRepository;
}
}

View File

@@ -0,0 +1,29 @@
/*
* 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.logout;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public interface ServerLogoutHandler {
Mono<Void> logout(WebFilterExchange exchange, Authentication authentication);
}

View File

@@ -0,0 +1,30 @@
/*
* 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.logout;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public interface ServerLogoutSuccessHandler {
Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication);
}

View File

@@ -0,0 +1,48 @@
/*
* 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.springframework.web.server.ServerWebExchange;
import java.util.Collections;
import java.util.Map;
/**
* @author Rob Winch
* @since 5.0
*/
public class AuthorizationContext {
private final ServerWebExchange exchange;
private final Map<String,Object> variables;
public AuthorizationContext(ServerWebExchange exchange) {
this(exchange, Collections.emptyMap());
}
public AuthorizationContext(ServerWebExchange exchange, Map<String,Object> variables) {
this.exchange = exchange;
this.variables = variables;
}
public ServerWebExchange getExchange() {
return exchange;
}
public Map<String,Object> getVariables() {
return Collections.unmodifiableMap(variables);
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class AuthorizationWebFilter implements WebFilter {
private ReactiveAuthorizationManager<? super ServerWebExchange> accessDecisionManager;
public AuthorizationWebFilter(ReactiveAuthorizationManager<? super ServerWebExchange> accessDecisionManager) {
this.accessDecisionManager = accessDecisionManager;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return accessDecisionManager.verify(exchange.getPrincipal(), exchange)
.switchIfEmpty( Mono.defer(() -> chain.filter(exchange)) );
}
}

View File

@@ -0,0 +1,75 @@
/*
* 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.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcherEntry;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.List;
/**
* @author Rob Winch
* @since 5.0
*/
public class DelegatingReactiveAuthorizationManager implements ReactiveAuthorizationManager<ServerWebExchange> {
private final List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings;
private DelegatingReactiveAuthorizationManager(List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings) {
this.mappings = mappings;
}
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, ServerWebExchange exchange) {
return Flux.fromIterable(mappings)
.concatMap(mapping -> mapping.getMatcher().matches(exchange)
.filter(ServerWebExchangeMatcher.MatchResult::isMatch)
.map(r -> r.getVariables())
.flatMap(variables -> mapping.getEntry()
.check(authentication, new AuthorizationContext(exchange, variables))
)
)
.next()
.defaultIfEmpty(new AuthorizationDecision(false));
}
public static DelegatingReactiveAuthorizationManager.Builder builder() {
return new DelegatingReactiveAuthorizationManager.Builder();
}
public static class Builder {
private final List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings = new ArrayList<>();
private Builder() {
}
public DelegatingReactiveAuthorizationManager.Builder add(ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>> entry) {
this.mappings.add(entry);
return this;
}
public DelegatingReactiveAuthorizationManager build() {
return new DelegatingReactiveAuthorizationManager(mappings);
}
}
}

View File

@@ -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.authorization;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class ExceptionTranslationWebFilter implements WebFilter {
private ServerAuthenticationEntryPoint serverAuthenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint();
private ServerAccessDeniedHandler serverAccessDeniedHandler = new HttpStatusServerAccessDeniedHandler(HttpStatus.FORBIDDEN);
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return chain.filter(exchange)
.onErrorResume(AccessDeniedException.class, denied -> exchange.getPrincipal()
.switchIfEmpty( commenceAuthentication(exchange, denied))
.flatMap( principal -> this.serverAccessDeniedHandler
.handle(exchange, denied))
);
}
/**
* Sets the access denied handler.
* @param serverAccessDeniedHandler the access denied handler to use. Default is
* HttpStatusAccessDeniedHandler with HttpStatus.FORBIDDEN
*/
public void setServerAccessDeniedHandler(ServerAccessDeniedHandler serverAccessDeniedHandler) {
Assert.notNull(serverAccessDeniedHandler, "accessDeniedHandler cannot be null");
this.serverAccessDeniedHandler = serverAccessDeniedHandler;
}
/**
* Sets the authentication entry point used when authentication is required
* @param serverAuthenticationEntryPoint the authentication entry point to use. Default is
* {@link HttpBasicServerAuthenticationEntryPoint}
*/
public void setServerAuthenticationEntryPoint(
ServerAuthenticationEntryPoint serverAuthenticationEntryPoint) {
Assert.notNull(serverAuthenticationEntryPoint, "authenticationEntryPoint cannot be null");
this.serverAuthenticationEntryPoint = serverAuthenticationEntryPoint;
}
private <T> Mono<T> commenceAuthentication(ServerWebExchange exchange, AccessDeniedException denied) {
return this.serverAuthenticationEntryPoint.commence(exchange, new AuthenticationCredentialsNotFoundException("Not Authenticated", denied))
.then(Mono.empty());
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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 reactor.core.publisher.Mono;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
/**
* Sets an HTTP Status that is provided when
* @author Rob Winch
* @since 5.0
*/
public class HttpStatusServerAccessDeniedHandler implements ServerAccessDeniedHandler {
private final HttpStatus httpStatus;
public HttpStatusServerAccessDeniedHandler(HttpStatus httpStatus) {
Assert.notNull(httpStatus, "httpStatus cannot be null");
this.httpStatus = httpStatus;
}
@Override
public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException e) {
return Mono.fromRunnable(() -> exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN));
}
}

View File

@@ -0,0 +1,31 @@
/*
* 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.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
*
* @author Rob Winch
* @since 5.0
*/
public interface ServerAccessDeniedHandler {
Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied);
}

View File

@@ -0,0 +1,43 @@
/*
* 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.springframework.security.core.Authentication;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import java.security.Principal;
/**
* Populate the {@link Principal} from {@link ServerWebExchange#getPrincipal()} into the
* Reactor {@link Context}.
*
* @author Rob Winch
* @since 5.0
*/
public class AuthenticationReactorContextWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return chain.filter(exchange)
.subscriberContext((Context context) -> context.put(Authentication.class, exchange.getPrincipal()));
}
}

View File

@@ -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 java.security.Principal;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebExchangeDecorator;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class SecurityContextRepositoryServerWebExchange extends ServerWebExchangeDecorator {
private final ServerSecurityContextRepository repository;
public SecurityContextRepositoryServerWebExchange(ServerWebExchange delegate, ServerSecurityContextRepository repository) {
super(delegate);
this.repository = repository;
}
@Override
@SuppressWarnings("unchecked")
public <T extends Principal> Mono<T> getPrincipal() {
return Mono.defer(() ->
this.repository.load(this)
.filter(c -> c.getAuthentication() != null)
.flatMap(c -> Mono.just((T) c.getAuthentication()))
.switchIfEmpty( super.getPrincipal() )
);
}
}

View File

@@ -0,0 +1,42 @@
/*
* 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.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class SecurityContextRepositoryWebFilter implements WebFilter {
private final ServerSecurityContextRepository repository;
public SecurityContextRepositoryWebFilter(ServerSecurityContextRepository repository) {
Assert.notNull(repository, "repository cannot be null");
this.repository = repository;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
SecurityContextRepositoryServerWebExchange delegate =
new SecurityContextRepositoryServerWebExchange(exchange, repository);
return chain.filter(delegate);
}
}

View File

@@ -0,0 +1,28 @@
/*
* 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.springframework.security.core.context.SecurityContext;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public interface ServerSecurityContextRepository {
Mono<Void> save(ServerWebExchange exchange, SecurityContext context);
Mono<SecurityContext> load(ServerWebExchange exchange);
}

View File

@@ -0,0 +1,40 @@
/*
* 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.springframework.security.core.context.SecurityContext;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class ServerWebExchangeAttributeServerSecurityContextRepository
implements ServerSecurityContextRepository {
final String ATTR = "USER";
public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
return Mono.fromRunnable(() ->exchange.getAttributes().put(ATTR, context));
}
public Mono<SecurityContext> load(ServerWebExchange exchange) {
return Mono.justOrEmpty(exchange.<SecurityContext>getAttribute(ATTR));
}
}

View File

@@ -0,0 +1,50 @@
/*
* 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.springframework.security.core.context.SecurityContext;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class WebSessionServerSecurityContextRepository
implements ServerSecurityContextRepository {
final String SESSION_ATTR = "USER";
public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
return exchange.getSession()
.doOnNext(session -> {
if(context == null) {
session.getAttributes().remove(SESSION_ATTR);
} else {
session.getAttributes().put(SESSION_ATTR, context);
}
})
.then();
}
public Mono<SecurityContext> load(ServerWebExchange exchange) {
return exchange.getSession().flatMap( session -> {
SecurityContext context = (SecurityContext) session.getAttributes().get(SESSION_ATTR);
return context == null ? Mono.empty() : Mono.just(context);
});
}
}

View File

@@ -0,0 +1,60 @@
/*
* 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 org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class CacheControlServerHttpHeadersWriter implements ServerHttpHeadersWriter {
/**
* The value for expires value
*/
public static final String EXPIRES_VALUE = "0";
/**
* The value for pragma value
*/
public static final String PRAGMA_VALUE = "no-cache";
/**
* The value for cache control value
*/
public static final String CACHE_CONTRTOL_VALUE = "no-cache, no-store, max-age=0, must-revalidate";
/**
* The delegate to write all the cache control related headers
*/
private static final ServerHttpHeadersWriter CACHE_HEADERS = StaticServerHttpHeadersWriter
.builder()
.header(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE)
.header(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE)
.header(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE)
.build();
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return CACHE_HEADERS.writeHttpHeaders(exchange);
}
}

View File

@@ -0,0 +1,49 @@
/*
* 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 java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class CompositeServerHttpHeadersWriter implements ServerHttpHeadersWriter {
private final List<ServerHttpHeadersWriter> writers;
public CompositeServerHttpHeadersWriter(ServerHttpHeadersWriter... writers) {
this(Arrays.asList(writers));
}
public CompositeServerHttpHeadersWriter(List<ServerHttpHeadersWriter> writers) {
this.writers = writers;
}
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
Stream<Mono<Void>> results = writers.stream().map( writer -> writer.writeHttpHeaders(exchange));
return Mono.when(results.collect(Collectors.toList()));
}
}

View File

@@ -0,0 +1,48 @@
/*
* 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 org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* Adds X-Content-Type-Options: nosniff
*
* @author Rob Winch
* @since 5.0
*/
public class ContentTypeOptionsServerHttpHeadersWriter
implements ServerHttpHeadersWriter {
public static final String X_CONTENT_OPTIONS = "X-Content-Type-Options";
public static final String NOSNIFF = "nosniff";
/**
* The delegate to write all the cache control related headers
*/
private static final ServerHttpHeadersWriter CONTENT_TYPE_HEADERS = StaticServerHttpHeadersWriter
.builder()
.header(X_CONTENT_OPTIONS, NOSNIFF)
.build();
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return CONTENT_TYPE_HEADERS.writeHttpHeaders(exchange);
}
}

View File

@@ -0,0 +1,46 @@
/*
* 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 org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
/**
* Invokes a {@link ServerHttpHeadersWriter} on
* {@link ServerHttpResponse#beforeCommit(java.util.function.Supplier)}.
*
* @author Rob Winch
* @since 5.0
*/
public class HttpHeaderWriterWebFilter implements WebFilter {
private final ServerHttpHeadersWriter writer;
public HttpHeaderWriterWebFilter(ServerHttpHeadersWriter writer) {
super();
this.writer = writer;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
exchange.getResponse().beforeCommit(() -> writer.writeHttpHeaders(exchange));
return chain.filter(exchange);
}
}

View File

@@ -0,0 +1,41 @@
/*
* 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 java.util.function.Supplier;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* Interface for writing headers just before the response is committed.
*
* @author Rob Winch
* @since 5.0
*/
public interface ServerHttpHeadersWriter {
/**
* Write the headers to the response.
*
* @param exchange
* @return A Mono which is returned to the {@link Supplier} of the
* {@link ServerHttpResponse#beforeCommit(Supplier)}.
*/
Mono<Void> writeHttpHeaders(ServerWebExchange exchange);
}

View File

@@ -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.header;
import java.util.Arrays;
import java.util.Collections;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class StaticServerHttpHeadersWriter implements ServerHttpHeadersWriter {
private final HttpHeaders headersToAdd;
public StaticServerHttpHeadersWriter(HttpHeaders headersToAdd) {
this.headersToAdd = headersToAdd;
}
/* (non-Javadoc)
* @see org.springframework.security.web.server.HttpHeadersWriter#writeHttpHeaders(org.springframework.web.server.ServerWebExchange)
*/
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
HttpHeaders headers = exchange.getResponse().getHeaders();
boolean containsOneHeaderToAdd = Collections.disjoint(headers.keySet(), this.headersToAdd.keySet());
if(containsOneHeaderToAdd) {
this.headersToAdd.forEach((name, values) -> {
headers.put(name, values);
});
}
return Mono.empty();
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private HttpHeaders headers = new HttpHeaders();
public Builder header(String headerName, String...values) {
headers.put(headerName, Arrays.asList(values));
return this;
}
public StaticServerHttpHeadersWriter build() {
return new StaticServerHttpHeadersWriter(headers);
}
}
}

View File

@@ -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 java.time.Duration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public final class StrictTransportSecurityServerHttpHeadersWriter
implements ServerHttpHeadersWriter {
public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security";
private String maxAge;
private String subdomain;
private ServerHttpHeadersWriter delegate;
/**
*
*/
public StrictTransportSecurityServerHttpHeadersWriter() {
setIncludeSubDomains(true);
setMaxAge(Duration.ofDays(365L));
updateDelegate();
}
/* (non-Javadoc)
* @see org.springframework.security.web.server.HttpHeadersWriter#writeHttpHeaders(org.springframework.http.HttpHeaders)
*/
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return isSecure(exchange) ? delegate.writeHttpHeaders(exchange) : Mono.empty();
}
public void setIncludeSubDomains(boolean includeSubDomains) {
subdomain = includeSubDomains ? " ; includeSubDomains" : "";
updateDelegate();
}
public void setMaxAge(Duration maxAge) {
this.maxAge = "max-age=" + maxAge.getSeconds();
updateDelegate();
}
private void updateDelegate() {
delegate = StaticServerHttpHeadersWriter.builder()
.header(STRICT_TRANSPORT_SECURITY, maxAge + subdomain)
.build();
}
private boolean isSecure(ServerWebExchange exchange) {
String scheme = exchange.getRequest().getURI().getScheme();
boolean isSecure = scheme != null && scheme.equalsIgnoreCase("https");
return isSecure;
}
}

View File

@@ -0,0 +1,49 @@
/*
* 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 org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* Adds X-Content-Type-Options: nosniff
*
* @author Rob Winch
* @since 5.0
*/
public class XContentTypeOptionsServerHttpHeadersWriter
implements ServerHttpHeadersWriter {
public static final String X_CONTENT_OPTIONS = "X-Content-Options";
public static final String NOSNIFF = "nosniff";
/**
* The delegate to write all the cache control related headers
*/
private static final ServerHttpHeadersWriter CONTENT_TYPE_HEADERS = StaticServerHttpHeadersWriter
.builder()
.header(X_CONTENT_OPTIONS, NOSNIFF)
.build();
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return CONTENT_TYPE_HEADERS.writeHttpHeaders(exchange);
}
}

View File

@@ -0,0 +1,91 @@
/*
* 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 org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class XFrameOptionsServerHttpHeadersWriter implements ServerHttpHeadersWriter {
public static final String X_FRAME_OPTIONS = "X-Frame-Options";
private ServerHttpHeadersWriter delegate = createDelegate(Mode.DENY);
/*
* (non-Javadoc)
*
* @see org.springframework.security.web.server.HttpHeadersWriter#
* writeHttpHeaders(org.springframework.web.server.ServerWebExchange)
*/
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return delegate.writeHttpHeaders(exchange);
}
/**
* Sets the X-Frame-Options mode. There is no support for ALLOW-FROM because
* not <a href=
* "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options">all
* browsers support it</a>. Consider using X-Frame-Options with
* Content-Security-Policy <a href=
* "https://w3c.github.io/webappsec/specs/content-security-policy/#directive-frame-ancestors">frame-ancestors</a>.
*
* @param mode
*/
public void setMode(Mode mode) {
this.delegate = createDelegate(mode);
}
/**
* The X-Frame-Options values. There is no support for ALLOW-FROM because
* not <a href=
* "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options">all
* browsers support it</a>. Consider using X-Frame-Options with
* Content-Security-Policy <a href=
* "https://w3c.github.io/webappsec/specs/content-security-policy/#directive-frame-ancestors">frame-ancestors</a>.
*
* @author Rob Winch
* @since 5.0
*/
public enum Mode {
/**
* A browser receiving content with this header field MUST NOT display
* this content in any frame.
*/
DENY,
/**
* A browser receiving content with this header field MUST NOT display
* this content in any frame from a page of different origin than the
* content itself.
*
* If a browser or plugin cannot reliably determine whether or not the
* origin of the content and the frame are the same, this MUST be
* treated as "DENY".
*/
SAMEORIGIN;
}
private static ServerHttpHeadersWriter createDelegate(Mode mode) {
// @formatter:off
return StaticServerHttpHeadersWriter.builder().header(X_FRAME_OPTIONS, mode.name()).build();
// @formatter:on
}
}

View File

@@ -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.header;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class XXssProtectionServerHttpHeadersWriter implements ServerHttpHeadersWriter {
public static final String X_XSS_PROTECTION = "X-XSS-Protection";
private boolean enabled;
private boolean block;
private ServerHttpHeadersWriter delegate;
/**
*
*/
public XXssProtectionServerHttpHeadersWriter() {
this.enabled = true;
this.block = true;
updateDelegate();
}
/* (non-Javadoc)
* @see org.springframework.security.web.server.HttpHeadersWriter#writeHttpHeaders(org.springframework.web.server.ServerWebExchange)
*/
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return delegate.writeHttpHeaders(exchange);
}
/**
* If true, will contain a value of 1. For example:
*
* <pre>
* X-XSS-Protection: 1
* </pre>
*
* or if {@link #setBlock(boolean)} is true
*
*
* <pre>
* X-XSS-Protection: 1; mode=block
* </pre>
*
* If false, will explicitly disable specify that X-XSS-Protection is disabled. For
* example:
*
* <pre>
* X-XSS-Protection: 0
* </pre>
*
* @param enabled the new value
*/
public void setEnabled(boolean enabled) {
if (!enabled) {
setBlock(false);
}
this.enabled = enabled;
updateDelegate();
}
/**
* If false, will not specify the mode as blocked. In this instance, any content will
* be attempted to be fixed. If true, the content will be replaced with "#".
*
* @param block the new value
*/
public void setBlock(boolean block) {
if (!enabled && block) {
throw new IllegalArgumentException(
"Cannot set block to true with enabled false");
}
this.block = block;
updateDelegate();
}
private void updateDelegate() {
this.delegate = StaticServerHttpHeadersWriter.builder()
.header(X_XSS_PROTECTION, createHeaderValue())
.build();
}
private String createHeaderValue() {
if (!enabled) {
return "0";
}
if(!block) {
return "1";
}
return "1 ; mode=block";
}
}

View File

@@ -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.ui;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.nio.charset.Charset;
/**
* @author Rob Winch
* @since 5.0
*/
public class LoginPageGeneratingWebFilter implements WebFilter {
private ServerWebExchangeMatcher matcher = ServerWebExchangeMatchers
.pathMatchers(HttpMethod.GET, "/login");
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return this.matcher.matches(exchange)
.filter(ServerWebExchangeMatcher.MatchResult::isMatch)
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.flatMap(matchResult -> render(exchange));
}
private Mono<Void> render(ServerWebExchange exchange) {
MultiValueMap<String, String> queryParams = exchange.getRequest()
.getQueryParams();
boolean isError = queryParams.containsKey("error");
boolean isLogoutSuccess = queryParams.containsKey("logout");
ServerHttpResponse result = exchange.getResponse();
result.setStatusCode(HttpStatus.FOUND);
result.getHeaders().setContentType(MediaType.TEXT_HTML);
byte[] bytes = createPage(isError, isLogoutSuccess);
DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
DataBuffer buffer = bufferFactory.wrap(bytes);
return result.writeWith(Mono.just(buffer))
.doOnError( error -> DataBufferUtils.release(buffer));
}
private static byte[] createPage(boolean isError, boolean isLogoutSuccess) {
String page = "<!DOCTYPE html>\n"
+ "<html lang=\"en\">\n"
+ " <head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"
+ " <meta name=\"description\" content=\"\">\n"
+ " <meta name=\"author\" content=\"\">\n"
+ " <title>Please sign in</title>\n"
+ " <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n"
+ " <link href=\"http://getbootstrap.com/docs/4.0/examples/signin/signin.css\" rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"container\">\n"
+ " <form class=\"form-signin\" method=\"post\" action=\"/login\">\n"
+ " <h2 class=\"form-signin-heading\">Please sign in</h2>\n"
+ createError(isError)
+ createLogoutSuccess(isLogoutSuccess)
+ " <p>\n"
+ " <label for=\"username\" class=\"sr-only\">Username</label>\n"
+ " <input type=\"text\" id=\"username\" name=\"username\" class=\"form-control\" placeholder=\"Username\" required autofocus>\n"
+ " </p>\n"
+ " <p>\n"
+ " <label for=\"password\" class=\"sr-only\">Password</label>\n"
+ " <input type=\"password\" id=\"password\" name=\"password\" class=\"form-control\" placeholder=\"Password\" required>\n"
+ " </p>\n"
+ " <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Sign in</button>\n"
+ " </form>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>";
return page.getBytes(Charset.defaultCharset());
}
private static String createError(boolean isError) {
return isError ? "<div class=\"alert alert-danger\" role=\"alert\">Invalid credentials</div>" : "";
}
private static String createLogoutSuccess(boolean isLogoutSuccess) {
return isLogoutSuccess ? "<div class=\"alert alert-success\" role=\"alert\">You have been signed out</div>" : "";
}
}

View File

@@ -0,0 +1,65 @@
/*
* 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.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Rob Winch
* @since 5.0
*/
public class AndServerWebExchangeMatcher implements ServerWebExchangeMatcher {
private final List<ServerWebExchangeMatcher> matchers;
public AndServerWebExchangeMatcher(List<ServerWebExchangeMatcher> matchers) {
Assert.notEmpty(matchers, "matchers cannot be empty");
this.matchers = matchers;
}
public AndServerWebExchangeMatcher(ServerWebExchangeMatcher... matchers) {
this(Arrays.asList(matchers));
}
/* (non-Javadoc)
* @see org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher#matches(org.springframework.web.server.ServerWebExchange)
*/
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
return Mono.defer(() -> {
Map<String, Object> variables = new HashMap<>();
return Flux.fromIterable(matchers)
.flatMap(matcher -> matcher.matches(exchange))
.doOnNext(matchResult -> variables.putAll(matchResult.getVariables()))
.all(MatchResult::isMatch)
.flatMap(allMatch -> allMatch ? MatchResult.match(variables) : MatchResult.notMatch());
});
}
@Override
public String toString() {
return "AndServerWebExchangeMatcher{" +
"matchers=" + matchers +
'}';
}
}

View File

@@ -0,0 +1,153 @@
/*
* 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.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.InvalidMediaTypeException;
import reactor.core.publisher.Mono;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.server.NotAcceptableStatusException;
import org.springframework.web.server.ServerWebExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public class MediaTypeServerWebExchangeMatcher implements ServerWebExchangeMatcher {
private final Log logger = LogFactory.getLog(getClass());
private final Collection<MediaType> matchingMediaTypes;
private boolean useEquals;
private Set<MediaType> ignoredMediaTypes = Collections.emptySet();
public MediaTypeServerWebExchangeMatcher(MediaType... matchingMediaTypes) {
Assert.notEmpty(matchingMediaTypes, "matchingMediaTypes cannot be null");
Assert.noNullElements(matchingMediaTypes, "matchingMediaTypes cannot contain null");
this.matchingMediaTypes = Arrays.asList(matchingMediaTypes);
}
public MediaTypeServerWebExchangeMatcher(Collection<MediaType> matchingMediaTypes) {
Assert.notEmpty(matchingMediaTypes, "matchingMediaTypes cannot be null");
Assert.isTrue(!matchingMediaTypes.contains(null), () -> "matchingMediaTypes cannot contain null. Got " + matchingMediaTypes);
this.matchingMediaTypes = matchingMediaTypes;
}
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
List<MediaType> httpRequestMediaTypes;
try {
httpRequestMediaTypes = resolveMediaTypes(exchange);
}
catch (NotAcceptableStatusException e) {
this.logger.debug("Failed to parse MediaTypes, returning false", e);
return MatchResult.notMatch();
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("httpRequestMediaTypes=" + httpRequestMediaTypes);
}
for (MediaType httpRequestMediaType : httpRequestMediaTypes) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Processing " + httpRequestMediaType);
}
if (shouldIgnore(httpRequestMediaType)) {
this.logger.debug("Ignoring");
continue;
}
if (this.useEquals) {
boolean isEqualTo = this.matchingMediaTypes
.contains(httpRequestMediaType);
this.logger.debug("isEqualTo " + isEqualTo);
return isEqualTo ? MatchResult.match() : MatchResult.notMatch();
}
for (MediaType matchingMediaType : this.matchingMediaTypes) {
boolean isCompatibleWith = matchingMediaType
.isCompatibleWith(httpRequestMediaType);
if (this.logger.isDebugEnabled()) {
this.logger.debug(matchingMediaType + " .isCompatibleWith "
+ httpRequestMediaType + " = " + isCompatibleWith);
}
if (isCompatibleWith) {
return MatchResult.match();
}
}
}
this.logger.debug("Did not match any media types");
return MatchResult.notMatch();
}
private boolean shouldIgnore(MediaType httpRequestMediaType) {
for (MediaType ignoredMediaType : this.ignoredMediaTypes) {
if (httpRequestMediaType.includes(ignoredMediaType)) {
return true;
}
}
return false;
}
/**
* If set to true, matches on exact {@link MediaType}, else uses
* {@link MediaType#isCompatibleWith(MediaType)}.
*
* @param useEquals specify if equals comparison should be used.
*/
public void setUseEquals(boolean useEquals) {
this.useEquals = useEquals;
}
/**
* Set the {@link MediaType} to ignore from the {@link ContentNegotiationStrategy}.
* This is useful if for example, you want to match on
* {@link MediaType#APPLICATION_JSON} but want to ignore {@link MediaType#ALL}.
*
* @param ignoredMediaTypes the {@link MediaType}'s to ignore from the
* {@link ContentNegotiationStrategy}
*/
public void setIgnoredMediaTypes(Set<MediaType> ignoredMediaTypes) {
this.ignoredMediaTypes = ignoredMediaTypes;
}
private List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
try {
List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
MediaType.sortBySpecificityAndQuality(mediaTypes);
return mediaTypes;
}
catch (InvalidMediaTypeException ex) {
String value = exchange.getRequest().getHeaders().getFirst("Accept");
throw new NotAcceptableStatusException(
"Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
}
}
@Override
public String toString() {
return "MediaTypeRequestMatcher [matchingMediaTypes="
+ this.matchingMediaTypes + ", useEquals=" + this.useEquals
+ ", ignoredMediaTypes=" + this.ignoredMediaTypes + "]";
}
}

View File

@@ -0,0 +1,62 @@
/*
* 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.Arrays;
import java.util.List;
import java.util.function.Predicate;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* @author Rob Winch
* @since 5.0
*/
public class OrServerWebExchangeMatcher implements ServerWebExchangeMatcher {
private final List<ServerWebExchangeMatcher> matchers;
public OrServerWebExchangeMatcher(List<ServerWebExchangeMatcher> matchers) {
Assert.notEmpty(matchers, "matchers cannot be empty");
this.matchers = matchers;
}
public OrServerWebExchangeMatcher(ServerWebExchangeMatcher... matchers) {
this(Arrays.asList(matchers));
}
/* (non-Javadoc)
* @see org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher#matches(org.springframework.web.server.ServerWebExchange)
*/
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
return Flux.fromIterable(matchers)
.flatMap(m -> m.matches(exchange))
.filter(m -> m.isMatch())
.next()
.switchIfEmpty(MatchResult.notMatch());
}
@Override
public String toString() {
return "OrServerWebExchangeMatcher{" +
"matchers=" + matchers +
'}';
}
}

View File

@@ -0,0 +1,83 @@
/*
* 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.springframework.http.HttpMethod;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
/**
* @author Rob Winch
* @since 5.0
*/
public final class PathPatternParserServerWebExchangeMatcher implements ServerWebExchangeMatcher {
private static final PathPatternParser DEFAULT_PATTERN_PARSER = new PathPatternParser();
private final PathPattern pattern;
private final HttpMethod method;
public PathPatternParserServerWebExchangeMatcher(PathPattern pattern) {
this(pattern, null);
}
public PathPatternParserServerWebExchangeMatcher(PathPattern pattern, HttpMethod method) {
Assert.notNull(pattern, "pattern cannot be null");
this.pattern = pattern;
this.method = method;
}
public PathPatternParserServerWebExchangeMatcher(String pattern, HttpMethod method) {
Assert.notNull(pattern, "pattern cannot be null");
this.pattern = DEFAULT_PATTERN_PARSER.parse(pattern);
this.method = method;
}
public PathPatternParserServerWebExchangeMatcher(String pattern) {
this(pattern, null);
}
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
ServerHttpRequest request = exchange.getRequest();
if(this.method != null && !this.method.equals(request.getMethod())) {
return MatchResult.notMatch();
}
PathContainer path = request.getPath().pathWithinApplication();
boolean match = this.pattern.matches(path);
if(!match) {
return MatchResult.notMatch();
}
Map<String,String> pathVariables = this.pattern.matchAndExtract(path).getUriVariables();
Map<String,Object> variables = new HashMap<>(pathVariables);
return MatchResult.match(variables);
}
@Override
public String toString() {
return "PathMatcherServerWebExchangeMatcher{" +
"pattern='" + pattern + '\'' +
", method=" + method +
'}';
}
}

View File

@@ -0,0 +1,62 @@
/*
* 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.Map;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
*
* @author Rob Winch
* @since 5.0
*/
public interface ServerWebExchangeMatcher {
Mono<MatchResult> matches(ServerWebExchange exchange);
class MatchResult {
private final boolean match;
private final Map<String,Object> variables;
private MatchResult(boolean match, Map<String, Object> variables) {
this.match = match;
this.variables = variables;
}
public boolean isMatch() {
return match;
}
public Map<String,Object> getVariables() {
return variables;
}
public static Mono<MatchResult> match() {
return match(Collections.emptyMap());
}
public static Mono<MatchResult> match(Map<String,Object> variables) {
return Mono.just(new MatchResult(true, variables));
}
public static Mono<MatchResult> notMatch() {
return Mono.just(new MatchResult(false, Collections.emptyMap()));
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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;
/**
* @author Rob Winch
* @since 5.0
*/
public class ServerWebExchangeMatcherEntry<T> {
private final ServerWebExchangeMatcher matcher;
private final T entry;
public ServerWebExchangeMatcherEntry(ServerWebExchangeMatcher matcher, T entry) {
this.matcher = matcher;
this.entry = entry;
}
public ServerWebExchangeMatcher getMatcher() {
return matcher;
}
public T getEntry() {
return entry;
}
}

View File

@@ -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.util.matcher;
import org.springframework.http.HttpMethod;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.List;
/**
* @author Rob Winch
* @since 5.0
*/
public abstract class ServerWebExchangeMatchers {
public static ServerWebExchangeMatcher pathMatchers(HttpMethod method, String... patterns) {
List<ServerWebExchangeMatcher> matchers = new ArrayList<>(patterns.length);
for (String pattern : patterns) {
matchers.add(new PathPatternParserServerWebExchangeMatcher(pattern, method));
}
return new OrServerWebExchangeMatcher(matchers);
}
public static ServerWebExchangeMatcher pathMatchers(String... patterns) {
return pathMatchers(null, patterns);
}
public static ServerWebExchangeMatcher matchers(ServerWebExchangeMatcher... matchers) {
return new OrServerWebExchangeMatcher(matchers);
}
public static ServerWebExchangeMatcher anyExchange() {
return new ServerWebExchangeMatcher() {
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
return ServerWebExchangeMatcher.MatchResult.match();
}
};
}
private ServerWebExchangeMatchers() {
}
}

View File

@@ -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";
}
}
}

View File

@@ -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();
}
}
}

View File

@@ -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;
}
}
}

View File

@@ -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 {}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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()));
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}