Remove blank lines from all tests

Remove all blank lines from test code so that test methods are
visually grouped together. This generally helps to make the test
classes easer to scan, however, the "given" / "when" / "then"
blocks used by some tests are now not as easy to discern.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-08-01 19:33:21 -07:00
committed by Rob Winch
parent 5bdd757108
commit a5aa6b3d7f
787 changed files with 9 additions and 10241 deletions

View File

@@ -58,7 +58,6 @@ public final class TestOAuth2AuthenticatedPrincipals {
attributes.put(OAuth2IntrospectionClaimNames.SUBJECT, "Z5O3upPC88QrAjx00dis");
attributes.put(OAuth2IntrospectionClaimNames.USERNAME, "jdoe");
attributesConsumer.accept(attributes);
Collection<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("SCOPE_read"),
new SimpleGrantedAuthority("SCOPE_write"), new SimpleGrantedAuthority("SCOPE_dolphin"));
return new OAuth2IntrospectionAuthenticatedPrincipal(attributes, authorities);

View File

@@ -43,7 +43,6 @@ public class BearerTokenAuthenticationTokenTests {
@Test
public void constructorWhenTokenHasValueThenConstructedCorrectly() {
BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token");
assertThat(token.getToken()).isEqualTo("token");
assertThat(token.getPrincipal()).isEqualTo("token");
assertThat(token.getCredentials()).isEqualTo("token");

View File

@@ -44,7 +44,6 @@ public class BearerTokenErrorTests {
@Test
public void constructorWithErrorCodeWhenErrorCodeIsValidThenCreated() {
BearerTokenError error = new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, null, null);
assertThat(error.getErrorCode()).isEqualTo(TEST_ERROR_CODE);
assertThat(error.getHttpStatus()).isEqualTo(TEST_HTTP_STATUS);
assertThat(error.getDescription()).isNull();
@@ -74,7 +73,6 @@ public class BearerTokenErrorTests {
public void constructorWithAllParametersWhenAllParametersAreValidThenCreated() {
BearerTokenError error = new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI,
TEST_SCOPE);
assertThat(error.getErrorCode()).isEqualTo(TEST_ERROR_CODE);
assertThat(error.getHttpStatus()).isEqualTo(TEST_HTTP_STATUS);
assertThat(error.getDescription()).isEqualTo(TEST_DESCRIPTION);

View File

@@ -44,10 +44,8 @@ public class JwtAuthenticationConverterTests {
@Test
public void convertWhenDefaultGrantedAuthoritiesConverterSet() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt);
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"),
new SimpleGrantedAuthority("SCOPE_message:write"));
}
@@ -62,15 +60,11 @@ public class JwtAuthenticationConverterTests {
@Test
public void convertWithOverriddenGrantedAuthoritiesConverter() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
Converter<Jwt, Collection<GrantedAuthority>> grantedAuthoritiesConverter = (token) -> Arrays
.asList(new SimpleGrantedAuthority("blah"));
this.jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt);
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("blah"));
}
@@ -97,10 +91,8 @@ public class JwtAuthenticationConverterTests {
@Test
public void convertWhenPrincipalClaimNameSet() {
this.jwtAuthenticationConverter.setPrincipalClaimName("user_id");
Jwt jwt = TestJwts.jwt().claim("user_id", "100").build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt);
assertThat(authentication.getName()).isEqualTo("100");
}

View File

