Using modern Java features

This commit is contained in:
Krzysztof Krason 2023-01-20 16:45:41 +01:00 committed by Josh Cummings
parent 7e01ebdd92
commit 9b603b99ab
72 changed files with 206 additions and 402 deletions

View File

@ -118,8 +118,7 @@ public class AclPermissionEvaluator implements PermissionEvaluator {
if (permission instanceof Permission[]) { if (permission instanceof Permission[]) {
return Arrays.asList((Permission[]) permission); return Arrays.asList((Permission[]) permission);
} }
if (permission instanceof String) { if (permission instanceof String permString) {
String permString = (String) permission;
Permission p = buildPermission(permString); Permission p = buildPermission(permString);
if (p != null) { if (p != null) {
return Arrays.asList(p); return Arrays.asList(p);

View File

@ -56,10 +56,9 @@ public abstract class AbstractPermission implements Permission {
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof Permission)) { if (!(obj instanceof Permission other)) {
return false; return false;
} }
Permission other = (Permission) obj;
return (this.mask == other.getMask()); return (this.mask == other.getMask());
} }

View File

@ -454,7 +454,7 @@ public class JdbcMutableAclServiceTests {
CustomSid customSid = new CustomSid("Custom sid"); CustomSid customSid = new CustomSid("Custom sid");
given(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).willReturn(1L); given(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).willReturn(1L);
Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(customSid, false); Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(customSid, false);
assertThat(new Long(1L)).isEqualTo(result); assertThat(Long.valueOf(1L)).isEqualTo(result);
} }
protected Authentication getAuth() { protected Authentication getAuth() {

View File

@ -4,7 +4,6 @@ import org.gradle.api.Action;
import org.gradle.api.GradleException; import org.gradle.api.GradleException;
import org.gradle.api.Plugin; import org.gradle.api.Plugin;
import org.gradle.api.Project; import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.tasks.TaskProvider; import org.gradle.api.tasks.TaskProvider;
import org.gradle.language.base.plugins.LifecycleBasePlugin; import org.gradle.language.base.plugins.LifecycleBasePlugin;
@ -27,12 +26,8 @@ public class AntoraVersionPlugin implements Plugin<Project> {
project.getPlugins().withType(LifecycleBasePlugin.class, new Action<LifecycleBasePlugin>() { project.getPlugins().withType(LifecycleBasePlugin.class, new Action<LifecycleBasePlugin>() {
@Override @Override
public void execute(LifecycleBasePlugin lifecycleBasePlugin) { public void execute(LifecycleBasePlugin lifecycleBasePlugin) {
project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME).configure(new Action<Task>() { project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME)
@Override .configure(check -> check.dependsOn(antoraCheckVersion));
public void execute(Task check) {
check.dependsOn(antoraCheckVersion);
}
});
} }
}); });
project.getTasks().register("antoraUpdateVersion", UpdateAntoraVersionTask.class, new Action<UpdateAntoraVersionTask>() { project.getTasks().register("antoraUpdateVersion", UpdateAntoraVersionTask.class, new Action<UpdateAntoraVersionTask>() {

View File

@ -35,9 +35,7 @@ public class CheckClasspathForProhibitedDependenciesPlugin implements Plugin<Pro
@Override @Override
public void apply(Project project) { public void apply(Project project) {
project.getPlugins().apply(CheckProhibitedDependenciesLifecyclePlugin.class); project.getPlugins().apply(CheckProhibitedDependenciesLifecyclePlugin.class);
project.getPlugins().withType(JavaBasePlugin.class, javaBasePlugin -> { project.getPlugins().withType(JavaBasePlugin.class, javaBasePlugin -> configureProhibitedDependencyChecks(project));
configureProhibitedDependencyChecks(project);
});
} }
private void configureProhibitedDependencyChecks(Project project) { private void configureProhibitedDependencyChecks(Project project) {

View File

@ -34,8 +34,6 @@ public class CheckProhibitedDependenciesLifecyclePlugin implements Plugin<Projec
task.setGroup(JavaBasePlugin.VERIFICATION_GROUP); task.setGroup(JavaBasePlugin.VERIFICATION_GROUP);
task.setDescription("Checks both the compile/runtime classpath of every SourceSet for prohibited dependencies"); task.setDescription("Checks both the compile/runtime classpath of every SourceSet for prohibited dependencies");
}); });
project.getTasks().named(JavaBasePlugin.CHECK_TASK_NAME, checkTask -> { project.getTasks().named(JavaBasePlugin.CHECK_TASK_NAME, checkTask -> checkTask.dependsOn(checkProhibitedDependencies));
checkTask.dependsOn(checkProhibitedDependencies);
});
} }
} }

View File

@ -26,7 +26,6 @@ import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.DependencySet; import org.gradle.api.artifacts.DependencySet;
import org.gradle.api.artifacts.repositories.ExclusiveContentRepository; import org.gradle.api.artifacts.repositories.ExclusiveContentRepository;
import org.gradle.api.artifacts.repositories.InclusiveRepositoryContentDescriptor;
import org.gradle.api.artifacts.repositories.IvyArtifactRepository; import org.gradle.api.artifacts.repositories.IvyArtifactRepository;
import org.gradle.api.artifacts.repositories.IvyPatternRepositoryLayout; import org.gradle.api.artifacts.repositories.IvyPatternRepositoryLayout;
import org.gradle.api.tasks.JavaExec; import org.gradle.api.tasks.JavaExec;
@ -91,12 +90,7 @@ public class GitHubChangelogPlugin implements Plugin<Project> {
@Override @Override
public void execute(ExclusiveContentRepository exclusiveContentRepository) { public void execute(ExclusiveContentRepository exclusiveContentRepository) {
exclusiveContentRepository.forRepositories(repository); exclusiveContentRepository.forRepositories(repository);
exclusiveContentRepository.filter(new Action<InclusiveRepositoryContentDescriptor>() { exclusiveContentRepository.filter(descriptor -> descriptor.includeGroup("spring-io"));
@Override
public void execute(InclusiveRepositoryContentDescriptor descriptor) {
descriptor.includeGroup("spring-io");
}
});
} }
}); });
} }

View File

@ -114,11 +114,11 @@ public final class SpringReleaseTrainSpec {
} }
public Builder train(int train) { public Builder train(int train) {
switch (train) { this.train = switch (train) {
case 1: this.train = Train.ONE; break; case 1 -> Train.ONE;
case 2: this.train = Train.TWO; break; case 2 -> Train.TWO;
default: throw new IllegalArgumentException("Invalid train: " + train); default -> throw new IllegalArgumentException("Invalid train: " + train);
} };
return this; return this;
} }
@ -156,13 +156,13 @@ public final class SpringReleaseTrainSpec {
} }
public Builder weekOfMonth(int weekOfMonth) { public Builder weekOfMonth(int weekOfMonth) {
switch (weekOfMonth) { this.weekOfMonth = switch (weekOfMonth) {
case 1: this.weekOfMonth = WeekOfMonth.FIRST; break; case 1 -> WeekOfMonth.FIRST;
case 2: this.weekOfMonth = WeekOfMonth.SECOND; break; case 2 -> WeekOfMonth.SECOND;
case 3: this.weekOfMonth = WeekOfMonth.THIRD; break; case 3 -> WeekOfMonth.THIRD;
case 4: this.weekOfMonth = WeekOfMonth.FOURTH; break; case 4 -> WeekOfMonth.FOURTH;
default: throw new IllegalArgumentException("Invalid weekOfMonth: " + weekOfMonth); default -> throw new IllegalArgumentException("Invalid weekOfMonth: " + weekOfMonth);
} };
return this; return this;
} }
@ -172,14 +172,14 @@ public final class SpringReleaseTrainSpec {
} }
public Builder dayOfWeek(int dayOfWeek) { public Builder dayOfWeek(int dayOfWeek) {
switch (dayOfWeek) { this.dayOfWeek = switch (dayOfWeek) {
case 1: this.dayOfWeek = DayOfWeek.MONDAY; break; case 1 -> DayOfWeek.MONDAY;
case 2: this.dayOfWeek = DayOfWeek.TUESDAY; break; case 2 -> DayOfWeek.TUESDAY;
case 3: this.dayOfWeek = DayOfWeek.WEDNESDAY; break; case 3 -> DayOfWeek.WEDNESDAY;
case 4: this.dayOfWeek = DayOfWeek.THURSDAY; break; case 4 -> DayOfWeek.THURSDAY;
case 5: this.dayOfWeek = DayOfWeek.FRIDAY; break; case 5 -> DayOfWeek.FRIDAY;
default: throw new IllegalArgumentException("Invalid dayOfWeek: " + dayOfWeek); default -> throw new IllegalArgumentException("Invalid dayOfWeek: " + dayOfWeek);
} };
return this; return this;
} }

