Add WebFlux

Fixes gh-4128
This commit is contained in:
Rob Winch
2017-05-02 21:19:14 -05:00
parent 051e3fb079
commit b4f2777755
91 changed files with 7036 additions and 1 deletions

View File

@@ -0,0 +1,112 @@
/*
*
* * 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.config.web.server;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
import org.springframework.security.web.server.authorization.ExceptionTranslationWebFilter;
import org.springframework.test.web.reactive.server.WebTestClient;
/**
* @author Rob Winch
* @since 5.0
*/
public class AuthorizeExchangeBuilderTests {
AuthorizeExchangeBuilder authorization = new AuthorizeExchangeBuilder();
@Test
public void antMatchersWhenMethodAndPatternsThenDiscriminatesByMethod() {
authorization.antMatchers(HttpMethod.POST, "/a", "/b").denyAll();
authorization.anyExchange().permitAll();
WebTestClient client = buildClient();
client.get()
.uri("/a")
.exchange()
.expectStatus().isOk();
client.get()
.uri("/b")
.exchange()
.expectStatus().isOk();
client.post()
.uri("/a")
.exchange()
.expectStatus().isUnauthorized();
client.post()
.uri("/b")
.exchange()
.expectStatus().isUnauthorized();
}
@Test
public void antMatchersWhenPatternsThenAnyMethod() {
authorization.antMatchers("/a", "/b").denyAll();
authorization.anyExchange().permitAll();
WebTestClient client = buildClient();
client.get()
.uri("/a")
.exchange()
.expectStatus().isUnauthorized();
client.get()
.uri("/b")
.exchange()
.expectStatus().isUnauthorized();
client.post()
.uri("/a")
.exchange()
.expectStatus().isUnauthorized();
client.post()
.uri("/b")
.exchange()
.expectStatus().isUnauthorized();
}
@Test(expected = IllegalStateException.class)
public void antMatchersWhenNoAccessAndAnotherMatcherThenThrowsException() {
authorization.antMatchers("/incomplete");
authorization.antMatchers("/throws-exception");
}
@Test(expected = IllegalStateException.class)
public void anyExchangeWhenFollowedByMatcherThenThrowsException() {
authorization.anyExchange().denyAll();
authorization.antMatchers("/never-reached");
}
@Test(expected = IllegalStateException.class)
public void buildWhenMatcherDefinedWithNoAccessThenThrowsException() {
authorization.antMatchers("/incomplete");
authorization.build();
}
private WebTestClient buildClient() {
return WebTestClientBuilder.bindToWebFilters(new ExceptionTranslationWebFilter(), authorization.build()).build();
}
}

View File