@@ -65,23 +65,17 @@ public class JwtAuthenticationProviderTests {
@Test
public void authenticateWhenJwtDecodesThenAuthenticationHasAttributesContainedInJwt() {
BearerTokenAuthenticationToken token = this.authentication();
Jwt jwt = TestJwts.jwt().claim("name", "value").build();
given(this.jwtDecoder.decode("token")).willReturn(jwt);
given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(new JwtAuthenticationToken(jwt));
JwtAuthenticationToken authentication = (JwtAuthenticationToken) this.provider.authenticate(token);
assertThat(authentication.getTokenAttributes()).containsEntry("name", "value");
}
@Test
public void authenticateWhenJwtDecodeFailsThenRespondsWithInvalidToken() {
BearerTokenAuthenticationToken token = this.authentication();
given(this.jwtDecoder.decode("token")).willThrow(BadJwtException.class);
assertThatCode(() -> this.provider.authenticate(token))
.matches((failed) -> failed instanceof OAuth2AuthenticationException)
.matches(errorCode(BearerTokenErrorCodes.INVALID_TOKEN));
@@ -90,9 +84,7 @@ public class JwtAuthenticationProviderTests {
@Test
public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGenericOne() {
BearerTokenAuthenticationToken token = this.authentication();
given(this.jwtDecoder.decode(token.getToken())).willThrow(new BadJwtException("with \"invalid\" chars"));
assertThatCode(() -> this.provider.authenticate(token)).isInstanceOf(OAuth2AuthenticationException.class)
.hasFieldOrPropertyWithValue("error.description", "Invalid token");
}
@@ -101,9 +93,7 @@ public class JwtAuthenticationProviderTests {
@Test
public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() {
BearerTokenAuthenticationToken token = this.authentication();
given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set"));
assertThatCode(() -> this.provider.authenticate(token)).isInstanceOf(AuthenticationException.class)
.isNotInstanceOf(OAuth2AuthenticationException.class);
}
@@ -113,13 +103,10 @@ public class JwtAuthenticationProviderTests {
BearerTokenAuthenticationToken token = this.authentication();
Object details = mock(Object.class);
token.setDetails(details);
Jwt jwt = TestJwts.jwt().build();
JwtAuthenticationToken authentication = new JwtAuthenticationToken(jwt);
given(this.jwtDecoder.decode(token.getToken())).willReturn(jwt);
given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(authentication);
assertThat(this.provider.authenticate(token)).isEqualTo(authentication).hasFieldOrPropertyWithValue("details",
details);
}

View File

@@ -42,7 +42,6 @@ public class JwtAuthenticationTokenTests {
public void getNameWhenJwtHasSubjectThenReturnsSubject() {
Jwt jwt = builder().subject("Carl").build();
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt);
assertThat(token.getName()).isEqualTo("Carl");
}
@@ -50,7 +49,6 @@ public class JwtAuthenticationTokenTests {
public void getNameWhenJwtHasNoSubjectThenReturnsNull() {
Jwt jwt = builder().claim("claim", "value").build();
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt);
assertThat(token.getName()).isNull();
}
@@ -65,7 +63,6 @@ public class JwtAuthenticationTokenTests {
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test");
Jwt jwt = builder().claim("claim", "value").build();
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities);
assertThat(token.getAuthorities()).isEqualTo(authorities);
assertThat(token.getPrincipal()).isEqualTo(jwt);
assertThat(token.getCredentials()).isEqualTo(jwt);
@@ -78,7 +75,6 @@ public class JwtAuthenticationTokenTests {
public void constructorWhenUsingOnlyJwtThenConstructedCorrectly() {
Jwt jwt = builder().claim("claim", "value").build();
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt);
assertThat(token.getAuthorities()).isEmpty();
assertThat(token.getPrincipal()).isEqualTo(jwt);
assertThat(token.getCredentials()).isEqualTo(jwt);
@@ -91,7 +87,6 @@ public class JwtAuthenticationTokenTests {
public void getNameWhenConstructedWithJwtThenReturnsSubject() {
Jwt jwt = builder().subject("Hayden").build();
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt);
assertThat(token.getName()).isEqualTo("Hayden");
}
@@ -100,7 +95,6 @@ public class JwtAuthenticationTokenTests {
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test");
Jwt jwt = builder().subject("Hayden").build();
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities);
assertThat(token.getName()).isEqualTo("Hayden");
}
@@ -109,7 +103,6 @@ public class JwtAuthenticationTokenTests {
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test");
Jwt jwt = builder().claim("claim", "value").build();
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities, "Hayden");
assertThat(token.getName()).isEqualTo("Hayden");
}
@@ -117,7 +110,6 @@ public class JwtAuthenticationTokenTests {
public void getNameWhenConstructedWithNoSubjectThenReturnsNull() {
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test");
Jwt jwt = builder().claim("claim", "value").build();
assertThat(new JwtAuthenticationToken(jwt, authorities, null).getName()).isNull();
assertThat(new JwtAuthenticationToken(jwt, authorities).getName()).isNull();
assertThat(new JwtAuthenticationToken(jwt).getName()).isNull();

View File

@@ -38,9 +38,7 @@ public class JwtBearerTokenAuthenticationConverterTests {
@Test
public void convertWhenJwtThenBearerTokenAuthentication() {
Jwt jwt = Jwt.withTokenValue("token-value").claim("claim", "value").header("header", "value").build();
AbstractAuthenticationToken token = this.converter.convert(jwt);
assertThat(token).isInstanceOf(BearerTokenAuthentication.class);
BearerTokenAuthentication bearerToken = (BearerTokenAuthentication) token;
assertThat(bearerToken.getToken().getTokenValue()).isEqualTo("token-value");
@@ -52,9 +50,7 @@ public class JwtBearerTokenAuthenticationConverterTests {
public void convertWhenJwtWithScopeAttributeThenBearerTokenAuthentication() {
Jwt jwt = Jwt.withTokenValue("token-value").claim("scope", "message:read message:write")
.header("header", "value").build();
AbstractAuthenticationToken token = this.converter.convert(jwt);
assertThat(token).isInstanceOf(BearerTokenAuthentication.class);
BearerTokenAuthentication bearerToken = (BearerTokenAuthentication) token;
assertThat(bearerToken.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"),
@@ -65,9 +61,7 @@ public class JwtBearerTokenAuthenticationConverterTests {
public void convertWhenJwtWithScpAttributeThenBearerTokenAuthentication() {
Jwt jwt = Jwt.withTokenValue("token-value").claim("scp", Arrays.asList("message:read", "message:write"))
.header("header", "value").build();
AbstractAuthenticationToken token = this.converter.convert(jwt);
assertThat(token).isInstanceOf(BearerTokenAuthentication.class);
BearerTokenAuthentication bearerToken = (BearerTokenAuthentication) token;
assertThat(bearerToken.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"),

View File

@@ -46,10 +46,8 @@ public class JwtGrantedAuthoritiesConverterTests {
@Test
public void convertWhenTokenHasScopeAttributeThenTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"),
new SimpleGrantedAuthority("SCOPE_message:write"));
}
@@ -57,11 +55,9 @@ public class JwtGrantedAuthoritiesConverterTests {
@Test
public void convertWithCustomAuthorityPrefixWhenTokenHasScopeAttributeThenTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("ROLE_message:read"),
new SimpleGrantedAuthority("ROLE_message:write"));
}
@@ -69,11 +65,9 @@ public class JwtGrantedAuthoritiesConverterTests {
@Test
public void convertWithBlankAsCustomAuthorityPrefixWhenTokenHasScopeAttributeThenTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("");
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("message:read"),
new SimpleGrantedAuthority("message:write"));
}
@@ -81,20 +75,16 @@ public class JwtGrantedAuthoritiesConverterTests {
@Test
public void convertWhenTokenHasEmptyScopeAttributeThenTranslatedToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scope", "").build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).isEmpty();
}
@Test
public void convertWhenTokenHasScpAttributeThenTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"),
new SimpleGrantedAuthority("SCOPE_message:write"));
}
@@ -102,11 +92,9 @@ public class JwtGrantedAuthoritiesConverterTests {
@Test
public void convertWithCustomAuthorityPrefixWhenTokenHasScpAttributeThenTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("ROLE_message:read"),
new SimpleGrantedAuthority("ROLE_message:write"));
}
@@ -114,11 +102,9 @@ public class JwtGrantedAuthoritiesConverterTests {
@Test
public void convertWithBlankAsCustomAuthorityPrefixWhenTokenHasScpAttributeThenTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", "message:read message:write").build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("");
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("message:read"),
new SimpleGrantedAuthority("message:write"));
}
@@ -126,10 +112,8 @@ public class JwtGrantedAuthoritiesConverterTests {
@Test
public void convertWhenTokenHasEmptyScpAttributeThenTranslatedToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Collections.emptyList()).build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).isEmpty();
}
@@ -137,10 +121,8 @@ public class JwtGrantedAuthoritiesConverterTests {
public void convertWhenTokenHasBothScopeAndScpThenScopeAttributeIsTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write"))
.claim("scope", "missive:read missive:write").build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_missive:read"),
new SimpleGrantedAuthority("SCOPE_missive:write"));
}
@@ -149,40 +131,32 @@ public class JwtGrantedAuthoritiesConverterTests {
public void convertWhenTokenHasEmptyScopeAndNonEmptyScpThenScopeAttributeIsTranslatedToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).claim("scope", "")
.build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).isEmpty();
}
@Test
public void convertWhenTokenHasEmptyScopeAndEmptyScpAttributeThenTranslatesToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Collections.emptyList()).claim("scope", Collections.emptyList()).build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).isEmpty();
}
@Test
public void convertWhenTokenHasNoScopeAndNoScpAttributeThenTranslatesToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("roles", Arrays.asList("message:read", "message:write")).build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).isEmpty();
}
@Test
public void convertWhenTokenHasUnsupportedTypeForScopeThenTranslatesToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scope", new String[] { "message:read", "message:write" }).build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).isEmpty();
}
@@ -190,11 +164,9 @@ public class JwtGrantedAuthoritiesConverterTests {
public void convertWhenTokenHasCustomClaimNameThenCustomClaimNameAttributeIsTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("roles", Arrays.asList("message:read", "message:write"))
.claim("scope", "missive:read missive:write").build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"),
new SimpleGrantedAuthority("SCOPE_message:write"));
}
@@ -203,22 +175,18 @@ public class JwtGrantedAuthoritiesConverterTests {
public void convertWhenTokenHasEmptyCustomClaimNameThenCustomClaimNameAttributeIsTranslatedToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("roles", Collections.emptyList()).claim("scope", "missive:read missive:write")
.build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).isEmpty();
}
@Test
public void convertWhenTokenHasNoCustomClaimNameThenCustomClaimNameAttributeIsTranslatedToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scope", "missive:read missive:write").build();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).isEmpty();
}