View File

@ -21,7 +21,6 @@ import org.gradle.api.Plugin;
import org.gradle.api.Project; import org.gradle.api.Project;
import org.gradle.api.publish.Publication; import org.gradle.api.publish.Publication;
import org.gradle.api.publish.PublishingExtension; import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.plugins.PublishingPlugin;
import org.gradle.plugins.signing.SigningExtension; import org.gradle.plugins.signing.SigningExtension;
import org.gradle.plugins.signing.SigningPlugin; import org.gradle.plugins.signing.SigningPlugin;
@ -44,12 +43,7 @@ public class SpringSigningPlugin implements Plugin<Project> {
private void sign(Project project) { private void sign(Project project) {
SigningExtension signing = project.getExtensions().findByType(SigningExtension.class); SigningExtension signing = project.getExtensions().findByType(SigningExtension.class);
signing.setRequired(new Callable<Boolean>() { signing.setRequired((Callable<Boolean>) () -> project.getGradle().getTaskGraph().hasTask("publishArtifacts"));
@Override
public Boolean call() throws Exception {
return project.getGradle().getTaskGraph().hasTask("publishArtifacts");
}
});
String signingKeyId = (String) project.findProperty("signingKeyId"); String signingKeyId = (String) project.findProperty("signingKeyId");
String signingKey = (String) project.findProperty("signingKey"); String signingKey = (String) project.findProperty("signingKey");
String signingPassword = (String) project.findProperty("signingPassword"); String signingPassword = (String) project.findProperty("signingPassword");

View File

@ -294,7 +294,7 @@ public class RSocketMessageHandlerITests {
@MessageMapping({ "secure.send", "send" }) @MessageMapping({ "secure.send", "send" })
Mono<Void> send(Mono<String> payload) { Mono<Void> send(Mono<String> payload) {
return payload.doOnNext(this::add).then(Mono.fromRunnable(() -> doNotifyAll())); return payload.doOnNext(this::add).then(Mono.fromRunnable(this::doNotifyAll));
} }
private synchronized void doNotifyAll() { private synchronized void doNotifyAll() {

View File

@ -68,8 +68,7 @@ public class RsaKeyConversionServicePostProcessor implements BeanFactoryPostProc
return; return;
} }
ConversionService service = beanFactory.getConversionService(); ConversionService service = beanFactory.getConversionService();
if (service instanceof ConverterRegistry) { if (service instanceof ConverterRegistry registry) {
ConverterRegistry registry = (ConverterRegistry) service;
registry.addConverter(String.class, RSAPrivateKey.class, this.pkcs8); registry.addConverter(String.class, RSAPrivateKey.class, this.pkcs8);
registry.addConverter(String.class, RSAPublicKey.class, this.x509); registry.addConverter(String.class, RSAPublicKey.class, this.x509);
} }

View File

@ -42,19 +42,12 @@ public final class ChannelAttributeFactory {
} }
public static List<ConfigAttribute> createChannelAttributes(String requiredChannel) { public static List<ConfigAttribute> createChannelAttributes(String requiredChannel) {
String channelConfigAttribute; String channelConfigAttribute = switch (requiredChannel) {
if (requiredChannel.equals(OPT_REQUIRES_HTTPS)) { case OPT_REQUIRES_HTTPS -> "REQUIRES_SECURE_CHANNEL";
channelConfigAttribute = "REQUIRES_SECURE_CHANNEL"; case OPT_REQUIRES_HTTP -> "REQUIRES_INSECURE_CHANNEL";
} case OPT_ANY_CHANNEL -> ChannelDecisionManagerImpl.ANY_CHANNEL;
else if (requiredChannel.equals(OPT_REQUIRES_HTTP)) { default -> throw new BeanCreationException("Unknown channel attribute " + requiredChannel);
channelConfigAttribute = "REQUIRES_INSECURE_CHANNEL"; };
}
else if (requiredChannel.equals(OPT_ANY_CHANNEL)) {
channelConfigAttribute = ChannelDecisionManagerImpl.ANY_CHANNEL;
}
else {
throw new BeanCreationException("Unknown channel attribute " + requiredChannel);
}
return SecurityConfig.createList(channelConfigAttribute); return SecurityConfig.createList(channelConfigAttribute);
} }

View File

@ -382,7 +382,7 @@ public class RequestCacheConfigurerTests {
.anyRequest().authenticated() .anyRequest().authenticated()
) )
.formLogin(Customizer.withDefaults()) .formLogin(Customizer.withDefaults())
.requestCache((cache) -> cache.disable()); .requestCache(RequestCacheConfigurer::disable);
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }

View File

@ -556,9 +556,7 @@ public class SessionManagementConfigurerTests {
.sessionManagement((sessionManagement) -> .sessionManagement((sessionManagement) ->
sessionManagement sessionManagement
.requireExplicitAuthenticationStrategy(false) .requireExplicitAuthenticationStrategy(false)
.sessionFixation((sessionFixation) -> .sessionFixation(SessionManagementConfigurer.SessionFixationConfigurer::newSession)
sessionFixation.newSession()
)
) )
.httpBasic(withDefaults()); .httpBasic(withDefaults());
// @formatter:on // @formatter:on

View File

@ -868,8 +868,7 @@ public class OAuth2ResourceServerConfigurerTests {
context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder); context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
this.spring.context(context).autowire(); this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt(); OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class) assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(jwtConfigurer::getJwtDecoder);
.isThrownBy(() -> jwtConfigurer.getJwtDecoder());
} }
@Test @Test
@ -1885,9 +1884,7 @@ public class OAuth2ResourceServerConfigurerTests {
.anyRequest().authenticated() .anyRequest().authenticated()
) )
.oauth2Login(withDefaults()) .oauth2Login(withDefaults())
.oauth2ResourceServer((oauth2) -> oauth2 .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
.jwt()
);
return http.build(); return http.build();
// @formatter:on // @formatter:on
} }

View File

