Skip to content
Permalink
Browse files

Replace streams spring-projectsgh-7154

First version of replacing streams

Fix wwwAuthenticate and codestyle

Fix errors in implementation to pass tests
  • Loading branch information...
kostya05983 committed Aug 4, 2019
1 parent 09c98da commit 2efebcf9a4be786ca7153d0d4977f217e0c773be
Showing with 295 additions and 180 deletions.
  1. +16 −6 ...ramework/security/config/annotation/authentication/configuration/AuthenticationConfiguration.java
  2. +9 −5 ...c/main/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManager.java
  3. +16 −13 core/src/main/java/org/springframework/security/converter/RsaKeyConverters.java
  4. +6 −3 core/src/main/java/org/springframework/security/core/userdetails/MapReactiveUserDetailsService.java
  5. +12 −6 ...ain/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProvider.java
  6. +5 −8 ...c/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilder.java
  7. +8 −4 ...ain/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenValidator.java
  8. +14 −9 ...org/springframework/security/oauth2/client/registration/InMemoryClientRegistrationRepository.java
  9. +10 −5 ...ngframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepository.java
  10. +8 −6 ...src/main/java/org/springframework/security/oauth2/core/converter/ObjectToListStringConverter.java
  11. +7 −4 ...e/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationRequest.java
  12. +16 −13 ...gframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverter.java
  13. +31 −9 ...h2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/user/DefaultOAuth2User.java
  14. +6 −5 oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/jws/MacAlgorithm.java
  15. +6 −6 ...h2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/jws/SignatureAlgorithm.java
  16. +12 −8 ...oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverter.java
  17. +10 −6 ...ork/security/oauth2/server/resource/authentication/OAuth2IntrospectionAuthenticationProvider.java
  18. +8 −6 ...urity/oauth2/server/resource/authentication/OAuth2IntrospectionReactiveAuthenticationManager.java
  19. +6 −4 ...framework/security/oauth2/server/resource/introspection/NimbusOAuth2TokenIntrospectionClient.java
  20. +6 −4 ...k/security/oauth2/server/resource/introspection/NimbusReactiveOAuth2TokenIntrospectionClient.java
  21. +12 −6 .../org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java
  22. +12 −6 ...rg/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java
  23. +12 −6 ...ework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandler.java
  24. +12 −6 ...amework/security/oauth2/server/resource/web/server/BearerTokenServerAuthenticationEntryPoint.java
  25. +10 −4 web/src/main/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriter.java
  26. +6 −4 ...ingframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandler.java
  27. +7 −7 .../org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandler.java
  28. +6 −6 ...ain/java/org/springframework/security/web/server/header/ClearSiteDataServerHttpHeadersWriter.java
  29. +6 −5 ...rc/main/java/org/springframework/security/web/server/header/CompositeServerHttpHeadersWriter.java
@@ -43,12 +43,11 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
* Exports the authentication {@link Configuration}
@@ -153,10 +152,7 @@ public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcess
}
String beanName;
if (beanNamesForType.length > 1) {
List<String> primaryBeanNames = Arrays.stream(beanNamesForType)
.filter(i -> applicationContext instanceof ConfigurableApplicationContext)
.filter(n -> ((ConfigurableApplicationContext) applicationContext).getBeanFactory().getBeanDefinition(n).isPrimary())
.collect(Collectors.toList());
List<String> primaryBeanNames = getPrimaryBeanNames(beanNamesForType);

Assert.isTrue(primaryBeanNames.size() != 0, () -> "Found " + beanNamesForType.length
+ " beans for type " + interfaceName + ", but none marked as primary");
@@ -175,6 +171,20 @@ public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcess
return (T) proxyFactory.getObject();
}

private List<String> getPrimaryBeanNames(String[] beanNamesForType) {
final List<String> list = new ArrayList<>();
if (!(applicationContext instanceof ConfigurableApplicationContext)) {
return Collections.emptyList();
}
for (String beanName: beanNamesForType) {
if (((ConfigurableApplicationContext) applicationContext).getBeanFactory()
.getBeanDefinition(beanName).isPrimary()) {
list.add(beanName);
}
}
return list;
}

private AuthenticationManager getAuthenticationManagerBean() {
return lazyBean(AuthenticationManager.class);
}
@@ -22,7 +22,6 @@

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
* A {@link ReactiveAuthorizationManager} that determines if the current user is
@@ -109,9 +108,14 @@ private AuthorityReactiveAuthorizationManager(String... authorities) {
Assert.notNull(role, "role cannot be null");
}