View File

@@ -68,15 +68,12 @@ public class JwtIssuerAuthenticationManagerResolverTests {
JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256),
new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer))));
jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY));
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver(
issuer);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + jws.serialize());
AuthenticationManager authenticationManager = authenticationManagerResolver.resolve(request);
assertThat(authenticationManager).isNotNull();
AuthenticationManager cachedAuthenticationManager = authenticationManagerResolver.resolve(request);
assertThat(authenticationManager).isSameAs(cachedAuthenticationManager);
}
@@ -88,7 +85,6 @@ public class JwtIssuerAuthenticationManagerResolverTests {
"other", "issuers");
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + this.jwt);
assertThatCode(() -> authenticationManagerResolver.resolve(request))
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer");
}
@@ -100,7 +96,6 @@ public class JwtIssuerAuthenticationManagerResolverTests {
(issuer) -> authenticationManager);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + this.jwt);
assertThat(authenticationManagerResolver.resolve(request)).isSameAs(authenticationManager);
}
@@ -108,17 +103,14 @@ public class JwtIssuerAuthenticationManagerResolverTests {
public void resolveWhenUsingExternalSourceThenRespondsToChanges() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + this.jwt);
Map<String, AuthenticationManager> authenticationManagers = new HashMap<>();
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver(
authenticationManagers::get);
assertThatCode(() -> authenticationManagerResolver.resolve(request))
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer");
AuthenticationManager authenticationManager = mock(AuthenticationManager.class);
authenticationManagers.put("trusted", authenticationManager);
assertThat(authenticationManagerResolver.resolve(request)).isSameAs(authenticationManager);
authenticationManagers.clear();
assertThatCode(() -> authenticationManagerResolver.resolve(request))
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer");

View File