@@ -0,0 +1,144 @@
/*
*
* * 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.config.web.server;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
import org.springframework.security.web.server.header.ContentTypeOptionsHttpHeadersWriter;
import org.springframework.security.web.server.header.StrictTransportSecurityHttpHeadersWriter;
import org.springframework.security.web.server.header.XFrameOptionsHttpHeadersWriter;
import org.springframework.security.web.server.header.XXssProtectionHttpHeadersWriter;
import org.springframework.test.web.reactive.server.FluxExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
/**
* @author Rob Winch
* @since 5.0
*/
public class HeaderBuilderTests {
HeaderBuilder headers = new HeaderBuilder();
HttpHeaders expectedHeaders = new HttpHeaders();
Set<String> ignoredHeaderNames = Collections.singleton(HttpHeaders.CONTENT_TYPE);
@Before
public void setup() {
expectedHeaders.add(StrictTransportSecurityHttpHeadersWriter.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains");
expectedHeaders.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate");
expectedHeaders.add(HttpHeaders.PRAGMA, "no-cache");
expectedHeaders.add(HttpHeaders.EXPIRES, "0");
expectedHeaders.add(ContentTypeOptionsHttpHeadersWriter.X_CONTENT_OPTIONS, "nosniff");
expectedHeaders.add(XFrameOptionsHttpHeadersWriter.X_FRAME_OPTIONS, "DENY");
expectedHeaders.add(XXssProtectionHttpHeadersWriter.X_XSS_PROTECTION, "1 ; mode=block");
}
@Test
public void headersWhenDefaultsThenAllDefaultsWritten() {
assertHeaders();
}
@Test
public void headersWhenCacheDisableThenCacheNotWritten() {
expectedHeaders.remove(HttpHeaders.CACHE_CONTROL);
expectedHeaders.remove(HttpHeaders.PRAGMA);
expectedHeaders.remove(HttpHeaders.EXPIRES);
headers.cache().disable();
assertHeaders();
}
@Test
public void headersWhenContentOptionsDisableThenContentTypeOptionsNotWritten() {
expectedHeaders.remove(ContentTypeOptionsHttpHeadersWriter.X_CONTENT_OPTIONS);
headers.contentTypeOptions().disable();
assertHeaders();
}
@Test
public void headersWhenHstsDisableThenHstsNotWritten() {
expectedHeaders.remove(StrictTransportSecurityHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
headers.hsts().disable();
assertHeaders();
}
@Test
public void headersWhenHstsCustomThenCustomHstsWritten() {
expectedHeaders.remove(StrictTransportSecurityHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
expectedHeaders.add(StrictTransportSecurityHttpHeadersWriter.STRICT_TRANSPORT_SECURITY, "max-age=60");
headers.hsts().maxAge(Duration.ofSeconds(60));
headers.hsts().includeSubdomains(false);
assertHeaders();
}
@Test
public void headersWhenFrameOptionsDisableThenFrameOptionsNotWritten() {
expectedHeaders.remove(XFrameOptionsHttpHeadersWriter.X_FRAME_OPTIONS);
headers.frameOptions().disable();
assertHeaders();
}
@Test
public void headersWhenFrameOptionsModeThenFrameOptionsCustomMode() {
expectedHeaders.remove(XFrameOptionsHttpHeadersWriter.X_FRAME_OPTIONS);
expectedHeaders.add(XFrameOptionsHttpHeadersWriter.X_FRAME_OPTIONS, "SAMEORIGIN");
headers.frameOptions().mode(XFrameOptionsHttpHeadersWriter.Mode.SAMEORIGIN);
assertHeaders();
}
@Test
public void headersWhenXssProtectionDisableThenXssProtectionNotWritten() {
expectedHeaders.remove("X-Xss-Protection");
headers.xssProtection().disable();
assertHeaders();
}
private void assertHeaders() {
WebTestClient client = buildClient();
FluxExchangeResult<String> response = client.get()
.uri("https://example.com/")
.exchange()
.returnResult(String.class);
Map<String,List<String>> responseHeaders = response.getResponseHeaders();
ignoredHeaderNames.stream().forEach(responseHeaders::remove);
assertThat(responseHeaders).describedAs(response.toString()).isEqualTo(expectedHeaders);
}
private WebTestClient buildClient() {
return WebTestClientBuilder.bindToWebFilters(headers.build()).build();
}
}

View File

@@ -0,0 +1,107 @@
/*
*
* * 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.config.web.server;
import org.apache.http.HttpHeaders;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
import org.springframework.security.web.server.context.SecurityContextRepository;
import org.springframework.security.web.server.context.WebSessionSecurityContextRepository;
import org.springframework.test.web.reactive.server.EntityExchangeResult;
import org.springframework.test.web.reactive.server.FluxExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;
/**
* @author Rob Winch
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
public class HttpSecurityTests {
@Mock
SecurityContextRepository contextRepository;
@Mock
ReactiveAuthenticationManager authenticationManager;
HttpSecurity http;
@Before
public void setup() {
http = HttpSecurity.http();
}
@Test
public void defaults() {
http.securityContextRepository(this.contextRepository);
WebTestClient client = buildClient();
FluxExchangeResult<String> result = client.get()
.uri("/")
.exchange()
.expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+")
.returnResult(String.class);
assertThat(result.getResponseCookies()).isEmpty();
// there is no need to try and load the SecurityContext by default
verifyZeroInteractions(contextRepository);
}
@Test
public void basic() {
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
http.securityContextRepository(new WebSessionSecurityContextRepository());
http.httpBasic();
http.authenticationManager(authenticationManager);
AuthorizeExchangeBuilder authorize = http.authorizeExchange();
authorize.anyExchange().authenticated();
WebTestClient client = buildClient();
EntityExchangeResult<byte[]> result = client
.filter(basicAuthentication("rob", "rob"))
.get()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+")
.expectBody().consumeAsStringWith( b-> assertThat(b).isEqualTo("ok"))
.returnResult();
assertThat(result.getResponseCookies().getFirst("SESSION")).isNotNull();
}
private WebTestClient buildClient() {
return WebTestClientBuilder.bindToWebFilters(http.build()).build();
}
}