return hasAnyAuthority(Stream.of(roles)
.map(r -> "ROLE_" + r)
.toArray(String[]::new)
);
return hasAnyAuthority(toNamedRolesArray(roles));
}

private static String[] toNamedRolesArray(String... roles) {
String[] result = new String[roles.length];
for (int i=0; i < roles.length; i++) {
result[i] = "ROLE_" + roles[i];
}
return result;
}
}
@@ -16,17 +16,14 @@

package org.springframework.security.converter;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.core.convert.converter.Converter;
@@ -66,10 +63,13 @@
Assert.isTrue(!lines.isEmpty() && lines.get(0).startsWith(PKCS8_PEM_HEADER),
"Key is not in PEM-encoded PKCS#8 format, " +
"please check that the header begins with -----" + PKCS8_PEM_HEADER + "-----");
String base64Encoded = lines.stream()
.filter(RsaKeyConverters::isNotPkcs8Wrapper)
.collect(Collectors.joining());
byte[] pkcs8 = Base64.getDecoder().decode(base64Encoded);
StringBuilder base64Encoded = new StringBuilder();
for (String line: lines) {
if (RsaKeyConverters.isNotPkcs8Wrapper(line)) {
base64Encoded.append(line);
}
}
byte[] pkcs8 = Base64.getDecoder().decode(base64Encoded.toString());