@@ -69,15 +69,12 @@ public class JwtIssuerReactiveAuthenticationManagerResolverTests {
JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256),
new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer))));
jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY));
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver(
issuer);
MockServerWebExchange exchange = withBearerToken(jws.serialize());
ReactiveAuthenticationManager authenticationManager = authenticationManagerResolver.resolve(exchange)
.block();
assertThat(authenticationManager).isNotNull();
ReactiveAuthenticationManager cachedAuthenticationManager = authenticationManagerResolver.resolve(exchange)
.block();
assertThat(authenticationManager).isSameAs(cachedAuthenticationManager);
@@ -89,7 +86,6 @@ public class JwtIssuerReactiveAuthenticationManagerResolverTests {
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver(
"other", "issuers");
MockServerWebExchange exchange = withBearerToken(this.jwt);
assertThatCode(() -> authenticationManagerResolver.resolve(exchange).block())
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer");
}
@@ -100,24 +96,20 @@ public class JwtIssuerReactiveAuthenticationManagerResolverTests {
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver(
(issuer) -> Mono.just(authenticationManager));
MockServerWebExchange exchange = withBearerToken(this.jwt);
assertThat(authenticationManagerResolver.resolve(exchange).block()).isSameAs(authenticationManager);
}
@Test
public void resolveWhenUsingExternalSourceThenRespondsToChanges() {
MockServerWebExchange exchange = withBearerToken(this.jwt);
Map<String, ReactiveAuthenticationManager> authenticationManagers = new HashMap<>();
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver(
(issuer) -> Mono.justOrEmpty(authenticationManagers.get(issuer)));
assertThatCode(() -> authenticationManagerResolver.resolve(exchange).block())
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer");
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
authenticationManagers.put("trusted", authenticationManager);
assertThat(authenticationManagerResolver.resolve(exchange).block()).isSameAs(authenticationManager);
authenticationManagers.clear();
assertThatCode(() -> authenticationManagerResolver.resolve(exchange).block())
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer");

View File

@@ -70,7 +70,6 @@ public class JwtReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenWrongTypeThenEmpty() {
TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar");
assertThat(this.manager.authenticate(token).block()).isNull();
}
@@ -78,7 +77,6 @@ public class JwtReactiveAuthenticationManagerTests {
public void authenticateWhenEmptyJwtThenEmpty() {
BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1");
given(this.jwtDecoder.decode(token.getToken())).willReturn(Mono.empty());
assertThat(this.manager.authenticate(token).block()).isNull();
}
@@ -86,7 +84,6 @@ public class JwtReactiveAuthenticationManagerTests {
public void authenticateWhenJwtExceptionThenOAuth2AuthenticationException() {
BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1");
given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new BadJwtException("Oops")));
assertThatCode(() -> this.manager.authenticate(token).block())
.isInstanceOf(OAuth2AuthenticationException.class);
}
@@ -96,7 +93,6 @@ public class JwtReactiveAuthenticationManagerTests {
public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGenericOne() {
BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1");
given(this.jwtDecoder.decode(token.getToken())).willThrow(new BadJwtException("with \"invalid\" chars"));
assertThatCode(() -> this.manager.authenticate(token).block()).isInstanceOf(OAuth2AuthenticationException.class)
.hasFieldOrPropertyWithValue("error.description", "Invalid token");
}
@@ -106,7 +102,6 @@ public class JwtReactiveAuthenticationManagerTests {
public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() {
BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1");
given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set"));
assertThatCode(() -> this.manager.authenticate(token).block()).isInstanceOf(AuthenticationException.class)
.isNotInstanceOf(OAuth2AuthenticationException.class);
}
@@ -115,7 +110,6 @@ public class JwtReactiveAuthenticationManagerTests {
public void authenticateWhenNotJwtExceptionThenPropagates() {
BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1");
given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new RuntimeException("Oops")));
assertThatCode(() -> this.manager.authenticate(token).block()).isInstanceOf(RuntimeException.class);
}
@@ -123,9 +117,7 @@ public class JwtReactiveAuthenticationManagerTests {
public void authenticateWhenJwtThenSuccess() {
BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1");
given(this.jwtDecoder.decode(token.getToken())).willReturn(Mono.just(this.jwt));
Authentication authentication = this.manager.authenticate(token).block();
assertThat(authentication).isNotNull();
assertThat(authentication.isAuthenticated()).isTrue();
assertThat(authentication.getAuthorities()).extracting(GrantedAuthority::getAuthority)

View File

@@ -54,11 +54,8 @@ public class OpaqueTokenAuthenticationProviderTests {
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(principal);
OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token"));
assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
assertThat(attributes).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE,
@@ -71,7 +68,6 @@ public class OpaqueTokenAuthenticationProviderTests {
.containsEntry(OAuth2IntrospectionClaimNames.SUBJECT, "Z5O3upPC88QrAjx00dis")
.containsEntry(OAuth2IntrospectionClaimNames.USERNAME, "jdoe")
.containsEntry("extension_field", "twenty-seven");
assertThat(result.getAuthorities()).extracting("authority").containsExactly("SCOPE_read", "SCOPE_write",
"SCOPE_dolphin");
}
@@ -83,13 +79,10 @@ public class OpaqueTokenAuthenticationProviderTests {
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(principal);
OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token"));
assertThat(result.getPrincipal()).isInstanceOf(OAuth2AuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
assertThat(attributes).isNotNull().doesNotContainKey(OAuth2IntrospectionClaimNames.SCOPE);
assertThat(result.getAuthorities()).isEmpty();
}
@@ -98,7 +91,6 @@ public class OpaqueTokenAuthenticationProviderTests {
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willThrow(new OAuth2IntrospectionException("with \"invalid\" chars"));
OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector);
assertThatCode(() -> provider.authenticate(new BearerTokenAuthenticationToken("token")))
.isInstanceOf(AuthenticationServiceException.class);
}

View File

@@ -55,11 +55,8 @@ public class OpaqueTokenReactiveAuthenticationManagerTests {
ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(Mono.just(authority));
OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block();
assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
assertThat(attributes).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE,
@@ -72,7 +69,6 @@ public class OpaqueTokenReactiveAuthenticationManagerTests {
.containsEntry(OAuth2IntrospectionClaimNames.SUBJECT, "Z5O3upPC88QrAjx00dis")
.containsEntry(OAuth2IntrospectionClaimNames.USERNAME, "jdoe")
.containsEntry("extension_field", "twenty-seven");
assertThat(result.getAuthorities()).extracting("authority").containsExactly("SCOPE_read", "SCOPE_write",
"SCOPE_dolphin");
}
@@ -84,13 +80,10 @@ public class OpaqueTokenReactiveAuthenticationManagerTests {
ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(Mono.just(authority));
OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block();
assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
assertThat(attributes).isNotNull().doesNotContainKey(OAuth2IntrospectionClaimNames.SCOPE);
assertThat(result.getAuthorities()).isEmpty();
}
@@ -100,7 +93,6 @@ public class OpaqueTokenReactiveAuthenticationManagerTests {
given(introspector.introspect(any()))
.willReturn(Mono.error(new OAuth2IntrospectionException("with \"invalid\" chars")));
OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector);
assertThatCode(() -> provider.authenticate(new BearerTokenAuthenticationToken("token")).block())
.isInstanceOf(AuthenticationServiceException.class);
}

View File

@@ -45,10 +45,8 @@ public class ReactiveJwtAuthenticationConverterAdapterTests {
@Test
public void convertWhenTokenHasScopeAttributeThenTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block();
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"),
new SimpleGrantedAuthority("SCOPE_message:write"));
}
@@ -56,22 +54,16 @@ public class ReactiveJwtAuthenticationConverterAdapterTests {
@Test
public void convertWhenTokenHasEmptyScopeAttributeThenTranslatedToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scope", "").build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block();
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly();
}
@Test
public void convertWhenTokenHasScpAttributeThenTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block();
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"),
new SimpleGrantedAuthority("SCOPE_message:write"));
}
@@ -79,11 +71,8 @@ public class ReactiveJwtAuthenticationConverterAdapterTests {
@Test
public void convertWhenTokenHasEmptyScpAttributeThenTranslatedToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList()).build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block();
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly();
}
@@ -91,11 +80,8 @@ public class ReactiveJwtAuthenticationConverterAdapterTests {
public void convertWhenTokenHasBothScopeAndScpThenScopeAttributeIsTranslatedToAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write"))
.claim("scope", "missive:read missive:write").build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block();
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_missive:read"),
new SimpleGrantedAuthority("SCOPE_missive:write"));
}
@@ -104,11 +90,8 @@ public class ReactiveJwtAuthenticationConverterAdapterTests {
public void convertWhenTokenHasEmptyScopeAndNonEmptyScpThenScopeAttributeIsTranslatedToNoAuthorities() {
Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).claim("scope", "")
.build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block();
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly();
}

View File

@@ -44,10 +44,8 @@ public class ReactiveJwtAuthenticationConverterTests {
@Test
public void convertWhenDefaultGrantedAuthoritiesConverterSet() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block();
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"),
new SimpleGrantedAuthority("SCOPE_message:write"));
}
@@ -62,15 +60,11 @@ public class ReactiveJwtAuthenticationConverterTests {
@Test
public void convertWithOverriddenGrantedAuthoritiesConverter() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
Converter<Jwt, Flux<GrantedAuthority>> grantedAuthoritiesConverter = (token) -> Flux
.just(new SimpleGrantedAuthority("blah"));
this.jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block();
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("blah"));
}

View File

@@ -42,13 +42,10 @@ public class ReactiveJwtGrantedAuthoritiesConverterAdapterTests {
@Test
public void convertWithGrantedAuthoritiesConverter() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
Converter<Jwt, Collection<GrantedAuthority>> grantedAuthoritiesConverter = (token) -> Arrays
.asList(new SimpleGrantedAuthority("blah"));
Collection<GrantedAuthority> authorities = new ReactiveJwtGrantedAuthoritiesConverterAdapter(
grantedAuthoritiesConverter).convert(jwt).toStream().collect(Collectors.toList());
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("blah"));
}

View File

@@ -44,7 +44,6 @@ public final class TestBearerTokenAuthentications {
Collections.singletonMap("sub", "user"), authorities);
OAuth2AccessToken token = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(),
Instant.now().plusSeconds(86400), new HashSet<>(Arrays.asList("USER")));
return new BearerTokenAuthentication(principal, token, authorities);
}

View File