@ -27,8 +27,7 @@ public class SyncExecutorSubscribableChannelPostProcessor implements BeanPostPro
@Override @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof ExecutorSubscribableChannel) { if (bean instanceof ExecutorSubscribableChannel original) {
ExecutorSubscribableChannel original = (ExecutorSubscribableChannel) bean;
ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel(); ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
channel.setInterceptors(original.getInterceptors()); channel.setInterceptors(original.getInterceptors());
return channel; return channel;

View File

@ -627,9 +627,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws HandshakeFailureException { Map<String, Object> attributes) throws HandshakeFailureException {
this.attributes = attributes; this.attributes = attributes;
if (wsHandler instanceof SockJsWebSocketHandler) { if (wsHandler instanceof SockJsWebSocketHandler sockJs) {
// work around SPR-12716 // work around SPR-12716
SockJsWebSocketHandler sockJs = (SockJsWebSocketHandler) wsHandler;
WebSocketServerSockJsSession session = (WebSocketServerSockJsSession) ReflectionTestUtils WebSocketServerSockJsSession session = (WebSocketServerSockJsSession) ReflectionTestUtils
.getField(sockJs, "sockJsSession"); .getField(sockJs, "sockJsSession");
this.attributes = session.getAttributes(); this.attributes = session.getAttributes();

View File

@ -58,8 +58,7 @@ public class XmlNode {
public Optional<XmlNode> parent() { public Optional<XmlNode> parent() {
// @formatter:off // @formatter:off
return Optional.ofNullable(this.node.getParentNode()) return Optional.ofNullable(this.node.getParentNode()).map(XmlNode::new);
.map((parent) -> new XmlNode(parent));
// @formatter:on // @formatter:on
} }
@ -67,7 +66,7 @@ public class XmlNode {
// @formatter:off // @formatter:off
return Optional.ofNullable(this.node.getAttributes()) return Optional.ofNullable(this.node.getAttributes())
.map((attrs) -> attrs.getNamedItem(name)) .map((attrs) -> attrs.getNamedItem(name))
.map((attr) -> attr.getTextContent()) .map(Node::getTextContent)
.orElse(null); .orElse(null);
// @formatter:on // @formatter:on
} }

View File

@ -31,7 +31,7 @@ public class SpringTestContextExtension implements BeforeEachCallback, AfterEach
@Override @Override
public void afterEach(ExtensionContext context) throws Exception { public void afterEach(ExtensionContext context) throws Exception {
TestSecurityContextHolder.clearContext(); TestSecurityContextHolder.clearContext();
getContexts(context.getRequiredTestInstance()).forEach((springTestContext) -> springTestContext.close()); getContexts(context.getRequiredTestInstance()).forEach(SpringTestContext::close);
} }
@Override @Override

View File

@ -38,8 +38,7 @@ public class SecurityConfig implements ConfigAttribute {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof ConfigAttribute) { if (obj instanceof ConfigAttribute attr) {
ConfigAttribute attr = (ConfigAttribute) obj;
return this.attrib.equals(attr.getAttribute()); return this.attrib.equals(attr.getAttribute());
} }
return false; return false;

View File

@ -89,8 +89,7 @@ public class Jsr250MethodSecurityMetadataSource extends AbstractFallbackMethodSe
attributes.add(Jsr250SecurityConfig.PERMIT_ALL_ATTRIBUTE); attributes.add(Jsr250SecurityConfig.PERMIT_ALL_ATTRIBUTE);
return attributes; return attributes;
} }
if (annotation instanceof RolesAllowed) { if (annotation instanceof RolesAllowed ra) {
RolesAllowed ra = (RolesAllowed) annotation;
for (String allowed : ra.value()) { for (String allowed : ra.value()) {
String defaultedAllowed = getRoleWithDefaultPrefix(allowed); String defaultedAllowed = getRoleWithDefaultPrefix(allowed);

View File

@ -43,8 +43,7 @@ public abstract class AbstractMethodSecurityMetadataSource implements MethodSecu
@Override @Override
public final Collection<ConfigAttribute> getAttributes(Object object) { public final Collection<ConfigAttribute> getAttributes(Object object) {
if (object instanceof MethodInvocation) { if (object instanceof MethodInvocation mi) {
MethodInvocation mi = (MethodInvocation) object;
Object target = mi.getThis(); Object target = mi.getThis();
Class<?> targetClass = null; Class<?> targetClass = null;
if (target != null) { if (target != null) {

View File

@ -264,8 +264,7 @@ public class MapBasedMethodSecurityMetadataSource extends AbstractFallbackMethod
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj != null && obj instanceof RegisteredMethod) { if (obj instanceof RegisteredMethod rhs) {
RegisteredMethod rhs = (RegisteredMethod) obj;
return this.method.equals(rhs.method) && this.registeredJavaType.equals(rhs.registeredJavaType); return this.method.equals(rhs.method) && this.registeredJavaType.equals(rhs.registeredJavaType);
} }
return false; return false;

View File

@ -71,14 +71,9 @@ public class ConsensusBased extends AbstractAccessDecisionManager {
for (AccessDecisionVoter voter : getDecisionVoters()) { for (AccessDecisionVoter voter : getDecisionVoters()) {
int result = voter.vote(authentication, object, configAttributes); int result = voter.vote(authentication, object, configAttributes);
switch (result) { switch (result) {
case AccessDecisionVoter.ACCESS_GRANTED: case AccessDecisionVoter.ACCESS_GRANTED -> grant++;
grant++; case AccessDecisionVoter.ACCESS_DENIED -> deny++;
break; default -> { }
case AccessDecisionVoter.ACCESS_DENIED:
deny++;
break;
default:
break;
} }
} }
if (grant > deny) { if (grant > deny) {

View File

@ -256,8 +256,7 @@ public class ProviderManager implements AuthenticationManager, MessageSourceAwar
* @param dest the destination authentication object * @param dest the destination authentication object
*/ */
private void copyDetails(Authentication source, Authentication dest) { private void copyDetails(Authentication source, Authentication dest) {
if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) { if ((dest instanceof AbstractAuthenticationToken token) && (dest.getDetails() == null)) {
AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest;
token.setDetails(source.getDetails()); token.setDetails(source.getDetails());
} }
} }

View File

@ -94,12 +94,8 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken {
if (!super.equals(obj)) { if (!super.equals(obj)) {
return false; return false;
} }
if (obj instanceof RememberMeAuthenticationToken) { if (obj instanceof RememberMeAuthenticationToken other) {
RememberMeAuthenticationToken other = (RememberMeAuthenticationToken) obj; return this.getKeyHash() == other.getKeyHash();
if (this.getKeyHash() != other.getKeyHash()) {
return false;
}
return true;
} }
return false; return false;
} }

View File

@ -160,10 +160,9 @@ public abstract class AbstractJaasAuthenticationProvider implements Authenticati
*/ */
@Override @Override
public Authentication authenticate(Authentication auth) throws AuthenticationException { public Authentication authenticate(Authentication auth) throws AuthenticationException {
if (!(auth instanceof UsernamePasswordAuthenticationToken)) { if (!(auth instanceof UsernamePasswordAuthenticationToken request)) {
return null; return null;
} }
UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;
Set<GrantedAuthority> authorities; Set<GrantedAuthority> authorities;
try { try {
// Create the LoginContext object, and pass our InternallCallbackHandler // Create the LoginContext object, and pass our InternallCallbackHandler
@ -233,8 +232,7 @@ public abstract class AbstractJaasAuthenticationProvider implements Authenticati
} }
for (SecurityContext context : contexts) { for (SecurityContext context : contexts) {
Authentication auth = context.getAuthentication(); Authentication auth = context.getAuthentication();
if ((auth != null) && (auth instanceof JaasAuthenticationToken)) { if ((auth instanceof JaasAuthenticationToken token)) {
JaasAuthenticationToken token = (JaasAuthenticationToken) auth;
try { try {
LoginContext loginContext = token.getLoginContext(); LoginContext loginContext = token.getLoginContext();
logout(token, loginContext); logout(token, loginContext);

View File

@ -58,8 +58,7 @@ public final class JaasGrantedAuthority implements GrantedAuthority {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj instanceof JaasGrantedAuthority) { if (obj instanceof JaasGrantedAuthority jga) {
JaasGrantedAuthority jga = (JaasGrantedAuthority) obj;
return this.role.equals(jga.role) && this.principal.equals(jga.principal); return this.role.equals(jga.role) && this.principal.equals(jga.principal);
} }
return false; return false;

View File

@ -130,23 +130,13 @@ class ComparableVersion implements Comparable<ComparableVersion> {
return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1 return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1
} }
switch (item.getType()) { return switch (item.getType()) {
case INT_ITEM: case INT_ITEM -> Integer.compare(value, ((IntItem) item).value);
int itemValue = ((IntItem) item).value; case LONG_ITEM, BIGINTEGER_ITEM -> -1;
return (value < itemValue) ? -1 : ((value == itemValue) ? 0 : 1); case STRING_ITEM -> 1; // 1.1 > 1-sp
case LONG_ITEM: case LIST_ITEM -> 1; // 1.1 > 1-1
case BIGINTEGER_ITEM: default -> throw new IllegalStateException("invalid item: " + item.getClass());
return -1; };
case STRING_ITEM:
return 1; // 1.1 > 1-sp
case LIST_ITEM:
return 1; // 1.1 > 1-1
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
} }
@Override @Override
@ -204,24 +194,14 @@ class ComparableVersion implements Comparable<ComparableVersion> {
return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1 return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1
} }
switch (item.getType()) { return switch (item.getType()) {
case INT_ITEM: case INT_ITEM -> 1;
return 1; case LONG_ITEM -> Long.compare(value, ((LongItem) item).value);
case LONG_ITEM: case BIGINTEGER_ITEM -> -1;
long itemValue = ((LongItem) item).value; case STRING_ITEM -> 1; // 1.1 > 1-sp
return (value < itemValue) ? -1 : ((value == itemValue) ? 0 : 1); case LIST_ITEM -> 1; // 1.1 > 1-1
case BIGINTEGER_ITEM: default -> throw new IllegalStateException("invalid item: " + item.getClass());
return -1; };
case STRING_ITEM:
return 1; // 1.1 > 1-sp
case LIST_ITEM:
return 1; // 1.1 > 1-1
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
} }
@Override @Override
@ -278,23 +258,13 @@ class ComparableVersion implements Comparable<ComparableVersion> {
return BigInteger.ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1 return BigInteger.ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1
} }
switch (item.getType()) { return switch (item.getType()) {
case INT_ITEM: case INT_ITEM, LONG_ITEM -> 1;
case LONG_ITEM: case BIGINTEGER_ITEM -> value.compareTo(((BigIntegerItem) item).value);
return 1; case STRING_ITEM -> 1; // 1.1 > 1-sp
case LIST_ITEM -> 1; // 1.1 > 1-1
case BIGINTEGER_ITEM: default -> throw new IllegalStateException("invalid item: " + item.getClass());
return value.compareTo(((BigIntegerItem) item).value); };
case STRING_ITEM:
return 1; // 1.1 > 1-sp
case LIST_ITEM:
return 1; // 1.1 > 1-1
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
} }
@Override @Override
@ -351,18 +321,12 @@ class ComparableVersion implements Comparable<ComparableVersion> {
StringItem(String value, boolean followedByDigit) { StringItem(String value, boolean followedByDigit) {
if (followedByDigit && value.length() == 1) { if (followedByDigit && value.length() == 1) {
// a1 = alpha-1, b1 = beta-1, m1 = milestone-1 // a1 = alpha-1, b1 = beta-1, m1 = milestone-1
switch (value.charAt(0)) { value = switch (value.charAt(0)) {
case 'a': case 'a' -> "alpha";
value = "alpha"; case 'b' -> "beta";
break; case 'm' -> "milestone";
case 'b': default -> value;
value = "beta"; };
break;
case 'm':
value = "milestone";
break;
default:
}
} }
this.value = ALIASES.getProperty(value, value); this.value = ALIASES.getProperty(value, value);
} }
@ -402,21 +366,13 @@ class ComparableVersion implements Comparable<ComparableVersion> {
// 1-rc < 1, 1-ga > 1 // 1-rc < 1, 1-ga > 1
return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX); return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX);
} }
switch (item.getType()) { return switch (item.getType()) {
case INT_ITEM: case INT_ITEM, LONG_ITEM, BIGINTEGER_ITEM -> -1; // 1.any < 1.1 ?
case LONG_ITEM: case STRING_ITEM ->
case BIGINTEGER_ITEM: comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value));
return -1; // 1.any < 1.1 ? case LIST_ITEM -> -1; // 1.any < 1-1
default -> throw new IllegalStateException("invalid item: " + item.getClass());
case STRING_ITEM: };
return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value));
case LIST_ITEM:
return -1; // 1.any < 1-1
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
} }
@Override @Override
@ -484,36 +440,27 @@ class ComparableVersion implements Comparable<ComparableVersion> {
Item first = get(0); Item first = get(0);
return first.compareTo(null); return first.compareTo(null);
} }
switch (item.getType()) { return switch (item.getType()) {
case INT_ITEM: case INT_ITEM, LONG_ITEM, BIGINTEGER_ITEM -> -1; // 1-1 < 1.0.x
case LONG_ITEM: case STRING_ITEM -> 1; // 1-1 > 1-sp
case BIGINTEGER_ITEM: case LIST_ITEM -> {
return -1; // 1-1 < 1.0.x Iterator<Item> left = iterator();
Iterator<Item> right = ((ListItem) item).iterator();
while (left.hasNext() || right.hasNext()) {
Item l = left.hasNext() ? left.next() : null;
Item r = right.hasNext() ? right.next() : null;
case STRING_ITEM: // if this is shorter, then invert the compare and mul with -1
return 1; // 1-1 > 1-sp int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r);
case LIST_ITEM: if (result != 0) {
Iterator<Item> left = iterator(); yield result;
Iterator<Item> right = ((ListItem) item).iterator(); }
while (left.hasNext() || right.hasNext()) {
Item l = left.hasNext() ? left.next() : null;
Item r = right.hasNext() ? right.next() : null;
// if this is shorter, then invert the compare and mul with -1
int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r);
if (result != 0) {
return result;
} }
yield 0;
} }
default -> throw new IllegalStateException("invalid item: " + item.getClass());
return 0; };
default:
throw new IllegalStateException("invalid item: " + item.getClass());
}
} }
@Override @Override

View File

@ -48,7 +48,7 @@ public interface SecurityContextHolderStrategy {
* @since 5.8 * @since 5.8
*/ */
default Supplier<SecurityContext> getDeferredContext() { default Supplier<SecurityContext> getDeferredContext() {
return () -> getContext(); return this::getContext;
} }
/** /**

View File

@ -42,8 +42,7 @@ public class SecurityContextImpl implements SecurityContext {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof SecurityContextImpl) { if (obj instanceof SecurityContextImpl other) {
SecurityContextImpl other = (SecurityContextImpl) obj;
if ((this.getAuthentication() == null) && (other.getAuthentication() == null)) { if ((this.getAuthentication() == null) && (other.getAuthentication() == null)) {
return true; return true;
} }

View File

@ -100,13 +100,11 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener
@Override @Override
public void onApplicationEvent(AbstractSessionEvent event) { public void onApplicationEvent(AbstractSessionEvent event) {
if (event instanceof SessionDestroyedEvent) { if (event instanceof SessionDestroyedEvent sessionDestroyedEvent) {
SessionDestroyedEvent sessionDestroyedEvent = (SessionDestroyedEvent) event;
String sessionId = sessionDestroyedEvent.getId(); String sessionId = sessionDestroyedEvent.getId();
removeSessionInformation(sessionId); removeSessionInformation(sessionId);
} }
else if (event instanceof SessionIdChangedEvent) { else if (event instanceof SessionIdChangedEvent sessionIdChangedEvent) {
SessionIdChangedEvent sessionIdChangedEvent = (SessionIdChangedEvent) event;
String oldSessionId = sessionIdChangedEvent.getOldSessionId(); String oldSessionId = sessionIdChangedEvent.getOldSessionId();
if (this.sessionIds.containsKey(oldSessionId)) { if (this.sessionIds.containsKey(oldSessionId)) {
Object principal = this.sessionIds.get(oldSessionId).getPrincipal(); Object principal = this.sessionIds.get(oldSessionId).getPrincipal();

View File

@ -59,8 +59,7 @@ public class DefaultToken implements Token {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj != null && obj instanceof DefaultToken) { if (obj instanceof DefaultToken rhs) {
DefaultToken rhs = (DefaultToken) obj;
return this.key.equals(rhs.key) && this.keyCreationTime == rhs.keyCreationTime return this.key.equals(rhs.key) && this.keyCreationTime == rhs.keyCreationTime
&& this.extendedInformation.equals(rhs.extendedInformation); && this.extendedInformation.equals(rhs.extendedInformation);
} }
@ -71,7 +70,7 @@ public class DefaultToken implements Token {
public int hashCode() { public int hashCode() {
int code = 979; int code = 979;
code = code * this.key.hashCode(); code = code * this.key.hashCode();
code = code * new Long(this.keyCreationTime).hashCode(); code = code * Long.valueOf(this.keyCreationTime).hashCode();
code = code * this.extendedInformation.hashCode(); code = code * this.extendedInformation.hashCode();
return code; return code;
} }

View File

@ -142,7 +142,7 @@ public class KeyBasedPersistenceTokenService implements TokenService, Initializi
} }
private String computeServerSecretApplicableAt(long time) { private String computeServerSecretApplicableAt(long time) {
return this.serverSecret + ":" + new Long(time % this.serverInteger).intValue(); return this.serverSecret + ":" + Long.valueOf(time % this.serverInteger).intValue();
} }
/** /**

View File

@ -44,8 +44,7 @@ class UnmodifiableListDeserializer extends JsonDeserializer<List> {
JsonNode node = mapper.readTree(jp); JsonNode node = mapper.readTree(jp);
List<Object> result = new ArrayList<>(); List<Object> result = new ArrayList<>();
if (node != null) { if (node != null) {
if (node instanceof ArrayNode) { if (node instanceof ArrayNode arrayNode) {
ArrayNode arrayNode = (ArrayNode) node;
for (JsonNode elementNode : arrayNode) { for (JsonNode elementNode : arrayNode) {
result.add(mapper.readValue(elementNode.traverse(mapper), Object.class)); result.add(mapper.readValue(elementNode.traverse(mapper), Object.class));
} }

View File

@ -44,8 +44,7 @@ class UnmodifiableSetDeserializer extends JsonDeserializer<Set> {
JsonNode node = mapper.readTree(jp); JsonNode node = mapper.readTree(jp);
Set<Object> resultSet = new HashSet<>(); Set<Object> resultSet = new HashSet<>();
if (node != null) { if (node != null) {
if (node instanceof ArrayNode) { if (node instanceof ArrayNode arrayNode) {
ArrayNode arrayNode = (ArrayNode) node;
for (JsonNode elementNode : arrayNode) { for (JsonNode elementNode : arrayNode) {
resultSet.add(mapper.readValue(elementNode.traverse(mapper), Object.class)); resultSet.add(mapper.readValue(elementNode.traverse(mapper), Object.class));
} }

View File

@ -60,8 +60,7 @@ public final class MethodInvocationUtils {
// Determine the type that declares the requested method, // Determine the type that declares the requested method,
// taking into account proxies // taking into account proxies
Class<?> target = AopUtils.getTargetClass(object); Class<?> target = AopUtils.getTargetClass(object);
if (object instanceof Advised) { if (object instanceof Advised a) {
Advised a = (Advised) object;
if (!a.isProxyTargetClass()) { if (!a.isProxyTargetClass()) {
Class<?>[] possibleInterfaces = a.getProxiedInterfaces(); Class<?>[] possibleInterfaces = a.getProxiedInterfaces();
for (Class<?> possibleInterface : possibleInterfaces) { for (Class<?> possibleInterface : possibleInterfaces) {

View File

@ -17,7 +17,6 @@
package org.springframework.security.access.vote; package org.springframework.security.access.vote;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.ConfigAttribute;
@ -47,9 +46,7 @@ public class DenyAgainVoter implements AccessDecisionVoter<Object> {
@Override @Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
Iterator<ConfigAttribute> iter = attributes.iterator(); for (ConfigAttribute attribute : attributes) {
while (iter.hasNext()) {
ConfigAttribute attribute = iter.next();
if (this.supports(attribute)) { if (this.supports(attribute)) {
return ACCESS_DENIED; return ACCESS_DENIED;
} }

View File

@ -17,7 +17,6 @@
package org.springframework.security.access.vote; package org.springframework.security.access.vote;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.ConfigAttribute;
@ -49,9 +48,7 @@ public class DenyVoter implements AccessDecisionVoter<Object> {
@Override @Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
Iterator<ConfigAttribute> iter = attributes.iterator(); for (ConfigAttribute attribute : attributes) {
while (iter.hasNext()) {
ConfigAttribute attribute = iter.next();
if (this.supports(attribute)) { if (this.supports(attribute)) {
return ACCESS_DENIED; return ACCESS_DENIED;
} }

View File

@ -222,16 +222,13 @@ public class DefaultJaasAuthenticationProviderTests {
public void javadocExample() { public void javadocExample() {
String resName = "/" + getClass().getName().replace('.', '/') + ".xml"; String resName = "/" + getClass().getName().replace('.', '/') + ".xml";
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(resName); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(resName);
context.registerShutdownHook(); try (context) {
try { context.registerShutdownHook();
this.provider = context.getBean(DefaultJaasAuthenticationProvider.class); this.provider = context.getBean(DefaultJaasAuthenticationProvider.class);
Authentication auth = this.provider.authenticate(this.token); Authentication auth = this.provider.authenticate(this.token);
assertThat(auth.isAuthenticated()).isEqualTo(true); assertThat(auth.isAuthenticated()).isEqualTo(true);
assertThat(auth.getPrincipal()).isEqualTo(this.token.getPrincipal()); assertThat(auth.getPrincipal()).isEqualTo(this.token.getPrincipal());
} }
finally {
context.close();
}
} }
private void verifyFailedLogin() { private void verifyFailedLogin() {

View File

@ -174,8 +174,7 @@ public class JaasAuthenticationProviderTests {
assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue(); assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue();
boolean foundit = false; boolean foundit = false;
for (GrantedAuthority a : list) { for (GrantedAuthority a : list) {
if (a instanceof JaasGrantedAuthority) { if (a instanceof JaasGrantedAuthority grant) {
JaasGrantedAuthority grant = (JaasGrantedAuthority) a;
assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority") assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority")
.isNotNull(); .isNotNull();
foundit = true; foundit = true;

View File

@ -30,8 +30,7 @@ public class TestCallbackHandler implements JaasAuthenticationCallbackHandler {
@Override @Override
public void handle(Callback callback, Authentication auth) { public void handle(Callback callback, Authentication auth) {
if (callback instanceof TextInputCallback) { if (callback instanceof TextInputCallback tic) {
TextInputCallback tic = (TextInputCallback) callback;
tic.setText(auth.getPrincipal().toString()); tic.setText(auth.getPrincipal().toString());
} }
} }

View File

@ -38,7 +38,7 @@ import static org.mockito.Mockito.verifyNoInteractions;
*/ */
public class SpringAuthorizationEventPublisherTests { public class SpringAuthorizationEventPublisherTests {
Supplier<Authentication> authentication = () -> TestAuthentication.authenticatedUser(); Supplier<Authentication> authentication = TestAuthentication::authenticatedUser;
ApplicationEventPublisher applicationEventPublisher; ApplicationEventPublisher applicationEventPublisher;

View File

@ -68,13 +68,7 @@ final class StaticFinalReflectionUtils {
field.set(null, newValue); field.set(null, newValue);
} }
} }
catch (SecurityException ex) { catch (SecurityException | IllegalAccessException | IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
catch (IllegalArgumentException ex) {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }

View File

@ -57,7 +57,7 @@ class ThreadLocalSecurityContextHolderStrategyTests {
void deferredContextValidates() { void deferredContextValidates() {
this.strategy.setDeferredContext(() -> null); this.strategy.setDeferredContext(() -> null);
Supplier<SecurityContext> deferredContext = this.strategy.getDeferredContext(); Supplier<SecurityContext> deferredContext = this.strategy.getDeferredContext();
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> deferredContext.get()); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(deferredContext::get);
} }
@Test @Test

View File

@ -58,19 +58,14 @@ final class Argon2EncodingUtils {
*/ */
static String encode(byte[] hash, Argon2Parameters parameters) throws IllegalArgumentException { static String encode(byte[] hash, Argon2Parameters parameters) throws IllegalArgumentException {
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
switch (parameters.getType()) { stringBuilder.append(
case Argon2Parameters.ARGON2_d: switch (parameters.getType()) {
stringBuilder.append("$argon2d"); case Argon2Parameters.ARGON2_d -> "$argon2d";
break; case Argon2Parameters.ARGON2_i -> "$argon2i";
case Argon2Parameters.ARGON2_i: case Argon2Parameters.ARGON2_id -> "$argon2id";
stringBuilder.append("$argon2i"); default -> throw new IllegalArgumentException("Invalid algorithm type: " + parameters.getType());
break; }
case Argon2Parameters.ARGON2_id: );
stringBuilder.append("$argon2id");
break;
default:
throw new IllegalArgumentException("Invalid algorithm type: " + parameters.getType());
}
stringBuilder.append("$v=").append(parameters.getVersion()).append("$m=").append(parameters.getMemory()) stringBuilder.append("$v=").append(parameters.getVersion()).append("$m=").append(parameters.getMemory())
.append(",t=").append(parameters.getIterations()).append(",p=").append(parameters.getLanes()); .append(",t=").append(parameters.getIterations()).append(",p=").append(parameters.getLanes());
if (parameters.getSalt() != null) { if (parameters.getSalt() != null) {
@ -107,19 +102,12 @@ final class Argon2EncodingUtils {
throw new IllegalArgumentException("Invalid encoded Argon2-hash"); throw new IllegalArgumentException("Invalid encoded Argon2-hash");
} }
int currentPart = 1; int currentPart = 1;
switch (parts[currentPart++]) { paramsBuilder = switch (parts[currentPart++]) {
case "argon2d": case "argon2d" -> new Argon2Parameters.Builder(Argon2Parameters.ARGON2_d);
paramsBuilder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_d); case "argon2i" -> new Argon2Parameters.Builder(Argon2Parameters.ARGON2_i);
break; case "argon2id" -> new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id);
case "argon2i": default -> throw new IllegalArgumentException("Invalid algorithm type: " + parts[0]);
paramsBuilder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_i); };
break;
case "argon2id":
paramsBuilder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id);
break;
default:
throw new IllegalArgumentException("Invalid algorithm type: " + parts[0]);
}
if (parts[currentPart].startsWith("v=")) { if (parts[currentPart].startsWith("v=")) {
paramsBuilder.withVersion(Integer.parseInt(parts[currentPart].substring(2))); paramsBuilder.withVersion(Integer.parseInt(parts[currentPart].substring(2)));
currentPart++; currentPart++;

View File

@ -260,43 +260,30 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
String hexString = Integer.toHexString(code); String hexString = Integer.toHexString(code);
Throwable cause = new ActiveDirectoryAuthenticationException(hexString, exception.getMessage(), exception); Throwable cause = new ActiveDirectoryAuthenticationException(hexString, exception.getMessage(), exception);
switch (code) { switch (code) {
case PASSWORD_EXPIRED: case PASSWORD_EXPIRED -> throw new CredentialsExpiredException(this.messages.getMessage(
throw new CredentialsExpiredException(this.messages.getMessage(
"LdapAuthenticationProvider.credentialsExpired", "User credentials have expired"), cause); "LdapAuthenticationProvider.credentialsExpired", "User credentials have expired"), cause);
case ACCOUNT_DISABLED: case ACCOUNT_DISABLED -> throw new DisabledException(
throw new DisabledException(
this.messages.getMessage("LdapAuthenticationProvider.disabled", "User is disabled"), cause); this.messages.getMessage("LdapAuthenticationProvider.disabled", "User is disabled"), cause);
case ACCOUNT_EXPIRED: case ACCOUNT_EXPIRED -> throw new AccountExpiredException(
throw new AccountExpiredException(
this.messages.getMessage("LdapAuthenticationProvider.expired", "User account has expired"), cause); this.messages.getMessage("LdapAuthenticationProvider.expired", "User account has expired"), cause);
case ACCOUNT_LOCKED: case ACCOUNT_LOCKED -> throw new LockedException(
throw new LockedException(
this.messages.getMessage("LdapAuthenticationProvider.locked", "User account is locked"), cause); this.messages.getMessage("LdapAuthenticationProvider.locked", "User account is locked"), cause);
default: default -> throw badCredentials(cause);
throw badCredentials(cause);
} }
} }
private String subCodeToLogMessage(int code) { private String subCodeToLogMessage(int code) {
switch (code) { return switch (code) {
case USERNAME_NOT_FOUND: case USERNAME_NOT_FOUND -> "User was not found in directory";
return "User was not found in directory"; case INVALID_PASSWORD -> "Supplied password was invalid";
case INVALID_PASSWORD: case NOT_PERMITTED -> "User not permitted to logon at this time";
return "Supplied password was invalid"; case PASSWORD_EXPIRED -> "Password has expired";
case NOT_PERMITTED: case ACCOUNT_DISABLED -> "Account is disabled";
return "User not permitted to logon at this time"; case ACCOUNT_EXPIRED -> "Account expired";
case PASSWORD_EXPIRED: case PASSWORD_NEEDS_RESET -> "User must reset password";
return "Password has expired"; case ACCOUNT_LOCKED -> "Account locked";
case ACCOUNT_DISABLED: default -> "Unknown (error code " + Integer.toHexString(code) + ")";
return "Account is disabled"; };
case ACCOUNT_EXPIRED:
return "Account expired";
case PASSWORD_NEEDS_RESET:
return "User must reset password";
case ACCOUNT_LOCKED:
return "Account locked";
}
return "Unknown (error code " + Integer.toHexString(code) + ")";
} }
private BadCredentialsException badCredentials() { private BadCredentialsException badCredentials() {

View File

@ -85,8 +85,7 @@ public final class MessageMatcherDelegatingAuthorizationManager implements Autho
if (!matcher.matches((Message) message)) { if (!matcher.matches((Message) message)) {
return null; return null;
} }
if (matcher instanceof SimpDestinationMessageMatcher) { if (matcher instanceof SimpDestinationMessageMatcher simp) {
SimpDestinationMessageMatcher simp = (SimpDestinationMessageMatcher) matcher;
return new MessageAuthorizationContext<>(message, simp.extractPathVariables(message)); return new MessageAuthorizationContext<>(message, simp.extractPathVariables(message));
} }
if (matcher instanceof Builder.LazySimpDestinationMessageMatcher) { if (matcher instanceof Builder.LazySimpDestinationMessageMatcher) {
@ -111,7 +110,7 @@ public final class MessageMatcherDelegatingAuthorizationManager implements Autho
private final List<Entry<AuthorizationManager<MessageAuthorizationContext<?>>>> mappings = new ArrayList<>(); private final List<Entry<AuthorizationManager<MessageAuthorizationContext<?>>>> mappings = new ArrayList<>();
private Supplier<PathMatcher> pathMatcher = () -> new AntPathMatcher(); private Supplier<PathMatcher> pathMatcher = AntPathMatcher::new;
public Builder() { public Builder() {
} }

View File

@ -57,10 +57,9 @@ public class SimpMessageTypeMatcher implements MessageMatcher<Object> {
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof SimpMessageTypeMatcher)) { if (!(other instanceof SimpMessageTypeMatcher otherMatcher)) {
return false; return false;
} }
SimpMessageTypeMatcher otherMatcher = (SimpMessageTypeMatcher) other;
return ObjectUtils.nullSafeEquals(this.typeToMatch, otherMatcher.typeToMatch); return ObjectUtils.nullSafeEquals(this.typeToMatch, otherMatcher.typeToMatch);
} }

View File

@ -396,8 +396,7 @@ public class JdbcOAuth2AuthorizedClientService implements OAuth2AuthorizedClient
@Override @Override
protected void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue) throws SQLException { protected void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue) throws SQLException {
if (argValue instanceof SqlParameterValue) { if (argValue instanceof SqlParameterValue paramValue) {
SqlParameterValue paramValue = (SqlParameterValue) argValue;
if (paramValue.getSqlType() == Types.BLOB) { if (paramValue.getSqlType() == Types.BLOB) {
if (paramValue.getValue() != null) { if (paramValue.getValue() != null) {
Assert.isInstanceOf(byte[].class, paramValue.getValue(), Assert.isInstanceOf(byte[].class, paramValue.getValue(),

View File

@ -110,9 +110,8 @@ public class RemoveAuthorizedClientOAuth2AuthorizationFailureHandler implements
@Override @Override
public void onAuthorizationFailure(OAuth2AuthorizationException authorizationException, Authentication principal, public void onAuthorizationFailure(OAuth2AuthorizationException authorizationException, Authentication principal,
Map<String, Object> attributes) { Map<String, Object> attributes) {
if (authorizationException instanceof ClientAuthorizationException if (authorizationException instanceof ClientAuthorizationException clientAuthorizationException
&& hasRemovalErrorCode(authorizationException)) { && hasRemovalErrorCode(authorizationException)) {
ClientAuthorizationException clientAuthorizationException = (ClientAuthorizationException) authorizationException;
this.delegate.removeAuthorizedClient(clientAuthorizationException.getClientRegistrationId(), principal, this.delegate.removeAuthorizedClient(clientAuthorizationException.getClientRegistrationId(), principal,
attributes); attributes);
} }

View File

@ -112,9 +112,8 @@ public class RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler
@Override @Override
public Mono<Void> onAuthorizationFailure(OAuth2AuthorizationException authorizationException, public Mono<Void> onAuthorizationFailure(OAuth2AuthorizationException authorizationException,
Authentication principal, Map<String, Object> attributes) { Authentication principal, Map<String, Object> attributes) {
if (authorizationException instanceof ClientAuthorizationException if (authorizationException instanceof ClientAuthorizationException clientAuthorizationException
&& hasRemovalErrorCode(authorizationException)) { && hasRemovalErrorCode(authorizationException)) {
ClientAuthorizationException clientAuthorizationException = (ClientAuthorizationException) authorizationException;
return this.delegate.removeAuthorizedClient(clientAuthorizationException.getClientRegistrationId(), return this.delegate.removeAuthorizedClient(clientAuthorizationException.getClientRegistrationId(),
principal, attributes); principal, attributes);
} }

View File

@ -70,13 +70,13 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests {
@Test @Test
public void authenticateWhenErrorThenOAuth2AuthorizationException() { public void authenticateWhenErrorThenOAuth2AuthorizationException() {
this.authorizationResponse = TestOAuth2AuthorizationResponses.error(); this.authorizationResponse = TestOAuth2AuthorizationResponses.error();
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate()); assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(this::authenticate);
} }
@Test @Test
public void authenticateWhenStateNotEqualThenOAuth2AuthorizationException() { public void authenticateWhenStateNotEqualThenOAuth2AuthorizationException() {
this.authorizationRequest.state("notequal"); this.authorizationRequest.state("notequal");
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate()); assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(this::authenticate);
} }
@Test @Test

View File

@ -478,12 +478,11 @@ public class ClientRegistrationsTests {
final Dispatcher dispatcher = new Dispatcher() { final Dispatcher dispatcher = new Dispatcher() {
@Override @Override
public MockResponse dispatch(RecordedRequest request) { public MockResponse dispatch(RecordedRequest request) {
switch (request.getPath()) { return switch (request.getPath()) {
case "/.well-known/oauth-authorization-server/issuer1": case "/.well-known/oauth-authorization-server/issuer1", "/.well-known/oauth-authorization-server/" ->
case "/.well-known/oauth-authorization-server/": buildSuccessMockResponse(responseBody);
return buildSuccessMockResponse(responseBody); default -> new MockResponse().setResponseCode(404);
} };
return new MockResponse().setResponseCode(404);
} }
}; };
this.server.setDispatcher(dispatcher); this.server.setDispatcher(dispatcher);
@ -514,12 +513,11 @@ public class ClientRegistrationsTests {
final Dispatcher dispatcher = new Dispatcher() { final Dispatcher dispatcher = new Dispatcher() {
@Override @Override
public MockResponse dispatch(RecordedRequest request) { public MockResponse dispatch(RecordedRequest request) {
switch (request.getPath()) { return switch (request.getPath()) {
case "/issuer1/.well-known/openid-configuration": case "/issuer1/.well-known/openid-configuration", "/.well-known/openid-configuration/" ->
case "/.well-known/openid-configuration/": buildSuccessMockResponse(responseBody);
return buildSuccessMockResponse(responseBody); default -> new MockResponse().setResponseCode(404);
} };
return new MockResponse().setResponseCode(404);
} }
}; };
this.server.setDispatcher(dispatcher); this.server.setDispatcher(dispatcher);

View File

@ -87,7 +87,7 @@ final class ReactiveJwtDecoderProviderConfigurationUtils {
} }
Assert.notEmpty(jwsAlgorithms, "Failed to find any algorithms from the JWK set"); Assert.notEmpty(jwsAlgorithms, "Failed to find any algorithms from the JWK set");
return jwsAlgorithms; return jwsAlgorithms;
}).onErrorMap(KeySourceException.class, (ex) -> new IllegalStateException(ex)); }).onErrorMap(KeySourceException.class, IllegalStateException::new);
} }
static Mono<Map<String, Object>> getConfigurationForIssuerLocation(String issuer, WebClient web) { static Mono<Map<String, Object>> getConfigurationForIssuerLocation(String issuer, WebClient web) {

View File

@ -61,10 +61,10 @@ class ReactiveRemoteJWKSource implements ReactiveJWKSource {
public Mono<List<JWK>> get(JWKSelector jwkSelector) { public Mono<List<JWK>> get(JWKSelector jwkSelector) {
// @formatter:off // @formatter:off
return this.cachedJWKSet.get() return this.cachedJWKSet.get()
.switchIfEmpty(Mono.defer(() -> getJWKSet())) .switchIfEmpty(Mono.defer(this::getJWKSet))
.flatMap((jwkSet) -> get(jwkSelector, jwkSet)) .flatMap((jwkSet) -> get(jwkSelector, jwkSet))
.switchIfEmpty(Mono.defer(() -> getJWKSet() .switchIfEmpty(Mono.defer(() -> getJWKSet()
.map((jwkSet) -> jwkSelector.select(jwkSet))) .map(jwkSelector::select))
); );
// @formatter:on // @formatter:on
} }

View File

@ -101,10 +101,9 @@ public final class OpaqueTokenAuthenticationProvider implements AuthenticationPr
*/ */
@Override @Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!(authentication instanceof BearerTokenAuthenticationToken)) { if (!(authentication instanceof BearerTokenAuthenticationToken bearer)) {
return null; return null;
} }
BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication;
OAuth2AuthenticatedPrincipal principal = getOAuth2AuthenticatedPrincipal(bearer); OAuth2AuthenticatedPrincipal principal = getOAuth2AuthenticatedPrincipal(bearer);
Authentication result = this.authenticationConverter.convert(bearer.getToken(), principal); Authentication result = this.authenticationConverter.convert(bearer.getToken(), principal);
if (result == null) { if (result == null) {

View File

@ -74,8 +74,7 @@ public final class BearerTokenAuthenticationEntryPoint implements Authentication
if (StringUtils.hasText(error.getUri())) { if (StringUtils.hasText(error.getUri())) {
parameters.put("error_uri", error.getUri()); parameters.put("error_uri", error.getUri());
} }
if (error instanceof BearerTokenError) { if (error instanceof BearerTokenError bearerTokenError) {
BearerTokenError bearerTokenError = (BearerTokenError) error;
if (StringUtils.hasText(bearerTokenError.getScope())) { if (StringUtils.hasText(bearerTokenError.getScope())) {
parameters.put("scope", bearerTokenError.getScope()); parameters.put("scope", bearerTokenError.getScope());
} }

View File

@ -82,8 +82,7 @@ public final class BearerTokenServerAuthenticationEntryPoint implements ServerAu
if (StringUtils.hasText(error.getUri())) { if (StringUtils.hasText(error.getUri())) {
parameters.put("error_uri", error.getUri()); parameters.put("error_uri", error.getUri());
} }
if (error instanceof BearerTokenError) { if (error instanceof BearerTokenError bearerTokenError) {
BearerTokenError bearerTokenError = (BearerTokenError) error;
if (StringUtils.hasText(bearerTokenError.getScope())) { if (StringUtils.hasText(bearerTokenError.getScope())) {
parameters.put("scope", bearerTokenError.getScope()); parameters.put("scope", bearerTokenError.getScope());
} }

View File

@ -91,9 +91,9 @@ class PayloadInterceptorRSocket extends RSocketProxy {
public Flux<Payload> requestChannel(Publisher<Payload> payloads) { public Flux<Payload> requestChannel(Publisher<Payload> payloads) {
return Flux.from(payloads).switchOnFirst((signal, innerFlux) -> { return Flux.from(payloads).switchOnFirst((signal, innerFlux) -> {
Payload firstPayload = signal.get(); Payload firstPayload = signal.get();
return intercept(PayloadExchangeType.REQUEST_CHANNEL, firstPayload).flatMapMany((context) -> innerFlux return intercept(PayloadExchangeType.REQUEST_CHANNEL, firstPayload).flatMapMany(
.index().concatMap((tuple) -> justOrIntercept(tuple.getT1(), tuple.getT2())) (context) -> innerFlux.index().concatMap((tuple) -> justOrIntercept(tuple.getT1(), tuple.getT2()))
.transform((securedPayloads) -> this.source.requestChannel(securedPayloads)).contextWrite(context)); .transform(this.source::requestChannel).contextWrite(context));
}); });
} }
@ -112,8 +112,8 @@ class PayloadInterceptorRSocket extends RSocketProxy {
ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors); ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors);
DefaultPayloadExchange exchange = new DefaultPayloadExchange(type, payload, this.metadataMimeType, DefaultPayloadExchange exchange = new DefaultPayloadExchange(type, payload, this.metadataMimeType,
this.dataMimeType); this.dataMimeType);
return chain.next(exchange).then(Mono.fromCallable(() -> chain.getContext())) return chain.next(exchange).then(Mono.fromCallable(chain::getContext)).defaultIfEmpty(Context.empty())
.defaultIfEmpty(Context.empty()).contextWrite(this.context); .contextWrite(this.context);
}); });
} }

View File

@ -83,8 +83,7 @@ class PayloadSocketAcceptor implements SocketAcceptor {
ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors); ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors);
DefaultPayloadExchange exchange = new DefaultPayloadExchange(PayloadExchangeType.SETUP, payload, DefaultPayloadExchange exchange = new DefaultPayloadExchange(PayloadExchangeType.SETUP, payload,
metadataMimeType, dataMimeType); metadataMimeType, dataMimeType);
return chain.next(exchange).then(Mono.fromCallable(() -> chain.getContext())) return chain.next(exchange).then(Mono.fromCallable(chain::getContext)).defaultIfEmpty(Context.empty());
.defaultIfEmpty(Context.empty());
}); });
} }

View File

@ -16,9 +16,6 @@
package org.springframework.security.rsocket.util.matcher; package org.springframework.security.rsocket.util.matcher;
import reactor.core.publisher.Mono;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadExchangeType; import org.springframework.security.rsocket.api.PayloadExchangeType;
/** /**
@ -30,37 +27,17 @@ public final class PayloadExchangeMatchers {
} }
public static PayloadExchangeMatcher setup() { public static PayloadExchangeMatcher setup() {
return new PayloadExchangeMatcher() { return (exchange) -> PayloadExchangeType.SETUP.equals(exchange.getType())
? PayloadExchangeMatcher.MatchResult.match() : PayloadExchangeMatcher.MatchResult.notMatch();
@Override
public Mono<MatchResult> matches(PayloadExchange exchange) {
return PayloadExchangeType.SETUP.equals(exchange.getType()) ? MatchResult.match()
: MatchResult.notMatch();
}
};
} }
public static PayloadExchangeMatcher anyRequest() { public static PayloadExchangeMatcher anyRequest() {
return new PayloadExchangeMatcher() { return (exchange) -> exchange.getType().isRequest() ? PayloadExchangeMatcher.MatchResult.match()
: PayloadExchangeMatcher.MatchResult.notMatch();
@Override
public Mono<MatchResult> matches(PayloadExchange exchange) {
return exchange.getType().isRequest() ? MatchResult.match() : MatchResult.notMatch();
}
};
} }
public static PayloadExchangeMatcher anyExchange() { public static PayloadExchangeMatcher anyExchange() {
return new PayloadExchangeMatcher() { return (exchange) -> PayloadExchangeMatcher.MatchResult.match();
@Override
public Mono<MatchResult> matches(PayloadExchange exchange) {
return MatchResult.match();
}
};
} }
} }

View File

@ -52,8 +52,8 @@ public class RoutePayloadExchangeMatcher implements PayloadExchangeMatcher {
Map<String, Object> metadata = this.metadataExtractor.extract(exchange.getPayload(), Map<String, Object> metadata = this.metadataExtractor.extract(exchange.getPayload(),
exchange.getMetadataMimeType()); exchange.getMetadataMimeType());
return Optional.ofNullable((String) metadata.get(MetadataExtractor.ROUTE_KEY)) return Optional.ofNullable((String) metadata.get(MetadataExtractor.ROUTE_KEY))
.map((routeValue) -> this.routeMatcher.parseRoute(routeValue)) .map(this.routeMatcher::parseRoute)
.map((route) -> this.routeMatcher.matchAndExtract(this.pattern, route)).map((v) -> MatchResult.match(v)) .map((route) -> this.routeMatcher.matchAndExtract(this.pattern, route)).map(MatchResult::match)
.orElse(MatchResult.notMatch()); .orElse(MatchResult.notMatch());
} }

View File

@ -129,8 +129,7 @@ public class Saml2WebSsoAuthenticationFilter extends AbstractAuthenticationProce
private void setAuthenticationRequestRepositoryIntoAuthenticationConverter( private void setAuthenticationRequestRepositoryIntoAuthenticationConverter(
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) { Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) {
if (this.authenticationConverter instanceof Saml2AuthenticationTokenConverter) { if (this.authenticationConverter instanceof Saml2AuthenticationTokenConverter authenticationTokenConverter) {
Saml2AuthenticationTokenConverter authenticationTokenConverter = (Saml2AuthenticationTokenConverter) this.authenticationConverter;
authenticationTokenConverter.setAuthenticationRequestRepository(authenticationRequestRepository); authenticationTokenConverter.setAuthenticationRequestRepository(authenticationRequestRepository);
} }
} }

View File

@ -48,10 +48,9 @@ public class RequestKey {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof RequestKey)) { if (!(obj instanceof RequestKey key)) {
return false; return false;
} }
RequestKey key = (RequestKey) obj;
if (!this.url.equals(key.url)) { if (!this.url.equals(key.url)) {
return false; return false;
} }

View File

@ -167,7 +167,7 @@ public class TokenBasedRememberMeServices extends AbstractRememberMeServices {
private long getTokenExpiryTime(String[] cookieTokens) { private long getTokenExpiryTime(String[] cookieTokens) {
try { try {
return new Long(cookieTokens[1]); return Long.valueOf(cookieTokens[1]);
} }
catch (NumberFormatException nfe) { catch (NumberFormatException nfe) {
throw new InvalidCookieException( throw new InvalidCookieException(

View File

@ -385,7 +385,7 @@ public class DigestAuthenticationFilter extends GenericFilterBean implements Mes
} }
// Extract expiry time from nonce // Extract expiry time from nonce
try { try {
this.nonceExpiryTime = new Long(nonceTokens[0]); this.nonceExpiryTime = Long.valueOf(nonceTokens[0]);
} }
catch (NumberFormatException nfe) { catch (NumberFormatException nfe) {
throw new BadCredentialsException(DigestAuthenticationFilter.this.messages.getMessage( throw new BadCredentialsException(DigestAuthenticationFilter.this.messages.getMessage(

View File

@ -46,7 +46,7 @@ public class ServerFormLoginAuthenticationConverter implements Function<ServerWe
@Override @Override
@Deprecated @Deprecated
public Mono<Authentication> apply(ServerWebExchange exchange) { public Mono<Authentication> apply(ServerWebExchange exchange) {
return exchange.getFormData().map((data) -> createAuthentication(data)); return exchange.getFormData().map(this::createAuthentication);
} }
private UsernamePasswordAuthenticationToken createAuthentication(MultiValueMap<String, String> data) { private UsernamePasswordAuthenticationToken createAuthentication(MultiValueMap<String, String> data) {

View File

@ -277,8 +277,7 @@ public class SwitchUserWebFilter implements WebFilter {
private Optional<Authentication> extractSourceAuthentication(Authentication currentAuthentication) { private Optional<Authentication> extractSourceAuthentication(Authentication currentAuthentication) {
// iterate over granted authorities and find the 'switch user' authority // iterate over granted authorities and find the 'switch user' authority
for (GrantedAuthority authority : currentAuthentication.getAuthorities()) { for (GrantedAuthority authority : currentAuthentication.getAuthorities()) {
if (authority instanceof SwitchUserGrantedAuthority) { if (authority instanceof SwitchUserGrantedAuthority switchAuthority) {
SwitchUserGrantedAuthority switchAuthority = (SwitchUserGrantedAuthority) authority;
return Optional.of(switchAuthority.getSource()); return Optional.of(switchAuthority.getSource());
} }
} }

View File

@ -41,7 +41,7 @@ public class ThrowableAnalyzer {
* *
* @see Throwable#getCause() * @see Throwable#getCause()
*/ */
public static final ThrowableCauseExtractor DEFAULT_EXTRACTOR = (throwable) -> throwable.getCause(); public static final ThrowableCauseExtractor DEFAULT_EXTRACTOR = Throwable::getCause;
/** /**
* Default extractor for {@link InvocationTargetException} instances. * Default extractor for {@link InvocationTargetException} instances.

View File

@ -226,10 +226,9 @@ public final class AntPathRequestMatcher implements RequestMatcher, RequestVaria
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof AntPathRequestMatcher)) { if (!(obj instanceof AntPathRequestMatcher other)) {
return false; return false;
} }
AntPathRequestMatcher other = (AntPathRequestMatcher) obj;
return this.pattern.equals(other.pattern) && this.httpMethod == other.httpMethod return this.pattern.equals(other.pattern) && this.httpMethod == other.httpMethod
&& this.caseSensitive == other.caseSensitive; && this.caseSensitive == other.caseSensitive;
} }

View File

@ -88,7 +88,7 @@ public class MediaTypeRequestMatcherTests {
@Test @Test
public void constructorWhenEmptyMediaTypeThenIAE() { public void constructorWhenEmptyMediaTypeThenIAE() {
assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeRequestMatcher()); assertThatIllegalArgumentException().isThrownBy(MediaTypeRequestMatcher::new);
} }
@Test @Test