try {
return (RSAPrivateKey) keyFactory.generatePrivate(
@@ -97,10 +97,13 @@
Assert.isTrue(!lines.isEmpty() && lines.get(0).startsWith(X509_PEM_HEADER),
"Key is not in PEM-encoded X.509 format, " +
"please check that the header begins with -----" + X509_PEM_HEADER + "-----");
String base64Encoded = lines.stream()
.filter(RsaKeyConverters::isNotX509Wrapper)
.collect(Collectors.joining());
byte[] x509 = Base64.getDecoder().decode(base64Encoded);
StringBuilder base64Encoded = new StringBuilder();
for (String line: lines) {
if (RsaKeyConverters.isNotX509Wrapper(line)) {
base64Encoded.append(line);
}
}
byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString());

try {
return (RSAPublicKey) keyFactory.generatePublic(
@@ -19,8 +19,7 @@
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.util.Assert;
import reactor.core.publisher.Mono;
@@ -56,7 +55,11 @@ public MapReactiveUserDetailsService(UserDetails... users) {
*/
public MapReactiveUserDetailsService(Collection<UserDetails> users) {
Assert.notEmpty(users, "users cannot be null or empty");
this.users = users.stream().collect(Collectors.toConcurrentMap( u -> getKey(u.getUsername()), Function.identity()));
final ConcurrentHashMap<String, UserDetails> map = new ConcurrentHashMap<>();
for (UserDetails user: users) {
map.put(user.getUsername(), user);
}
this.users = map;
}

@Override
@@ -22,7 +22,6 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
* An implementation of an {@link OAuth2AuthorizedClientProvider} that simply delegates
@@ -64,10 +63,17 @@ public DelegatingOAuth2AuthorizedClientProvider(List<OAuth2AuthorizedClientProvi
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
return this.authorizedClientProviders.stream()
.map(authorizedClientProvider -> authorizedClientProvider.authorize(context))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
final List<OAuth2AuthorizedClient> clients = new ArrayList<>();
for (OAuth2AuthorizedClientProvider authorizedClientProvider: authorizedClientProviders) {
final OAuth2AuthorizedClient auth2AuthorizedClient = authorizedClientProvider.authorize(context);
if (auth2AuthorizedClient != null) {
clients.add(auth2AuthorizedClient);
}
}
if (!clients.isEmpty()) {
return clients.get(0);
} else {
return null;
}
}
}
@@ -21,11 +21,8 @@
import org.springframework.util.Assert;

import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
* A builder that builds a {@link DelegatingOAuth2AuthorizedClientProvider} composed of
@@ -254,10 +251,10 @@ public OAuth2AuthorizedClientProvider build() {
* @return the {@link DelegatingOAuth2AuthorizedClientProvider}
*/
public OAuth2AuthorizedClientProvider build() {
List<OAuth2AuthorizedClientProvider> authorizedClientProviders =
this.builders.values().stream()
.map(Builder::build)
.collect(Collectors.toList());
List<OAuth2AuthorizedClientProvider> authorizedClientProviders = new ArrayList<>();
for (Builder builder : this.builders.values()) {
authorizedClientProviders.add(builder.build());
}
return new DelegatingOAuth2AuthorizedClientProvider(authorizedClientProviders);
}

@@ -32,7 +32,6 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* An {@link OAuth2TokenValidator} responsible for
@@ -137,9 +136,14 @@ public final void setClockSkew(Duration clockSkew) {
}

private static OAuth2Error invalidIdToken(Map<String, Object> invalidClaims) {
String claimsDetail = invalidClaims.entrySet().stream()
.map(it -> it.getKey() + " (" + it.getValue() + ")")
.collect(Collectors.joining(", "));
final StringBuilder claimsDetail = new StringBuilder();
int i = 0;
for (Map.Entry<String, Object> entry : invalidClaims.entrySet()) {
claimsDetail.append(entry.getKey()).append(" (").append(entry.getValue()).append(")");
if (i != invalidClaims.size() - 1) {
claimsDetail.append(", ");
}
}
return new OAuth2Error("invalid_id_token",
"The ID Token contains invalid claims: " + claimsDetail,
"https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation");
@@ -22,12 +22,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collector;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;

/**
* A {@link ClientRegistrationRepository} that stores {@link ClientRegistration}(s) in-memory.
@@ -62,9 +57,19 @@ public InMemoryClientRegistrationRepository(List<ClientRegistration> registratio

private static Map<String, ClientRegistration> createRegistrationsMap(List<ClientRegistration> registrations) {
Assert.notEmpty(registrations, "registrations cannot be empty");
Collector<ClientRegistration, ?, ConcurrentMap<String, ClientRegistration>> collector =
toConcurrentMap(ClientRegistration::getRegistrationId, Function.identity());
return registrations.stream().collect(collectingAndThen(collector, Collections::unmodifiableMap));
return toUnmodifiableConcurrentMap(registrations);
}

private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) {
final ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>();
for (ClientRegistration registration : registrations) {
if (result.containsKey(registration.getRegistrationId())) {
throw new IllegalStateException(String.format("Duplicate key %s",
registration.getRegistrationId()));
}
result.put(registration.getRegistrationId(), registration);
}
return Collections.unmodifiableMap(result);
}

/**
@@ -18,8 +18,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.util.Assert;
import org.springframework.util.ConcurrentReferenceHashMap;
@@ -60,11 +59,9 @@ public InMemoryReactiveClientRegistrationRepository(ClientRegistration... regist
*/
public InMemoryReactiveClientRegistrationRepository(List<ClientRegistration> registrations) {
Assert.notEmpty(registrations, "registrations cannot be null or empty");
this.clientIdToClientRegistration = registrations.stream()
.collect(Collectors.toConcurrentMap(ClientRegistration::getRegistrationId, Function.identity()));
this.clientIdToClientRegistration = toConcurrentMap(registrations);
}


@Override
public Mono<ClientRegistration> findByRegistrationId(String registrationId) {
return Mono.justOrEmpty(this.clientIdToClientRegistration.get(registrationId));
@@ -79,4 +76,12 @@ public InMemoryReactiveClientRegistrationRepository(List<ClientRegistration> reg
public Iterator<ClientRegistration> iterator() {
return this.clientIdToClientRegistration.values().iterator();
}

private ConcurrentHashMap<String, ClientRegistration> toConcurrentMap(List<ClientRegistration> registrations) {
final ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>();
for (ClientRegistration registration : registrations) {
result.put(registration.getRegistrationId(), registration);
}
return result;
}
}
@@ -23,9 +23,8 @@
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.ArrayList;

/**
* @author Joe Grandja
@@ -64,10 +63,13 @@ public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor t
}
}
if (source instanceof Collection) {
return ((Collection<?>) source).stream()
.filter(Objects::nonNull)
.map(Objects::toString)
.collect(Collectors.toList());
final Collection<String> results = new ArrayList<>();
for (Object object : ((Collection<?>) source)) {
if (object != null) {
results.add(object.toString());
}
}
return results;
}
return Collections.singletonList(source.toString());
}
@@ -26,13 +26,11 @@

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* A representation of an OAuth 2.0 Authorization Request
@@ -275,8 +273,7 @@ public Builder redirectUri(String redirectUri) {
*/
public Builder scope(String... scope) {
if (scope != null && scope.length > 0) {
return this.scopes(Arrays.stream(scope).collect(
Collectors.toCollection(LinkedHashSet::new)));
return this.scopes(toLinkedHashSet(scope));
}
return this;
}
@@ -401,5 +398,11 @@ private String buildAuthorizationRequestUri() {
.build()
.toUriString();
}

private LinkedHashSet<String> toLinkedHashSet(String... scope) {
final LinkedHashSet<String> result = new LinkedHashSet<>();
Collections.addAll(result, scope);
return result;
}
}
}

0 comments on commit 2efebcf

Please sign in to comment.
You can’t perform that action at this time.