@@ -102,11 +102,9 @@ public class NimbusOpaqueTokenIntrospectorTests {
public void introspectWhenActiveTokenThenOk() throws Exception {
try (MockWebServer server = new MockWebServer()) {
server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE));
String introspectUri = server.url("/introspect").toString();
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(introspectUri, CLIENT_ID,
CLIENT_SECRET);
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token");
assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE,
@@ -125,11 +123,9 @@ public class NimbusOpaqueTokenIntrospectorTests {
public void introspectWhenBadClientCredentialsThenError() throws IOException {
try (MockWebServer server = new MockWebServer()) {
server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE));
String introspectUri = server.url("/introspect").toString();
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(introspectUri, CLIENT_ID,
"wrong");
assertThatCode(() -> introspectionClient.introspect("token"))
.isInstanceOf(OAuth2IntrospectionException.class);
}
@@ -141,7 +137,6 @@ public class NimbusOpaqueTokenIntrospectorTests {
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL,
restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INACTIVE);
assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class)
.extracting("message").isEqualTo("Provided token isn't active");
}
@@ -152,13 +147,11 @@ public class NimbusOpaqueTokenIntrospectorTests {
introspectedValues.put(OAuth2IntrospectionClaimNames.ACTIVE, true);
introspectedValues.put(OAuth2IntrospectionClaimNames.AUDIENCE, Arrays.asList("aud"));
introspectedValues.put(OAuth2IntrospectionClaimNames.NOT_BEFORE, 29348723984L);
RestOperations restOperations = mock(RestOperations.class);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL,
restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willReturn(response(new JSONObject(introspectedValues).toJSONString()));
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token");
assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE, Arrays.asList("aud"))
@@ -174,7 +167,6 @@ public class NimbusOpaqueTokenIntrospectorTests {
restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willThrow(new IllegalStateException("server was unresponsive"));
assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class)
.extracting("message").isEqualTo("server was unresponsive");
}
@@ -185,7 +177,6 @@ public class NimbusOpaqueTokenIntrospectorTests {
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL,
restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(response("malformed"));
assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class);
}
@@ -195,7 +186,6 @@ public class NimbusOpaqueTokenIntrospectorTests {
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL,
restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INVALID);
assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class);
}
@@ -205,7 +195,6 @@ public class NimbusOpaqueTokenIntrospectorTests {
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL,
restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_ISSUER);
assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class);
}
@@ -216,7 +205,6 @@ public class NimbusOpaqueTokenIntrospectorTests {
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL,
restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_SCOPE);
OAuth2AuthenticatedPrincipal principal = introspectionClient.introspect("token");
assertThat(principal.getAuthorities()).isEmpty();
JSONArray scope = principal.getAttribute("scope");
@@ -250,10 +238,8 @@ public class NimbusOpaqueTokenIntrospectorTests {
@Test
public void setRequestEntityConverterWhenConverterIsNullThenExceptionIsThrown() {
RestOperations restOperations = mock(RestOperations.class);
NimbusOpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL,
restOperations);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> introspectionClient.setRequestEntityConverter(null));
}
@@ -270,9 +256,7 @@ public class NimbusOpaqueTokenIntrospectorTests {
NimbusOpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL,
restOperations);
introspectionClient.setRequestEntityConverter(requestEntityConverter);
introspectionClient.introspect(tokenToIntrospect);
verify(requestEntityConverter).convert(tokenToIntrospect);
}

View File

