Merge branch '6.0.x' into 6.1.x
Closes gh-13883
This commit is contained in:
@@ -43,6 +43,7 @@ import java.lang.annotation.Target;
|
||||
* @Secured({ "ROLE_ADMIN" })
|
||||
* public void delete(Contact contact);
|
||||
* </pre>
|
||||
*
|
||||
* @author Mark St.Godard
|
||||
*/
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ public class SecuredAnnotationSecurityMetadataSource extends AbstractFallbackMet
|
||||
Assert.notNull(annotationMetadataExtractor, "annotationMetadataExtractor cannot be null");
|
||||
this.annotationExtractor = annotationMetadataExtractor;
|
||||
this.annotationType = (Class<? extends Annotation>) GenericTypeResolver
|
||||
.resolveTypeArgument(this.annotationExtractor.getClass(), AnnotationMetadataExtractor.class);
|
||||
.resolveTypeArgument(this.annotationExtractor.getClass(), AnnotationMetadataExtractor.class);
|
||||
Assert.notNull(this.annotationType, () -> this.annotationExtractor.getClass().getName()
|
||||
+ " must supply a generic parameter for AnnotationMetadataExtractor");
|
||||
}
|
||||
|
||||
+1
-1
@@ -119,7 +119,7 @@ public class DefaultMethodSecurityExpressionHandler extends AbstractSecurityExpr
|
||||
@Override
|
||||
public Object filter(Object filterTarget, Expression filterExpression, EvaluationContext ctx) {
|
||||
MethodSecurityExpressionOperations rootObject = (MethodSecurityExpressionOperations) ctx.getRootObject()
|
||||
.getValue();
|
||||
.getValue();
|
||||
this.logger.debug(LogMessage.format("Filtering with expression: %s", filterExpression.getExpressionString()));
|
||||
if (filterTarget instanceof Collection) {
|
||||
return filterCollection((Collection<?>) filterTarget, filterExpression, ctx, rootObject);
|
||||
|
||||
+4
-4
@@ -123,7 +123,7 @@ public abstract class AbstractSecurityInterceptor
|
||||
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
@@ -182,7 +182,7 @@ public abstract class AbstractSecurityInterceptor
|
||||
}
|
||||
if (unsupportedAttrs.size() != 0) {
|
||||
this.logger
|
||||
.trace("Did not validate configuration attributes since validateConfigurationAttributes is false");
|
||||
.trace("Did not validate configuration attributes since validateConfigurationAttributes is false");
|
||||
throw new IllegalArgumentException("Unsupported configuration attributes: " + unsupportedAttrs);
|
||||
}
|
||||
else {
|
||||
@@ -276,8 +276,8 @@ public abstract class AbstractSecurityInterceptor
|
||||
if (token != null && token.isContextHolderRefreshRequired()) {
|
||||
this.securityContextHolderStrategy.setContext(token.getSecurityContext());
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug(LogMessage.of(
|
||||
() -> "Reverted to original authentication " + token.getSecurityContext().getAuthentication()));
|
||||
this.logger.debug(LogMessage
|
||||
.of(() -> "Reverted to original authentication " + token.getSecurityContext().getAuthentication()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -62,7 +62,7 @@ public class MethodInvocationPrivilegeEvaluator implements InitializingBean {
|
||||
Assert.notNull(invocation, "MethodInvocation required");
|
||||
Assert.notNull(invocation.getMethod(), "MethodInvocation must provide a non-null getMethod()");
|
||||
Collection<ConfigAttribute> attrs = this.securityInterceptor.obtainSecurityMetadataSource()
|
||||
.getAttributes(invocation);
|
||||
.getAttributes(invocation);
|
||||
if (attrs == null) {
|
||||
return !this.securityInterceptor.isRejectPublicInvocations();
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ import org.springframework.security.core.parameters.AnnotationParameterNameDisco
|
||||
* contain the parameter names.
|
||||
*
|
||||
* @see AnnotationParameterNameDiscoverer
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
* @deprecated use @{code org.springframework.security.core.parameters.P}
|
||||
|
||||
+14
-14
@@ -97,7 +97,7 @@ public class PrePostAdviceReactiveMethodInterceptor implements MethodInterceptor
|
||||
|
||||
boolean isSuspendingFunction = KotlinDetector.isSuspendingFunction(method);
|
||||
boolean hasFlowReturnType = COROUTINES_FLOW_CLASS_NAME
|
||||
.equals(new MethodParameter(method, RETURN_TYPE_METHOD_PARAMETER_INDEX).getParameterType().getName());
|
||||
.equals(new MethodParameter(method, RETURN_TYPE_METHOD_PARAMETER_INDEX).getParameterType().getName());
|
||||
boolean hasReactiveReturnType = Publisher.class.isAssignableFrom(returnType) || isSuspendingFunction
|
||||
|| hasFlowReturnType;
|
||||
|
||||
@@ -119,41 +119,41 @@ public class PrePostAdviceReactiveMethodInterceptor implements MethodInterceptor
|
||||
PostInvocationAttribute attr = findPostInvocationAttribute(attributes);
|
||||
if (Mono.class.isAssignableFrom(returnType)) {
|
||||
return toInvoke.flatMap((auth) -> PrePostAdviceReactiveMethodInterceptor.<Mono<?>>proceed(invocation)
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
}
|
||||
if (Flux.class.isAssignableFrom(returnType)) {
|
||||
return toInvoke.flatMapMany((auth) -> PrePostAdviceReactiveMethodInterceptor.<Flux<?>>proceed(invocation)
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
}
|
||||
if (hasFlowReturnType) {
|
||||
Flux<?> response;
|
||||
if (isSuspendingFunction) {
|
||||
response = toInvoke.flatMapMany((auth) -> Flux
|
||||
.from(CoroutinesUtils.invokeSuspendingFunction(invocation.getMethod(), invocation.getThis(),
|
||||
invocation.getArguments()))
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
.from(CoroutinesUtils.invokeSuspendingFunction(invocation.getMethod(), invocation.getThis(),
|
||||
invocation.getArguments()))
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
}
|
||||
else {
|
||||
ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(returnType);
|
||||
Assert.state(adapter != null, () -> "The returnType " + returnType + " on " + method
|
||||
+ " must have a org.springframework.core.ReactiveAdapter registered");
|
||||
response = toInvoke.flatMapMany((auth) -> Flux
|
||||
.from(adapter.toPublisher(PrePostAdviceReactiveMethodInterceptor.flowProceed(invocation)))
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
.from(adapter.toPublisher(PrePostAdviceReactiveMethodInterceptor.flowProceed(invocation)))
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
}
|
||||
return KotlinDelegate.asFlow(response);
|
||||
}
|
||||
if (isSuspendingFunction) {
|
||||
Mono<?> response = toInvoke.flatMap((auth) -> Mono
|
||||
.from(CoroutinesUtils.invokeSuspendingFunction(invocation.getMethod(), invocation.getThis(),
|
||||
invocation.getArguments()))
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
.from(CoroutinesUtils.invokeSuspendingFunction(invocation.getMethod(), invocation.getThis(),
|
||||
invocation.getArguments()))
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
return KotlinDelegate.awaitSingleOrNull(response,
|
||||
invocation.getArguments()[invocation.getArguments().length - 1]);
|
||||
}
|
||||
return toInvoke.flatMapMany(
|
||||
(auth) -> Flux.from(PrePostAdviceReactiveMethodInterceptor.<Publisher<?>>proceed(invocation))
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
return toInvoke
|
||||
.flatMapMany((auth) -> Flux.from(PrePostAdviceReactiveMethodInterceptor.<Publisher<?>>proceed(invocation))
|
||||
.map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r));
|
||||
}
|
||||
|
||||
private static <T extends Publisher<?>> T proceed(final MethodInvocation invocation) {
|
||||
|
||||
+2
-2
@@ -130,8 +130,8 @@ public class PrePostAnnotationSecurityMetadataSource extends AbstractMethodSecur
|
||||
// actually implement the method)
|
||||
annotation = AnnotationUtils.findAnnotation(specificMethod.getDeclaringClass(), annotationClass);
|
||||
if (annotation != null) {
|
||||
this.logger.debug(
|
||||
LogMessage.format("%s found on: %s", annotation, specificMethod.getDeclaringClass().getName()));
|
||||
this.logger
|
||||
.debug(LogMessage.format("%s found on: %s", annotation, specificMethod.getDeclaringClass().getName()));
|
||||
return annotation;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -63,13 +63,13 @@ public class AffirmativeBased extends AbstractAccessDecisionManager {
|
||||
for (AccessDecisionVoter voter : getDecisionVoters()) {
|
||||
int result = voter.vote(authentication, object, configAttributes);
|
||||
switch (result) {
|
||||
case AccessDecisionVoter.ACCESS_GRANTED:
|
||||
return;
|
||||
case AccessDecisionVoter.ACCESS_DENIED:
|
||||
deny++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
case AccessDecisionVoter.ACCESS_GRANTED:
|
||||
return;
|
||||
case AccessDecisionVoter.ACCESS_DENIED:
|
||||
deny++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (deny > 0) {
|
||||
|
||||
@@ -71,14 +71,14 @@ public class ConsensusBased extends AbstractAccessDecisionManager {
|
||||
for (AccessDecisionVoter voter : getDecisionVoters()) {
|
||||
int result = voter.vote(authentication, object, configAttributes);
|
||||
switch (result) {
|
||||
case AccessDecisionVoter.ACCESS_GRANTED:
|
||||
grant++;
|
||||
break;
|
||||
case AccessDecisionVoter.ACCESS_DENIED:
|
||||
deny++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
case AccessDecisionVoter.ACCESS_GRANTED:
|
||||
grant++;
|
||||
break;
|
||||
case AccessDecisionVoter.ACCESS_DENIED:
|
||||
deny++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (grant > deny) {
|
||||
|
||||
@@ -71,14 +71,14 @@ public class UnanimousBased extends AbstractAccessDecisionManager {
|
||||
for (AccessDecisionVoter voter : getDecisionVoters()) {
|
||||
int result = voter.vote(authentication, object, singleAttributeList);
|
||||
switch (result) {
|
||||
case AccessDecisionVoter.ACCESS_GRANTED:
|
||||
grant++;
|
||||
break;
|
||||
case AccessDecisionVoter.ACCESS_DENIED:
|
||||
throw new AccessDeniedException(
|
||||
this.messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"));
|
||||
default:
|
||||
break;
|
||||
case AccessDecisionVoter.ACCESS_GRANTED:
|
||||
grant++;
|
||||
break;
|
||||
case AccessDecisionVoter.ACCESS_DENIED:
|
||||
throw new AccessDeniedException(this.messages
|
||||
.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"));
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+30
-22
@@ -64,35 +64,42 @@ class CoreSecurityRuntimeHints implements RuntimeHintsRegistrar {
|
||||
}
|
||||
|
||||
private void registerMethodSecurityHints(RuntimeHints hints) {
|
||||
hints.reflection().registerType(
|
||||
TypeReference.of("org.springframework.security.access.expression.method.MethodSecurityExpressionRoot"),
|
||||
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
|
||||
hints.reflection().registerType(AbstractAuthenticationToken.class,
|
||||
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
|
||||
hints.reflection()
|
||||
.registerType(
|
||||
TypeReference
|
||||
.of("org.springframework.security.access.expression.method.MethodSecurityExpressionRoot"),
|
||||
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
|
||||
hints.reflection()
|
||||
.registerType(AbstractAuthenticationToken.class,
|
||||
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
|
||||
}
|
||||
|
||||
private void registerExpressionEvaluationHints(RuntimeHints hints) {
|
||||
hints.reflection().registerTypes(
|
||||
List.of(TypeReference.of(SecurityExpressionOperations.class),
|
||||
TypeReference.of(SecurityExpressionRoot.class)),
|
||||
(builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS,
|
||||
MemberCategory.INVOKE_DECLARED_METHODS));
|
||||
hints.reflection()
|
||||
.registerTypes(
|
||||
List.of(TypeReference.of(SecurityExpressionOperations.class),
|
||||
TypeReference.of(SecurityExpressionRoot.class)),
|
||||
(builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS,
|
||||
MemberCategory.INVOKE_DECLARED_METHODS));
|
||||
}
|
||||
|
||||
private void registerExceptionEventsHints(RuntimeHints hints) {
|
||||
hints.reflection().registerTypes(getDefaultAuthenticationExceptionEventPublisherTypes(),
|
||||
(builder) -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
|
||||
hints.reflection()
|
||||
.registerTypes(getDefaultAuthenticationExceptionEventPublisherTypes(),
|
||||
(builder) -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
|
||||
}
|
||||
|
||||
private List<TypeReference> getDefaultAuthenticationExceptionEventPublisherTypes() {
|
||||
return Stream.of(AuthenticationFailureBadCredentialsEvent.class,
|
||||
AuthenticationFailureCredentialsExpiredEvent.class, AuthenticationFailureDisabledEvent.class,
|
||||
AuthenticationFailureExpiredEvent.class, AuthenticationFailureLockedEvent.class,
|
||||
AuthenticationFailureProviderNotFoundEvent.class, AuthenticationFailureProxyUntrustedEvent.class,
|
||||
AuthenticationFailureServiceExceptionEvent.class, AuthenticationServiceException.class,
|
||||
AccountExpiredException.class, BadCredentialsException.class, CredentialsExpiredException.class,
|
||||
DisabledException.class, LockedException.class, UsernameNotFoundException.class,
|
||||
ProviderNotFoundException.class).map(TypeReference::of).toList();
|
||||
return Stream
|
||||
.of(AuthenticationFailureBadCredentialsEvent.class, AuthenticationFailureCredentialsExpiredEvent.class,
|
||||
AuthenticationFailureDisabledEvent.class, AuthenticationFailureExpiredEvent.class,
|
||||
AuthenticationFailureLockedEvent.class, AuthenticationFailureProviderNotFoundEvent.class,
|
||||
AuthenticationFailureProxyUntrustedEvent.class, AuthenticationFailureServiceExceptionEvent.class,
|
||||
AuthenticationServiceException.class, AccountExpiredException.class, BadCredentialsException.class,
|
||||
CredentialsExpiredException.class, DisabledException.class, LockedException.class,
|
||||
UsernameNotFoundException.class, ProviderNotFoundException.class)
|
||||
.map(TypeReference::of)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void registerDefaultJdbcSchemaFileHint(RuntimeHints hints) {
|
||||
@@ -100,8 +107,9 @@ class CoreSecurityRuntimeHints implements RuntimeHintsRegistrar {
|
||||
}
|
||||
|
||||
private void registerSecurityContextHints(RuntimeHints hints) {
|
||||
hints.reflection().registerType(SecurityContextImpl.class,
|
||||
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
|
||||
hints.reflection()
|
||||
.registerType(SecurityContextImpl.class,
|
||||
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ public abstract class AbstractUserDetailsReactiveAuthenticationManager
|
||||
if (!user.isAccountNonExpired()) {
|
||||
this.logger.debug("User account is expired");
|
||||
throw new AccountExpiredException(this.messages
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ public class AccountStatusUserDetailsChecker implements UserDetailsChecker, Mess
|
||||
if (!user.isCredentialsNonExpired()) {
|
||||
this.logger.debug("Failed to authenticate since user account credentials have expired");
|
||||
throw new CredentialsExpiredException(this.messages
|
||||
.getMessage("AccountStatusUserDetailsChecker.credentialsExpired", "User credentials have expired"));
|
||||
.getMessage("AccountStatusUserDetailsChecker.credentialsExpired", "User credentials have expired"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -65,9 +65,9 @@ public final class AuthenticationObservationConvention
|
||||
@Override
|
||||
public KeyValues getLowCardinalityKeyValues(@NonNull AuthenticationObservationContext context) {
|
||||
return KeyValues.of("authentication.request.type", getAuthenticationType(context))
|
||||
.and("authentication.method", getAuthenticationMethod(context))
|
||||
.and("authentication.result.type", getAuthenticationResult(context))
|
||||
.and("authentication.failure.type", getAuthenticationFailureType(context));
|
||||
.and("authentication.method", getAuthenticationMethod(context))
|
||||
.and("authentication.result.type", getAuthenticationResult(context))
|
||||
.and("authentication.failure.type", getAuthenticationFailureType(context));
|
||||
}
|
||||
|
||||
private String getAuthenticationType(AuthenticationObservationContext context) {
|
||||
|
||||
+4
-4
@@ -125,7 +125,7 @@ public class DefaultAuthenticationEventPublisher
|
||||
|
||||
private Constructor<? extends AbstractAuthenticationEvent> getEventConstructor(AuthenticationException exception) {
|
||||
Constructor<? extends AbstractAuthenticationEvent> eventConstructor = this.exceptionMappings
|
||||
.get(exception.getClass().getName());
|
||||
.get(exception.getClass().getName());
|
||||
return (eventConstructor != null) ? eventConstructor : this.defaultAuthenticationFailureEventConstructor;
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ public class DefaultAuthenticationEventPublisher
|
||||
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings) {
|
||||
Assert.notEmpty(mappings, "The mappings Map must not be empty nor null");
|
||||
for (Map.Entry<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> entry : mappings
|
||||
.entrySet()) {
|
||||
.entrySet()) {
|
||||
Class<?> exceptionClass = entry.getKey();
|
||||
Class<?> eventClass = entry.getValue();
|
||||
Assert.notNull(exceptionClass, "exceptionClass cannot be null");
|
||||
@@ -190,7 +190,7 @@ public class DefaultAuthenticationEventPublisher
|
||||
"defaultAuthenticationFailureEventClass must not be null");
|
||||
try {
|
||||
this.defaultAuthenticationFailureEventConstructor = defaultAuthenticationFailureEventClass
|
||||
.getConstructor(Authentication.class, AuthenticationException.class);
|
||||
.getConstructor(Authentication.class, AuthenticationException.class);
|
||||
}
|
||||
catch (NoSuchMethodException ex) {
|
||||
throw new RuntimeException("Default Authentication Failure event class "
|
||||
@@ -201,7 +201,7 @@ public class DefaultAuthenticationEventPublisher
|
||||
private void addMapping(String exceptionClass, Class<? extends AbstractAuthenticationFailureEvent> eventClass) {
|
||||
try {
|
||||
Constructor<? extends AbstractAuthenticationEvent> constructor = eventClass
|
||||
.getConstructor(Authentication.class, AuthenticationException.class);
|
||||
.getConstructor(Authentication.class, AuthenticationException.class);
|
||||
this.exceptionMappings.put(exceptionClass, constructor);
|
||||
}
|
||||
catch (NoSuchMethodException ex) {
|
||||
|
||||
+2
-1
@@ -53,7 +53,8 @@ public class ObservationReactiveAuthenticationManager implements ReactiveAuthent
|
||||
context.setAuthenticationManagerClass(this.delegate.getClass());
|
||||
return Mono.deferContextual((contextView) -> {
|
||||
Observation observation = Observation.createNotStarted(this.convention, () -> context, this.registry)
|
||||
.parentObservation(contextView.getOrDefault(ObservationThreadLocalAccessor.KEY, null)).start();
|
||||
.parentObservation(contextView.getOrDefault(ObservationThreadLocalAccessor.KEY, null))
|
||||
.start();
|
||||
return this.delegate.authenticate(authentication).doOnSuccess((result) -> {
|
||||
context.setAuthenticationResult(result);
|
||||
observation.stop();
|
||||
|
||||
+10
-10
@@ -138,7 +138,7 @@ public abstract class AbstractUserDetailsAuthenticationProvider
|
||||
throw ex;
|
||||
}
|
||||
throw new BadCredentialsException(this.messages
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
|
||||
}
|
||||
Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
|
||||
}
|
||||
@@ -320,21 +320,21 @@ public abstract class AbstractUserDetailsAuthenticationProvider
|
||||
public void check(UserDetails user) {
|
||||
if (!user.isAccountNonLocked()) {
|
||||
AbstractUserDetailsAuthenticationProvider.this.logger
|
||||
.debug("Failed to authenticate since user account is locked");
|
||||
.debug("Failed to authenticate since user account is locked");
|
||||
throw new LockedException(AbstractUserDetailsAuthenticationProvider.this.messages
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"));
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"));
|
||||
}
|
||||
if (!user.isEnabled()) {
|
||||
AbstractUserDetailsAuthenticationProvider.this.logger
|
||||
.debug("Failed to authenticate since user account is disabled");
|
||||
.debug("Failed to authenticate since user account is disabled");
|
||||
throw new DisabledException(AbstractUserDetailsAuthenticationProvider.this.messages
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
|
||||
}
|
||||
if (!user.isAccountNonExpired()) {
|
||||
AbstractUserDetailsAuthenticationProvider.this.logger
|
||||
.debug("Failed to authenticate since user account has expired");
|
||||
.debug("Failed to authenticate since user account has expired");
|
||||
throw new AccountExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,10 +346,10 @@ public abstract class AbstractUserDetailsAuthenticationProvider
|
||||
public void check(UserDetails user) {
|
||||
if (!user.isCredentialsNonExpired()) {
|
||||
AbstractUserDetailsAuthenticationProvider.this.logger
|
||||
.debug("Failed to authenticate since user account credentials have expired");
|
||||
.debug("Failed to authenticate since user account credentials have expired");
|
||||
throw new CredentialsExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired",
|
||||
"User credentials have expired"));
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired",
|
||||
"User credentials have expired"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -80,13 +80,13 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication
|
||||
if (authentication.getCredentials() == null) {
|
||||
this.logger.debug("Failed to authenticate since no credentials provided");
|
||||
throw new BadCredentialsException(this.messages
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
|
||||
}
|
||||
String presentedPassword = authentication.getCredentials().toString();
|
||||
if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
|
||||
this.logger.debug("Failed to authenticate since password does not match stored value");
|
||||
throw new BadCredentialsException(this.messages
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
|
||||
.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -248,8 +248,8 @@ public abstract class AbstractJaasAuthenticationProvider implements Authenticati
|
||||
|
||||
private void logout(JaasAuthenticationToken token, LoginContext loginContext) throws LoginException {
|
||||
if (loginContext != null) {
|
||||
this.log.debug(
|
||||
LogMessage.of(() -> "Logging principal: [" + token.getPrincipal() + "] out of LoginContext"));
|
||||
this.log
|
||||
.debug(LogMessage.of(() -> "Logging principal: [" + token.getPrincipal() + "] out of LoginContext"));
|
||||
loginContext.logout();
|
||||
return;
|
||||
}
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ public class SecurityContextLoginModule implements LoginModule {
|
||||
private static final Log log = LogFactory.getLog(SecurityContextLoginModule.class);
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
private Authentication authen;
|
||||
|
||||
|
||||
+3
-2
@@ -39,8 +39,9 @@ public class AuthenticatedReactiveAuthorizationManager<T> implements ReactiveAut
|
||||
|
||||
@Override
|
||||
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, T object) {
|
||||
return authentication.filter(this::isNotAnonymous).map(this::getAuthorizationDecision)
|
||||
.defaultIfEmpty(new AuthorizationDecision(false));
|
||||
return authentication.filter(this::isNotAnonymous)
|
||||
.map(this::getAuthorizationDecision)
|
||||
.defaultIfEmpty(new AuthorizationDecision(false));
|
||||
}
|
||||
|
||||
private AuthorizationDecision getAuthorizationDecision(Authentication authentication) {
|
||||
|
||||
+3
-3
@@ -53,8 +53,8 @@ public final class AuthorizationObservationConvention
|
||||
@Override
|
||||
public KeyValues getLowCardinalityKeyValues(AuthorizationObservationContext<?> context) {
|
||||
return KeyValues.of("spring.security.authentication.type", getAuthenticationType(context))
|
||||
.and("spring.security.object", getObjectType(context))
|
||||
.and("spring.security.authorization.decision", getAuthorizationDecision(context));
|
||||
.and("spring.security.object", getObjectType(context))
|
||||
.and("spring.security.authorization.decision", getAuthorizationDecision(context));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,7 +63,7 @@ public final class AuthorizationObservationConvention
|
||||
@Override
|
||||
public KeyValues getHighCardinalityKeyValues(AuthorizationObservationContext<?> context) {
|
||||
return KeyValues.of("spring.security.authentication.authorities", getAuthorities(context))
|
||||
.and("spring.security.authorization.decision.details", getDecisionDetails(context));
|
||||
.and("spring.security.authorization.decision.details", getDecisionDetails(context));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+2
-1
@@ -55,7 +55,8 @@ public final class ObservationReactiveAuthorizationManager<T> implements Reactiv
|
||||
});
|
||||
return Mono.deferContextual((contextView) -> {
|
||||
Observation observation = Observation.createNotStarted(this.convention, () -> context, this.registry)
|
||||
.parentObservation(contextView.getOrDefault(ObservationThreadLocalAccessor.KEY, null)).start();
|
||||
.parentObservation(contextView.getOrDefault(ObservationThreadLocalAccessor.KEY, null))
|
||||
.start();
|
||||
return this.delegate.check(wrapped, object).doOnSuccess((decision) -> {
|
||||
context.setDecision(decision);
|
||||
if (decision == null || !decision.isGranted()) {
|
||||
|
||||
+7
-4
@@ -99,9 +99,12 @@ public final class AuthorizationManagerAfterReactiveMethodInterceptor
|
||||
public Object invoke(MethodInvocation mi) throws Throwable {
|
||||
Method method = mi.getMethod();
|
||||
Class<?> type = method.getReturnType();
|
||||
Assert.state(Publisher.class.isAssignableFrom(type),
|
||||
() -> String.format("The returnType %s on %s must return an instance of org.reactivestreams.Publisher "
|
||||
+ "(for example, a Mono or Flux) in order to support Reactor Context", type, method));
|
||||
Assert
|
||||
.state(Publisher.class.isAssignableFrom(type),
|
||||
() -> String.format(
|
||||
"The returnType %s on %s must return an instance of org.reactivestreams.Publisher "
|
||||
+ "(for example, a Mono or Flux) in order to support Reactor Context",
|
||||
type, method));
|
||||
Mono<Authentication> authentication = ReactiveAuthenticationUtils.getAuthentication();
|
||||
Function<Object, Mono<?>> postAuthorize = (result) -> postAuthorize(authentication, mi, result);
|
||||
ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(type);
|
||||
@@ -123,7 +126,7 @@ public final class AuthorizationManagerAfterReactiveMethodInterceptor
|
||||
|
||||
private Mono<?> postAuthorize(Mono<Authentication> authentication, MethodInvocation mi, Object result) {
|
||||
return this.authorizationManager.verify(authentication, new MethodInvocationResult(mi, result))
|
||||
.thenReturn(result);
|
||||
.thenReturn(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+6
-3
@@ -99,9 +99,12 @@ public final class AuthorizationManagerBeforeReactiveMethodInterceptor
|
||||
public Object invoke(MethodInvocation mi) throws Throwable {
|
||||
Method method = mi.getMethod();
|
||||
Class<?> type = method.getReturnType();
|
||||
Assert.state(Publisher.class.isAssignableFrom(type),
|
||||
() -> String.format("The returnType %s on %s must return an instance of org.reactivestreams.Publisher "
|
||||
+ "(for example, a Mono or Flux) in order to support Reactor Context", type, method));
|
||||
Assert
|
||||
.state(Publisher.class.isAssignableFrom(type),
|
||||
() -> String.format(
|
||||
"The returnType %s on %s must return an instance of org.reactivestreams.Publisher "
|
||||
+ "(for example, a Mono or Flux) in order to support Reactor Context",
|
||||
type, method));
|
||||
Mono<Authentication> authentication = ReactiveAuthenticationUtils.getAuthentication();
|
||||
ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(type);
|
||||
Mono<Void> preAuthorize = this.authorizationManager.verify(authentication, mi);
|
||||
|
||||
+1
-1
@@ -62,7 +62,7 @@ public final class MethodExpressionAuthorizationManager implements Authorization
|
||||
Assert.notNull(expressionHandler, "expressionHandler cannot be null");
|
||||
this.expressionHandler = expressionHandler;
|
||||
this.expression = expressionHandler.getExpressionParser()
|
||||
.parseExpression(this.expression.getExpressionString());
|
||||
.parseExpression(this.expression.getExpressionString());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -59,7 +59,7 @@ final class PostAuthorizeExpressionAttributeRegistry extends AbstractExpressionA
|
||||
return ExpressionAttribute.NULL_ATTRIBUTE;
|
||||
}
|
||||
Expression postAuthorizeExpression = this.expressionHandler.getExpressionParser()
|
||||
.parseExpression(postAuthorize.value());
|
||||
.parseExpression(postAuthorize.value());
|
||||
return new ExpressionAttribute(postAuthorizeExpression);
|
||||
}
|
||||
|
||||
|
||||
+14
-9
@@ -83,12 +83,15 @@ public final class PostFilterAuthorizationReactiveMethodInterceptor
|
||||
return ReactiveMethodInvocationUtils.proceed(mi);
|
||||
}
|
||||
Mono<EvaluationContext> toInvoke = ReactiveAuthenticationUtils.getAuthentication()
|
||||
.map((auth) -> this.registry.getExpressionHandler().createEvaluationContext(auth, mi));
|
||||
.map((auth) -> this.registry.getExpressionHandler().createEvaluationContext(auth, mi));
|
||||
Method method = mi.getMethod();
|
||||
Class<?> type = method.getReturnType();
|
||||
Assert.state(Publisher.class.isAssignableFrom(type),
|
||||
() -> String.format("The parameter type %s on %s must be an instance of org.reactivestreams.Publisher "
|
||||
+ "(for example, a Mono or Flux) in order to support Reactor Context", type, method));
|
||||
Assert
|
||||
.state(Publisher.class.isAssignableFrom(type),
|
||||
() -> String.format(
|
||||
"The parameter type %s on %s must be an instance of org.reactivestreams.Publisher "
|
||||
+ "(for example, a Mono or Flux) in order to support Reactor Context",
|
||||
type, method));
|
||||
ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(type);
|
||||
if (isMultiValue(type, adapter)) {
|
||||
Publisher<?> publisher = Flux.defer(() -> ReactiveMethodInvocationUtils.proceed(mi));
|
||||
@@ -108,13 +111,15 @@ public final class PostFilterAuthorizationReactiveMethodInterceptor
|
||||
}
|
||||
|
||||
private Mono<?> filterSingleValue(Publisher<?> publisher, EvaluationContext ctx, ExpressionAttribute attribute) {
|
||||
return Mono.from(publisher).doOnNext((result) -> setFilterObject(ctx, result))
|
||||
.flatMap((result) -> postFilter(ctx, result, attribute));
|
||||
return Mono.from(publisher)
|
||||
.doOnNext((result) -> setFilterObject(ctx, result))
|
||||
.flatMap((result) -> postFilter(ctx, result, attribute));
|
||||
}
|
||||
|
||||
private Flux<?> filterMultiValue(Publisher<?> publisher, EvaluationContext ctx, ExpressionAttribute attribute) {
|
||||
return Flux.from(publisher).doOnNext((result) -> setFilterObject(ctx, result))
|
||||
.flatMap((result) -> postFilter(ctx, result, attribute));
|
||||
return Flux.from(publisher)
|
||||
.doOnNext((result) -> setFilterObject(ctx, result))
|
||||
.flatMap((result) -> postFilter(ctx, result, attribute));
|
||||
}
|
||||
|
||||
private void setFilterObject(EvaluationContext ctx, Object result) {
|
||||
@@ -123,7 +128,7 @@ public final class PostFilterAuthorizationReactiveMethodInterceptor
|
||||
|
||||
private Mono<?> postFilter(EvaluationContext ctx, Object result, ExpressionAttribute attribute) {
|
||||
return ReactiveExpressionUtils.evaluateAsBoolean(attribute.getExpression(), ctx)
|
||||
.flatMap((granted) -> granted ? Mono.just(result) : Mono.empty());
|
||||
.flatMap((granted) -> granted ? Mono.just(result) : Mono.empty());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ final class PostFilterExpressionAttributeRegistry extends AbstractExpressionAttr
|
||||
return ExpressionAttribute.NULL_ATTRIBUTE;
|
||||
}
|
||||
Expression postFilterExpression = this.expressionHandler.getExpressionParser()
|
||||
.parseExpression(postFilter.value());
|
||||
.parseExpression(postFilter.value());
|
||||
return new ExpressionAttribute(postFilterExpression);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ final class PreAuthorizeExpressionAttributeRegistry extends AbstractExpressionAt
|
||||
return ExpressionAttribute.NULL_ATTRIBUTE;
|
||||
}
|
||||
Expression preAuthorizeExpression = this.expressionHandler.getExpressionParser()
|
||||
.parseExpression(preAuthorize.value());
|
||||
.parseExpression(preAuthorize.value());
|
||||
return new ExpressionAttribute(preAuthorizeExpression);
|
||||
}
|
||||
|
||||
|
||||
+11
-8
@@ -96,21 +96,24 @@ public final class PreFilterAuthorizationReactiveMethodInterceptor
|
||||
}
|
||||
FilterTarget filterTarget = findFilterTarget(attribute.getFilterTarget(), mi);
|
||||
Mono<EvaluationContext> toInvoke = ReactiveAuthenticationUtils.getAuthentication()
|
||||
.map((auth) -> this.registry.getExpressionHandler().createEvaluationContext(auth, mi));
|
||||
.map((auth) -> this.registry.getExpressionHandler().createEvaluationContext(auth, mi));
|
||||
Method method = mi.getMethod();
|
||||
Class<?> type = filterTarget.value.getClass();
|
||||
Assert.state(Publisher.class.isAssignableFrom(type),
|
||||
() -> String.format("The parameter type %s on %s must be an instance of org.reactivestreams.Publisher "
|
||||
+ "(for example, a Mono or Flux) in order to support Reactor Context", type, method));
|
||||
Assert
|
||||
.state(Publisher.class.isAssignableFrom(type),
|
||||
() -> String.format(
|
||||
"The parameter type %s on %s must be an instance of org.reactivestreams.Publisher "
|
||||
+ "(for example, a Mono or Flux) in order to support Reactor Context",
|
||||
type, method));
|
||||
ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(type);
|
||||
if (isMultiValue(type, adapter)) {
|
||||
Flux<?> result = toInvoke
|
||||
.flatMapMany((ctx) -> filterMultiValue(filterTarget.value, attribute.getExpression(), ctx));
|
||||
.flatMapMany((ctx) -> filterMultiValue(filterTarget.value, attribute.getExpression(), ctx));
|
||||
mi.getArguments()[filterTarget.index] = (adapter != null) ? adapter.fromPublisher(result) : result;
|
||||
}
|
||||
else {
|
||||
Mono<?> result = toInvoke
|
||||
.flatMap((ctx) -> filterSingleValue(filterTarget.value, attribute.getExpression(), ctx));
|
||||
.flatMap((ctx) -> filterSingleValue(filterTarget.value, attribute.getExpression(), ctx));
|
||||
mi.getArguments()[filterTarget.index] = (adapter != null) ? adapter.fromPublisher(result) : result;
|
||||
}
|
||||
return ReactiveMethodInvocationUtils.proceed(mi);
|
||||
@@ -157,7 +160,7 @@ public final class PreFilterAuthorizationReactiveMethodInterceptor
|
||||
|
||||
private Mono<?> filterSingleValue(Publisher<?> filterTarget, Expression filterExpression, EvaluationContext ctx) {
|
||||
MethodSecurityExpressionOperations rootObject = (MethodSecurityExpressionOperations) ctx.getRootObject()
|
||||
.getValue();
|
||||
.getValue();
|
||||
return Mono.from(filterTarget).filterWhen((filterObject) -> {
|
||||
rootObject.setFilterObject(filterObject);
|
||||
return ReactiveExpressionUtils.evaluateAsBoolean(filterExpression, ctx);
|
||||
@@ -166,7 +169,7 @@ public final class PreFilterAuthorizationReactiveMethodInterceptor
|
||||
|
||||
private Flux<?> filterMultiValue(Publisher<?> filterTarget, Expression filterExpression, EvaluationContext ctx) {
|
||||
MethodSecurityExpressionOperations rootObject = (MethodSecurityExpressionOperations) ctx.getRootObject()
|
||||
.getValue();
|
||||
.getValue();
|
||||
return Flux.from(filterTarget).filterWhen((filterObject) -> {
|
||||
rootObject.setFilterObject(filterObject);
|
||||
return ReactiveExpressionUtils.evaluateAsBoolean(filterExpression, ctx);
|
||||
|
||||
+1
-1
@@ -59,7 +59,7 @@ final class PreFilterExpressionAttributeRegistry
|
||||
return PreFilterExpressionAttribute.NULL_ATTRIBUTE;
|
||||
}
|
||||
Expression preFilterExpression = this.expressionHandler.getExpressionParser()
|
||||
.parseExpression(preFilter.value());
|
||||
.parseExpression(preFilter.value());
|
||||
return new PreFilterExpressionAttribute(preFilterExpression, preFilter.filterTarget());
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -36,8 +36,9 @@ final class ReactiveAuthenticationUtils {
|
||||
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
|
||||
|
||||
static Mono<Authentication> getAuthentication() {
|
||||
return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
|
||||
.defaultIfEmpty(ANONYMOUS);
|
||||
return ReactiveSecurityContextHolder.getContext()
|
||||
.map(SecurityContext::getAuthentication)
|
||||
.defaultIfEmpty(ANONYMOUS);
|
||||
}
|
||||
|
||||
private ReactiveAuthenticationUtils() {
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ import org.springframework.util.Assert;
|
||||
abstract class AbstractDelegatingSecurityContextSupport {
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
private final SecurityContext securityContext;
|
||||
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ public final class DelegatingSecurityContextCallable<V> implements Callable<V> {
|
||||
private SecurityContext delegateSecurityContext;
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
/**
|
||||
* The {@link SecurityContext} that was on the {@link SecurityContextHolder} prior to
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ public final class DelegatingSecurityContextRunnable implements Runnable {
|
||||
private final boolean explicitSecurityContextProvided;
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
/**
|
||||
* The {@link SecurityContext} that the delegate {@link Runnable} will be ran as.
|
||||
|
||||
@@ -205,7 +205,7 @@ public final class RsaKeyConverters {
|
||||
byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString());
|
||||
try (InputStream x509CertStream = new ByteArrayInputStream(x509)) {
|
||||
X509Certificate certificate = (X509Certificate) this.certificateFactory
|
||||
.generateCertificate(x509CertStream);
|
||||
.generateCertificate(x509CertStream);
|
||||
return (RSAPublicKey) certificate.getPublicKey();
|
||||
}
|
||||
catch (CertificateException | IOException ex) {
|
||||
|
||||
@@ -131,21 +131,21 @@ class ComparableVersion implements Comparable<ComparableVersion> {
|
||||
}
|
||||
|
||||
switch (item.getType()) {
|
||||
case INT_ITEM:
|
||||
int itemValue = ((IntItem) item).value;
|
||||
return (value < itemValue) ? -1 : ((value == itemValue) ? 0 : 1);
|
||||
case LONG_ITEM:
|
||||
case BIGINTEGER_ITEM:
|
||||
return -1;
|
||||
case INT_ITEM:
|
||||
int itemValue = ((IntItem) item).value;
|
||||
return (value < itemValue) ? -1 : ((value == itemValue) ? 0 : 1);
|
||||
case LONG_ITEM:
|
||||
case BIGINTEGER_ITEM:
|
||||
return -1;
|
||||
|
||||
case STRING_ITEM:
|
||||
return 1; // 1.1 > 1-sp
|
||||
case STRING_ITEM:
|
||||
return 1; // 1.1 > 1-sp
|
||||
|
||||
case LIST_ITEM:
|
||||
return 1; // 1.1 > 1-1
|
||||
case LIST_ITEM:
|
||||
return 1; // 1.1 > 1-1
|
||||
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,22 +205,22 @@ class ComparableVersion implements Comparable<ComparableVersion> {
|
||||
}
|
||||
|
||||
switch (item.getType()) {
|
||||
case INT_ITEM:
|
||||
return 1;
|
||||
case LONG_ITEM:
|
||||
long itemValue = ((LongItem) item).value;
|
||||
return (value < itemValue) ? -1 : ((value == itemValue) ? 0 : 1);
|
||||
case BIGINTEGER_ITEM:
|
||||
return -1;
|
||||
case INT_ITEM:
|
||||
return 1;
|
||||
case LONG_ITEM:
|
||||
long itemValue = ((LongItem) item).value;
|
||||
return (value < itemValue) ? -1 : ((value == itemValue) ? 0 : 1);
|
||||
case BIGINTEGER_ITEM:
|
||||
return -1;
|
||||
|
||||
case STRING_ITEM:
|
||||
return 1; // 1.1 > 1-sp
|
||||
case STRING_ITEM:
|
||||
return 1; // 1.1 > 1-sp
|
||||
|
||||
case LIST_ITEM:
|
||||
return 1; // 1.1 > 1-1
|
||||
case LIST_ITEM:
|
||||
return 1; // 1.1 > 1-1
|
||||
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,21 +279,21 @@ class ComparableVersion implements Comparable<ComparableVersion> {
|
||||
}
|
||||
|
||||
switch (item.getType()) {
|
||||
case INT_ITEM:
|
||||
case LONG_ITEM:
|
||||
return 1;
|
||||
case INT_ITEM:
|
||||
case LONG_ITEM:
|
||||
return 1;
|
||||
|
||||
case BIGINTEGER_ITEM:
|
||||
return value.compareTo(((BigIntegerItem) item).value);
|
||||
case BIGINTEGER_ITEM:
|
||||
return value.compareTo(((BigIntegerItem) item).value);
|
||||
|
||||
case STRING_ITEM:
|
||||
return 1; // 1.1 > 1-sp
|
||||
case STRING_ITEM:
|
||||
return 1; // 1.1 > 1-sp
|
||||
|
||||
case LIST_ITEM:
|
||||
return 1; // 1.1 > 1-1
|
||||
case LIST_ITEM:
|
||||
return 1; // 1.1 > 1-1
|
||||
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,16 +352,16 @@ class ComparableVersion implements Comparable<ComparableVersion> {
|
||||
if (followedByDigit && value.length() == 1) {
|
||||
// a1 = alpha-1, b1 = beta-1, m1 = milestone-1
|
||||
switch (value.charAt(0)) {
|
||||
case 'a':
|
||||
value = "alpha";
|
||||
break;
|
||||
case 'b':
|
||||
value = "beta";
|
||||
break;
|
||||
case 'm':
|
||||
value = "milestone";
|
||||
break;
|
||||
default:
|
||||
case 'a':
|
||||
value = "alpha";
|
||||
break;
|
||||
case 'b':
|
||||
value = "beta";
|
||||
break;
|
||||
case 'm':
|
||||
value = "milestone";
|
||||
break;
|
||||
default:
|
||||
}
|
||||
}
|
||||
this.value = ALIASES.getProperty(value, value);
|
||||
@@ -403,19 +403,19 @@ class ComparableVersion implements Comparable<ComparableVersion> {
|
||||
return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX);
|
||||
}
|
||||
switch (item.getType()) {
|
||||
case INT_ITEM:
|
||||
case LONG_ITEM:
|
||||
case BIGINTEGER_ITEM:
|
||||
return -1; // 1.any < 1.1 ?
|
||||
case INT_ITEM:
|
||||
case LONG_ITEM:
|
||||
case BIGINTEGER_ITEM:
|
||||
return -1; // 1.any < 1.1 ?
|
||||
|
||||
case STRING_ITEM:
|
||||
return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value));
|
||||
case STRING_ITEM:
|
||||
return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value));
|
||||
|
||||
case LIST_ITEM:
|
||||
return -1; // 1.any < 1-1
|
||||
case LIST_ITEM:
|
||||
return -1; // 1.any < 1-1
|
||||
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -485,34 +485,34 @@ class ComparableVersion implements Comparable<ComparableVersion> {
|
||||
return first.compareTo(null);
|
||||
}
|
||||
switch (item.getType()) {
|
||||
case INT_ITEM:
|
||||
case LONG_ITEM:
|
||||
case BIGINTEGER_ITEM:
|
||||
return -1; // 1-1 < 1.0.x
|
||||
case INT_ITEM:
|
||||
case LONG_ITEM:
|
||||
case BIGINTEGER_ITEM:
|
||||
return -1; // 1-1 < 1.0.x
|
||||
|
||||
case STRING_ITEM:
|
||||
return 1; // 1-1 > 1-sp
|
||||
case STRING_ITEM:
|
||||
return 1; // 1-1 > 1-sp
|
||||
|
||||
case LIST_ITEM:
|
||||
Iterator<Item> left = iterator();
|
||||
Iterator<Item> right = ((ListItem) item).iterator();
|
||||
case LIST_ITEM:
|
||||
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;
|
||||
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 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;
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
return 0;
|
||||
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
default:
|
||||
throw new IllegalStateException("invalid item: " + item.getClass());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ public final class SpringSecurityCoreVersion {
|
||||
private static String getSpringVersion() {
|
||||
Properties properties = new Properties();
|
||||
try (InputStream is = SpringSecurityCoreVersion.class.getClassLoader()
|
||||
.getResourceAsStream("META-INF/spring-security.versions")) {
|
||||
.getResourceAsStream("META-INF/spring-security.versions")) {
|
||||
properties.load(is);
|
||||
}
|
||||
catch (IOException | NullPointerException ex) {
|
||||
|
||||
+2
-2
@@ -32,8 +32,8 @@ import org.springframework.security.core.Authentication;
|
||||
* @since 4.0
|
||||
*
|
||||
* See: <a href=
|
||||
* "{@docRoot}/org/springframework/security/web/method/annotation/AuthenticationPrincipalArgumentResolver.html"
|
||||
* > AuthenticationPrincipalArgumentResolver </a>
|
||||
* "{@docRoot}/org/springframework/security/web/method/annotation/AuthenticationPrincipalArgumentResolver.html" >
|
||||
* AuthenticationPrincipalArgumentResolver </a>
|
||||
*/
|
||||
@Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
|
||||
+4
-4
@@ -31,14 +31,14 @@ import java.lang.annotation.Target;
|
||||
*
|
||||
* <p>
|
||||
* See: <a href=
|
||||
* "{@docRoot}/org/springframework/security/web/bind/support/CurrentSecurityContextArgumentResolver.html"
|
||||
* > CurrentSecurityContextArgumentResolver</a> For Servlet
|
||||
* "{@docRoot}/org/springframework/security/web/bind/support/CurrentSecurityContextArgumentResolver.html" >
|
||||
* CurrentSecurityContextArgumentResolver</a> For Servlet
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* See: <a href=
|
||||
* "{@docRoot}/org/springframework/security/web/reactive/result/method/annotation/CurrentSecurityContextArgumentResolver.html"
|
||||
* > CurrentSecurityContextArgumentResolver</a> For WebFlux
|
||||
* "{@docRoot}/org/springframework/security/web/reactive/result/method/annotation/CurrentSecurityContextArgumentResolver.html" >
|
||||
* CurrentSecurityContextArgumentResolver</a> For WebFlux
|
||||
* </p>
|
||||
*/
|
||||
@Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
|
||||
|
||||
+7
-7
@@ -69,21 +69,21 @@ public final class ObservationSecurityContextChangedListener implements Security
|
||||
return;
|
||||
}
|
||||
if (oldAuthentication == null) {
|
||||
observation.event(Observation.Event.of(SECURITY_CONTEXT_CREATED, "%s [%s]").format(SECURITY_CONTEXT_CREATED,
|
||||
newAuthentication.getClass().getSimpleName()));
|
||||
observation.event(Observation.Event.of(SECURITY_CONTEXT_CREATED, "%s [%s]")
|
||||
.format(SECURITY_CONTEXT_CREATED, newAuthentication.getClass().getSimpleName()));
|
||||
return;
|
||||
}
|
||||
if (newAuthentication == null) {
|
||||
observation.event(Observation.Event.of(SECURITY_CONTEXT_CLEARED, "%s [%s]").format(SECURITY_CONTEXT_CLEARED,
|
||||
oldAuthentication.getClass().getSimpleName()));
|
||||
observation.event(Observation.Event.of(SECURITY_CONTEXT_CLEARED, "%s [%s]")
|
||||
.format(SECURITY_CONTEXT_CLEARED, oldAuthentication.getClass().getSimpleName()));
|
||||
return;
|
||||
}
|
||||
if (oldAuthentication.equals(newAuthentication)) {
|
||||
return;
|
||||
}
|
||||
observation.event(
|
||||
Observation.Event.of(SECURITY_CONTEXT_CHANGED, "%s [%s] -> [%s]").format(SECURITY_CONTEXT_CHANGED,
|
||||
oldAuthentication.getClass().getSimpleName(), newAuthentication.getClass().getSimpleName()));
|
||||
observation.event(Observation.Event.of(SECURITY_CONTEXT_CHANGED, "%s [%s] -> [%s]")
|
||||
.format(SECURITY_CONTEXT_CHANGED, oldAuthentication.getClass().getSimpleName(),
|
||||
newAuthentication.getClass().getSimpleName()));
|
||||
}
|
||||
|
||||
private static Authentication getAuthentication(SecurityContext context) {
|
||||
|
||||
@@ -28,7 +28,6 @@ import java.lang.annotation.Target;
|
||||
* contain the parameter names.
|
||||
*
|
||||
* @see AnnotationParameterNameDiscoverer
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
*/
|
||||
|
||||
+6
-6
@@ -41,8 +41,8 @@ import org.springframework.util.Assert;
|
||||
* <p>
|
||||
* For this class to function correctly in a web application, it is important that you
|
||||
* register an <a href="
|
||||
* {@docRoot}/org/springframework/security/web/session/HttpSessionEventPublisher.html">HttpSessionEventPublisher</a>
|
||||
* in the <tt>web.xml</tt> file so that this class is notified of sessions that expire.
|
||||
* {@docRoot}/org/springframework/security/web/session/HttpSessionEventPublisher.html">HttpSessionEventPublisher</a> in
|
||||
* the <tt>web.xml</tt> file so that this class is notified of sessions that expire.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @author Luke Taylor
|
||||
@@ -158,16 +158,16 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener
|
||||
}
|
||||
this.sessionIds.remove(sessionId);
|
||||
this.principals.computeIfPresent(info.getPrincipal(), (key, sessionsUsedByPrincipal) -> {
|
||||
this.logger.debug(
|
||||
LogMessage.format("Removing session %s from principal's set of registered sessions", sessionId));
|
||||
this.logger
|
||||
.debug(LogMessage.format("Removing session %s from principal's set of registered sessions", sessionId));
|
||||
sessionsUsedByPrincipal.remove(sessionId);
|
||||
if (sessionsUsedByPrincipal.isEmpty()) {
|
||||
// No need to keep object in principals Map anymore
|
||||
this.logger.debug(LogMessage.format("Removing principal %s from registry", info.getPrincipal()));
|
||||
sessionsUsedByPrincipal = null;
|
||||
}
|
||||
this.logger.trace(
|
||||
LogMessage.format("Sessions used by '%s' : %s", info.getPrincipal(), sessionsUsedByPrincipal));
|
||||
this.logger
|
||||
.trace(LogMessage.format("Sessions used by '%s' : %s", info.getPrincipal(), sessionsUsedByPrincipal));
|
||||
return sessionsUsedByPrincipal;
|
||||
});
|
||||
}
|
||||
|
||||
+1
-1
@@ -105,7 +105,7 @@ public class KeyBasedPersistenceTokenService implements TokenService, Initializi
|
||||
return null;
|
||||
}
|
||||
String[] tokens = StringUtils
|
||||
.delimitedListToStringArray(Utf8.decode(Base64.getDecoder().decode(Utf8.encode(key))), ":");
|
||||
.delimitedListToStringArray(Utf8.decode(Base64.getDecoder().decode(Utf8.encode(key))), ":");
|
||||
Assert.isTrue(tokens.length >= 4, () -> "Expected 4 or more tokens but found " + tokens.length);
|
||||
long creationTime;
|
||||
try {
|
||||
|
||||
+2
-2
@@ -57,7 +57,7 @@ public class InMemoryUserDetailsManager implements UserDetailsManager, UserDetai
|
||||
private final Map<String, MutableUserDetails> users = new HashMap<>();
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@@ -130,7 +130,7 @@ public class InMemoryUserDetailsManager implements UserDetailsManager, UserDetai
|
||||
if (this.authenticationManager != null) {
|
||||
this.logger.debug(LogMessage.format("Reauthenticating user '%s' for password change request.", username));
|
||||
this.authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, oldPassword));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, oldPassword));
|
||||
}
|
||||
else {
|
||||
this.logger.debug("No authentication manager set. Password won't be re-checked.");
|
||||
|
||||
+2
-2
@@ -110,7 +110,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
private String createUserSql = DEF_CREATE_USER_SQL;
|
||||
|
||||
@@ -276,7 +276,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
|
||||
if (this.authenticationManager != null) {
|
||||
this.logger.debug(LogMessage.format("Reauthenticating user '%s' for password change request.", username));
|
||||
this.authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, oldPassword));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, oldPassword));
|
||||
}
|
||||
else {
|
||||
this.logger.debug("No authentication manager set. Password won't be re-checked.");
|
||||
|
||||
+4
-4
@@ -40,15 +40,15 @@ public class AuthenticationCredentialsNotFoundEventTests {
|
||||
@Test
|
||||
public void testRejectsNulls2() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), null,
|
||||
new AuthenticationCredentialsNotFoundException("test")));
|
||||
.isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), null,
|
||||
new AuthenticationCredentialsNotFoundException("test")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRejectsNulls3() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(),
|
||||
SecurityConfig.createList("TEST"), null));
|
||||
.isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(),
|
||||
SecurityConfig.createList("TEST"), null));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+3
-3
@@ -44,7 +44,7 @@ public class AuthorizationFailureEventTests {
|
||||
@Test
|
||||
public void rejectsNullSecureObject() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AuthorizationFailureEvent(null, this.attributes, this.foo, this.exception));
|
||||
.isThrownBy(() -> new AuthorizationFailureEvent(null, this.attributes, this.foo, this.exception));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -56,8 +56,8 @@ public class AuthorizationFailureEventTests {
|
||||
@Test
|
||||
public void rejectsNullAuthentication() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, null,
|
||||
this.exception));
|
||||
.isThrownBy(() -> new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, null,
|
||||
this.exception));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -48,7 +48,7 @@ public class SecurityConfigTests {
|
||||
@Test
|
||||
public void testNoArgConstructorDoesntExist() throws Exception {
|
||||
assertThatExceptionOfType(NoSuchMethodException.class)
|
||||
.isThrownBy(() -> SecurityConfig.class.getDeclaredConstructor((Class[]) null));
|
||||
.isThrownBy(() -> SecurityConfig.class.getDeclaredConstructor((Class[]) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-3
@@ -68,21 +68,21 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void noRoleMethodHasNoAttributes() throws Exception {
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds
|
||||
.findAttributes(this.a.getClass().getMethod("noRoleMethod"), null);
|
||||
.findAttributes(this.a.getClass().getMethod("noRoleMethod"), null);
|
||||
assertThat(accessAttributes).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void classRoleIsAppliedToNoRoleMethod() throws Exception {
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds
|
||||
.findAttributes(this.userAllowed.getClass().getMethod("noRoleMethod"), null);
|
||||
.findAttributes(this.userAllowed.getClass().getMethod("noRoleMethod"), null);
|
||||
assertThat(accessAttributes).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void methodRoleOverridesClassRole() throws Exception {
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds
|
||||
.findAttributes(this.userAllowed.getClass().getMethod("adminMethod"), null);
|
||||
.findAttributes(this.userAllowed.getClass().getMethod("adminMethod"), null);
|
||||
assertThat(accessAttributes).hasSize(1);
|
||||
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_ADMIN");
|
||||
}
|
||||
|
||||
+6
-5
@@ -42,15 +42,16 @@ public class Jsr250VoterTests {
|
||||
attrs.add(new Jsr250SecurityConfig("B"));
|
||||
attrs.add(new Jsr250SecurityConfig("C"));
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "A"), new Object(), attrs))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "B"), new Object(), attrs))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "C"), new Object(), attrs))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "NONE"), new Object(), attrs))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "A"), new Object(),
|
||||
SecurityConfig.createList("A", "B", "C"))).isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
|
||||
SecurityConfig.createList("A", "B", "C")))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -53,9 +53,9 @@ public class AbstractSecurityExpressionHandlerTests {
|
||||
public void beanNamesAreCorrectlyResolved() {
|
||||
this.handler.setApplicationContext(new AnnotationConfigApplicationContext(TestConfiguration.class));
|
||||
Expression expression = this.handler.getExpressionParser()
|
||||
.parseExpression("@number10.compareTo(@number20) < 0");
|
||||
.parseExpression("@number10.compareTo(@number20) < 0");
|
||||
assertThat(expression.getValue(this.handler.createEvaluationContext(mock(Authentication.class), new Object())))
|
||||
.isEqualTo(true);
|
||||
.isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-3
@@ -138,7 +138,7 @@ public class DefaultMethodSecurityExpressionHandlerTests {
|
||||
map.put("key2", "value2");
|
||||
map.put("key3", "value3");
|
||||
Expression expression = this.handler.getExpressionParser()
|
||||
.parseExpression("(filterObject.key eq 'key1') or (filterObject.value eq 'value2')");
|
||||
.parseExpression("(filterObject.key eq 'key1') or (filterObject.value eq 'value2')");
|
||||
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
|
||||
Object filtered = this.handler.filter(map, expression, context);
|
||||
assertThat(filtered == map);
|
||||
@@ -181,8 +181,9 @@ public class DefaultMethodSecurityExpressionHandlerTests {
|
||||
this.methodInvocation);
|
||||
verifyNoInteractions(mockAuthenticationSupplier);
|
||||
assertThat(context.getRootObject()).extracting(TypedValue::getValue)
|
||||
.asInstanceOf(InstanceOfAssertFactories.type(MethodSecurityExpressionRoot.class))
|
||||
.extracting(SecurityExpressionRoot::getAuthentication).isEqualTo(this.authentication);
|
||||
.asInstanceOf(InstanceOfAssertFactories.type(MethodSecurityExpressionRoot.class))
|
||||
.extracting(SecurityExpressionRoot::getAuthentication)
|
||||
.isEqualTo(this.authentication);
|
||||
verify(mockAuthenticationSupplier).get();
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -47,7 +47,7 @@ public class MethodExpressionVoterTests {
|
||||
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray());
|
||||
assertThat(this.am.vote(this.joe, mi,
|
||||
createAttributes(new PreInvocationExpressionAttribute(null, null, "hasRole('blah')"))))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -64,7 +64,7 @@ public class MethodExpressionVoterTests {
|
||||
assertThat(this.am.vote(this.joe, mi,
|
||||
createAttributes(new PreInvocationExpressionAttribute(null, null,
|
||||
"(#argument == principal) and (principal == 'joe')"))))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,7 +73,7 @@ public class MethodExpressionVoterTests {
|
||||
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(), arg);
|
||||
assertThat(this.am.vote(this.joe, mi,
|
||||
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'jim')", "collection", null))))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
// All objects should have been removed, because the expression is always false
|
||||
assertThat(arg).isEmpty();
|
||||
}
|
||||
@@ -117,7 +117,7 @@ public class MethodExpressionVoterTests {
|
||||
assertThat(this.am.vote(this.joe, mi,
|
||||
createAttributes(new PreInvocationExpressionAttribute(null, null,
|
||||
"T(org.springframework.security.access.expression.method.SecurityRules).isJoe(#argument)"))))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
}
|
||||
|
||||
private List<ConfigAttribute> createAttributes(ConfigAttribute... attributes) {
|
||||
|
||||
+1
-1
@@ -164,7 +164,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void customAnnotationAtInterfaceLevelIsDetected() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtInterfaceLevel)
|
||||
.toArray(new ConfigAttribute[0]);
|
||||
.toArray(new ConfigAttribute[0]);
|
||||
assertThat(attrs).hasSize(1);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ public class RoleHierarchyAuthoritiesMapperTests {
|
||||
rh.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C");
|
||||
RoleHierarchyAuthoritiesMapper mapper = new RoleHierarchyAuthoritiesMapper(rh);
|
||||
Collection<? extends GrantedAuthority> authorities = mapper
|
||||
.mapAuthorities(AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_D"));
|
||||
.mapAuthorities(AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_D"));
|
||||
assertThat(authorities).hasSize(4);
|
||||
mapper = new RoleHierarchyAuthoritiesMapper(new NullRoleHierarchy());
|
||||
authorities = mapper.mapAuthorities(AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_D"));
|
||||
|
||||
+38
-24
@@ -55,11 +55,14 @@ public class RoleHierarchyImplTests {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), authorities0)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), authorities0))
|
||||
.isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2))
|
||||
.isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2), authorities2)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2), authorities2))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -71,10 +74,12 @@ public class RoleHierarchyImplTests {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2))
|
||||
.isTrue();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_D");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities3)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities3))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -91,35 +96,39 @@ public class RoleHierarchyImplTests {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput1), authoritiesOutput1)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput1), authoritiesOutput1))
|
||||
.isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput2), authoritiesOutput2)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput2), authoritiesOutput2))
|
||||
.isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput3), authoritiesOutput3)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput3), authoritiesOutput3))
|
||||
.isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput4), authoritiesOutput4)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput4), authoritiesOutput4))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCyclesInRoleHierarchy() {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
assertThatExceptionOfType(CycleInRoleHierarchyException.class)
|
||||
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_A"));
|
||||
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_A"));
|
||||
assertThatExceptionOfType(CycleInRoleHierarchyException.class)
|
||||
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_A"));
|
||||
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_A"));
|
||||
assertThatExceptionOfType(CycleInRoleHierarchyException.class)
|
||||
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A"));
|
||||
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A"));
|
||||
assertThatExceptionOfType(CycleInRoleHierarchyException.class).isThrownBy(() -> roleHierarchyImpl
|
||||
.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B"));
|
||||
.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B"));
|
||||
assertThatExceptionOfType(CycleInRoleHierarchyException.class)
|
||||
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B"));
|
||||
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoCyclesInRoleHierarchy() {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
assertThatNoException().isThrownBy(() -> roleHierarchyImpl
|
||||
.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"));
|
||||
.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"));
|
||||
}
|
||||
|
||||
// SEC-863
|
||||
@@ -131,11 +140,14 @@ public class RoleHierarchyImplTests {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), authorities0)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), authorities0))
|
||||
.isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2))
|
||||
.isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2), authorities2)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2), authorities2))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -147,10 +159,12 @@ public class RoleHierarchyImplTests {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE A > ROLE B\nROLE B > ROLE>C");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2))
|
||||
.isTrue();
|
||||
roleHierarchyImpl.setHierarchy("ROLE A > ROLE B\nROLE B > ROLE>C\nROLE>C > ROLE D");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities3)).isTrue();
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities3))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
// gh-6954
|
||||
@@ -163,7 +177,7 @@ public class RoleHierarchyImplTests {
|
||||
roleHierarchyImpl.setHierarchy(
|
||||
"ROLE_A > ROLE_B\n" + "ROLE_B > ROLE_AUTHENTICATED\n" + "ROLE_AUTHENTICATED > ROLE_UNAUTHENTICATED");
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
|
||||
.containsExactlyInAnyOrderElementsOf(allAuthorities);
|
||||
.containsExactlyInAnyOrderElementsOf(allAuthorities);
|
||||
}
|
||||
|
||||
// gh-6954
|
||||
@@ -174,9 +188,9 @@ public class RoleHierarchyImplTests {
|
||||
"ROLE_LOW", "ROLE_LOWER");
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl
|
||||
.setHierarchy("ROLE_HIGHEST > ROLE_HIGHER\n" + "ROLE_HIGHER > ROLE_LOW\n" + "ROLE_LOW > ROLE_LOWER");
|
||||
.setHierarchy("ROLE_HIGHEST > ROLE_HIGHER\n" + "ROLE_HIGHER > ROLE_LOW\n" + "ROLE_LOW > ROLE_LOWER");
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
|
||||
.containsExactlyInAnyOrderElementsOf(allAuthorities);
|
||||
.containsExactlyInAnyOrderElementsOf(allAuthorities);
|
||||
}
|
||||
|
||||
// gh-6954
|
||||
@@ -188,7 +202,7 @@ public class RoleHierarchyImplTests {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_HIGHEST > ROLE_HIGHER > ROLE_LOW > ROLE_LOWER");
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
|
||||
.containsExactlyInAnyOrderElementsOf(allAuthorities);
|
||||
.containsExactlyInAnyOrderElementsOf(allAuthorities);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+6
-6
@@ -60,8 +60,8 @@ public class RoleHierarchyUtilsTests {
|
||||
|
||||
@Test
|
||||
public void roleHierarchyFromMapWhenMapEmptyThenThrowsIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> RoleHierarchyUtils.roleHierarchyFromMap(Collections.<String, List<String>>emptyMap()));
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(Collections.<String, List<String>>emptyMap()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -69,7 +69,7 @@ public class RoleHierarchyUtilsTests {
|
||||
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
|
||||
roleHierarchyMap.put(null, Arrays.asList("ROLE_B", "ROLE_C"));
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
|
||||
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -77,7 +77,7 @@ public class RoleHierarchyUtilsTests {
|
||||
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
|
||||
roleHierarchyMap.put("", Arrays.asList("ROLE_B", "ROLE_C"));
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
|
||||
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -85,7 +85,7 @@ public class RoleHierarchyUtilsTests {
|
||||
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
|
||||
roleHierarchyMap.put("ROLE_A", null);
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
|
||||
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -93,7 +93,7 @@ public class RoleHierarchyUtilsTests {
|
||||
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
|
||||
roleHierarchyMap.put("ROLE_A", Collections.<String>emptyList());
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
|
||||
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+7
-6
@@ -79,19 +79,19 @@ public class TestHelperTests {
|
||||
authoritiesStrings5.add("ROLE_A");
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities1), authoritiesStrings1))
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities2), authoritiesStrings2))
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities3), authoritiesStrings3))
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities4), authoritiesStrings4))
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities5), authoritiesStrings5))
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
// SEC-863
|
||||
@@ -121,7 +121,8 @@ public class TestHelperTests {
|
||||
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A", "ROLE_B");
|
||||
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(authorities1,
|
||||
authorities2)).isTrue();
|
||||
authorities2))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
// SEC-863
|
||||
|
||||
+5
-5
@@ -57,15 +57,15 @@ public class AfterInvocationProviderManagerTests {
|
||||
List<ConfigAttribute> attr2and3 = SecurityConfig.createList(new String[] { "GIVE_ME_SWAP2", "GIVE_ME_SWAP3" });
|
||||
List<ConfigAttribute> attr4 = SecurityConfig.createList(new String[] { "NEVER_CAUSES_SWAP" });
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr1, "content-before-swapping"))
|
||||
.isEqualTo("swap1");
|
||||
.isEqualTo("swap1");
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2, "content-before-swapping"))
|
||||
.isEqualTo("swap2");
|
||||
.isEqualTo("swap2");
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr3, "content-before-swapping"))
|
||||
.isEqualTo("swap3");
|
||||
.isEqualTo("swap3");
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr4, "content-before-swapping"))
|
||||
.isEqualTo("content-before-swapping");
|
||||
.isEqualTo("content-before-swapping");
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2and3, "content-before-swapping"))
|
||||
.isEqualTo("swap3");
|
||||
.isEqualTo("swap3");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-3
@@ -53,7 +53,7 @@ public class RunAsUserTokenTests {
|
||||
@Test
|
||||
public void testNoArgConstructorDoesntExist() {
|
||||
assertThatExceptionOfType(NoSuchMethodException.class)
|
||||
.isThrownBy(() -> RunAsUserToken.class.getDeclaredConstructor((Class[]) null));
|
||||
.isThrownBy(() -> RunAsUserToken.class.getDeclaredConstructor((Class[]) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -61,8 +61,8 @@ public class RunAsUserTokenTests {
|
||||
RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class);
|
||||
assertThat(token.toString()
|
||||
.lastIndexOf("Original Class: " + UsernamePasswordAuthenticationToken.class.getName().toString()) != -1)
|
||||
.isTrue();
|
||||
.lastIndexOf("Original Class: " + UsernamePasswordAuthenticationToken.class.getName().toString()) != -1)
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
// SEC-1792
|
||||
|
||||
+7
-7
@@ -216,7 +216,7 @@ public class MethodSecurityInterceptorTests {
|
||||
mdsReturnsNull();
|
||||
SecurityContextHolder.getContext().setAuthentication(this.token);
|
||||
assertThat(this.advisedTarget.publicMakeLowerCase("HELLO"))
|
||||
.isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken false");
|
||||
.isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken false");
|
||||
assertThat(!this.token.isAuthenticated()).isTrue();
|
||||
}
|
||||
|
||||
@@ -227,7 +227,7 @@ public class MethodSecurityInterceptorTests {
|
||||
mdsReturnsUserRole();
|
||||
given(this.authman.authenticate(token)).willThrow(new BadCredentialsException("rejected"));
|
||||
assertThatExceptionOfType(AuthenticationException.class)
|
||||
.isThrownBy(() -> this.advisedTarget.makeLowerCase("HELLO"));
|
||||
.isThrownBy(() -> this.advisedTarget.makeLowerCase("HELLO"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -239,7 +239,7 @@ public class MethodSecurityInterceptorTests {
|
||||
String result = this.advisedTarget.makeLowerCase("HELLO");
|
||||
// Note we check the isAuthenticated remained true in following line
|
||||
assertThat(result)
|
||||
.isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken true");
|
||||
.isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken true");
|
||||
verify(this.eventPublisher).publishEvent(any(AuthorizedEvent.class));
|
||||
}
|
||||
|
||||
@@ -251,10 +251,10 @@ public class MethodSecurityInterceptorTests {
|
||||
createTarget(true);
|
||||
mdsReturnsUserRole();
|
||||
given(this.authman.authenticate(this.token)).willReturn(this.token);
|
||||
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(any(Authentication.class),
|
||||
any(MethodInvocation.class), any(List.class));
|
||||
willThrow(new AccessDeniedException("rejected")).given(this.adm)
|
||||
.decide(any(Authentication.class), any(MethodInvocation.class), any(List.class));
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.advisedTarget.makeUpperCase("HELLO"));
|
||||
.isThrownBy(() -> this.advisedTarget.makeUpperCase("HELLO"));
|
||||
verify(this.eventPublisher).publishEvent(any(AuthorizationFailureEvent.class));
|
||||
}
|
||||
|
||||
@@ -305,7 +305,7 @@ public class MethodSecurityInterceptorTests {
|
||||
public void emptySecurityContextIsRejected() {
|
||||
mdsReturnsUserRole();
|
||||
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
|
||||
.isThrownBy(() -> this.advisedTarget.makeUpperCase("hello"));
|
||||
.isThrownBy(() -> this.advisedTarget.makeUpperCase("hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-3
@@ -128,7 +128,7 @@ public class AspectJMethodSecurityInterceptorTests {
|
||||
willThrow(new AccessDeniedException("denied")).given(this.adm).decide(any(), any(), any());
|
||||
SecurityContextHolder.getContext().setAuthentication(this.token);
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
|
||||
.isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
|
||||
verify(this.aspectJCallback, never()).proceedWithObject();
|
||||
}
|
||||
|
||||
@@ -153,7 +153,7 @@ public class AspectJMethodSecurityInterceptorTests {
|
||||
this.interceptor.setAfterInvocationManager(aim);
|
||||
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
|
||||
assertThatExceptionOfType(RuntimeException.class)
|
||||
.isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
|
||||
.isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
|
||||
verifyNoMoreInteractions(aim);
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ public class AspectJMethodSecurityInterceptorTests {
|
||||
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
|
||||
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
|
||||
assertThatExceptionOfType(RuntimeException.class)
|
||||
.isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
|
||||
.isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
|
||||
// Check we've changed back
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
|
||||
|
||||
+2
-2
@@ -46,7 +46,7 @@ public class DelegatingMethodSecurityMetadataSourceTests {
|
||||
List sources = new ArrayList();
|
||||
MethodSecurityMetadataSource delegate = mock(MethodSecurityMetadataSource.class);
|
||||
given(delegate.getAttributes(ArgumentMatchers.<Method>any(), ArgumentMatchers.any(Class.class)))
|
||||
.willReturn(null);
|
||||
.willReturn(null);
|
||||
sources.add(delegate);
|
||||
this.mds = new DelegatingMethodSecurityMetadataSource(sources);
|
||||
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);
|
||||
@@ -74,7 +74,7 @@ public class DelegatingMethodSecurityMetadataSourceTests {
|
||||
// Exercise the cached case
|
||||
assertThat(this.mds.getAttributes(mi)).isSameAs(attributes);
|
||||
assertThat(this.mds.getAttributes(new SimpleMethodInvocation(null, String.class.getMethod("length"))))
|
||||
.isEmpty();
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+5
-5
@@ -61,11 +61,11 @@ public class AffirmativeBasedTests {
|
||||
this.abstain = mock(AccessDecisionVoter.class);
|
||||
this.deny = mock(AccessDecisionVoter.class);
|
||||
given(this.grant.vote(any(Authentication.class), any(Object.class), any(List.class)))
|
||||
.willReturn(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.willReturn(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
given(this.abstain.vote(any(Authentication.class), any(Object.class), any(List.class)))
|
||||
.willReturn(AccessDecisionVoter.ACCESS_ABSTAIN);
|
||||
.willReturn(AccessDecisionVoter.ACCESS_ABSTAIN);
|
||||
given(this.deny.vote(any(Authentication.class), any(Object.class), any(List.class)))
|
||||
.willReturn(AccessDecisionVoter.ACCESS_DENIED);
|
||||
.willReturn(AccessDecisionVoter.ACCESS_DENIED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -95,7 +95,7 @@ public class AffirmativeBasedTests {
|
||||
this.mgr = new AffirmativeBased(
|
||||
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.deny, this.abstain, this.abstain));
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.mgr.decide(this.user, new Object(), this.attrs));
|
||||
.isThrownBy(() -> this.mgr.decide(this.user, new Object(), this.attrs));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -104,7 +104,7 @@ public class AffirmativeBasedTests {
|
||||
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.abstain, this.abstain, this.abstain));
|
||||
assertThat(!this.mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.mgr.decide(this.user, new Object(), this.attrs));
|
||||
.isThrownBy(() -> this.mgr.decide(this.user, new Object(), this.attrs));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-2
@@ -68,7 +68,7 @@ public class ConsensusBasedTests {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
ConsensusBased mgr = makeDecisionManager();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE")));
|
||||
.isThrownBy(() -> mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -77,7 +77,7 @@ public class ConsensusBasedTests {
|
||||
ConsensusBased mgr = makeDecisionManager();
|
||||
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL")));
|
||||
.isThrownBy(() -> mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ public class RoleHierarchyVoterTests {
|
||||
TestingAuthenticationToken auth = new TestingAuthenticationToken("user", "password", "ROLE_A");
|
||||
RoleHierarchyVoter voter = new RoleHierarchyVoter(roleHierarchyImpl);
|
||||
assertThat(voter.vote(auth, new Object(), SecurityConfig.createList("ROLE_B")))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ public class RoleVoterTests {
|
||||
Authentication userAB = new TestingAuthenticationToken("user", "pass", "A", "B");
|
||||
// Vote on attribute list that has two attributes A and C (i.e. only one matching)
|
||||
assertThat(voter.vote(userAB, this, SecurityConfig.createList("A", "C")))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
}
|
||||
|
||||
// SEC-3128
|
||||
@@ -47,7 +47,7 @@ public class RoleVoterTests {
|
||||
voter.setRolePrefix("");
|
||||
Authentication notAuthenitcated = null;
|
||||
assertThat(voter.vote(notAuthenitcated, this, SecurityConfig.createList("A")))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+28
-21
@@ -66,49 +66,54 @@ class CoreSecurityRuntimeHintsTests {
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories").load(RuntimeHintsRegistrar.class)
|
||||
.forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
|
||||
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
|
||||
.load(RuntimeHintsRegistrar.class)
|
||||
.forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void springSecurityMessagesBundleHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.resource().forBundle("org.springframework.security.messages"))
|
||||
.accepts(this.hints);
|
||||
.accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
void securityExpressionOperationsHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(SecurityExpressionOperations.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS))
|
||||
.accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(SecurityExpressionOperations.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS))
|
||||
.accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
void securityExpressionRootHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(SecurityExpressionRoot.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS))
|
||||
.accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(SecurityExpressionRoot.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS))
|
||||
.accepts(this.hints);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("getAuthenticationEvents")
|
||||
void exceptionEventsHasHints(Class<? extends AbstractAuthenticationEvent> event) {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(event)
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(event)
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
void methodSecurityExpressionRootHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(TypeReference
|
||||
.of("org.springframework.security.access.expression.method.MethodSecurityExpressionRoot"))
|
||||
.withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(this.hints);
|
||||
.onType(TypeReference
|
||||
.of("org.springframework.security.access.expression.method.MethodSecurityExpressionRoot"))
|
||||
.withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
void abstractAuthenticationTokenHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(AbstractAuthenticationToken.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(AbstractAuthenticationToken.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
private static Stream<Class<? extends AbstractAuthenticationEvent>> getAuthenticationEvents() {
|
||||
@@ -122,8 +127,9 @@ class CoreSecurityRuntimeHintsTests {
|
||||
@ParameterizedTest
|
||||
@MethodSource("getAuthenticationExceptions")
|
||||
void exceptionHasHints(Class<? extends AuthenticationException> exception) {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(exception)
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(exception)
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
private static Stream<Class<? extends AuthenticationException>> getAuthenticationExceptions() {
|
||||
@@ -135,13 +141,14 @@ class CoreSecurityRuntimeHintsTests {
|
||||
@Test
|
||||
void defaultJdbcSchemaFileHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.resource()
|
||||
.forResource("org/springframework/security/core/userdetails/jdbc/users.ddl")).accepts(this.hints);
|
||||
.forResource("org/springframework/security/core/userdetails/jdbc/users.ddl")).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
void securityContextHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(SecurityContextImpl.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(SecurityContextImpl.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ public class AbstractAuthenticationTokenTests {
|
||||
List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token.getAuthorities();
|
||||
assertThat(gotAuthorities).isNotSameAs(this.authorities);
|
||||
assertThatExceptionOfType(UnsupportedOperationException.class)
|
||||
.isThrownBy(() -> gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER")));
|
||||
.isThrownBy(() -> gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-4
@@ -35,10 +35,10 @@ public class AuthenticationTrustResolverImplTests {
|
||||
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
|
||||
assertThat(trustResolver.isAnonymous(
|
||||
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))))
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
assertThat(trustResolver.isAnonymous(
|
||||
new TestingAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))))
|
||||
.isFalse();
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -46,10 +46,10 @@ public class AuthenticationTrustResolverImplTests {
|
||||
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
|
||||
assertThat(trustResolver.isRememberMe(
|
||||
new RememberMeAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))))
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
assertThat(trustResolver.isAnonymous(
|
||||
new TestingAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))))
|
||||
.isFalse();
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-3
@@ -118,7 +118,7 @@ public class DefaultAuthenticationEventPublisherTests {
|
||||
Properties p = new Properties();
|
||||
p.put(MockAuthenticationException.class.getName(), "NoSuchClass");
|
||||
assertThatExceptionOfType(RuntimeException.class)
|
||||
.isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(p));
|
||||
.isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -174,7 +174,7 @@ public class DefaultAuthenticationEventPublisherTests {
|
||||
public void defaultAuthenticationFailureEventClassSetNullThen() {
|
||||
this.publisher = new DefaultAuthenticationEventPublisher();
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.publisher.setDefaultAuthenticationFailureEvent(null));
|
||||
.isThrownBy(() -> this.publisher.setDefaultAuthenticationFailureEvent(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -192,7 +192,7 @@ public class DefaultAuthenticationEventPublisherTests {
|
||||
public void defaultAuthenticationFailureEventMissingAppropriateConstructorThen() {
|
||||
this.publisher = new DefaultAuthenticationEventPublisher();
|
||||
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.publisher
|
||||
.setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class));
|
||||
.setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class));
|
||||
}
|
||||
|
||||
private static final class AuthenticationFailureEventWithoutAppropriateConstructor
|
||||
|
||||
+4
-3
@@ -61,7 +61,7 @@ public class DelegatingReactiveAuthenticationManagerTests {
|
||||
// delay to try and force delegate2 to finish (i.e. make sure we didn't use
|
||||
// flatMap)
|
||||
given(this.delegate1.authenticate(any()))
|
||||
.willReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
|
||||
.willReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
|
||||
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
|
||||
this.delegate2);
|
||||
StepVerifier.create(manager.authenticate(this.authentication)).expectNext(this.authentication).verifyComplete();
|
||||
@@ -72,8 +72,9 @@ public class DelegatingReactiveAuthenticationManagerTests {
|
||||
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
|
||||
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
|
||||
this.delegate2);
|
||||
StepVerifier.create(manager.authenticate(this.authentication)).expectError(BadCredentialsException.class)
|
||||
.verify();
|
||||
StepVerifier.create(manager.authenticate(this.authentication))
|
||||
.expectError(BadCredentialsException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -96,7 +96,7 @@ public class ObservationAuthenticationManagerTests {
|
||||
@Test
|
||||
void setObservationConventionWhenNullThenException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.tested.setObservationConvention(null));
|
||||
.isThrownBy(() -> this.tested.setObservationConvention(null));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+3
-3
@@ -82,9 +82,9 @@ public class ObservationReactiveAuthenticationManagerTests {
|
||||
void authenticationWhenErrorsThenObserves() {
|
||||
given(this.handler.supportsContext(any())).willReturn(true);
|
||||
given(this.authenticationManager.authenticate(any()))
|
||||
.willReturn(Mono.error(new BadCredentialsException("fail")));
|
||||
.willReturn(Mono.error(new BadCredentialsException("fail")));
|
||||
assertThatExceptionOfType(BadCredentialsException.class)
|
||||
.isThrownBy(() -> this.tested.authenticate(this.token).block());
|
||||
.isThrownBy(() -> this.tested.authenticate(this.token).block());
|
||||
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
|
||||
verify(this.handler).onStart(captor.capture());
|
||||
assertThat(captor.getValue().getName()).isEqualTo(AuthenticationObservationConvention.OBSERVATION_NAME);
|
||||
@@ -99,7 +99,7 @@ public class ObservationReactiveAuthenticationManagerTests {
|
||||
@Test
|
||||
void setObservationConventionWhenNullThenException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.tested.setObservationConvention(null));
|
||||
.isThrownBy(() -> this.tested.setObservationConvention(null));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+9
-9
@@ -113,7 +113,7 @@ public class ProviderManagerTests {
|
||||
@Test
|
||||
public void testStartupFailsIfProvidersContainNullElement() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new ProviderManager(Arrays.asList(mock(AuthenticationProvider.class), null)));
|
||||
.isThrownBy(() -> new ProviderManager(Arrays.asList(mock(AuthenticationProvider.class), null)));
|
||||
}
|
||||
|
||||
// gh-8689
|
||||
@@ -173,9 +173,9 @@ public class ProviderManagerTests {
|
||||
@Test
|
||||
public void authenticationExceptionIsRethrownIfNoLaterProviderAuthenticates() {
|
||||
ProviderManager mgr = new ProviderManager(Arrays
|
||||
.asList(createProviderWhichThrows(new BadCredentialsException("")), createProviderWhichReturns(null)));
|
||||
.asList(createProviderWhichThrows(new BadCredentialsException("")), createProviderWhichReturns(null)));
|
||||
assertThatExceptionOfType(BadCredentialsException.class)
|
||||
.isThrownBy(() -> mgr.authenticate(mock(Authentication.class)));
|
||||
.isThrownBy(() -> mgr.authenticate(mock(Authentication.class)));
|
||||
}
|
||||
|
||||
// SEC-546
|
||||
@@ -186,7 +186,7 @@ public class ProviderManagerTests {
|
||||
AuthenticationProvider otherProvider = mock(AuthenticationProvider.class);
|
||||
ProviderManager authMgr = new ProviderManager(Arrays.asList(iThrowAccountStatusException, otherProvider));
|
||||
assertThatExceptionOfType(AccountStatusException.class)
|
||||
.isThrownBy(() -> authMgr.authenticate(mock(Authentication.class)));
|
||||
.isThrownBy(() -> authMgr.authenticate(mock(Authentication.class)));
|
||||
verifyNoInteractions(otherProvider);
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@ public class ProviderManagerTests {
|
||||
AuthenticationManager parent = mock(AuthenticationManager.class);
|
||||
ProviderManager mgr = new ProviderManager(Collections.singletonList(iThrowAccountStatusException), parent);
|
||||
assertThatExceptionOfType(AccountStatusException.class)
|
||||
.isThrownBy(() -> mgr.authenticate(mock(Authentication.class)));
|
||||
.isThrownBy(() -> mgr.authenticate(mock(Authentication.class)));
|
||||
verifyNoInteractions(parent);
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ public class ProviderManagerTests {
|
||||
Collections.singletonList(createProviderWhichThrows(new BadCredentialsException(""))), parent);
|
||||
mgr.setAuthenticationEventPublisher(publisher);
|
||||
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq))
|
||||
.satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, authReq));
|
||||
.satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, authReq));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -240,7 +240,7 @@ public class ProviderManagerTests {
|
||||
BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
|
||||
given(parent.authenticate(authReq)).willThrow(expected);
|
||||
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq))
|
||||
.isSameAs(expected);
|
||||
.isSameAs(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -264,7 +264,7 @@ public class ProviderManagerTests {
|
||||
createProviderWhichThrows(new BadCredentialsException("Oops"))), null);
|
||||
Authentication authReq = mock(Authentication.class);
|
||||
assertThatExceptionOfType(InternalAuthenticationServiceException.class)
|
||||
.isThrownBy(() -> mgr.authenticate(authReq));
|
||||
.isThrownBy(() -> mgr.authenticate(authReq));
|
||||
}
|
||||
|
||||
// gh-6281
|
||||
@@ -279,7 +279,7 @@ public class ProviderManagerTests {
|
||||
childMgr.setAuthenticationEventPublisher(publisher);
|
||||
final Authentication authReq = mock(Authentication.class);
|
||||
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> childMgr.authenticate(authReq))
|
||||
.isSameAs(badCredentialsExParent);
|
||||
.isSameAs(badCredentialsExParent);
|
||||
verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq); // Parent
|
||||
// publishes
|
||||
verifyNoMoreInteractions(publisher); // Child should not publish (duplicate event)
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
|
||||
@Test
|
||||
public void constructorNullUserDetailsService() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new UserDetailsRepositoryReactiveAuthenticationManager(null));
|
||||
.isThrownBy(() -> new UserDetailsRepositoryReactiveAuthenticationManager(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-4
@@ -127,7 +127,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user,
|
||||
this.user.getPassword());
|
||||
assertThatExceptionOfType(BadCredentialsException.class)
|
||||
.isThrownBy(() -> this.manager.authenticate(token).block());
|
||||
.isThrownBy(() -> this.manager.authenticate(token).block());
|
||||
verifyNoMoreInteractions(this.userDetailsPasswordService);
|
||||
}
|
||||
|
||||
@@ -151,9 +151,11 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
given(this.encoder.matches(any(), any())).willReturn(true);
|
||||
this.manager.setPasswordEncoder(this.encoder);
|
||||
this.manager.setPostAuthenticationChecks(this.postAuthenticationChecks);
|
||||
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager
|
||||
assertThatExceptionOfType(LockedException.class)
|
||||
.isThrownBy(() -> this.manager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword()))
|
||||
.block()).withMessage("account is locked");
|
||||
.block())
|
||||
.withMessage("account is locked");
|
||||
verify(this.postAuthenticationChecks).check(eq(this.user));
|
||||
}
|
||||
|
||||
@@ -182,7 +184,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(expiredUser,
|
||||
expiredUser.getPassword());
|
||||
assertThatExceptionOfType(AccountExpiredException.class)
|
||||
.isThrownBy(() -> this.manager.authenticate(token).block());
|
||||
.isThrownBy(() -> this.manager.authenticate(token).block());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-2
@@ -45,7 +45,7 @@ public class UsernamePasswordAuthenticationTokenTests {
|
||||
// Now let's create a UsernamePasswordAuthenticationToken without any
|
||||
// GrantedAuthorty[]s (different constructor)
|
||||
UsernamePasswordAuthenticationToken noneGrantedToken = UsernamePasswordAuthenticationToken
|
||||
.unauthenticated("Test", "Password");
|
||||
.unauthenticated("Test", "Password");
|
||||
assertThat(!noneGrantedToken.isAuthenticated()).isTrue();
|
||||
// check we're allowed to still set it to untrusted
|
||||
noneGrantedToken.setAuthenticated(false);
|
||||
@@ -68,7 +68,7 @@ public class UsernamePasswordAuthenticationTokenTests {
|
||||
public void testNoArgConstructorDoesntExist() throws Exception {
|
||||
Class<?> clazz = UsernamePasswordAuthenticationToken.class;
|
||||
assertThatExceptionOfType(NoSuchMethodException.class)
|
||||
.isThrownBy(() -> clazz.getDeclaredConstructor((Class[]) null));
|
||||
.isThrownBy(() -> clazz.getDeclaredConstructor((Class[]) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-3
@@ -45,7 +45,7 @@ public class AnonymousAuthenticationTokenTests {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", null, ROLES_12));
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", "Test", null));
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES));
|
||||
.isThrownBy(() -> new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -68,7 +68,7 @@ public class AnonymousAuthenticationTokenTests {
|
||||
@Test
|
||||
public void testNoArgConstructorDoesntExist() {
|
||||
assertThatExceptionOfType(NoSuchMethodException.class)
|
||||
.isThrownBy(() -> AnonymousAuthenticationToken.class.getDeclaredConstructor((Class[]) null));
|
||||
.isThrownBy(() -> AnonymousAuthenticationToken.class.getDeclaredConstructor((Class[]) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -104,7 +104,7 @@ public class AnonymousAuthenticationTokenTests {
|
||||
@Test
|
||||
public void constructorWhenNullAuthoritiesThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AnonymousAuthenticationToken("key", "principal", null));
|
||||
.isThrownBy(() -> new AnonymousAuthenticationToken("key", "principal", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+11
-9
@@ -89,9 +89,9 @@ public class DaoAuthenticationProviderTests {
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken
|
||||
.unauthenticated("rod", null);
|
||||
.unauthenticated("rod", null);
|
||||
assertThatExceptionOfType(BadCredentialsException.class)
|
||||
.isThrownBy(() -> provider.authenticate(authenticationToken));
|
||||
.isThrownBy(() -> provider.authenticate(authenticationToken));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -124,7 +124,7 @@ public class DaoAuthenticationProviderTests {
|
||||
// Check that wrong password causes BadCredentialsException, rather than
|
||||
// CredentialsExpiredException
|
||||
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("peter", "wrong_password")));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("peter", "wrong_password")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -144,7 +144,7 @@ public class DaoAuthenticationProviderTests {
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceSimulateBackendError());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
assertThatExceptionOfType(InternalAuthenticationServiceException.class)
|
||||
.isThrownBy(() -> provider.authenticate(token));
|
||||
.isThrownBy(() -> provider.authenticate(token));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -330,7 +330,7 @@ public class DaoAuthenticationProviderTests {
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceReturnsNull());
|
||||
assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(token))
|
||||
.withMessage("UserDetailsService returned null, which is an interface contract violation");
|
||||
.withMessage("UserDetailsService returned null, which is an interface contract violation");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -457,7 +457,7 @@ public class DaoAuthenticationProviderTests {
|
||||
UsernamePasswordAuthenticationToken foundUser = UsernamePasswordAuthenticationToken.unauthenticated("rod",
|
||||
"koala");
|
||||
UsernamePasswordAuthenticationToken notFoundUser = UsernamePasswordAuthenticationToken
|
||||
.unauthenticated("notFound", "koala");
|
||||
.unauthenticated("notFound", "koala");
|
||||
PasswordEncoder encoder = new BCryptPasswordEncoder(10, new SecureRandom());
|
||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||
provider.setHideUserNotFoundExceptions(false);
|
||||
@@ -476,13 +476,15 @@ public class DaoAuthenticationProviderTests {
|
||||
for (int i = 0; i < sampleSize; i++) {
|
||||
long start = System.currentTimeMillis();
|
||||
assertThatExceptionOfType(UsernameNotFoundException.class)
|
||||
.isThrownBy(() -> provider.authenticate(notFoundUser));
|
||||
.isThrownBy(() -> provider.authenticate(notFoundUser));
|
||||
userNotFoundTimes.add(System.currentTimeMillis() - start);
|
||||
}
|
||||
double userFoundAvg = avg(userFoundTimes);
|
||||
double userNotFoundAvg = avg(userNotFoundTimes);
|
||||
assertThat(Math.abs(userNotFoundAvg - userFoundAvg) <= 3).withFailMessage("User not found average "
|
||||
+ userNotFoundAvg + " should be within 3ms of user found average " + userFoundAvg).isTrue();
|
||||
assertThat(Math.abs(userNotFoundAvg - userFoundAvg) <= 3)
|
||||
.withFailMessage("User not found average " + userNotFoundAvg
|
||||
+ " should be within 3ms of user found average " + userFoundAvg)
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
private double avg(List<Long> counts) {
|
||||
|
||||
+2
-2
@@ -35,7 +35,7 @@ public class AuthenticationEventTests {
|
||||
|
||||
private Authentication getAuthentication() {
|
||||
UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken
|
||||
.unauthenticated("Principal", "Credentials");
|
||||
.unauthenticated("Principal", "Credentials");
|
||||
authentication.setDetails("127.0.0.1");
|
||||
return authentication;
|
||||
}
|
||||
@@ -65,7 +65,7 @@ public class AuthenticationEventTests {
|
||||
@Test
|
||||
public void testRejectsNullAuthenticationException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AuthenticationFailureDisabledEvent(getAuthentication(), null));
|
||||
.isThrownBy(() -> new AuthenticationFailureDisabledEvent(getAuthentication(), null));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ public class LoggerListenerTests {
|
||||
|
||||
private Authentication getAuthentication() {
|
||||
UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken
|
||||
.unauthenticated("Principal", "Credentials");
|
||||
.unauthenticated("Principal", "Credentials");
|
||||
authentication.setDetails("127.0.0.1");
|
||||
return authentication;
|
||||
}
|
||||
|
||||
+2
-2
@@ -121,7 +121,7 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
@Test
|
||||
public void authenticateBadUser() {
|
||||
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.provider
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("asdf", "password")));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("asdf", "password")));
|
||||
verifyFailedLogin();
|
||||
}
|
||||
|
||||
@@ -236,7 +236,7 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
|
||||
private void verifyFailedLogin() {
|
||||
ArgumentCaptor<JaasAuthenticationFailedEvent> event = ArgumentCaptor
|
||||
.forClass(JaasAuthenticationFailedEvent.class);
|
||||
.forClass(JaasAuthenticationFailedEvent.class);
|
||||
verify(this.publisher).publishEvent(event.capture());
|
||||
assertThat(event.getValue()).isInstanceOf(JaasAuthenticationFailedEvent.class);
|
||||
assertThat(event.getValue().getException()).isNotNull();
|
||||
|
||||
+12
-12
@@ -76,20 +76,20 @@ public class JaasAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testBadPassword() {
|
||||
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.jaasProvider
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "asdf")));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "asdf")));
|
||||
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
|
||||
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
|
||||
.isNotNull();
|
||||
.isNotNull();
|
||||
assertThat(this.eventCheck.successEvent).as("Success event was fired").isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBadUser() {
|
||||
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.jaasProvider
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("asdf", "password")));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("asdf", "password")));
|
||||
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
|
||||
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
|
||||
.isNotNull();
|
||||
.isNotNull();
|
||||
assertThat(this.eventCheck.successEvent).as("Success event was fired").isNull();
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ public class JaasAuthenticationProviderTests {
|
||||
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
|
||||
myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName());
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> myJaasProvider.afterPropertiesSet())
|
||||
.withMessageStartingWith("loginConfig must be set on");
|
||||
.withMessageStartingWith("loginConfig must be set on");
|
||||
}
|
||||
|
||||
// SEC-1239
|
||||
@@ -150,10 +150,10 @@ public class JaasAuthenticationProviderTests {
|
||||
myJaasProvider.setLoginConfig(this.jaasProvider.getLoginConfig());
|
||||
myJaasProvider.setLoginContextName(null);
|
||||
assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet)
|
||||
.withMessageStartingWith("loginContextName must be set on");
|
||||
.withMessageStartingWith("loginContextName must be set on");
|
||||
myJaasProvider.setLoginContextName("");
|
||||
assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet)
|
||||
.withMessageStartingWith("loginContextName must be set on");
|
||||
.withMessageStartingWith("loginContextName must be set on");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -169,7 +169,7 @@ public class JaasAuthenticationProviderTests {
|
||||
Collection<? extends GrantedAuthority> list = auth.getAuthorities();
|
||||
Set<String> set = AuthorityUtils.authorityListToSet(list);
|
||||
assertThat(set.contains("ROLE_ONE")).withFailMessage("GrantedAuthorities should not contain ROLE_ONE")
|
||||
.isFalse();
|
||||
.isFalse();
|
||||
assertThat(set.contains("ROLE_TEST1")).withFailMessage("GrantedAuthorities should contain ROLE_TEST1").isTrue();
|
||||
assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue();
|
||||
boolean foundit = false;
|
||||
@@ -177,14 +177,14 @@ public class JaasAuthenticationProviderTests {
|
||||
if (a instanceof JaasGrantedAuthority) {
|
||||
JaasGrantedAuthority grant = (JaasGrantedAuthority) a;
|
||||
assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority")
|
||||
.isNotNull();
|
||||
.isNotNull();
|
||||
foundit = true;
|
||||
}
|
||||
}
|
||||
assertThat(foundit).as("Could not find a JaasGrantedAuthority").isTrue();
|
||||
assertThat(this.eventCheck.successEvent).as("Success event should be fired").isNotNull();
|
||||
assertThat(this.eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal")
|
||||
.isEqualTo(auth);
|
||||
.isEqualTo(auth);
|
||||
assertThat(this.eventCheck.failedEvent).as("Failure event should not be fired").isNull();
|
||||
}
|
||||
|
||||
@@ -226,13 +226,13 @@ public class JaasAuthenticationProviderTests {
|
||||
assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
|
||||
Authentication auth = this.jaasProvider.authenticate(token);
|
||||
assertThat(auth.getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned")
|
||||
.hasSize(2);
|
||||
.hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnsupportedAuthenticationObjectReturnsNull() {
|
||||
assertThat(this.jaasProvider
|
||||
.authenticate(new TestingAuthenticationToken("foo", "bar", AuthorityUtils.NO_AUTHORITIES))).isNull();
|
||||
.authenticate(new TestingAuthenticationToken("foo", "bar", AuthorityUtils.NO_AUTHORITIES))).isNull();
|
||||
}
|
||||
|
||||
private static class MockLoginContext extends LoginContext {
|
||||
|
||||
+2
-2
@@ -29,13 +29,13 @@ public class JaasGrantedAuthorityTests {
|
||||
@Test
|
||||
public void authorityWithNullRoleFailsAssertion() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new JaasGrantedAuthority(null, null))
|
||||
.withMessageContaining("role cannot be null");
|
||||
.withMessageContaining("role cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorityWithNullPrincipleFailsAssertion() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new JaasGrantedAuthority("role", null))
|
||||
.withMessageContaining("principal cannot be null");
|
||||
.withMessageContaining("principal cannot be null");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+8
-5
@@ -83,9 +83,10 @@ public class SecurityContextLoginModuleTests {
|
||||
SecurityContextHolder.getContext().setAuthentication(this.auth);
|
||||
assertThat(this.module.login()).as("Login should succeed, there is an authentication set").isTrue();
|
||||
assertThat(this.module.commit()).withFailMessage("The authentication is not null, this should return true")
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
assertThat(this.subject.getPrincipals().contains(this.auth))
|
||||
.withFailMessage("Principals should contain the authentication").isTrue();
|
||||
.withFailMessage("Principals should contain the authentication")
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -95,9 +96,10 @@ public class SecurityContextLoginModuleTests {
|
||||
this.module.setSecurityContextHolderStrategy(securityContextHolderStrategy);
|
||||
assertThat(this.module.login()).as("Login should succeed, there is an authentication set").isTrue();
|
||||
assertThat(this.module.commit()).withFailMessage("The authentication is not null, this should return true")
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
assertThat(this.subject.getPrincipals().contains(this.auth))
|
||||
.withFailMessage("Principals should contain the authentication").isTrue();
|
||||
.withFailMessage("Principals should contain the authentication")
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -107,7 +109,8 @@ public class SecurityContextLoginModuleTests {
|
||||
assertThat(this.module.logout()).as("Should return true as it succeeds").isTrue();
|
||||
assertThat(this.module.getAuthentication()).as("Authentication should be null").isNull();
|
||||
assertThat(this.subject.getPrincipals().contains(this.auth))
|
||||
.withFailMessage("Principals should not contain the authentication after logout").isFalse();
|
||||
.withFailMessage("Principals should not contain the authentication after logout")
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-3
@@ -59,19 +59,19 @@ public class InMemoryConfigurationTests {
|
||||
@Test
|
||||
public void constructorNullMapped() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new InMemoryConfiguration((Map<String, AppConfigurationEntry[]>) null));
|
||||
.isThrownBy(() -> new InMemoryConfiguration((Map<String, AppConfigurationEntry[]>) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorEmptyMap() {
|
||||
assertThat(new InMemoryConfiguration(Collections.<String, AppConfigurationEntry[]>emptyMap())
|
||||
.getAppConfigurationEntry("name")).isNull();
|
||||
.getAppConfigurationEntry("name")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorEmptyMapNullDefault() {
|
||||
assertThat(new InMemoryConfiguration(Collections.<String, AppConfigurationEntry[]>emptyMap(), null)
|
||||
.getAppConfigurationEntry("name")).isNull();
|
||||
.getAppConfigurationEntry("name")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-3
@@ -41,10 +41,10 @@ public class RememberMeAuthenticationTokenTests {
|
||||
@Test
|
||||
public void testConstructorRejectsNulls() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new RememberMeAuthenticationToken(null, "Test", ROLES_12));
|
||||
.isThrownBy(() -> new RememberMeAuthenticationToken(null, "Test", ROLES_12));
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new RememberMeAuthenticationToken("key", null, ROLES_12));
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> new RememberMeAuthenticationToken("key", "Test", Arrays.asList((GrantedAuthority) null)));
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new RememberMeAuthenticationToken("key", "Test", Arrays.asList((GrantedAuthority) null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ public class AuthenticatedReactiveAuthorizationManagerTests {
|
||||
Authentication authentication;
|
||||
|
||||
AuthenticatedReactiveAuthorizationManager<Object> manager = AuthenticatedReactiveAuthorizationManager
|
||||
.authenticated();
|
||||
.authenticated();
|
||||
|
||||
@Test
|
||||
public void checkWhenAuthenticatedThenReturnTrue() {
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ class AuthoritiesAuthorizationManagerTests {
|
||||
void setRoleHierarchyWhenNullThenIllegalArgumentException() {
|
||||
AuthoritiesAuthorizationManager manager = new AuthoritiesAuthorizationManager();
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> manager.setRoleHierarchy(null))
|
||||
.withMessage("roleHierarchy cannot be null");
|
||||
.withMessage("roleHierarchy cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+19
-19
@@ -41,7 +41,7 @@ public class AuthorityAuthorizationManagerTests {
|
||||
@Test
|
||||
public void hasRoleWhenNullThenException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> AuthorityAuthorizationManager.hasRole(null))
|
||||
.withMessage("role cannot be null");
|
||||
.withMessage("role cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -49,40 +49,40 @@ public class AuthorityAuthorizationManagerTests {
|
||||
String ROLE_PREFIX = "ROLE_";
|
||||
String ROLE_USER = ROLE_PREFIX + "USER";
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> AuthorityAuthorizationManager.hasRole(ROLE_USER))
|
||||
.withMessage(ROLE_USER + " should not start with " + ROLE_PREFIX + " since " + ROLE_PREFIX
|
||||
+ " is automatically prepended when using hasRole. Consider using hasAuthority instead.");
|
||||
.withMessage(ROLE_USER + " should not start with " + ROLE_PREFIX + " since " + ROLE_PREFIX
|
||||
+ " is automatically prepended when using hasRole. Consider using hasAuthority instead.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAuthorityWhenNullThenException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> AuthorityAuthorizationManager.hasAuthority(null))
|
||||
.withMessage("authority cannot be null");
|
||||
.withMessage("authority cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyRoleWhenNullThenException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> AuthorityAuthorizationManager.hasAnyRole(null))
|
||||
.withMessage("roles cannot be empty");
|
||||
.withMessage("roles cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyRoleWhenEmptyThenException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> AuthorityAuthorizationManager.hasAnyRole(new String[] {}))
|
||||
.withMessage("roles cannot be empty");
|
||||
.withMessage("roles cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyRoleWhenContainNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyRole("ADMIN", null, "USER"))
|
||||
.withMessage("roles cannot contain null values");
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyRole("ADMIN", null, "USER"))
|
||||
.withMessage("roles cannot contain null values");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyRoleWhenCustomRolePrefixNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyRole(null, new String[] { "ADMIN", "USER" }))
|
||||
.withMessage("rolePrefix cannot be null");
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyRole(null, new String[] { "ADMIN", "USER" }))
|
||||
.withMessage("rolePrefix cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -90,29 +90,29 @@ public class AuthorityAuthorizationManagerTests {
|
||||
String ROLE_PREFIX = "ROLE_";
|
||||
String ROLE_USER = ROLE_PREFIX + "USER";
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyRole(new String[] { ROLE_USER }))
|
||||
.withMessage(ROLE_USER + " should not start with " + ROLE_PREFIX + " since " + ROLE_PREFIX
|
||||
+ " is automatically prepended when using hasAnyRole. Consider using hasAnyAuthority instead.");
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyRole(new String[] { ROLE_USER }))
|
||||
.withMessage(ROLE_USER + " should not start with " + ROLE_PREFIX + " since " + ROLE_PREFIX
|
||||
+ " is automatically prepended when using hasAnyRole. Consider using hasAnyAuthority instead.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyAuthorityWhenNullThenException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> AuthorityAuthorizationManager.hasAnyAuthority(null))
|
||||
.withMessage("authorities cannot be empty");
|
||||
.withMessage("authorities cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyAuthorityWhenEmptyThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyAuthority(new String[] {}))
|
||||
.withMessage("authorities cannot be empty");
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyAuthority(new String[] {}))
|
||||
.withMessage("authorities cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyAuthorityWhenContainNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyAuthority("ADMIN", null, "USER"))
|
||||
.withMessage("authorities cannot contain null values");
|
||||
.isThrownBy(() -> AuthorityAuthorizationManager.hasAnyAuthority("ADMIN", null, "USER"))
|
||||
.withMessage("authorities cannot contain null values");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -237,7 +237,7 @@ public class AuthorityAuthorizationManagerTests {
|
||||
public void setRoleHierarchyWhenNullThenIllegalArgumentException() {
|
||||
AuthorityAuthorizationManager<Object> manager = AuthorityAuthorizationManager.hasRole("USER");
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> manager.setRoleHierarchy(null))
|
||||
.withMessage("roleHierarchy cannot be null");
|
||||
.withMessage("roleHierarchy cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-6
@@ -143,37 +143,37 @@ public class AuthorityReactiveAuthorizationManagerTests {
|
||||
@Test
|
||||
public void hasRoleWhenNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasRole((String) null));
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasRole((String) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAuthorityWhenNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAuthority((String) null));
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAuthority((String) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyRoleWhenNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyRole((String) null));
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyRole((String) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyAuthorityWhenNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyAuthority((String) null));
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyAuthority((String) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyRoleWhenOneIsNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyRole("ROLE_ADMIN", (String) null));
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyRole("ROLE_ADMIN", (String) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasAnyAuthorityWhenOneIsNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyAuthority("ADMIN", (String) null));
|
||||
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyAuthority("ADMIN", (String) null));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-1
@@ -59,7 +59,8 @@ public class AuthorizationManagerTests {
|
||||
Object object = new Object();
|
||||
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> manager.verify(() -> authentication, object)).withMessage("Access Denied");
|
||||
.isThrownBy(() -> manager.verify(() -> authentication, object))
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -88,7 +88,7 @@ public class ObservationAuthorizationManagerTests {
|
||||
given(this.handler.supportsContext(any())).willReturn(true);
|
||||
given(this.authorizationManager.check(any(), any())).willReturn(this.deny);
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.tested.verify(this.token, this.object));
|
||||
.isThrownBy(() -> this.tested.verify(this.token, this.object));
|
||||
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
|
||||
verify(this.handler).onStart(captor.capture());
|
||||
assertThat(captor.getValue().getName()).isEqualTo(AuthorizationObservationConvention.OBSERVATION_NAME);
|
||||
@@ -121,7 +121,7 @@ public class ObservationAuthorizationManagerTests {
|
||||
@Test
|
||||
void setObservationConventionWhenNullThenException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.tested.setObservationConvention(null));
|
||||
.isThrownBy(() -> this.tested.setObservationConvention(null));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -87,7 +87,7 @@ public class ObservationReactiveAuthorizationManagerTests {
|
||||
given(this.handler.supportsContext(any())).willReturn(true);
|
||||
given(this.authorizationManager.check(any(), any())).willReturn(Mono.just(this.deny));
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.tested.verify(this.token, this.object).block());
|
||||
.isThrownBy(() -> this.tested.verify(this.token, this.object).block());
|
||||
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
|
||||
verify(this.handler).onStart(captor.capture());
|
||||
assertThat(captor.getValue().getName()).isEqualTo(AuthorizationObservationConvention.OBSERVATION_NAME);
|
||||
@@ -120,7 +120,7 @@ public class ObservationReactiveAuthorizationManagerTests {
|
||||
@Test
|
||||
void setObservationConventionWhenNullThenException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.tested.setObservationConvention(null));
|
||||
.isThrownBy(() -> this.tested.setObservationConvention(null));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ class AuthorizationAnnotationUtilsTests {
|
||||
(p, m, args) -> null);
|
||||
Method method = proxy.getClass().getDeclaredMethod("findAll");
|
||||
assertThatNoException()
|
||||
.isThrownBy(() -> AuthorizationAnnotationUtils.findUniqueAnnotation(method, PreAuthorize.class));
|
||||
.isThrownBy(() -> AuthorizationAnnotationUtils.findUniqueAnnotation(method, PreAuthorize.class));
|
||||
}
|
||||
|
||||
private interface BaseRepository<T> {
|
||||
|
||||
+6
-6
@@ -52,15 +52,15 @@ public class AuthorizationManagerAfterMethodInterceptorTests {
|
||||
public void instantiateWhenMethodMatcherNullThenException() {
|
||||
AuthorizationManager<MethodInvocationResult> mockAuthorizationManager = mock(AuthorizationManager.class);
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AuthorizationManagerAfterMethodInterceptor(null, mockAuthorizationManager))
|
||||
.withMessage("pointcut cannot be null");
|
||||
.isThrownBy(() -> new AuthorizationManagerAfterMethodInterceptor(null, mockAuthorizationManager))
|
||||
.withMessage("pointcut cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void instantiateWhenAuthorizationManagerNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AuthorizationManagerAfterMethodInterceptor(mock(Pointcut.class), null))
|
||||
.withMessage("authorizationManager cannot be null");
|
||||
.isThrownBy(() -> new AuthorizationManagerAfterMethodInterceptor(mock(Pointcut.class), null))
|
||||
.withMessage("authorizationManager cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -83,7 +83,7 @@ public class AuthorizationManagerAfterMethodInterceptorTests {
|
||||
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
|
||||
MethodInvocation invocation = mock(MethodInvocation.class);
|
||||
AuthorizationManager<MethodInvocationResult> authorizationManager = AuthenticatedAuthorizationManager
|
||||
.authenticated();
|
||||
.authenticated();
|
||||
AuthorizationManagerAfterMethodInterceptor advice = new AuthorizationManagerAfterMethodInterceptor(
|
||||
Pointcut.TRUE, authorizationManager);
|
||||
advice.setSecurityContextHolderStrategy(strategy);
|
||||
@@ -96,7 +96,7 @@ public class AuthorizationManagerAfterMethodInterceptorTests {
|
||||
AuthorizationManagerAfterMethodInterceptor advice = new AuthorizationManagerAfterMethodInterceptor(
|
||||
Pointcut.TRUE, AuthenticatedAuthorizationManager.authenticated());
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> advice.setAuthorizationEventPublisher(null))
|
||||
.withMessage("eventPublisher cannot be null");
|
||||
.withMessage("eventPublisher cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user