Skip to content

Commit

Permalink
Polish oauth2-resource-server format
Browse files Browse the repository at this point in the history
  • Loading branch information
rwinch committed Aug 24, 2020
1 parent d5ae433 commit 36ae1fe
Show file tree
Hide file tree
Showing 30 changed files with 674 additions and 202 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,23 +87,38 @@ public String getScope() {
}

private static boolean isDescriptionValid(String description) {
return description == null || description.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21)
|| withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:off
return description == null || description.chars().allMatch((c) ->
withinTheRangeOf(c, 0x20, 0x21) ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:on
}

private static boolean isErrorCodeValid(String errorCode) {
return errorCode.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21) || withinTheRangeOf(c, 0x23, 0x5B)
|| withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:off
return errorCode.chars().allMatch((c) ->
withinTheRangeOf(c, 0x20, 0x21) ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:on
}

private static boolean isErrorUriValid(String errorUri) {
return errorUri == null || errorUri.chars()
.allMatch((c) -> c == 0x21 || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
.allMatch((c) ->
c == 0x21 ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
}

private static boolean isScopeValid(String scope) {
return scope == null || scope.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21)
|| withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:off
return scope == null || scope.chars().allMatch((c) ->
withinTheRangeOf(c, 0x20, 0x21) ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:on
}

private static boolean withinTheRangeOf(int c, int min, int max) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,13 @@ public JwtIssuerReactiveAuthenticationManagerResolver(
*/
@Override
public Mono<ReactiveAuthenticationManager> resolve(ServerWebExchange exchange) {
// @formatter:off
return this.issuerConverter.convert(exchange)
.flatMap((issuer) -> this.issuerAuthenticationManagerResolver.resolve(issuer)
.switchIfEmpty(Mono.error(() -> new InvalidBearerTokenException("Invalid issuer " + issuer))));
.flatMap((issuer) -> this.issuerAuthenticationManagerResolver
.resolve(issuer)
.switchIfEmpty(Mono.error(() -> new InvalidBearerTokenException("Invalid issuer " + issuer)))
);
// @formatter:on
}

private static class JwtClaimIssuerConverter implements Converter<ServerWebExchange, Mono<String>> {
Expand Down Expand Up @@ -166,10 +170,13 @@ public Mono<ReactiveAuthenticationManager> resolve(String issuer) {
if (!this.trustedIssuer.test(issuer)) {
return Mono.empty();
}
// @formatter:off
return this.authenticationManagers.computeIfAbsent(issuer,
(k) -> Mono.<ReactiveAuthenticationManager>fromCallable(
() -> new JwtReactiveAuthenticationManager(ReactiveJwtDecoders.fromIssuerLocation(k)))
.subscribeOn(Schedulers.boundedElastic()).cache());
(k) -> Mono.<ReactiveAuthenticationManager>fromCallable(() -> new JwtReactiveAuthenticationManager(ReactiveJwtDecoders.fromIssuerLocation(k)))
.subscribeOn(Schedulers.boundedElastic())
.cache()
);
// @formatter:on
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,16 @@ public JwtReactiveAuthenticationManager(ReactiveJwtDecoder jwtDecoder) {

@Override
public Mono<Authentication> authenticate(Authentication authentication) {
return Mono.justOrEmpty(authentication).filter((a) -> a instanceof BearerTokenAuthenticationToken)
.cast(BearerTokenAuthenticationToken.class).map(BearerTokenAuthenticationToken::getToken)
.flatMap(this.jwtDecoder::decode).flatMap(this.jwtAuthenticationConverter::convert)
.cast(Authentication.class).onErrorMap(JwtException.class, this::onError);
// @formatter:off
return Mono.justOrEmpty(authentication)
.filter((a) -> a instanceof BearerTokenAuthenticationToken)
.cast(BearerTokenAuthenticationToken.class)
.map(BearerTokenAuthenticationToken::getToken)
.flatMap(this.jwtDecoder::decode)
.flatMap(this.jwtAuthenticationConverter::convert)
.cast(Authentication.class)
.onErrorMap(JwtException.class, this::onError);
// @formatter:on
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,28 @@ public OpaqueTokenReactiveAuthenticationManager(ReactiveOpaqueTokenIntrospector

@Override
public Mono<Authentication> authenticate(Authentication authentication) {
return Mono.justOrEmpty(authentication).filter(BearerTokenAuthenticationToken.class::isInstance)
.cast(BearerTokenAuthenticationToken.class).map(BearerTokenAuthenticationToken::getToken)
.flatMap(this::authenticate).cast(Authentication.class);
// @formatter:off
return Mono.justOrEmpty(authentication)
.filter(BearerTokenAuthenticationToken.class::isInstance)
.cast(BearerTokenAuthenticationToken.class)
.map(BearerTokenAuthenticationToken::getToken)
.flatMap(this::authenticate)
.cast(Authentication.class);
// @formatter:on
}

private Mono<BearerTokenAuthentication> authenticate(String token) {
return this.introspector.introspect(token).map((principal) -> {
Instant iat = principal.getAttribute(OAuth2IntrospectionClaimNames.ISSUED_AT);
Instant exp = principal.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
// construct token
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, token, iat, exp);
return new BearerTokenAuthentication(principal, accessToken, principal.getAuthorities());
}).onErrorMap(OAuth2IntrospectionException.class, this::onError);
// @formatter:off
return this.introspector.introspect(token)
.map((principal) -> {
Instant iat = principal.getAttribute(OAuth2IntrospectionClaimNames.ISSUED_AT);
Instant exp = principal.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
// construct token
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, token, iat, exp);
return new BearerTokenAuthentication(principal, accessToken, principal.getAuthorities());
})
.onErrorMap(OAuth2IntrospectionException.class, this::onError);
// @formatter:on
}

private AuthenticationException onError(OAuth2IntrospectionException ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@ public final class ReactiveJwtAuthenticationConverter implements Converter<Jwt,

@Override
public Mono<AbstractAuthenticationToken> convert(Jwt jwt) {
return this.jwtGrantedAuthoritiesConverter.convert(jwt).collectList()
// @formatter:off
return this.jwtGrantedAuthoritiesConverter.convert(jwt)
.collectList()
.map((authorities) -> new JwtAuthenticationToken(jwt, authorities));
// @formatter:on
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,25 +90,39 @@ public NimbusReactiveOpaqueTokenIntrospector(String introspectionUri, WebClient

@Override
public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
return Mono.just(token).flatMap(this::makeRequest).flatMap(this::adaptToNimbusResponse)
.map(this::parseNimbusResponse).map(this::castToNimbusSuccess)
.doOnNext((response) -> validate(token, response)).map(this::convertClaimsSet)
// @formatter:off
return Mono.just(token)
.flatMap(this::makeRequest)
.flatMap(this::adaptToNimbusResponse)
.map(this::parseNimbusResponse)
.map(this::castToNimbusSuccess)
.doOnNext((response) -> validate(token, response))
.map(this::convertClaimsSet)
.onErrorMap((e) -> !(e instanceof OAuth2IntrospectionException), this::onError);
// @formatter:on
}

private Mono<ClientResponse> makeRequest(String token) {
return this.webClient.post().uri(this.introspectionUri)
// @formatter:off
return this.webClient.post()
.uri(this.introspectionUri)
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_UTF8_VALUE)
.body(BodyInserters.fromFormData("token", token)).exchange();
.body(BodyInserters.fromFormData("token", token))
.exchange();
// @formatter:on
}

private Mono<HTTPResponse> adaptToNimbusResponse(ClientResponse responseEntity) {
HTTPResponse response = new HTTPResponse(responseEntity.rawStatusCode());
response.setHeader(HttpHeaders.CONTENT_TYPE, responseEntity.headers().contentType().get().toString());
if (response.getStatusCode() != HTTPResponse.SC_OK) {
return responseEntity.bodyToFlux(DataBuffer.class).map(DataBufferUtils::release)
// @formatter:off
return responseEntity.bodyToFlux(DataBuffer.class)
.map(DataBufferUtils::release)
.then(Mono.error(new OAuth2IntrospectionException(
"Introspection endpoint responded with " + response.getStatusCode())));
"Introspection endpoint responded with " + response.getStatusCode()))
);
// @formatter:on
}
return responseEntity.bodyToMono(String.class).doOnNext(response::setContent).map((body) -> response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,13 @@ public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denie
if (this.realmName != null) {
parameters.put("realm", this.realmName);
}
return exchange.getPrincipal().filter(AbstractOAuth2TokenAuthenticationToken.class::isInstance)
.map((token) -> errorMessageParameters(parameters)).switchIfEmpty(Mono.just(parameters))
// @formatter:off
return exchange.getPrincipal()
.filter(AbstractOAuth2TokenAuthenticationToken.class::isInstance)
.map((token) -> errorMessageParameters(parameters))
.switchIfEmpty(Mono.just(parameters))
.flatMap((params) -> respond(exchange, params));
// @formatter:on
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,21 +53,35 @@ public final class ServerBearerExchangeFilterFunction implements ExchangeFilterF

@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return oauth2Token().map((token) -> bearer(request, token)).defaultIfEmpty(request).flatMap(next::exchange);
// @formatter:off
return oauth2Token().map((token) -> bearer(request, token))
.defaultIfEmpty(request)
.flatMap(next::exchange);
// @formatter:on
}

private Mono<AbstractOAuth2Token> oauth2Token() {
// @formatter:off
return currentAuthentication()
.filter((authentication) -> authentication.getCredentials() instanceof AbstractOAuth2Token)
.map(Authentication::getCredentials).cast(AbstractOAuth2Token.class);
.map(Authentication::getCredentials)
.cast(AbstractOAuth2Token.class);
// @formatter:on
}

private Mono<Authentication> currentAuthentication() {
return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication);
// @formatter:off
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication);
// @formatter:on
}

private ClientRequest bearer(ClientRequest request, AbstractOAuth2Token token) {
return ClientRequest.from(request).headers((headers) -> headers.setBearerAuth(token.getTokenValue())).build();
// @formatter:off
return ClientRequest.from(request)
.headers((headers) -> headers.setBearerAuth(token.getTokenValue()))
.build();
// @formatter:on
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,21 @@ public final class ServletBearerExchangeFilterFunction implements ExchangeFilter

@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return oauth2Token().map((token) -> bearer(request, token)).defaultIfEmpty(request).flatMap(next::exchange);
// @formatter:off
return oauth2Token().map((token) -> bearer(request, token))
.defaultIfEmpty(request)
.flatMap(next::exchange);
// @formatter:on
}

private Mono<AbstractOAuth2Token> oauth2Token() {
return Mono.subscriberContext().flatMap(this::currentAuthentication)
// @formatter:off
return Mono.subscriberContext()
.flatMap(this::currentAuthentication)
.filter((authentication) -> authentication.getCredentials() instanceof AbstractOAuth2Token)
.map(Authentication::getCredentials).cast(AbstractOAuth2Token.class);
.map(Authentication::getCredentials)
.cast(AbstractOAuth2Token.class);
// @formatter:on
}

private Mono<Authentication> currentAuthentication(Context ctx) {
Expand All @@ -88,7 +96,11 @@ private <T> T getAttribute(Context ctx, Class<T> clazz) {
}

private ClientRequest bearer(ClientRequest request, AbstractOAuth2Token token) {
return ClientRequest.from(request).headers((headers) -> headers.setBearerAuth(token.getTokenValue())).build();
// @formatter:off
return ClientRequest.from(request)
.headers((headers) -> headers.setBearerAuth(token.getTokenValue()))
.build();
// @formatter:on
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,20 @@ public class BearerTokenAuthenticationTokenTests {

@Test
public void constructorWhenTokenIsNullThenThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenAuthenticationToken(null))
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenAuthenticationToken(null))
.withMessageContaining("token cannot be empty");
// @formatter:on
}

@Test
public void constructorWhenTokenIsEmptyThenThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenAuthenticationToken(""))
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenAuthenticationToken(""))
.withMessageContaining("token cannot be empty");
// @formatter:on
}

@Test
Expand Down
Loading

0 comments on commit 36ae1fe

Please sign in to comment.