@@ -80,11 +80,9 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests {
public void authenticateWhenActiveTokenThenOk() throws Exception {
try (MockWebServer server = new MockWebServer()) {
server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE));
String introspectUri = server.url("/introspect").toString();
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
introspectUri, CLIENT_ID, CLIENT_SECRET);
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token").block();
assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE,
@@ -103,11 +101,9 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests {
public void authenticateWhenBadClientCredentialsThenAuthenticationException() throws IOException {
try (MockWebServer server = new MockWebServer()) {
server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE));
String introspectUri = server.url("/introspect").toString();
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
introspectUri, CLIENT_ID, "wrong");
assertThatCode(() -> introspectionClient.introspect("token").block())
.isInstanceOf(OAuth2IntrospectionException.class);
}
@@ -118,7 +114,6 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests {
WebClient webClient = mockResponse(INACTIVE_RESPONSE);
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
assertThatCode(() -> introspectionClient.introspect("token").block())
.isInstanceOf(BadOpaqueTokenException.class).extracting("message")
.isEqualTo("Provided token isn't active");
@@ -130,11 +125,9 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests {
introspectedValues.put(OAuth2IntrospectionClaimNames.ACTIVE, true);
introspectedValues.put(OAuth2IntrospectionClaimNames.AUDIENCE, Arrays.asList("aud"));
introspectedValues.put(OAuth2IntrospectionClaimNames.NOT_BEFORE, 29348723984L);
WebClient webClient = mockResponse(new JSONObject(introspectedValues).toJSONString());
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token").block();
assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE, Arrays.asList("aud"))
@@ -148,7 +141,6 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests {
WebClient webClient = mockResponse(new IllegalStateException("server was unresponsive"));
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
assertThatCode(() -> introspectionClient.introspect("token").block())
.isInstanceOf(OAuth2IntrospectionException.class).extracting("message")
.isEqualTo("server was unresponsive");
@@ -159,7 +151,6 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests {
WebClient webClient = mockResponse("malformed");
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
assertThatCode(() -> introspectionClient.introspect("token").block())
.isInstanceOf(OAuth2IntrospectionException.class);
}
@@ -169,7 +160,6 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests {
WebClient webClient = mockResponse(INVALID_RESPONSE);
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
assertThatCode(() -> introspectionClient.introspect("token").block())
.isInstanceOf(OAuth2IntrospectionException.class);
}
@@ -179,7 +169,6 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests {
WebClient webClient = mockResponse(MALFORMED_ISSUER_RESPONSE);
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
assertThatCode(() -> introspectionClient.introspect("token").block())
.isInstanceOf(OAuth2IntrospectionException.class);
}

View File

@@ -91,7 +91,6 @@ public class OAuth2IntrospectionAuthenticatedPrincipalTests {
private static final String JTI_VALUE = "jwt-id-1";
private static final Map<String, Object> CLAIMS;
static {
CLAIMS = new HashMap<>();
CLAIMS.put(ACTIVE_CLAIM, ACTIVE_VALUE);
@@ -111,7 +110,6 @@ public class OAuth2IntrospectionAuthenticatedPrincipalTests {
public void constructorWhenAttributesIsNullOrEmptyThenIllegalArgumentException() {
assertThatCode(() -> new OAuth2IntrospectionAuthenticatedPrincipal(null, AUTHORITIES))
.isInstanceOf(IllegalArgumentException.class);
assertThatCode(() -> new OAuth2IntrospectionAuthenticatedPrincipal(Collections.emptyMap(), AUTHORITIES))
.isInstanceOf(IllegalArgumentException.class);
}
@@ -121,7 +119,6 @@ public class OAuth2IntrospectionAuthenticatedPrincipalTests {
Collection<? extends GrantedAuthority> authorities = new OAuth2IntrospectionAuthenticatedPrincipal(CLAIMS, null)
.getAuthorities();
assertThat(authorities).isEmpty();
authorities = new OAuth2IntrospectionAuthenticatedPrincipal(CLAIMS, Collections.emptyList()).getAuthorities();
assertThat(authorities).isEmpty();
}
@@ -137,7 +134,6 @@ public class OAuth2IntrospectionAuthenticatedPrincipalTests {
public void constructorWhenAttributesAuthoritiesProvidedThenCreated() {
OAuth2IntrospectionAuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal(CLAIMS,
AUTHORITIES);
assertThat(principal.getName()).isEqualTo(CLAIMS.get(SUB_CLAIM));
assertThat(principal.getAttributes()).isEqualTo(CLAIMS);
assertThat(principal.getClaims()).isEqualTo(CLAIMS);
@@ -160,7 +156,6 @@ public class OAuth2IntrospectionAuthenticatedPrincipalTests {
public void constructorWhenAllParametersProvidedAndValidThenCreated() {
OAuth2IntrospectionAuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal(SUBJECT,
CLAIMS, AUTHORITIES);
assertThat(principal.getName()).isEqualTo(SUBJECT);
assertThat(principal.getAttributes()).isEqualTo(CLAIMS);
assertThat(principal.getClaims()).isEqualTo(CLAIMS);

View File

@@ -47,53 +47,41 @@ public class BearerTokenAuthenticationEntryPointTests {
@Test
public void commenceWhenNoBearerTokenErrorThenStatus401AndAuthHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
this.authenticationEntryPoint.commence(request, response, new BadCredentialsException("test"));
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer");
}
@Test
public void commenceWhenNoBearerTokenErrorAndRealmSetThenStatus401AndAuthHeaderWithRealm() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
this.authenticationEntryPoint.setRealmName("test");
this.authenticationEntryPoint.commence(request, response, new BadCredentialsException("test"));
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer realm=\"test\"");
}
@Test
public void commenceWhenInvalidRequestErrorThenStatus400AndHeaderWithError() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST,
null, null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer error=\"invalid_request\"");
}
@Test
public void commenceWhenInvalidRequestErrorThenStatus400AndHeaderWithErrorDetails() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST,
"The access token expired", null, null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.getHeader("WWW-Authenticate"))
.isEqualTo("Bearer error=\"invalid_request\", error_description=\"The access token expired\"");
@@ -101,14 +89,11 @@ public class BearerTokenAuthenticationEntryPointTests {
@Test
public void commenceWhenInvalidRequestErrorThenStatus400AndHeaderWithErrorUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST,
null, "https://example.com", null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.getHeader("WWW-Authenticate"))
.isEqualTo("Bearer error=\"invalid_request\", error_uri=\"https://example.com\"");
@@ -116,42 +101,33 @@ public class BearerTokenAuthenticationEntryPointTests {
@Test
public void commenceWhenInvalidTokenErrorThenStatus401AndHeaderWithError() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED,
null, null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer error=\"invalid_token\"");
}
@Test
public void commenceWhenInsufficientScopeErrorThenStatus403AndHeaderWithError() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN,
null, null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer error=\"insufficient_scope\"");
}
@Test
public void commenceWhenInsufficientScopeErrorThenStatus403AndHeaderWithErrorAndScope() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN,
null, null, "test.read test.write");
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate"))
.isEqualTo("Bearer error=\"insufficient_scope\", scope=\"test.read test.write\"");
@@ -160,15 +136,12 @@ public class BearerTokenAuthenticationEntryPointTests {
@Test
public void commenceWhenInsufficientScopeAndRealmSetThenStatus403AndHeaderWithErrorAndAllDetails()
throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN,
"Insufficient scope", "https://example.com", "test.read test.write");
this.authenticationEntryPoint.setRealmName("test");
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo(
"Bearer realm=\"test\", error=\"insufficient_scope\", error_description=\"Insufficient scope\", "

View File

@@ -87,16 +87,12 @@ public class BearerTokenAuthenticationFilterTests {
@Test
public void doFilterWhenBearerTokenPresentThenAuthenticates() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
ArgumentCaptor<BearerTokenAuthenticationToken> captor = ArgumentCaptor
.forClass(BearerTokenAuthenticationToken.class);
verify(this.authenticationManager).authenticate(captor.capture());
assertThat(captor.getValue().getPrincipal()).isEqualTo("token");
}
@@ -104,25 +100,18 @@ public class BearerTokenAuthenticationFilterTests {
public void doFilterWhenUsingAuthenticationManagerResolverThenAuthenticates() throws Exception {
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManagerResolver));
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManagerResolver.resolve(any())).willReturn(this.authenticationManager);
filter.doFilter(this.request, this.response, this.filterChain);
ArgumentCaptor<BearerTokenAuthenticationToken> captor = ArgumentCaptor
.forClass(BearerTokenAuthenticationToken.class);
verify(this.authenticationManager).authenticate(captor.capture());
assertThat(captor.getValue().getPrincipal()).isEqualTo("token");
}
@Test
public void doFilterWhenNoBearerTokenPresentThenDoesNotAuthenticate() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn(null);
dontAuthenticate();
}
@@ -130,13 +119,9 @@ public class BearerTokenAuthenticationFilterTests {
public void doFilterWhenMalformedBearerTokenThenPropagatesError() throws ServletException, IOException {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST,
"description", "uri");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
given(this.bearerTokenResolver.resolve(this.request)).willThrow(exception);
dontAuthenticate();
verify(this.authenticationEntryPoint).commence(this.request, this.response, exception);
}
@@ -145,16 +130,12 @@ public class BearerTokenAuthenticationFilterTests {
throws ServletException, IOException {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED,
"description", "uri");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
verify(this.authenticationEntryPoint).commence(this.request, this.response, exception);
}
@@ -163,17 +144,13 @@ public class BearerTokenAuthenticationFilterTests {
throws ServletException, IOException {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED,
"description", "uri");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.setAuthenticationFailureHandler(this.authenticationFailureHandler);
filter.doFilter(this.request, this.response, this.filterChain);
verify(this.authenticationFailureHandler).onAuthenticationFailure(this.request, this.response, exception);
}
@@ -213,11 +190,9 @@ public class BearerTokenAuthenticationFilterTests {
}
private void dontAuthenticate() throws ServletException, IOException {
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
verifyNoMoreInteractions(this.authenticationManager);
}

View File

@@ -49,7 +49,6 @@ public class DefaultBearerTokenResolverTests {
public void resolveWhenValidHeaderIsPresentThenTokenIsResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@@ -59,7 +58,6 @@ public class DefaultBearerTokenResolverTests {
String token = TEST_TOKEN + "==";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + token);
assertThat(this.resolver.resolve(request)).isEqualTo(token);
}
@@ -68,7 +66,6 @@ public class DefaultBearerTokenResolverTests {
this.resolver.setBearerTokenHeaderName(CUSTOM_HEADER);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(CUSTOM_HEADER, "Bearer " + TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@@ -76,14 +73,12 @@ public class DefaultBearerTokenResolverTests {
public void resolveWhenLowercaseHeaderIsPresentThenTokenIsResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("authorization", "bearer " + TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenNoHeaderIsPresentThenTokenIsNotResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
assertThat(this.resolver.resolve(request)).isNull();
}
@@ -91,7 +86,6 @@ public class DefaultBearerTokenResolverTests {
public void resolveWhenHeaderWithWrongSchemeIsPresentThenTokenIsNotResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("test:test".getBytes()));
assertThat(this.resolver.resolve(request)).isNull();
}
@@ -99,7 +93,6 @@ public class DefaultBearerTokenResolverTests {
public void resolveWhenHeaderWithMissingTokenIsPresentThenAuthenticationExceptionIsThrown() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer ");
assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining(("Bearer token is malformed"));
}
@@ -108,7 +101,6 @@ public class DefaultBearerTokenResolverTests {
public void resolveWhenHeaderWithInvalidCharactersIsPresentThenAuthenticationExceptionIsThrown() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer an\"invalid\"token");
assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining(("Bearer token is malformed"));
}
@@ -120,7 +112,6 @@ public class DefaultBearerTokenResolverTests {
request.setMethod("POST");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining("Found multiple bearer tokens in the request");
}
@@ -131,7 +122,6 @@ public class DefaultBearerTokenResolverTests {
request.addHeader("Authorization", "Bearer " + TEST_TOKEN);
request.setMethod("GET");
request.addParameter("access_token", TEST_TOKEN);
assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining("Found multiple bearer tokens in the request");
}
@@ -140,7 +130,6 @@ public class DefaultBearerTokenResolverTests {
public void resolveWhenRequestContainsTwoAccessTokenParametersThenAuthenticationExceptionIsThrown() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("access_token", "token1", "token2");
assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining("Found multiple bearer tokens in the request");
}
@@ -148,12 +137,10 @@ public class DefaultBearerTokenResolverTests {
@Test
public void resolveWhenFormParameterIsPresentAndSupportedThenTokenIsResolved() {
this.resolver.setAllowFormEncodedBodyParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@@ -163,18 +150,15 @@ public class DefaultBearerTokenResolverTests {
request.setMethod("POST");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isNull();
}
@Test
public void resolveWhenQueryParameterIsPresentAndSupportedThenTokenIsResolved() {
this.resolver.setAllowUriQueryParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@@ -183,7 +167,6 @@ public class DefaultBearerTokenResolverTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isNull();
}

View File

@@ -52,14 +52,12 @@ public class HeaderBearerTokenResolverTests {
public void resolveWhenTokenPresentThenTokenIsResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(CORRECT_HEADER, TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenTokenNotPresentThenTokenIsNotResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
assertThat(this.resolver.resolve(request)).isNull();
}

View File

@@ -48,31 +48,23 @@ public class BearerTokenAccessDeniedHandlerTests {
@Test
public void handleWhenNotOAuth2AuthenticatedThenStatus403() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication authentication = new TestingAuthenticationToken("user", "pass");
request.setUserPrincipal(authentication);
this.accessDeniedHandler.handle(request, response, null);
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer");
}
@Test
public void handleWhenNotOAuth2AuthenticatedAndRealmSetThenStatus403AndAuthHeaderWithRealm() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication authentication = new TestingAuthenticationToken("user", "pass");
request.setUserPrincipal(authentication);
this.accessDeniedHandler.setRealmName("test");
this.accessDeniedHandler.handle(request, response, null);
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer realm=\"test\"");
}
@@ -80,15 +72,11 @@ public class BearerTokenAccessDeniedHandlerTests {
@Test
public void handleWhenOAuth2AuthenticatedThenStatus403AndAuthHeaderWithInsufficientScopeErrorAttribute()
throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication token = new TestingOAuth2TokenAuthenticationToken(Collections.emptyMap());
request.setUserPrincipal(token);
this.accessDeniedHandler.handle(request, response, null);
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer error=\"insufficient_scope\", "
+ "error_description=\"The request requires higher privileges than provided by the access token.\", "

View File

@@ -48,29 +48,23 @@ public class BearerTokenServerAccessDeniedHandlerTests {
@Test
public void handleWhenNotOAuth2AuthenticatedThenStatus403() {
Authentication token = new TestingAuthenticationToken("user", "pass");
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(token));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate")).isEqualTo(Arrays.asList("Bearer"));
}
@Test
public void handleWhenNotOAuth2AuthenticatedAndRealmSetThenStatus403AndAuthHeaderWithRealm() {
Authentication token = new TestingAuthenticationToken("user", "pass");
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(token));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
this.accessDeniedHandler.setRealmName("test");
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate"))
.isEqualTo(Arrays.asList("Bearer realm=\"test\""));
@@ -78,14 +72,11 @@ public class BearerTokenServerAccessDeniedHandlerTests {
@Test
public void handleWhenOAuth2AuthenticatedThenStatus403AndAuthHeaderWithInsufficientScopeErrorAttribute() {
Authentication token = new TestingOAuth2TokenAuthenticationToken(Collections.emptyMap());
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(token));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate"))
.isEqualTo(Arrays.asList("Bearer error=\"insufficient_scope\", "

View File

@@ -61,19 +61,15 @@ public class ServerBearerExchangeFilterFunctionTests {
@Test
public void filterWhenUnauthenticatedThenAuthorizationHeaderNull() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@Test
public void filterWhenAuthenticatedThenAuthorizationHeaderNull() throws Exception {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
@@ -82,11 +78,9 @@ public class ServerBearerExchangeFilterFunctionTests {
@Test
public void filterWhenAuthenticatedWithOtherTokenThenAuthorizationHeaderNull() throws Exception {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "pass");
this.function.filter(request, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(token)).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@@ -94,10 +88,8 @@ public class ServerBearerExchangeFilterFunctionTests {
public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.header(HttpHeaders.AUTHORIZATION, "Existing").build();
this.function.filter(request, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block();
HttpHeaders headers = this.exchange.getRequest().headers();
assertThat(headers.get(HttpHeaders.AUTHORIZATION)).containsOnly("Bearer " + this.accessToken.getTokenValue());
}

View File

@@ -65,9 +65,7 @@ public class ServletBearerExchangeFilterFunctionTests {
@Test
public void filterWhenUnauthenticatedThenAuthorizationHeaderNull() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@@ -76,18 +74,14 @@ public class ServletBearerExchangeFilterFunctionTests {
public void filterWhenAuthenticatedWithOtherTokenThenAuthorizationHeaderNull() {
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "pass");
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).subscriberContext(context(token)).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@Test
public void filterWhenAuthenticatedThenAuthorizationHeader() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).subscriberContext(context(this.authentication)).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
@@ -96,9 +90,7 @@ public class ServletBearerExchangeFilterFunctionTests {
public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.header(HttpHeaders.AUTHORIZATION, "Existing").build();
this.function.filter(request, this.exchange).subscriberContext(context(this.authentication)).block();
HttpHeaders headers = this.exchange.getRequest().headers();
assertThat(headers.get(HttpHeaders.AUTHORIZATION)).containsOnly("Bearer " + this.accessToken.getTokenValue());
}

View File

@@ -44,7 +44,6 @@ public class BearerTokenServerAuthenticationEntryPointTests {
@Test
public void commenceWhenNotOAuth2AuthenticationExceptionThenBearer() {
this.entryPoint.commence(this.exchange, new BadCredentialsException("")).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE)).isEqualTo("Bearer");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@@ -52,9 +51,7 @@ public class BearerTokenServerAuthenticationEntryPointTests {
@Test
public void commenceWhenRealmNameThenHasRealmName() {
this.entryPoint.setRealmName("Realm");
this.entryPoint.commence(this.exchange, new BadCredentialsException("")).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE))
.isEqualTo("Bearer realm=\"Realm\"");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
@@ -64,9 +61,7 @@ public class BearerTokenServerAuthenticationEntryPointTests {
public void commenceWhenOAuth2AuthenticationExceptionThenContainsErrorInformation() {
OAuth2Error oauthError = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST);
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(oauthError);
this.entryPoint.commence(this.exchange, exception).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE))
.isEqualTo("Bearer error=\"invalid_request\"");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
@@ -76,9 +71,7 @@ public class BearerTokenServerAuthenticationEntryPointTests {
public void commenceWhenOAuth2ErrorCompleteThenContainsErrorInformation() {
OAuth2Error oauthError = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, "Oops", "https://example.com");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(oauthError);
this.entryPoint.commence(this.exchange, exception).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE)).isEqualTo(
"Bearer error=\"invalid_request\", error_description=\"Oops\", error_uri=\"https://example.com\"");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
@@ -89,9 +82,7 @@ public class BearerTokenServerAuthenticationEntryPointTests {
OAuth2Error oauthError = new BearerTokenError(OAuth2ErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, "Oops",
"https://example.com");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(oauthError);
this.entryPoint.commence(this.exchange, exception).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE)).isEqualTo(
"Bearer error=\"invalid_request\", error_description=\"Oops\", error_uri=\"https://example.com\"");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
@@ -100,7 +91,6 @@ public class BearerTokenServerAuthenticationEntryPointTests {
@Test
public void commenceWhenNoSubscriberThenNothingHappens() {
this.entryPoint.commence(this.exchange, new BadCredentialsException(""));
assertThat(getResponse().getHeaders()).isEmpty();
assertThat(getResponse().getStatusCode()).isNull();
}

View File

@@ -55,7 +55,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
public void resolveWhenValidHeaderIsPresentThenTokenIsResolved() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION,
"Bearer " + TEST_TOKEN);
assertThat(convertToToken(request).getToken()).isEqualTo(TEST_TOKEN);
}
@@ -65,7 +64,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
String token = TEST_TOKEN + "==";
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION,
"Bearer " + token);
assertThat(convertToToken(request).getToken()).isEqualTo(token);
}
@@ -74,7 +72,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
this.converter.setBearerTokenHeaderName(CUSTOM_HEADER);
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(CUSTOM_HEADER,
"Bearer " + TEST_TOKEN);
assertThat(convertToToken(request).getToken()).isEqualTo(TEST_TOKEN);
}
@@ -83,7 +80,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
public void resolveWhenValidHeaderIsEmptyStringThenTokenIsResolved() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION,
"Bearer ");
OAuth2AuthenticationException expected = catchThrowableOfType(() -> convertToToken(request),
OAuth2AuthenticationException.class);
BearerTokenError error = (BearerTokenError) expected.getError();
@@ -96,14 +92,12 @@ public class ServerBearerTokenAuthenticationConverterTests {
public void resolveWhenLowercaseHeaderIsPresentThenTokenIsResolved() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION,
"bearer " + TEST_TOKEN);
assertThat(convertToToken(request).getToken()).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenNoHeaderIsPresentThenTokenIsNotResolved() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/");
assertThat(convertToToken(request)).isNull();
}
@@ -111,7 +105,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
public void resolveWhenHeaderWithWrongSchemeIsPresentThenTokenIsNotResolved() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION,
"Basic " + Base64.getEncoder().encodeToString("test:test".getBytes()));
assertThat(convertToToken(request)).isNull();
}
@@ -119,7 +112,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
public void resolveWhenHeaderWithMissingTokenIsPresentThenAuthenticationExceptionIsThrown() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION,
"Bearer ");
assertThatCode(() -> convertToToken(request)).isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining(("Bearer token is malformed"));
}
@@ -128,7 +120,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
public void resolveWhenHeaderWithInvalidCharactersIsPresentThenAuthenticationExceptionIsThrown() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION,
"Bearer an\"invalid\"token");
assertThatCode(() -> convertToToken(request)).isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining(("Bearer token is malformed"));
}
@@ -138,7 +129,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
public void resolveWhenHeaderWithInvalidCharactersIsPresentAndNotSubscribedThenNoneExceptionIsThrown() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION,
"Bearer an\"invalid\"token");
assertThatCode(() -> this.converter.convert(MockServerWebExchange.from(request))).doesNotThrowAnyException();
}
@@ -146,7 +136,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
public void resolveWhenValidHeaderIsPresentTogetherWithQueryParameterThenAuthenticationExceptionIsThrown() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.queryParam("access_token", TEST_TOKEN).header(HttpHeaders.AUTHORIZATION, "Bearer " + TEST_TOKEN);
assertThatCode(() -> convertToToken(request)).isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining("Found multiple bearer tokens in the request");
}
@@ -154,10 +143,8 @@ public class ServerBearerTokenAuthenticationConverterTests {
@Test
public void resolveWhenQueryParameterIsPresentAndSupportedThenTokenIsResolved() {
this.converter.setAllowUriQueryParameter(true);
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").queryParam("access_token",
TEST_TOKEN);
assertThat(convertToToken(request).getToken()).isEqualTo(TEST_TOKEN);
}
@@ -165,9 +152,7 @@ public class ServerBearerTokenAuthenticationConverterTests {
@Test
public void resolveWhenQueryParameterIsEmptyAndSupportedThenOAuth2AuthenticationException() {
this.converter.setAllowUriQueryParameter(true);
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").queryParam("access_token", "");
OAuth2AuthenticationException expected = catchThrowableOfType(() -> convertToToken(request),
OAuth2AuthenticationException.class);
BearerTokenError error = (BearerTokenError) expected.getError();
@@ -180,7 +165,6 @@ public class ServerBearerTokenAuthenticationConverterTests {
public void resolveWhenQueryParameterIsPresentAndNotSupportedThenTokenIsNotResolved() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").queryParam("access_token",
TEST_TOKEN);
assertThat(convertToToken(request)).isNull();
}