From 27ac046d8a534dc691e86f43d94192f50cd54254 Mon Sep 17 00:00:00 2001
From: Phillip Webb
Date: Wed, 5 Aug 2020 17:24:50 -0700
Subject: [PATCH 01/84] Rename *Test.java -> *Tests.java
Rename a few test classes that accidentally ended in `Test` instead of
`Tests`.
Issue gh-8945
---
.../{AclClassIdUtilsTest.java => AclClassIdUtilsTests.java} | 2 +-
....java => LdapAuthenticationProviderConfigurerTests.java} | 2 +-
...nTest.java => ServerHttpSecurityConfigurationTests.java} | 2 +-
...anTest.java => UserDetailsResourceFactoryBeanTests.java} | 2 +-
.../security/config/http/FormLoginConfigTests.java | 6 +++---
.../{WebConfigUtilsTest.java => WebConfigUtilsTests.java} | 2 +-
...ssorTest.java => MessageSecurityPostProcessorTests.java} | 2 +-
.../security/config/http/FormLoginConfigTests-UsingSpel.xml | 6 +++---
...RsaKeyConvertersTest.java => RsaKeyConvertersTests.java} | 2 +-
...a => BouncyCastleAesBytesEncryptorEquivalencyTests.java} | 2 +-
...torTest.java => BouncyCastleAesBytesEncryptorTests.java} | 2 +-
...dMessageMatcherTest.java => AndMessageMatcherTests.java} | 2 +-
...OrMessageMatcherTest.java => OrMessageMatcherTests.java} | 2 +-
...RegistrationsTest.java => ClientRegistrationsTests.java} | 2 +-
...AuthorizationCodeAuthenticationTokenConverterTests.java} | 2 +-
...java => MapOAuth2AccessTokenResponseConverterTests.java} | 2 +-
...java => OAuth2AccessTokenResponseMapConverterTests.java} | 2 +-
...adExchangeMatcherReactiveAuthorizationManagerTests.java} | 2 +-
...etadataFilterTest.java => Saml2MetadataFilterTests.java} | 2 +-
.../debug/{DebugFilterTest.java => DebugFilterTests.java} | 2 +-
...ReactivePreAuthenticatedAuthenticationManagerTests.java} | 2 +-
21 files changed, 25 insertions(+), 25 deletions(-)
rename acl/src/test/java/org/springframework/security/acls/jdbc/{AclClassIdUtilsTest.java => AclClassIdUtilsTests.java} (99%)
rename config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/{LdapAuthenticationProviderConfigurerTest.java => LdapAuthenticationProviderConfigurerTests.java} (96%)
rename config/src/test/java/org/springframework/security/config/annotation/web/reactive/{ServerHttpSecurityConfigurationTest.java => ServerHttpSecurityConfigurationTests.java} (97%)
rename config/src/test/java/org/springframework/security/config/core/userdetails/{UserDetailsResourceFactoryBeanTest.java => UserDetailsResourceFactoryBeanTests.java} (98%)
rename config/src/test/java/org/springframework/security/config/http/{WebConfigUtilsTest.java => WebConfigUtilsTests.java} (97%)
rename config/src/test/java/org/springframework/security/config/websocket/{MessageSecurityPostProcessorTest.java => MessageSecurityPostProcessorTests.java} (96%)
rename core/src/test/java/org/springframework/security/converter/{RsaKeyConvertersTest.java => RsaKeyConvertersTests.java} (99%)
rename crypto/src/test/java/org/springframework/security/crypto/encrypt/{BouncyCastleAesBytesEncryptorEquivalencyTest.java => BouncyCastleAesBytesEncryptorEquivalencyTests.java} (98%)
rename crypto/src/test/java/org/springframework/security/crypto/encrypt/{BouncyCastleAesBytesEncryptorTest.java => BouncyCastleAesBytesEncryptorTests.java} (98%)
rename messaging/src/test/java/org/springframework/security/messaging/util/matcher/{AndMessageMatcherTest.java => AndMessageMatcherTests.java} (98%)
rename messaging/src/test/java/org/springframework/security/messaging/util/matcher/{OrMessageMatcherTest.java => OrMessageMatcherTests.java} (98%)
rename oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/{ClientRegistrationsTest.java => ClientRegistrationsTests.java} (99%)
rename oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/{ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTest.java => ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java} (99%)
rename oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/{MapOAuth2AccessTokenResponseConverterTest.java => MapOAuth2AccessTokenResponseConverterTests.java} (98%)
rename oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/{OAuth2AccessTokenResponseMapConverterTest.java => OAuth2AccessTokenResponseMapConverterTests.java} (98%)
rename rsocket/src/test/java/org/springframework/security/rsocket/authorization/{PayloadExchangeMatcherReactiveAuthorizationManagerTest.java => PayloadExchangeMatcherReactiveAuthorizationManagerTests.java} (99%)
rename saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/{Saml2MetadataFilterTest.java => Saml2MetadataFilterTests.java} (99%)
rename web/src/test/java/org/springframework/security/web/debug/{DebugFilterTest.java => DebugFilterTests.java} (99%)
rename web/src/test/java/org/springframework/security/web/server/authentication/{ReactivePreAuthenticatedAuthenticationManagerTest.java => ReactivePreAuthenticatedAuthenticationManagerTests.java} (98%)
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTest.java b/acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTests.java
similarity index 99%
rename from acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTest.java
rename to acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTests.java
index 5dd2e36f31..d41341c466 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTest.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTests.java
@@ -37,7 +37,7 @@ import static org.mockito.BDDMockito.given;
* @author paulwheeler
*/
@RunWith(MockitoJUnitRunner.class)
-public class AclClassIdUtilsTest {
+public class AclClassIdUtilsTests {
private static final Long DEFAULT_IDENTIFIER = 999L;
private static final BigInteger BIGINT_IDENTIFIER = new BigInteger("999");
diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTest.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTests.java
similarity index 96%
rename from config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTest.java
rename to config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTests.java
index f3f33a91d9..b8b98509e6 100644
--- a/config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTest.java
+++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTests.java
@@ -24,7 +24,7 @@ import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper
import static org.assertj.core.api.Assertions.assertThat;
-public class LdapAuthenticationProviderConfigurerTest {
+public class LdapAuthenticationProviderConfigurerTests {
private LdapAuthenticationProviderConfigurer configurer;
diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/reactive/ServerHttpSecurityConfigurationTest.java b/config/src/test/java/org/springframework/security/config/annotation/web/reactive/ServerHttpSecurityConfigurationTests.java
similarity index 97%
rename from config/src/test/java/org/springframework/security/config/annotation/web/reactive/ServerHttpSecurityConfigurationTest.java
rename to config/src/test/java/org/springframework/security/config/annotation/web/reactive/ServerHttpSecurityConfigurationTests.java
index 31c07cc2e0..c7ae2e2d78 100644
--- a/config/src/test/java/org/springframework/security/config/annotation/web/reactive/ServerHttpSecurityConfigurationTest.java
+++ b/config/src/test/java/org/springframework/security/config/annotation/web/reactive/ServerHttpSecurityConfigurationTests.java
@@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Eleftheria Stein
*/
-public class ServerHttpSecurityConfigurationTest {
+public class ServerHttpSecurityConfigurationTests {
@Rule
public final SpringTestRule spring = new SpringTestRule();
diff --git a/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTest.java b/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java
similarity index 98%
rename from config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTest.java
rename to config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java
index 8b53fc0e34..6317995e78 100644
--- a/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTest.java
+++ b/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java
@@ -35,7 +35,7 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
-public class UserDetailsResourceFactoryBeanTest {
+public class UserDetailsResourceFactoryBeanTests {
@Mock
ResourceLoader resourceLoader;
diff --git a/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java b/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java
index 1fd9c265e2..56bbe0b062 100644
--- a/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java
+++ b/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java
@@ -95,16 +95,16 @@ public class FormLoginConfigTests {
.param("username", "user")
.param("password", "password")
.with(csrf()))
- .andExpect(redirectedUrl(WebConfigUtilsTest.URL + "/default"));
+ .andExpect(redirectedUrl(WebConfigUtilsTests.URL + "/default"));
this.mvc.perform(post("/login")
.param("username", "user")
.param("password", "wrong")
.with(csrf()))
- .andExpect(redirectedUrl(WebConfigUtilsTest.URL + "/failure"));
+ .andExpect(redirectedUrl(WebConfigUtilsTests.URL + "/failure"));
this.mvc.perform(get("/"))
- .andExpect(redirectedUrl("http://localhost" + WebConfigUtilsTest.URL + "/login"));
+ .andExpect(redirectedUrl("http://localhost" + WebConfigUtilsTests.URL + "/login"));
}
@Test
diff --git a/config/src/test/java/org/springframework/security/config/http/WebConfigUtilsTest.java b/config/src/test/java/org/springframework/security/config/http/WebConfigUtilsTests.java
similarity index 97%
rename from config/src/test/java/org/springframework/security/config/http/WebConfigUtilsTest.java
rename to config/src/test/java/org/springframework/security/config/http/WebConfigUtilsTests.java
index 0eb0023f65..532fea1706 100644
--- a/config/src/test/java/org/springframework/security/config/http/WebConfigUtilsTest.java
+++ b/config/src/test/java/org/springframework/security/config/http/WebConfigUtilsTests.java
@@ -26,7 +26,7 @@ import org.springframework.beans.factory.xml.ParserContext;
@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(ParserContext.class)
-public class WebConfigUtilsTest {
+public class WebConfigUtilsTests {
public final static String URL = "/url";
@Mock
diff --git a/config/src/test/java/org/springframework/security/config/websocket/MessageSecurityPostProcessorTest.java b/config/src/test/java/org/springframework/security/config/websocket/MessageSecurityPostProcessorTests.java
similarity index 96%
rename from config/src/test/java/org/springframework/security/config/websocket/MessageSecurityPostProcessorTest.java
rename to config/src/test/java/org/springframework/security/config/websocket/MessageSecurityPostProcessorTests.java
index e05ee31365..cf8a615684 100644
--- a/config/src/test/java/org/springframework/security/config/websocket/MessageSecurityPostProcessorTest.java
+++ b/config/src/test/java/org/springframework/security/config/websocket/MessageSecurityPostProcessorTests.java
@@ -20,7 +20,7 @@ import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry;
-public class MessageSecurityPostProcessorTest {
+public class MessageSecurityPostProcessorTests {
private WebSocketMessageBrokerSecurityBeanDefinitionParser.MessageSecurityPostProcessor postProcessor =
new WebSocketMessageBrokerSecurityBeanDefinitionParser.MessageSecurityPostProcessor("id", false);
diff --git a/config/src/test/resources/org/springframework/security/config/http/FormLoginConfigTests-UsingSpel.xml b/config/src/test/resources/org/springframework/security/config/http/FormLoginConfigTests-UsingSpel.xml
index 7cc3784f25..8146964536 100644
--- a/config/src/test/resources/org/springframework/security/config/http/FormLoginConfigTests-UsingSpel.xml
+++ b/config/src/test/resources/org/springframework/security/config/http/FormLoginConfigTests-UsingSpel.xml
@@ -27,9 +27,9 @@
+ default-target-url="#{T(org.springframework.security.config.http.WebConfigUtilsTests).URL}/default"
+ authentication-failure-url="#{T(org.springframework.security.config.http.WebConfigUtilsTests).URL}/failure"
+ login-page="#{T(org.springframework.security.config.http.WebConfigUtilsTests).URL}/login"/>
diff --git a/core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTest.java b/core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTests.java
similarity index 99%
rename from core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTest.java
rename to core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTests.java
index f1ba277e12..90a4450149 100644
--- a/core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTest.java
+++ b/core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTests.java
@@ -32,7 +32,7 @@ import org.springframework.core.convert.converter.Converter;
/**
* Tests for {@link RsaKeyConverters}
*/
-public class RsaKeyConvertersTest {
+public class RsaKeyConvertersTests {
private static final String PKCS8_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n" +
"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCMk7CKSTfu3QoV\n" +
"HoPVXxwZO+qweztd36cVWYqGOZinrOR2crWFu50AgR2CsdIH0+cqo7F4Vx7/3O8i\n" +
diff --git a/crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorEquivalencyTest.java b/crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorEquivalencyTests.java
similarity index 98%
rename from crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorEquivalencyTest.java
rename to crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorEquivalencyTests.java
index 548b3791af..d4c5c73e72 100644
--- a/crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorEquivalencyTest.java
+++ b/crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorEquivalencyTests.java
@@ -27,7 +27,7 @@ import org.springframework.security.crypto.encrypt.AesBytesEncryptor.CipherAlgor
import org.springframework.security.crypto.keygen.BytesKeyGenerator;
import org.springframework.security.crypto.keygen.KeyGenerators;
-public class BouncyCastleAesBytesEncryptorEquivalencyTest {
+public class BouncyCastleAesBytesEncryptorEquivalencyTests {
private byte[] testData;
private String password;
diff --git a/crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorTest.java b/crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorTests.java
similarity index 98%
rename from crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorTest.java
rename to crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorTests.java
index 3efe507387..f4bd049c33 100644
--- a/crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorTest.java
+++ b/crypto/src/test/java/org/springframework/security/crypto/encrypt/BouncyCastleAesBytesEncryptorTests.java
@@ -25,7 +25,7 @@ import org.junit.Test;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.keygen.KeyGenerators;
-public class BouncyCastleAesBytesEncryptorTest {
+public class BouncyCastleAesBytesEncryptorTests {
private byte[] testData;
private String password;
diff --git a/messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTest.java b/messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTests.java
similarity index 98%
rename from messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTest.java
rename to messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTests.java
index a765f18e77..f0d3777729 100644
--- a/messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTest.java
+++ b/messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTests.java
@@ -29,7 +29,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.messaging.Message;
@RunWith(MockitoJUnitRunner.class)
-public class AndMessageMatcherTest {
+public class AndMessageMatcherTests {
@Mock
private MessageMatcher
- *
* @return the identifier (unique within this type; never null)
*/
Serializable getIdentifier();
@@ -62,7 +61,6 @@ public interface ObjectIdentity extends Serializable {
* Obtains the "type" metadata for the domain object. This will often be a Java type
* name (an interface or a class) – traditionally it is the name of the domain
* object implementation class.
- *
* @return the "type" of the domain object (never null).
*/
String getType();
@@ -72,4 +70,5 @@ public interface ObjectIdentity extends Serializable {
* @see Object#hashCode()
*/
int hashCode();
+
}
diff --git a/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityGenerator.java b/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityGenerator.java
index 1814295874..b78059c8f1 100644
--- a/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityGenerator.java
+++ b/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityGenerator.java
@@ -30,7 +30,6 @@ import java.io.Serializable;
public interface ObjectIdentityGenerator {
/**
- *
* @param id the identifier of the domain object, not null
* @param type the type of the object (often a class name), not null
* @return the identity constructed using the supplied identifier and type
diff --git a/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityRetrievalStrategy.java b/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityRetrievalStrategy.java
index cd1b53031e..da817471b1 100644
--- a/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityRetrievalStrategy.java
+++ b/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityRetrievalStrategy.java
@@ -24,8 +24,10 @@ package org.springframework.security.acls.model;
*
*/
public interface ObjectIdentityRetrievalStrategy {
+
// ~ Methods
// ========================================================================================================
ObjectIdentity getObjectIdentity(Object domainObject);
+
}
diff --git a/acl/src/main/java/org/springframework/security/acls/model/OwnershipAcl.java b/acl/src/main/java/org/springframework/security/acls/model/OwnershipAcl.java
index edda240b19..856bd2f3b4 100644
--- a/acl/src/main/java/org/springframework/security/acls/model/OwnershipAcl.java
+++ b/acl/src/main/java/org/springframework/security/acls/model/OwnershipAcl.java
@@ -25,8 +25,10 @@ package org.springframework.security.acls.model;
* @author Ben Alex
*/
public interface OwnershipAcl extends MutableAcl {
+
// ~ Methods
// ========================================================================================================
void setOwner(Sid newOwner);
+
}
diff --git a/acl/src/main/java/org/springframework/security/acls/model/Permission.java b/acl/src/main/java/org/springframework/security/acls/model/Permission.java
index 68beec8568..ea44686f29 100644
--- a/acl/src/main/java/org/springframework/security/acls/model/Permission.java
+++ b/acl/src/main/java/org/springframework/security/acls/model/Permission.java
@@ -23,11 +23,14 @@ import java.io.Serializable;
* @author Ben Alex
*/
public interface Permission extends Serializable {
+
// ~ Static fields/initializers
// =====================================================================================
char RESERVED_ON = '~';
+
char RESERVED_OFF = '.';
+
String THIRTY_TWO_RESERVED_OFF = "................................";
// ~ Methods
@@ -35,7 +38,6 @@ public interface Permission extends Serializable {
/**
* Returns the bits that represents the permission.
- *
* @return the bits that represent the permission
*/
int getMask();
@@ -56,8 +58,8 @@ public interface Permission extends Serializable {
* This method is only used for user interface and logging purposes. It is not used in
* any permission calculations. Therefore, duplication of characters within the output
* is permitted.
- *
* @return a 32-character bit pattern
*/
String getPattern();
+
}
diff --git a/acl/src/main/java/org/springframework/security/acls/model/PermissionGrantingStrategy.java b/acl/src/main/java/org/springframework/security/acls/model/PermissionGrantingStrategy.java
index 14c8185c18..f9d5ffe351 100644
--- a/acl/src/main/java/org/springframework/security/acls/model/PermissionGrantingStrategy.java
+++ b/acl/src/main/java/org/springframework/security/acls/model/PermissionGrantingStrategy.java
@@ -27,10 +27,9 @@ import java.util.List;
public interface PermissionGrantingStrategy {
/**
- * Returns true if the supplied strategy decides that the supplied {@code Acl}
- * grants access based on the supplied list of permissions and sids.
+ * Returns true if the supplied strategy decides that the supplied {@code Acl} grants
+ * access based on the supplied list of permissions and sids.
*/
- boolean isGranted(Acl acl, List permission, List sids,
- boolean administrativeMode);
+ boolean isGranted(Acl acl, List permission, List sids, boolean administrativeMode);
}
diff --git a/acl/src/main/java/org/springframework/security/acls/model/Sid.java b/acl/src/main/java/org/springframework/security/acls/model/Sid.java
index 134fc0ed7a..4ced8b26f7 100644
--- a/acl/src/main/java/org/springframework/security/acls/model/Sid.java
+++ b/acl/src/main/java/org/springframework/security/acls/model/Sid.java
@@ -31,15 +31,14 @@ import java.io.Serializable;
* @author Ben Alex
*/
public interface Sid extends Serializable {
+
// ~ Methods
// ========================================================================================================
/**
* Refer to the java.lang.Object documentation for the interface
* contract.
- *
* @param obj to be compared
- *
* @return true if the objects are equal, false otherwise
*/
boolean equals(Object obj);
@@ -47,8 +46,8 @@ public interface Sid extends Serializable {
/**
* Refer to the java.lang.Object documentation for the interface
* contract.
- *
* @return a hash code representation of this object
*/
int hashCode();
+
}
diff --git a/acl/src/main/java/org/springframework/security/acls/model/SidRetrievalStrategy.java b/acl/src/main/java/org/springframework/security/acls/model/SidRetrievalStrategy.java
index 3f605440c0..24397ea1cc 100644
--- a/acl/src/main/java/org/springframework/security/acls/model/SidRetrievalStrategy.java
+++ b/acl/src/main/java/org/springframework/security/acls/model/SidRetrievalStrategy.java
@@ -27,8 +27,10 @@ import org.springframework.security.core.Authentication;
* @author Ben Alex
*/
public interface SidRetrievalStrategy {
+
// ~ Methods
// ========================================================================================================
List getSids(Authentication authentication);
+
}
diff --git a/acl/src/main/java/org/springframework/security/acls/model/UnloadedSidException.java b/acl/src/main/java/org/springframework/security/acls/model/UnloadedSidException.java
index b692ad79ca..f48b60e11b 100644
--- a/acl/src/main/java/org/springframework/security/acls/model/UnloadedSidException.java
+++ b/acl/src/main/java/org/springframework/security/acls/model/UnloadedSidException.java
@@ -23,12 +23,12 @@ package org.springframework.security.acls.model;
* @author Ben Alex
*/
public class UnloadedSidException extends AclDataAccessException {
+
// ~ Constructors
// ===================================================================================================
/**
* Constructs an NotFoundException with the specified message.
- *
* @param msg the detail message
*/
public UnloadedSidException(String msg) {
@@ -38,11 +38,11 @@ public class UnloadedSidException extends AclDataAccessException {
/**
* Constructs an NotFoundException with the specified message and root
* cause.
- *
* @param msg the detail message
* @param t root cause
*/
public UnloadedSidException(String msg, Throwable t) {
super(msg, t);
}
+
}
diff --git a/acl/src/main/java/org/springframework/security/acls/model/package-info.java b/acl/src/main/java/org/springframework/security/acls/model/package-info.java
index c6f8389ae9..7b06410450 100644
--- a/acl/src/main/java/org/springframework/security/acls/model/package-info.java
+++ b/acl/src/main/java/org/springframework/security/acls/model/package-info.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
/**
- * Interfaces and shared classes to manage access control lists (ACLs) for domain object instances.
+ * Interfaces and shared classes to manage access control lists (ACLs) for domain object
+ * instances.
*/
package org.springframework.security.acls.model;
-
diff --git a/acl/src/main/java/org/springframework/security/acls/package-info.java b/acl/src/main/java/org/springframework/security/acls/package-info.java
index 75d4de804f..7b764596d5 100644
--- a/acl/src/main/java/org/springframework/security/acls/package-info.java
+++ b/acl/src/main/java/org/springframework/security/acls/package-info.java
@@ -14,11 +14,13 @@
* limitations under the License.
*/
/**
- * The Spring Security ACL package which implements instance-based security for domain objects.
+ * The Spring Security ACL package which implements instance-based security for domain
+ * objects.
*
- * Consider using the annotation based approach ({@code @PreAuthorize}, {@code @PostFilter} annotations) combined
- * with a {@link org.springframework.security.acls.AclPermissionEvaluator} in preference to the older and more verbose
- * attribute/voter/after-invocation approach from versions before Spring Security 3.0.
+ * Consider using the annotation based approach ({@code @PreAuthorize},
+ * {@code @PostFilter} annotations) combined with a
+ * {@link org.springframework.security.acls.AclPermissionEvaluator} in preference to the
+ * older and more verbose attribute/voter/after-invocation approach from versions before
+ * Spring Security 3.0.
*/
package org.springframework.security.acls;
-
diff --git a/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java b/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java
index acf951ef06..87fcd2e0e9 100644
--- a/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java
@@ -66,13 +66,11 @@ public class AclFormattingUtilsTests {
public final void testDemergePatterns() {
String original = "...........................A...R";
String removeBits = "...............................R";
- assertThat(AclFormattingUtils.demergePatterns(original, removeBits)).isEqualTo(
- "...........................A....");
+ assertThat(AclFormattingUtils.demergePatterns(original, removeBits))
+ .isEqualTo("...........................A....");
- assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo(
- "ABCDEF");
- assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo(
- "......");
+ assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF");
+ assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo("......");
}
@Test
@@ -109,19 +107,15 @@ public class AclFormattingUtilsTests {
public final void testMergePatterns() {
String original = "...............................R";
String extraBits = "...........................A....";
- assertThat(AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo(
- "...........................A...R");
+ assertThat(AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo("...........................A...R");
- assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......")).isEqualTo(
- "ABCDEF");
- assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")).isEqualTo(
- "GHIJKL");
+ assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF");
+ assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")).isEqualTo("GHIJKL");
}
@Test
public final void testBinaryPrints() {
- assertThat(AclFormattingUtils.printBinary(15)).isEqualTo(
- "............................****");
+ assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****");
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
@@ -137,19 +131,17 @@ public class AclFormattingUtilsTests {
catch (IllegalArgumentException notExpected) {
}
- assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo(
- "............................xxxx");
+ assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx");
}
@Test
public void testPrintBinaryNegative() {
- assertThat(AclFormattingUtils.printBinary(0x80000000)).isEqualTo(
- "*...............................");
+ assertThat(AclFormattingUtils.printBinary(0x80000000)).isEqualTo("*...............................");
}
@Test
public void testPrintBinaryMinusOne() {
- assertThat(AclFormattingUtils.printBinary(0xffffffff)).isEqualTo(
- "********************************");
+ assertThat(AclFormattingUtils.printBinary(0xffffffff)).isEqualTo("********************************");
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/AclPermissionCacheOptimizerTests.java b/acl/src/test/java/org/springframework/security/acls/AclPermissionCacheOptimizerTests.java
index d499a79ca7..f922d20c9c 100644
--- a/acl/src/test/java/org/springframework/security/acls/AclPermissionCacheOptimizerTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/AclPermissionCacheOptimizerTests.java
@@ -44,8 +44,7 @@ public class AclPermissionCacheOptimizerTests {
pco.setObjectIdentityRetrievalStrategy(oidStrat);
pco.setSidRetrievalStrategy(sidStrat);
Object[] dos = { new Object(), null, new Object() };
- ObjectIdentity[] oids = { new ObjectIdentityImpl("A", "1"),
- new ObjectIdentityImpl("A", "2") };
+ ObjectIdentity[] oids = { new ObjectIdentityImpl("A", "1"), new ObjectIdentityImpl("A", "2") };
when(oidStrat.getObjectIdentity(dos[0])).thenReturn(oids[0]);
when(oidStrat.getObjectIdentity(dos[2])).thenReturn(oids[1]);
diff --git a/acl/src/test/java/org/springframework/security/acls/AclPermissionEvaluatorTests.java b/acl/src/test/java/org/springframework/security/acls/AclPermissionEvaluatorTests.java
index 47df332908..148083b750 100644
--- a/acl/src/test/java/org/springframework/security/acls/AclPermissionEvaluatorTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/AclPermissionEvaluatorTests.java
@@ -30,7 +30,6 @@ import org.springframework.security.acls.model.SidRetrievalStrategy;
import org.springframework.security.core.Authentication;
/**
- *
* @author Luke Taylor
* @since 3.0
*/
@@ -74,4 +73,5 @@ public class AclPermissionEvaluatorTests {
Locale.setDefault(systemLocale);
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/TargetObjectWithUUID.java b/acl/src/test/java/org/springframework/security/acls/TargetObjectWithUUID.java
index 426956f7ea..11b297257d 100644
--- a/acl/src/test/java/org/springframework/security/acls/TargetObjectWithUUID.java
+++ b/acl/src/test/java/org/springframework/security/acls/TargetObjectWithUUID.java
@@ -33,4 +33,5 @@ public final class TargetObjectWithUUID {
public void setId(UUID id) {
this.id = id;
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java
index b85b01d3dd..f9a1c8f4b6 100644
--- a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java
@@ -15,7 +15,6 @@
*/
package org.springframework.security.acls.afterinvocation;
-
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
@@ -36,14 +35,13 @@ import java.util.List;
*/
@SuppressWarnings({ "unchecked" })
public class AclEntryAfterInvocationCollectionFilteringProviderTests {
+
@Test
public void objectsAreRemovedIfPermissionDenied() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
- when(acl.isGranted(any(), any(), anyBoolean())).thenReturn(
- false);
- when(service.readAclById(any(), any())).thenReturn(
- acl);
+ when(acl.isGranted(any(), any(), anyBoolean())).thenReturn(false);
+ when(service.readAclById(any(), any())).thenReturn(acl);
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(
service, Arrays.asList(mock(Permission.class)));
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
@@ -51,8 +49,8 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = provider.decide(mock(Authentication.class), new Object(),
- SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), new ArrayList(
- Arrays.asList(new Object(), new Object())));
+ SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"),
+ new ArrayList(Arrays.asList(new Object(), new Object())));
assertThat(returned).isInstanceOf(List.class);
assertThat(((List) returned)).isEmpty();
returned = provider.decide(mock(Authentication.class), new Object(),
@@ -68,10 +66,8 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
mock(AclService.class), Arrays.asList(mock(Permission.class)));
Object returned = new Object();
- assertThat(returned)
- .isSameAs(
- provider.decide(mock(Authentication.class), new Object(),
- Collections. emptyList(), returned));
+ assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(),
+ Collections.emptyList(), returned));
}
@Test
@@ -81,8 +77,7 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
service, Arrays.asList(mock(Permission.class)));
assertThat(provider.decide(mock(Authentication.class), new Object(),
- SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null))
- .isNull();
+ SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null)).isNull();
verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class));
}
diff --git a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java
index 322bb3d11f..a541f72215 100644
--- a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java
@@ -44,74 +44,59 @@ public class AclEntryAfterInvocationProviderTests {
}
catch (IllegalArgumentException expected) {
}
- new AclEntryAfterInvocationProvider(mock(AclService.class),
- Collections. emptyList());
+ new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.emptyList());
}
@Test
public void accessIsAllowedIfPermissionIsGranted() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
- when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(
- true);
- when(service.readAclById(any(), any())).thenReturn(
- acl);
- AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(
- service, Arrays.asList(mock(Permission.class)));
+ when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(true);
+ when(service.readAclById(any(), any())).thenReturn(acl);
+ AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service,
+ Arrays.asList(mock(Permission.class)));
provider.setMessageSource(new SpringSecurityMessageSource());
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = new Object();
- assertThat(
- returned)
- .isSameAs(
- provider.decide(mock(Authentication.class), new Object(),
- SecurityConfig.createList("AFTER_ACL_READ"), returned));
+ assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(),
+ SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
@Test
public void accessIsGrantedIfNoAttributesDefined() {
- AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(
- mock(AclService.class), Arrays.asList(mock(Permission.class)));
+ AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(mock(AclService.class),
+ Arrays.asList(mock(Permission.class)));
Object returned = new Object();
- assertThat(
- returned)
- .isSameAs(
- provider.decide(mock(Authentication.class), new Object(),
- Collections. emptyList(), returned));
+ assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(),
+ Collections.emptyList(), returned));
}
@Test
public void accessIsGrantedIfObjectTypeNotSupported() {
- AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(
- mock(AclService.class), Arrays.asList(mock(Permission.class)));
+ AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(mock(AclService.class),
+ Arrays.asList(mock(Permission.class)));
provider.setProcessDomainObjectClass(String.class);
// Not a String
Object returned = new Object();
- assertThat(
- returned)
- .isSameAs(
- provider.decide(mock(Authentication.class), new Object(),
- SecurityConfig.createList("AFTER_ACL_READ"), returned));
+ assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(),
+ SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
@Test(expected = AccessDeniedException.class)
public void accessIsDeniedIfPermissionIsNotGranted() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
- when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(
- false);
+ when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(false);
// Try a second time with no permissions found
- when(acl.isGranted(any(), any(List.class), anyBoolean())).thenThrow(
- new NotFoundException(""));
- when(service.readAclById(any(), any())).thenReturn(
- acl);
- AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(
- service, Arrays.asList(mock(Permission.class)));
+ when(acl.isGranted(any(), any(List.class), anyBoolean())).thenThrow(new NotFoundException(""));
+ when(service.readAclById(any(), any())).thenReturn(acl);
+ AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service,
+ Arrays.asList(mock(Permission.class)));
provider.setProcessConfigAttribute("MY_ATTRIBUTE");
provider.setMessageSource(new SpringSecurityMessageSource());
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
@@ -119,8 +104,7 @@ public class AclEntryAfterInvocationProviderTests {
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
try {
provider.decide(mock(Authentication.class), new Object(),
- SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"),
- new Object());
+ SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object());
fail("Expected Exception");
}
catch (AccessDeniedException expected) {
@@ -133,12 +117,12 @@ public class AclEntryAfterInvocationProviderTests {
@Test
public void nullReturnObjectIsIgnored() {
AclService service = mock(AclService.class);
- AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(
- service, Arrays.asList(mock(Permission.class)));
+ AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service,
+ Arrays.asList(mock(Permission.class)));
assertThat(provider.decide(mock(Authentication.class), new Object(),
- SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null))
- .isNull();
+ SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null)).isNull();
verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class));
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java
index bbf33dfef4..0def085888 100644
--- a/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java
@@ -39,8 +39,8 @@ public class AccessControlImplEntryTests {
public void testConstructorRequiredFields() {
// Check Acl field is present
try {
- new AccessControlEntryImpl(null, null, new PrincipalSid("johndoe"),
- BasePermission.ADMINISTRATION, true, true, true);
+ new AccessControlEntryImpl(null, null, new PrincipalSid("johndoe"), BasePermission.ADMINISTRATION, true,
+ true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -48,8 +48,7 @@ public class AccessControlImplEntryTests {
// Check Sid field is present
try {
- new AccessControlEntryImpl(null, mock(Acl.class), null,
- BasePermission.ADMINISTRATION, true, true, true);
+ new AccessControlEntryImpl(null, mock(Acl.class), null, BasePermission.ADMINISTRATION, true, true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -57,8 +56,7 @@ public class AccessControlImplEntryTests {
// Check Permission field is present
try {
- new AccessControlEntryImpl(null, mock(Acl.class),
- new PrincipalSid("johndoe"), null, true, true, true);
+ new AccessControlEntryImpl(null, mock(Acl.class), new PrincipalSid("johndoe"), null, true, true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -71,8 +69,8 @@ public class AccessControlImplEntryTests {
Sid sid = new PrincipalSid("johndoe");
// Create a sample entry
- AccessControlEntry ace = new AccessControlEntryImpl(1L, mockAcl,
- sid, BasePermission.ADMINISTRATION, true, true, true);
+ AccessControlEntry ace = new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true,
+ true);
// and check every get() method
assertThat(ace.getId()).isEqualTo(1L);
@@ -92,26 +90,26 @@ public class AccessControlImplEntryTests {
when(mockAcl.getObjectIdentity()).thenReturn(oid);
Sid sid = new PrincipalSid("johndoe");
- AccessControlEntry ace = new AccessControlEntryImpl(1L, mockAcl,
- sid, BasePermission.ADMINISTRATION, true, true, true);
+ AccessControlEntry ace = new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true,
+ true);
assertThat(ace).isNotNull();
assertThat(ace).isNotEqualTo(100L);
assertThat(ace).isEqualTo(ace);
- assertThat(ace).isEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid,
+ assertThat(ace).isEqualTo(
+ new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true));
+ assertThat(ace).isNotEqualTo(
+ new AccessControlEntryImpl(2L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true));
+ assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, new PrincipalSid("scott"),
BasePermission.ADMINISTRATION, true, true, true));
- assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(2L, mockAcl, sid,
- BasePermission.ADMINISTRATION, true, true, true));
- assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl,
- new PrincipalSid("scott"), BasePermission.ADMINISTRATION, true, true,
- true));
- assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid,
- BasePermission.WRITE, true, true, true));
- assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid,
- BasePermission.ADMINISTRATION, false, true, true));
- assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid,
- BasePermission.ADMINISTRATION, true, false, true));
- assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid,
- BasePermission.ADMINISTRATION, true, true, false));
+ assertThat(ace)
+ .isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.WRITE, true, true, true));
+ assertThat(ace).isNotEqualTo(
+ new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, false, true, true));
+ assertThat(ace).isNotEqualTo(
+ new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, false, true));
+ assertThat(ace).isNotEqualTo(
+ new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, false));
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AclAuthorizationStrategyImplTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AclAuthorizationStrategyImplTests.java
index 0e8d7c12ff..348122d0c4 100644
--- a/acl/src/test/java/org/springframework/security/acls/domain/AclAuthorizationStrategyImplTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/domain/AclAuthorizationStrategyImplTests.java
@@ -15,7 +15,6 @@
*/
package org.springframework.security.acls.domain;
-
import java.util.Arrays;
import org.junit.After;
@@ -31,21 +30,24 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
/**
- *
* @author Rob Winch
*
*/
@RunWith(MockitoJUnitRunner.class)
public class AclAuthorizationStrategyImplTests {
+
@Mock
Acl acl;
+
GrantedAuthority authority;
+
AclAuthorizationStrategyImpl strategy;
@Before
public void setup() {
authority = new SimpleGrantedAuthority("ROLE_AUTH");
- TestingAuthenticationToken authentication = new TestingAuthenticationToken("foo", "bar", Arrays.asList(authority));
+ TestingAuthenticationToken authentication = new TestingAuthenticationToken("foo", "bar",
+ Arrays.asList(authority));
authentication.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
@@ -64,9 +66,12 @@ public class AclAuthorizationStrategyImplTests {
@SuppressWarnings("serial")
class CustomAuthority implements GrantedAuthority {
+
@Override
public String getAuthority() {
return authority.getAuthority();
}
+
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java
index 7313048d20..fddbe66610 100644
--- a/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java
@@ -35,20 +35,31 @@ import java.util.*;
* @author Andrei Stefan
*/
public class AclImplTests {
+
private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject";
+
private static final List READ = Arrays.asList(BasePermission.READ);
+
private static final List WRITE = Arrays.asList(BasePermission.WRITE);
+
private static final List CREATE = Arrays.asList(BasePermission.CREATE);
+
private static final List DELETE = Arrays.asList(BasePermission.DELETE);
+
private static final List SCOTT = Arrays.asList((Sid) new PrincipalSid("scott"));
+
private static final List BEN = Arrays.asList((Sid) new PrincipalSid("ben"));
- Authentication auth = new TestingAuthenticationToken("joe", "ignored",
- "ROLE_ADMINISTRATOR");
+ Authentication auth = new TestingAuthenticationToken("joe", "ignored", "ROLE_ADMINISTRATOR");
+
AclAuthorizationStrategy authzStrategy;
+
PermissionGrantingStrategy pgs;
+
AuditLogger mockAuditLogger;
+
ObjectIdentity objectIdentity = new ObjectIdentityImpl(TARGET_CLASS, 100);
+
private DefaultPermissionFactory permissionFactory;
// ~ Methods
@@ -72,8 +83,7 @@ public class AclImplTests {
@Test(expected = IllegalArgumentException.class)
public void constructorsRejectNullObjectIdentity() {
try {
- new AclImpl(null, 1, authzStrategy, pgs, null, null, true, new PrincipalSid(
- "joe"));
+ new AclImpl(null, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -84,8 +94,7 @@ public class AclImplTests {
@Test(expected = IllegalArgumentException.class)
public void constructorsRejectNullId() {
try {
- new AclImpl(objectIdentity, null, authzStrategy, pgs, null, null, true,
- new PrincipalSid("joe"));
+ new AclImpl(objectIdentity, null, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -97,8 +106,8 @@ public class AclImplTests {
@Test(expected = IllegalArgumentException.class)
public void constructorsRejectNullAclAuthzStrategy() {
try {
- new AclImpl(objectIdentity, 1, null, new DefaultPermissionGrantingStrategy(
- mockAuditLogger), null, null, true, new PrincipalSid("joe"));
+ new AclImpl(objectIdentity, 1, null, new DefaultPermissionGrantingStrategy(mockAuditLogger), null, null,
+ true, new PrincipalSid("joe"));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -108,8 +117,7 @@ public class AclImplTests {
@Test
public void insertAceRejectsNullParameters() {
- MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
try {
acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true);
fail("It should have thrown IllegalArgumentException");
@@ -126,8 +134,7 @@ public class AclImplTests {
@Test
public void insertAceAddsElementAtCorrectIndex() {
- MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
MockAclService service = new MockAclService();
// Insert one permission
@@ -137,8 +144,7 @@ public class AclImplTests {
assertThat(acl.getEntries()).hasSize(1);
assertThat(acl).isEqualTo(acl.getEntries().get(0).getAcl());
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission());
- assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid(
- "ROLE_TEST1"));
+ assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST1"));
// Add a second permission
acl.insertAce(1, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
@@ -147,44 +153,36 @@ public class AclImplTests {
assertThat(acl.getEntries()).hasSize(2);
assertThat(acl).isEqualTo(acl.getEntries().get(1).getAcl());
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(1).getPermission());
- assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid(
- "ROLE_TEST2"));
+ assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2"));
// Add a third permission, after the first one
- acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_TEST3"),
- false);
+ acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_TEST3"), false);
service.updateAcl(acl);
assertThat(acl.getEntries()).hasSize(3);
// Check the third entry was added between the two existent ones
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission());
- assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid(
- "ROLE_TEST1"));
+ assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST1"));
assertThat(BasePermission.WRITE).isEqualTo(acl.getEntries().get(1).getPermission());
- assertThat(acl.getEntries().get(1).getSid()).isEqualTo( new GrantedAuthoritySid(
- "ROLE_TEST3"));
+ assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST3"));
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(2).getPermission());
- assertThat(acl.getEntries().get(2).getSid()).isEqualTo(new GrantedAuthoritySid(
- "ROLE_TEST2"));
+ assertThat(acl.getEntries().get(2).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2"));
}
@Test(expected = NotFoundException.class)
public void insertAceFailsForNonExistentElement() {
- MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
MockAclService service = new MockAclService();
// Insert one permission
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
service.updateAcl(acl);
- acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"),
- true);
+ acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
}
@Test
public void deleteAceKeepsInitialOrdering() {
- MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
MockAclService service = new MockAclService();
// Add several permissions
@@ -197,20 +195,16 @@ public class AclImplTests {
// kept
acl.deleteAce(0);
assertThat(acl.getEntries()).hasSize(2);
- assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid(
- "ROLE_TEST2"));
- assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid(
- "ROLE_TEST3"));
+ assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2"));
+ assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST3"));
// Add one more permission and remove the permission in the middle
acl.insertAce(2, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST4"), true);
service.updateAcl(acl);
acl.deleteAce(1);
assertThat(acl.getEntries()).hasSize(2);
- assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid(
- "ROLE_TEST2"));
- assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid(
- "ROLE_TEST4"));
+ assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2"));
+ assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST4"));
// Remove remaining permissions
acl.deleteAce(1);
@@ -221,10 +215,9 @@ public class AclImplTests {
@Test
public void deleteAceFailsForNonExistentElement() {
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority(
- "ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL"));
- MutableAcl acl = new AclImpl(objectIdentity, (1), strategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
+ new SimpleGrantedAuthority("ROLE_GENERAL"));
+ MutableAcl acl = new AclImpl(objectIdentity, (1), strategy, pgs, null, null, true, new PrincipalSid("joe"));
try {
acl.deleteAce(99);
fail("It should have thrown NotFoundException");
@@ -235,8 +228,7 @@ public class AclImplTests {
@Test
public void isGrantingRejectsEmptyParameters() {
- MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
Sid ben = new PrincipalSid("ben");
try {
acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false);
@@ -254,28 +246,23 @@ public class AclImplTests {
@Test
public void isGrantingGrantsAccessForAclWithNoParent() {
- Authentication auth = new TestingAuthenticationToken("ben", "ignored",
- "ROLE_GENERAL", "ROLE_GUEST");
+ Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL", "ROLE_GUEST");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity rootOid = new ObjectIdentityImpl(TARGET_CLASS, 100);
// Create an ACL which owner is not the authenticated principal
- MutableAcl rootAcl = new AclImpl(rootOid, 1, authzStrategy, pgs, null, null,
- false, new PrincipalSid("joe"));
+ MutableAcl rootAcl = new AclImpl(rootOid, 1, authzStrategy, pgs, null, null, false, new PrincipalSid("joe"));
// Grant some permissions
rootAcl.insertAce(0, BasePermission.READ, new PrincipalSid("ben"), false);
rootAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid("scott"), true);
rootAcl.insertAce(2, BasePermission.WRITE, new PrincipalSid("rod"), false);
- rootAcl.insertAce(3, BasePermission.WRITE, new GrantedAuthoritySid(
- "WRITE_ACCESS_ROLE"), true);
+ rootAcl.insertAce(3, BasePermission.WRITE, new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), true);
// Check permissions granting
- List permissions = Arrays.asList(BasePermission.READ,
- BasePermission.CREATE);
- List sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid(
- "ROLE_GUEST"));
+ List permissions = Arrays.asList(BasePermission.READ, BasePermission.CREATE);
+ List sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST"));
assertThat(rootAcl.isGranted(permissions, sids, false)).isFalse();
try {
rootAcl.isGranted(permissions, SCOTT, false);
@@ -284,14 +271,14 @@ public class AclImplTests {
catch (NotFoundException expected) {
}
assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue();
- assertThat(rootAcl.isGranted(WRITE, Arrays.asList(new PrincipalSid("rod"),
- new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false)).isFalse();
- assertThat(rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid(
- "WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false)).isTrue();
+ assertThat(rootAcl.isGranted(WRITE,
+ Arrays.asList(new PrincipalSid("rod"), new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false)).isFalse();
+ assertThat(rootAcl.isGranted(WRITE,
+ Arrays.asList(new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false)).isTrue();
try {
// Change the type of the Sid and check the granting process
- rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid("rod"),
- new PrincipalSid("WRITE_ACCESS_ROLE")), false);
+ rootAcl.isGranted(WRITE,
+ Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
@@ -300,8 +287,7 @@ public class AclImplTests {
@Test
public void isGrantingGrantsAccessForInheritableAcls() {
- Authentication auth = new TestingAuthenticationToken("ben", "ignored",
- "ROLE_GENERAL");
+ Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity grandParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100);
@@ -312,16 +298,11 @@ public class AclImplTests {
// Create ACLs
PrincipalSid joe = new PrincipalSid("joe");
- MutableAcl grandParentAcl = new AclImpl(grandParentOid, 1, authzStrategy, pgs,
- null, null, false, joe);
- MutableAcl parentAcl1 = new AclImpl(parentOid1, 2, authzStrategy, pgs, null,
- null, true, joe);
- MutableAcl parentAcl2 = new AclImpl(parentOid2, 3, authzStrategy, pgs, null,
- null, true, joe);
- MutableAcl childAcl1 = new AclImpl(childOid1, 4, authzStrategy, pgs, null, null,
- true, joe);
- MutableAcl childAcl2 = new AclImpl(childOid2, 4, authzStrategy, pgs, null, null,
- false, joe);
+ MutableAcl grandParentAcl = new AclImpl(grandParentOid, 1, authzStrategy, pgs, null, null, false, joe);
+ MutableAcl parentAcl1 = new AclImpl(parentOid1, 2, authzStrategy, pgs, null, null, true, joe);
+ MutableAcl parentAcl2 = new AclImpl(parentOid2, 3, authzStrategy, pgs, null, null, true, joe);
+ MutableAcl childAcl1 = new AclImpl(childOid1, 4, authzStrategy, pgs, null, null, true, joe);
+ MutableAcl childAcl2 = new AclImpl(childOid2, 4, authzStrategy, pgs, null, null, false, joe);
// Create hierarchies
childAcl2.setParent(childAcl1);
@@ -330,13 +311,10 @@ public class AclImplTests {
parentAcl1.setParent(grandParentAcl);
// Add some permissions
- grandParentAcl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid(
- "ROLE_USER_READ"), true);
+ grandParentAcl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
grandParentAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid("ben"), true);
- grandParentAcl
- .insertAce(2, BasePermission.DELETE, new PrincipalSid("ben"), false);
- grandParentAcl.insertAce(3, BasePermission.DELETE, new PrincipalSid("scott"),
- true);
+ grandParentAcl.insertAce(2, BasePermission.DELETE, new PrincipalSid("ben"), false);
+ grandParentAcl.insertAce(3, BasePermission.DELETE, new PrincipalSid("scott"), true);
parentAcl1.insertAce(0, BasePermission.READ, new PrincipalSid("scott"), true);
parentAcl1.insertAce(1, BasePermission.DELETE, new PrincipalSid("scott"), false);
parentAcl2.insertAce(0, BasePermission.CREATE, new PrincipalSid("ben"), true);
@@ -344,8 +322,7 @@ public class AclImplTests {
// Check granting process for parent1
assertThat(parentAcl1.isGranted(READ, SCOTT, false)).isTrue();
- assertThat(parentAcl1.isGranted(READ,
- Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false))
+ assertThat(parentAcl1.isGranted(READ, Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false))
.isTrue();
assertThat(parentAcl1.isGranted(WRITE, BEN, false)).isTrue();
assertThat(parentAcl1.isGranted(DELETE, BEN, false)).isFalse();
@@ -358,8 +335,7 @@ public class AclImplTests {
// Check granting process for child1
assertThat(childAcl1.isGranted(CREATE, SCOTT, false)).isTrue();
- assertThat(childAcl1.isGranted(READ,
- Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false))
+ assertThat(childAcl1.isGranted(READ, Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false))
.isTrue();
assertThat(childAcl1.isGranted(DELETE, BEN, false)).isFalse();
@@ -372,8 +348,7 @@ public class AclImplTests {
catch (NotFoundException expected) {
}
try {
- childAcl2.isGranted(CREATE,
- Arrays.asList((Sid) new PrincipalSid("joe")), false);
+ childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
@@ -382,18 +357,14 @@ public class AclImplTests {
@Test
public void updatedAceValuesAreCorrectlyReflectedInAcl() {
- Authentication auth = new TestingAuthenticationToken("ben", "ignored",
- "ROLE_GENERAL");
+ Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
- MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- false, new PrincipalSid("joe"));
+ MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, false, new PrincipalSid("joe"));
MockAclService service = new MockAclService();
- acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"),
- true);
- acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"),
- true);
+ acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
+ acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
acl.insertAce(2, BasePermission.CREATE, new PrincipalSid("ben"), true);
service.updateAcl(acl);
@@ -414,32 +385,20 @@ public class AclImplTests {
@Test
public void auditableEntryFlagsAreUpdatedCorrectly() {
- Authentication auth = new TestingAuthenticationToken("ben", "ignored",
- "ROLE_AUDITING", "ROLE_GENERAL");
+ Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_AUDITING", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
- MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- false, new PrincipalSid("joe"));
+ MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, false, new PrincipalSid("joe"));
MockAclService service = new MockAclService();
- acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"),
- true);
- acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"),
- true);
+ acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
+ acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
service.updateAcl(acl);
- assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0))
- .isAuditFailure())
- .isFalse();
- assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1))
- .isAuditFailure())
- .isFalse();
- assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0))
- .isAuditSuccess())
- .isFalse();
- assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1))
- .isAuditSuccess())
- .isFalse();
+ assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditFailure()).isFalse();
+ assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditFailure()).isFalse();
+ assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditSuccess()).isFalse();
+ assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditSuccess()).isFalse();
// Change each permission
((AuditableAcl) acl).updateAuditing(0, true, true);
@@ -452,21 +411,16 @@ public class AclImplTests {
@Test
public void gettersAndSettersAreConsistent() {
- Authentication auth = new TestingAuthenticationToken("ben", "ignored",
- "ROLE_GENERAL");
+ Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, (100));
ObjectIdentity identity2 = new ObjectIdentityImpl(TARGET_CLASS, (101));
- MutableAcl acl = new AclImpl(identity, 1, authzStrategy, pgs, null, null, true,
- new PrincipalSid("joe"));
- MutableAcl parentAcl = new AclImpl(identity2, 2, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ MutableAcl acl = new AclImpl(identity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
+ MutableAcl parentAcl = new AclImpl(identity2, 2, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
MockAclService service = new MockAclService();
- acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"),
- true);
- acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"),
- true);
+ acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
+ acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
service.updateAcl(acl);
assertThat(1).isEqualTo(acl.getId());
@@ -488,50 +442,43 @@ public class AclImplTests {
@Test
public void isSidLoadedBehavesAsExpected() {
- List loadedSids = Arrays.asList(new PrincipalSid("ben"),
- new GrantedAuthoritySid("ROLE_IGNORED"));
- MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null,
- loadedSids, true, new PrincipalSid("joe"));
+ List loadedSids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_IGNORED"));
+ MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, loadedSids, true,
+ new PrincipalSid("joe"));
assertThat(acl.isSidLoaded(loadedSids)).isTrue();
- assertThat(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"),
- new PrincipalSid("ben"))))
- .isTrue();
- assertThat(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid(
- "ROLE_IGNORED"))))
- .isTrue();
+ assertThat(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new PrincipalSid("ben"))))
+ .isTrue();
+ assertThat(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_IGNORED")))).isTrue();
assertThat(acl.isSidLoaded(BEN)).isTrue();
assertThat(acl.isSidLoaded(null)).isTrue();
assertThat(acl.isSidLoaded(new ArrayList<>(0))).isTrue();
- assertThat(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid(
- "ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_IGNORED"))))
- .isTrue();
- assertThat(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid(
- "ROLE_GENERAL"), new GrantedAuthoritySid("ROLE_IGNORED"))))
- .isFalse();
- assertThat(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid(
- "ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_GENERAL"))))
- .isFalse();
+ assertThat(acl.isSidLoaded(
+ Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_IGNORED"))))
+ .isTrue();
+ assertThat(acl.isSidLoaded(
+ Arrays.asList(new GrantedAuthoritySid("ROLE_GENERAL"), new GrantedAuthoritySid("ROLE_IGNORED"))))
+ .isFalse();
+ assertThat(acl.isSidLoaded(
+ Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_GENERAL"))))
+ .isFalse();
}
@Test(expected = NotFoundException.class)
public void insertAceRaisesNotFoundExceptionForIndexLessThanZero() {
- AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true);
}
@Test(expected = NotFoundException.class)
public void deleteAceRaisesNotFoundExceptionForIndexLessThanZero() {
- AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
acl.deleteAce(-1);
}
@Test(expected = NotFoundException.class)
public void insertAceRaisesNotFoundExceptionForIndexGreaterThanSize() {
- AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
// Insert at zero, OK.
acl.insertAce(0, mock(Permission.class), mock(Sid.class), true);
// Size is now 1
@@ -541,8 +488,7 @@ public class AclImplTests {
// SEC-1151
@Test(expected = NotFoundException.class)
public void deleteAceRaisesNotFoundExceptionForIndexEqualToSize() {
- AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null,
- true, new PrincipalSid("joe"));
+ AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe"));
acl.insertAce(0, mock(Permission.class), mock(Sid.class), true);
// Size is now 1
acl.deleteAce(1);
@@ -551,11 +497,9 @@ public class AclImplTests {
// SEC-1795
@Test
public void changingParentIsSuccessful() {
- AclImpl parentAcl = new AclImpl(objectIdentity, 1L, authzStrategy,
- mockAuditLogger);
+ AclImpl parentAcl = new AclImpl(objectIdentity, 1L, authzStrategy, mockAuditLogger);
AclImpl childAcl = new AclImpl(objectIdentity, 2L, authzStrategy, mockAuditLogger);
- AclImpl changeParentAcl = new AclImpl(objectIdentity, 3L, authzStrategy,
- mockAuditLogger);
+ AclImpl changeParentAcl = new AclImpl(objectIdentity, 3L, authzStrategy, mockAuditLogger);
childAcl.setParent(parentAcl);
childAcl.setParent(changeParentAcl);
@@ -566,9 +510,9 @@ public class AclImplTests {
public void maskPermissionGrantingStrategy() {
DefaultPermissionGrantingStrategy maskPgs = new MaskPermissionGrantingStrategy(mockAuditLogger);
MockAclService service = new MockAclService();
- AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, maskPgs, null, null,
- true, new PrincipalSid("joe"));
- Permission permission = permissionFactory.buildFromMask(BasePermission.READ.getMask() | BasePermission.WRITE.getMask());
+ AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, maskPgs, null, null, true, new PrincipalSid("joe"));
+ Permission permission = permissionFactory
+ .buildFromMask(BasePermission.READ.getMask() | BasePermission.WRITE.getMask());
Sid sid = new PrincipalSid("ben");
acl.insertAce(0, permission, sid, true);
service.updateAcl(acl);
@@ -579,20 +523,20 @@ public class AclImplTests {
@Test
public void hashCodeWithoutStackOverFlow() throws Exception {
- //given
+ // given
Sid sid = new PrincipalSid("pSid");
ObjectIdentity oid = new ObjectIdentityImpl("type", 1);
AclAuthorizationStrategy authStrategy = new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("role"));
PermissionGrantingStrategy grantingStrategy = new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger());
- AclImpl acl = new AclImpl(oid, 1L, authStrategy, grantingStrategy, null, null, false, sid);
+ AclImpl acl = new AclImpl(oid, 1L, authStrategy, grantingStrategy, null, null, false, sid);
AccessControlEntryImpl ace = new AccessControlEntryImpl(1L, acl, sid, BasePermission.READ, true, true, true);
- Field fieldAces = FieldUtils.getField(AclImpl.class, "aces");
+ Field fieldAces = FieldUtils.getField(AclImpl.class, "aces");
fieldAces.setAccessible(true);
List aces = (List) fieldAces.get(acl);
aces.add(ace);
- //when - then none StackOverFlowError been raised
+ // when - then none StackOverFlowError been raised
ace.hashCode();
}
@@ -600,6 +544,7 @@ public class AclImplTests {
// ==================================================================================================
private static class MaskPermissionGrantingStrategy extends DefaultPermissionGrantingStrategy {
+
MaskPermissionGrantingStrategy(AuditLogger auditLogger) {
super(auditLogger);
}
@@ -611,25 +556,24 @@ public class AclImplTests {
}
return super.isGranted(ace, p);
}
+
}
private class MockAclService implements MutableAclService {
- public MutableAcl createAcl(ObjectIdentity objectIdentity)
- throws AlreadyExistsException {
+
+ public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException {
return null;
}
- public void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren)
- throws ChildrenExistException {
+ public void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren) throws ChildrenExistException {
}
/*
* Mock implementation that populates the aces list with fully initialized
* AccessControlEntries
*
- * @see
- * org.springframework.security.acls.MutableAclService#updateAcl(org.springframework
- * .security.acls.MutableAcl)
+ * @see org.springframework.security.acls.MutableAclService#updateAcl(org.
+ * springframework .security.acls.MutableAcl)
*/
@SuppressWarnings("unchecked")
public MutableAcl updateAcl(MutableAcl acl) throws NotFoundException {
@@ -645,9 +589,8 @@ public class AclImplTests {
AccessControlEntry ac = oldAces.get(i);
// Just give an ID to all this acl's aces, rest of the fields are just
// copied
- newAces.add(new AccessControlEntryImpl((i + 1), ac.getAcl(), ac
- .getSid(), ac.getPermission(), ac.isGranting(),
- ((AuditableAccessControlEntry) ac).isAuditSuccess(),
+ newAces.add(new AccessControlEntryImpl((i + 1), ac.getAcl(), ac.getSid(), ac.getPermission(),
+ ac.isGranting(), ((AuditableAccessControlEntry) ac).isAuditSuccess(),
((AuditableAccessControlEntry) ac).isAuditFailure()));
}
}
@@ -666,19 +609,19 @@ public class AclImplTests {
return null;
}
- public Acl readAclById(ObjectIdentity object, List sids)
+ public Acl readAclById(ObjectIdentity object, List sids) throws NotFoundException {
+ return null;
+ }
+
+ public Map readAclsById(List objects) throws NotFoundException {
+ return null;
+ }
+
+ public Map readAclsById(List objects, List sids)
throws NotFoundException {
return null;
}
- public Map readAclsById(List objects)
- throws NotFoundException {
- return null;
- }
-
- public Map readAclsById(List objects,
- List sids) throws NotFoundException {
- return null;
- }
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java
index 0eab9940ac..a20536c691 100644
--- a/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java
@@ -35,6 +35,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
* @author Andrei Stefan
*/
public class AclImplementationSecurityCheckTests {
+
private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject";
// ~ Methods
@@ -52,50 +53,42 @@ public class AclImplementationSecurityCheckTests {
@Test
public void testSecurityCheckNoACEs() {
- Authentication auth = new TestingAuthenticationToken("user", "password",
- "ROLE_GENERAL", "ROLE_AUDITING", "ROLE_OWNERSHIP");
+ Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL", "ROLE_AUDITING",
+ "ROLE_OWNERSHIP");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority(
- "ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL"));
+ new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
+ new SimpleGrantedAuthority("ROLE_GENERAL"));
- Acl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy,
- new ConsoleAuditLogger());
+ Acl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
- aclAuthorizationStrategy.securityCheck(acl,
- AclAuthorizationStrategy.CHANGE_GENERAL);
- aclAuthorizationStrategy.securityCheck(acl,
- AclAuthorizationStrategy.CHANGE_AUDITING);
- aclAuthorizationStrategy.securityCheck(acl,
- AclAuthorizationStrategy.CHANGE_OWNERSHIP);
+ aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL);
+ aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING);
+ aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
// Create another authorization strategy
AclAuthorizationStrategy aclAuthorizationStrategy2 = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_ONE"), new SimpleGrantedAuthority(
- "ROLE_TWO"), new SimpleGrantedAuthority("ROLE_THREE"));
- Acl acl2 = new AclImpl(identity, 1L, aclAuthorizationStrategy2,
- new ConsoleAuditLogger());
+ new SimpleGrantedAuthority("ROLE_ONE"), new SimpleGrantedAuthority("ROLE_TWO"),
+ new SimpleGrantedAuthority("ROLE_THREE"));
+ Acl acl2 = new AclImpl(identity, 1L, aclAuthorizationStrategy2, new ConsoleAuditLogger());
// Check access in case the principal has no authorization rights
try {
- aclAuthorizationStrategy2.securityCheck(acl2,
- AclAuthorizationStrategy.CHANGE_GENERAL);
+ aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
- aclAuthorizationStrategy2.securityCheck(acl2,
- AclAuthorizationStrategy.CHANGE_AUDITING);
+ aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
- aclAuthorizationStrategy2.securityCheck(acl2,
- AclAuthorizationStrategy.CHANGE_OWNERSHIP);
+ aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
@@ -105,54 +98,46 @@ public class AclImplementationSecurityCheckTests {
@Test
public void testSecurityCheckWithMultipleACEs() {
// Create a simple authentication with ROLE_GENERAL
- Authentication auth = new TestingAuthenticationToken("user", "password",
- "ROLE_GENERAL");
+ Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L);
// Authorization strategy will require a different role for each access
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority(
- "ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL"));
+ new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
+ new SimpleGrantedAuthority("ROLE_GENERAL"));
// Let's give the principal the ADMINISTRATION permission, without
// granting access
- MutableAcl aclFirstDeny = new AclImpl(identity, 1L,
- aclAuthorizationStrategy, new ConsoleAuditLogger());
- aclFirstDeny.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth),
- false);
+ MutableAcl aclFirstDeny = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
+ aclFirstDeny.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
// The CHANGE_GENERAL test should pass as the principal has ROLE_GENERAL
- aclAuthorizationStrategy.securityCheck(aclFirstDeny,
- AclAuthorizationStrategy.CHANGE_GENERAL);
+ aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_GENERAL);
// The CHANGE_AUDITING and CHANGE_OWNERSHIP should fail since the
// principal doesn't have these authorities,
// nor granting access
try {
- aclAuthorizationStrategy.securityCheck(aclFirstDeny,
- AclAuthorizationStrategy.CHANGE_AUDITING);
+ aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
try {
- aclAuthorizationStrategy.securityCheck(aclFirstDeny,
- AclAuthorizationStrategy.CHANGE_OWNERSHIP);
+ aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
// Add granting access to this principal
- aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth),
- true);
+ aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// and try again for CHANGE_AUDITING - the first ACE's granting flag
// (false) will deny this access
try {
- aclAuthorizationStrategy.securityCheck(aclFirstDeny,
- AclAuthorizationStrategy.CHANGE_AUDITING);
+ aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
@@ -160,23 +145,18 @@ public class AclImplementationSecurityCheckTests {
// Create another ACL and give the principal the ADMINISTRATION
// permission, with granting access
- MutableAcl aclFirstAllow = new AclImpl(identity, 1L,
- aclAuthorizationStrategy, new ConsoleAuditLogger());
- aclFirstAllow.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth),
- true);
+ MutableAcl aclFirstAllow = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
+ aclFirstAllow.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// The CHANGE_AUDITING test should pass as there is one ACE with
// granting access
- aclAuthorizationStrategy.securityCheck(aclFirstAllow,
- AclAuthorizationStrategy.CHANGE_AUDITING);
+ aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
// Add a deny ACE and test again for CHANGE_AUDITING
- aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth),
- false);
+ aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
try {
- aclAuthorizationStrategy.securityCheck(aclFirstAllow,
- AclAuthorizationStrategy.CHANGE_AUDITING);
+ aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
}
catch (AccessDeniedException notExpected) {
@@ -184,11 +164,9 @@ public class AclImplementationSecurityCheckTests {
}
// Create an ACL with no ACE
- MutableAcl aclNoACE = new AclImpl(identity, 1L,
- aclAuthorizationStrategy, new ConsoleAuditLogger());
+ MutableAcl aclNoACE = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
try {
- aclAuthorizationStrategy.securityCheck(aclNoACE,
- AclAuthorizationStrategy.CHANGE_AUDITING);
+ aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
@@ -196,8 +174,7 @@ public class AclImplementationSecurityCheckTests {
}
// and still grant access for CHANGE_GENERAL
try {
- aclAuthorizationStrategy.securityCheck(aclNoACE,
- AclAuthorizationStrategy.CHANGE_GENERAL);
+ aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL);
}
catch (NotFoundException expected) {
@@ -208,31 +185,26 @@ public class AclImplementationSecurityCheckTests {
@Test
public void testSecurityCheckWithInheritableACEs() {
// Create a simple authentication with ROLE_GENERAL
- Authentication auth = new TestingAuthenticationToken("user", "password",
- "ROLE_GENERAL");
+ Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100);
// Authorization strategy will require a different role for each access
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_ONE"), new SimpleGrantedAuthority(
- "ROLE_TWO"), new SimpleGrantedAuthority("ROLE_GENERAL"));
+ new SimpleGrantedAuthority("ROLE_ONE"), new SimpleGrantedAuthority("ROLE_TWO"),
+ new SimpleGrantedAuthority("ROLE_GENERAL"));
// Let's give the principal an ADMINISTRATION permission, with granting
// access
- MutableAcl parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy,
- new ConsoleAuditLogger());
- parentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth),
- true);
- MutableAcl childAcl = new AclImpl(identity, 2, aclAuthorizationStrategy,
- new ConsoleAuditLogger());
+ MutableAcl parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
+ parentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
+ MutableAcl childAcl = new AclImpl(identity, 2, aclAuthorizationStrategy, new ConsoleAuditLogger());
// Check against the 'child' acl, which doesn't offer any authorization
// rights on CHANGE_OWNERSHIP
try {
- aclAuthorizationStrategy.securityCheck(childAcl,
- AclAuthorizationStrategy.CHANGE_OWNERSHIP);
+ aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
@@ -244,8 +216,7 @@ public class AclImplementationSecurityCheckTests {
childAcl.setParent(parentAcl);
childAcl.setEntriesInheriting(true);
try {
- aclAuthorizationStrategy.securityCheck(childAcl,
- AclAuthorizationStrategy.CHANGE_OWNERSHIP);
+ aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
}
catch (NotFoundException expected) {
@@ -253,18 +224,14 @@ public class AclImplementationSecurityCheckTests {
}
// Create a root parent and link it to the middle parent
- MutableAcl rootParentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy,
- new ConsoleAuditLogger());
- parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy,
- new ConsoleAuditLogger());
- rootParentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth),
- true);
+ MutableAcl rootParentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
+ parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
+ rootParentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
parentAcl.setEntriesInheriting(true);
parentAcl.setParent(rootParentAcl);
childAcl.setParent(parentAcl);
try {
- aclAuthorizationStrategy.securityCheck(childAcl,
- AclAuthorizationStrategy.CHANGE_OWNERSHIP);
+ aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
}
catch (NotFoundException expected) {
@@ -274,39 +241,36 @@ public class AclImplementationSecurityCheckTests {
@Test
public void testSecurityCheckPrincipalOwner() {
- Authentication auth = new TestingAuthenticationToken("user", "password",
- "ROLE_ONE");
+ Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_ONE");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority(
- "ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL"));
+ new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
+ new SimpleGrantedAuthority("ROLE_GENERAL"));
Acl acl = new AclImpl(identity, 1, aclAuthorizationStrategy,
- new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null,
- null, false, new PrincipalSid(auth));
+ new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false,
+ new PrincipalSid(auth));
try {
- aclAuthorizationStrategy.securityCheck(acl,
- AclAuthorizationStrategy.CHANGE_GENERAL);
+ aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL);
}
catch (AccessDeniedException notExpected) {
fail("It shouldn't have thrown AccessDeniedException");
}
try {
- aclAuthorizationStrategy.securityCheck(acl,
- AclAuthorizationStrategy.CHANGE_AUDITING);
+ aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It shouldn't have thrown AccessDeniedException");
}
catch (NotFoundException expected) {
}
try {
- aclAuthorizationStrategy.securityCheck(acl,
- AclAuthorizationStrategy.CHANGE_OWNERSHIP);
+ aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
}
catch (AccessDeniedException notExpected) {
fail("It shouldn't have thrown AccessDeniedException");
}
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java
index 001e0450e3..3cd3daba23 100644
--- a/acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java
@@ -33,11 +33,15 @@ import org.springframework.security.acls.model.AuditableAccessControlEntry;
* @author Andrei Stefan
*/
public class AuditLoggerTests {
+
// ~ Instance fields
// ================================================================================================
private PrintStream console;
+
private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+
private ConsoleAuditLogger logger;
+
private AuditableAccessControlEntry ace;
// ~ Methods
@@ -92,4 +96,5 @@ public class AuditLoggerTests {
logger.logIfNeeded(false, ace);
assertThat(bytes.toString()).startsWith("DENIED due to ACE");
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityImplTests.java b/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityImplTests.java
index 93adac3837..a66c933441 100644
--- a/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityImplTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityImplTests.java
@@ -141,8 +141,7 @@ public class ObjectIdentityImplTests {
assertThat(obj).isNotEqualTo("DIFFERENT_OBJECT_TYPE");
assertThat(obj).isNotEqualTo(new ObjectIdentityImpl(DOMAIN_CLASS, 2L));
assertThat(obj).isNotEqualTo(new ObjectIdentityImpl(
- "org.springframework.security.acls.domain.ObjectIdentityImplTests$MockOtherIdDomainObject",
- 1L));
+ "org.springframework.security.acls.domain.ObjectIdentityImplTests$MockOtherIdDomainObject", 1L));
assertThat(new ObjectIdentityImpl(DOMAIN_CLASS, 1L)).isEqualTo(obj);
assertThat(new ObjectIdentityImpl(mockObj)).isEqualTo(obj);
}
@@ -182,6 +181,7 @@ public class ObjectIdentityImplTests {
// ==================================================================================================
private class MockIdDomainObject {
+
private Object id;
public Object getId() {
@@ -191,9 +191,11 @@ public class ObjectIdentityImplTests {
public void setId(Object id) {
this.id = id;
}
+
}
private class MockOtherIdDomainObject {
+
private Object id;
public Object getId() {
@@ -203,5 +205,7 @@ public class ObjectIdentityImplTests {
public void setId(Object id) {
this.id = id;
}
+
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImplTests.java b/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImplTests.java
index 67e068c947..7164690017 100644
--- a/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImplTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImplTests.java
@@ -56,5 +56,7 @@ public class ObjectIdentityRetrievalStrategyImplTests {
public void setId(Object id) {
this.id = id;
}
+
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/domain/PermissionTests.java b/acl/src/test/java/org/springframework/security/acls/domain/PermissionTests.java
index f71c50755d..af6f1ed928 100644
--- a/acl/src/test/java/org/springframework/security/acls/domain/PermissionTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/domain/PermissionTests.java
@@ -45,14 +45,10 @@ public class PermissionTests {
public void expectedIntegerValues() {
assertThat(BasePermission.READ.getMask()).isEqualTo(1);
assertThat(BasePermission.ADMINISTRATION.getMask()).isEqualTo(16);
- assertThat(
- new CumulativePermission().set(BasePermission.READ)
- .set(BasePermission.WRITE).set(BasePermission.CREATE).getMask())
- .isEqualTo(7);
- assertThat(
- new CumulativePermission().set(BasePermission.READ)
- .set(BasePermission.ADMINISTRATION).getMask())
- .isEqualTo(17);
+ assertThat(new CumulativePermission().set(BasePermission.READ).set(BasePermission.WRITE)
+ .set(BasePermission.CREATE).getMask()).isEqualTo(7);
+ assertThat(new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION).getMask())
+ .isEqualTo(17);
}
@Test
@@ -65,33 +61,28 @@ public class PermissionTests {
public void stringConversion() {
permissionFactory.registerPublicPermissions(SpecialPermission.class);
- assertThat(BasePermission.READ.toString())
- .isEqualTo("BasePermission[...............................R=1]");
+ assertThat(BasePermission.READ.toString()).isEqualTo("BasePermission[...............................R=1]");
+
+ assertThat(BasePermission.ADMINISTRATION.toString())
+ .isEqualTo("BasePermission[...........................A....=16]");
+
+ assertThat(new CumulativePermission().set(BasePermission.READ).toString())
+ .isEqualTo("CumulativePermission[...............................R=1]");
assertThat(
- BasePermission.ADMINISTRATION.toString())
- .isEqualTo("BasePermission[...........................A....=16]");
+ new CumulativePermission().set(SpecialPermission.ENTER).set(BasePermission.ADMINISTRATION).toString())
+ .isEqualTo("CumulativePermission[..........................EA....=48]");
- assertThat(
- new CumulativePermission().set(BasePermission.READ).toString())
- .isEqualTo("CumulativePermission[...............................R=1]");
+ assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ).toString())
+ .isEqualTo("CumulativePermission[...........................A...R=17]");
- assertThat(new CumulativePermission().set(SpecialPermission.ENTER)
- .set(BasePermission.ADMINISTRATION).toString())
- .isEqualTo("CumulativePermission[..........................EA....=48]");
+ assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
+ .clear(BasePermission.ADMINISTRATION).toString())
+ .isEqualTo("CumulativePermission[...............................R=1]");
- assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION)
- .set(BasePermission.READ).toString())
- .isEqualTo("CumulativePermission[...........................A...R=17]");
-
- assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION)
- .set(BasePermission.READ).clear(BasePermission.ADMINISTRATION)
- .toString())
- .isEqualTo("CumulativePermission[...............................R=1]");
-
- assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION)
- .set(BasePermission.READ).clear(BasePermission.ADMINISTRATION)
- .clear(BasePermission.READ).toString())
- .isEqualTo("CumulativePermission[................................=0]");
+ assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
+ .clear(BasePermission.ADMINISTRATION).clear(BasePermission.READ).toString())
+ .isEqualTo("CumulativePermission[................................=0]");
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/domain/SpecialPermission.java b/acl/src/test/java/org/springframework/security/acls/domain/SpecialPermission.java
index 0aedb10afe..c6ebb59d02 100644
--- a/acl/src/test/java/org/springframework/security/acls/domain/SpecialPermission.java
+++ b/acl/src/test/java/org/springframework/security/acls/domain/SpecialPermission.java
@@ -23,10 +23,13 @@ import org.springframework.security.acls.model.Permission;
* @author Ben Alex
*/
public class SpecialPermission extends BasePermission {
+
public static final Permission ENTER = new SpecialPermission(1 << 5, 'E'); // 32
+
public static final Permission LEAVE = new SpecialPermission(1 << 6, 'L');
protected SpecialPermission(int mask, char code) {
super(mask, code);
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java
index a2cefecab5..7c95c5dfbf 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java
@@ -47,15 +47,20 @@ import javax.sql.DataSource;
public abstract class AbstractBasicLookupStrategyTests {
protected static final Sid BEN_SID = new PrincipalSid("ben");
+
protected static final String TARGET_CLASS = TargetObject.class.getName();
+
protected static final String TARGET_CLASS_WITH_UUID = TargetObjectWithUUID.class.getName();
+
protected static final UUID OBJECT_IDENTITY_UUID = UUID.randomUUID();
+
protected static final Long OBJECT_IDENTITY_LONG_AS_UUID = 110L;
// ~ Instance fields
// ================================================================================================
private BasicLookupStrategy strategy;
+
private static CacheManager cacheManager;
// ~ Methods
@@ -80,44 +85,41 @@ public abstract class AbstractBasicLookupStrategyTests {
@Before
public void populateDatabase() {
String query = "INSERT INTO acl_sid(ID,PRINCIPAL,SID) VALUES (1,1,'ben');"
- + "INSERT INTO acl_class(ID,CLASS) VALUES (2,'" + TARGET_CLASS + "');"
- + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (1,2,100,null,1,1);"
- + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (2,2,101,1,1,1);"
- + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (3,2,102,2,1,1);"
- + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (1,1,0,1,1,1,0,0);"
- + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (2,1,1,1,2,0,0,0);"
- + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (3,2,0,1,8,1,0,0);"
- + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (4,3,0,1,8,0,0,0);";
+ + "INSERT INTO acl_class(ID,CLASS) VALUES (2,'" + TARGET_CLASS + "');"
+ + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (1,2,100,null,1,1);"
+ + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (2,2,101,1,1,1);"
+ + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (3,2,102,2,1,1);"
+ + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (1,1,0,1,1,1,0,0);"
+ + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (2,1,1,1,2,0,0,0);"
+ + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (3,2,0,1,8,1,0,0);"
+ + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (4,3,0,1,8,0,0,0);";
getJdbcTemplate().execute(query);
}
@Before
public void initializeBeans() {
strategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(),
- new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()));
+ new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()));
strategy.setPermissionFactory(new DefaultPermissionFactory());
}
protected AclAuthorizationStrategy aclAuthStrategy() {
- return new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_ADMINISTRATOR"));
+ return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMINISTRATOR"));
}
protected EhCacheBasedAclCache aclCache() {
- return new EhCacheBasedAclCache(getCache(),
- new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
- new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER")));
+ return new EhCacheBasedAclCache(getCache(), new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
+ new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER")));
}
-
@After
public void emptyDatabase() {
String query = "DELETE FROM acl_entry;" + "DELETE FROM acl_object_identity WHERE ID = 9;"
- + "DELETE FROM acl_object_identity WHERE ID = 8;" + "DELETE FROM acl_object_identity WHERE ID = 7;"
- + "DELETE FROM acl_object_identity WHERE ID = 6;" + "DELETE FROM acl_object_identity WHERE ID = 5;"
- + "DELETE FROM acl_object_identity WHERE ID = 4;" + "DELETE FROM acl_object_identity WHERE ID = 3;"
- + "DELETE FROM acl_object_identity WHERE ID = 2;" + "DELETE FROM acl_object_identity WHERE ID = 1;"
- + "DELETE FROM acl_class;" + "DELETE FROM acl_sid;";
+ + "DELETE FROM acl_object_identity WHERE ID = 8;" + "DELETE FROM acl_object_identity WHERE ID = 7;"
+ + "DELETE FROM acl_object_identity WHERE ID = 6;" + "DELETE FROM acl_object_identity WHERE ID = 5;"
+ + "DELETE FROM acl_object_identity WHERE ID = 4;" + "DELETE FROM acl_object_identity WHERE ID = 3;"
+ + "DELETE FROM acl_object_identity WHERE ID = 2;" + "DELETE FROM acl_object_identity WHERE ID = 1;"
+ + "DELETE FROM acl_class;" + "DELETE FROM acl_sid;";
getJdbcTemplate().execute(query);
}
@@ -135,7 +137,7 @@ public abstract class AbstractBasicLookupStrategyTests {
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102);
Map map = this.strategy
- .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
+ .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
@@ -151,7 +153,7 @@ public abstract class AbstractBasicLookupStrategyTests {
// Let's empty the database to force acls retrieval from cache
emptyDatabase();
Map map = this.strategy
- .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
+ .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
@@ -166,12 +168,12 @@ public abstract class AbstractBasicLookupStrategyTests {
// acls
this.strategy.setBatchSize(1);
Map map = this.strategy
- .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
+ .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid,
- Map map) {
+ Map map) {
assertThat(map).hasSize(3);
MutableAcl topParent = (MutableAcl) map.get(topParentOid);
@@ -268,10 +270,10 @@ public abstract class AbstractBasicLookupStrategyTests {
@Test
public void testReadAllObjectIdentitiesWhenLastElementIsAlreadyCached() {
String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,105,null,1,1);"
- + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (7,2,106,6,1,1);"
- + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (8,2,107,6,1,1);"
- + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (9,2,108,7,1,1);"
- + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (7,6,0,1,1,1,0,0)";
+ + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (7,2,106,6,1,1);"
+ + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (8,2,107,6,1,1);"
+ + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (9,2,108,7,1,1);"
+ + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (7,6,0,1,1,1,0,0)";
getJdbcTemplate().execute(query);
ObjectIdentity grandParentOid = new ObjectIdentityImpl(TARGET_CLASS, 104L);
@@ -302,7 +304,8 @@ public abstract class AbstractBasicLookupStrategyTests {
try {
foundAcls = strategy.readAclsById(allOids, sids);
- } catch (NotFoundException notExpected) {
+ }
+ catch (NotFoundException notExpected) {
fail("It shouldn't have thrown NotFoundException");
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTests.java
index d41341c466..ecc16ffa3d 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTests.java
@@ -15,7 +15,6 @@
*/
package org.springframework.security.acls.jdbc;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -34,17 +33,21 @@ import static org.mockito.BDDMockito.given;
/**
* Tests for {@link AclClassIdUtils}.
+ *
* @author paulwheeler
*/
@RunWith(MockitoJUnitRunner.class)
public class AclClassIdUtilsTests {
private static final Long DEFAULT_IDENTIFIER = 999L;
+
private static final BigInteger BIGINT_IDENTIFIER = new BigInteger("999");
+
private static final String DEFAULT_IDENTIFIER_AS_STRING = DEFAULT_IDENTIFIER.toString();
@Mock
private ResultSet resultSet;
+
@Mock
private ConversionService conversionService;
@@ -172,4 +175,5 @@ public class AclClassIdUtilsTests {
// when
aclClassIdUtils.setConversionService(null);
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java
index 4f5f7c13a7..2116fdb0bf 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java
@@ -28,8 +28,8 @@ import org.springframework.jdbc.core.JdbcTemplate;
* @author Paul Wheeler
*/
public class BasicLookupStrategyTests extends AbstractBasicLookupStrategyTests {
- private static final BasicLookupStrategyTestsDbHelper DATABASE_HELPER = new BasicLookupStrategyTestsDbHelper();
+ private static final BasicLookupStrategyTestsDbHelper DATABASE_HELPER = new BasicLookupStrategyTestsDbHelper();
@BeforeClass
public static void createDatabase() throws Exception {
@@ -50,4 +50,5 @@ public class BasicLookupStrategyTests extends AbstractBasicLookupStrategyTests {
public DataSource getDataSource() {
return DATABASE_HELPER.getDataSource();
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTestsDbHelper.java b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTestsDbHelper.java
index 8c1f7042dc..c181522900 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTestsDbHelper.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTestsDbHelper.java
@@ -23,15 +23,20 @@ import org.springframework.util.FileCopyUtils;
/**
* Helper class to initialize the database for BasicLookupStrategyTests.
+ *
* @author Andrei Stefan
* @author Paul Wheeler
*/
public class BasicLookupStrategyTestsDbHelper {
+
private static final String ACL_SCHEMA_SQL_FILE = "createAclSchema.sql";
+
private static final String ACL_SCHEMA_SQL_FILE_WITH_ACL_CLASS_ID = "createAclSchemaWithAclClassIdType.sql";
private SingleConnectionDataSource dataSource;
+
private JdbcTemplate jdbcTemplate;
+
private boolean withAclClassIdType;
public BasicLookupStrategyTestsDbHelper() {
@@ -48,7 +53,8 @@ public class BasicLookupStrategyTestsDbHelper {
if (!withAclClassIdType) {
connectionUrl = "jdbc:hsqldb:mem:lookupstrategytest";
sqlClassPathResource = ACL_SCHEMA_SQL_FILE;
- } else {
+ }
+ else {
connectionUrl = "jdbc:hsqldb:mem:lookupstrategytestWithAclClassIdType";
sqlClassPathResource = ACL_SCHEMA_SQL_FILE_WITH_ACL_CLASS_ID;
@@ -69,4 +75,5 @@ public class BasicLookupStrategyTestsDbHelper {
public SingleConnectionDataSource getDataSource() {
return dataSource;
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyWithAclClassTypeTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyWithAclClassTypeTests.java
index 60ca2508f7..9ac5360675 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyWithAclClassTypeTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyWithAclClassTypeTests.java
@@ -71,7 +71,7 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
public void initializeBeans() {
super.initializeBeans();
uuidEnabledStrategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(),
- new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()));
+ new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()));
uuidEnabledStrategy.setPermissionFactory(new DefaultPermissionFactory());
uuidEnabledStrategy.setAclClassIdSupported(true);
uuidEnabledStrategy.setConversionService(new DefaultConversionService());
@@ -79,22 +79,22 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
@Before
public void populateDatabaseForAclClassTypeTests() {
- String query = "INSERT INTO acl_class(ID,CLASS,CLASS_ID_TYPE) VALUES (3,'"
- + TARGET_CLASS_WITH_UUID
- + "', 'java.util.UUID');"
- + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (4,3,'"
- + OBJECT_IDENTITY_UUID.toString() + "',null,1,1);"
- + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (5,3,'"
- + OBJECT_IDENTITY_LONG_AS_UUID + "',null,1,1);"
- + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (5,4,0,1,8,0,0,0);"
- + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (6,5,0,1,8,0,0,0);";
+ String query = "INSERT INTO acl_class(ID,CLASS,CLASS_ID_TYPE) VALUES (3,'" + TARGET_CLASS_WITH_UUID
+ + "', 'java.util.UUID');"
+ + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (4,3,'"
+ + OBJECT_IDENTITY_UUID.toString() + "',null,1,1);"
+ + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (5,3,'"
+ + OBJECT_IDENTITY_LONG_AS_UUID + "',null,1,1);"
+ + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (5,4,0,1,8,0,0,0);"
+ + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (6,5,0,1,8,0,0,0);";
DATABASE_HELPER.getJdbcTemplate().execute(query);
}
@Test
public void testReadObjectIdentityUsingUuidType() {
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_UUID);
- Map foundAcls = uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID));
+ Map foundAcls = uuidEnabledStrategy.readAclsById(Arrays.asList(oid),
+ Arrays.asList(BEN_SID));
Assert.assertEquals(1, foundAcls.size());
Assert.assertNotNull(foundAcls.get(oid));
}
@@ -102,7 +102,8 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
@Test
public void testReadObjectIdentityUsingLongTypeWithConversionServiceEnabled() {
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
- Map foundAcls = uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID));
+ Map foundAcls = uuidEnabledStrategy.readAclsById(Arrays.asList(oid),
+ Arrays.asList(BEN_SID));
Assert.assertEquals(1, foundAcls.size());
Assert.assertNotNull(foundAcls.get(oid));
}
@@ -112,4 +113,5 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_LONG_AS_UUID);
uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID));
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/DatabaseSeeder.java b/acl/src/test/java/org/springframework/security/acls/jdbc/DatabaseSeeder.java
index d8170b3081..4533e58966 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/DatabaseSeeder.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/DatabaseSeeder.java
@@ -32,6 +32,7 @@ import javax.sql.DataSource;
* @author Ben Alex
*/
public class DatabaseSeeder {
+
// ~ Constructors
// ===================================================================================================
@@ -43,4 +44,5 @@ public class DatabaseSeeder {
String sql = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
template.execute(sql);
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java
index 1e90a4ddc0..7cec850f45 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java
@@ -54,10 +54,12 @@ import org.springframework.test.util.ReflectionTestUtils;
*/
@RunWith(MockitoJUnitRunner.class)
public class EhCacheBasedAclCacheTests {
+
private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject";
@Mock
private Ehcache cache;
+
@Captor
private ArgumentCaptor element;
@@ -67,17 +69,15 @@ public class EhCacheBasedAclCacheTests {
@Before
public void setup() {
- myCache = new EhCacheBasedAclCache(cache, new DefaultPermissionGrantingStrategy(
- new ConsoleAuditLogger()), new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_USER")));
+ myCache = new EhCacheBasedAclCache(cache, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
+ new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER")));
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority(
- "ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL"));
+ new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
+ new SimpleGrantedAuthority("ROLE_GENERAL"));
- acl = new AclImpl(identity, 1L, aclAuthorizationStrategy,
- new ConsoleAuditLogger());
+ acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
}
@After
@@ -87,9 +87,8 @@ public class EhCacheBasedAclCacheTests {
@Test(expected = IllegalArgumentException.class)
public void constructorRejectsNullParameters() {
- new EhCacheBasedAclCache(null, new DefaultPermissionGrantingStrategy(
- new ConsoleAuditLogger()), new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_USER")));
+ new EhCacheBasedAclCache(null, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
+ new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER")));
}
@Test
@@ -152,12 +151,10 @@ public class EhCacheBasedAclCacheTests {
assertThat(retrieved).isEqualTo(acl);
- Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy",
- retrieved);
+ Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", retrieved);
assertThat(retrieved1).isNull();
- Object retrieved2 = FieldUtils.getProtectedFieldValue(
- "permissionGrantingStrategy", retrieved);
+ Object retrieved2 = FieldUtils.getProtectedFieldValue("permissionGrantingStrategy", retrieved);
assertThat(retrieved2).isNull();
}
@@ -175,25 +172,21 @@ public class EhCacheBasedAclCacheTests {
verify(cache, times(2)).put(element.capture());
assertThat(element.getValue().getKey()).isEqualTo(acl.getId());
assertThat(element.getValue().getObjectValue()).isEqualTo(acl);
- assertThat(element.getAllValues().get(0).getKey()).isEqualTo(
- acl.getObjectIdentity());
+ assertThat(element.getAllValues().get(0).getKey()).isEqualTo(acl.getObjectIdentity());
assertThat(element.getAllValues().get(0).getObjectValue()).isEqualTo(acl);
}
@Test
public void putInCacheAclWithParent() {
- Authentication auth = new TestingAuthenticationToken("user", "password",
- "ROLE_GENERAL");
+ Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
- ObjectIdentity identityParent = new ObjectIdentityImpl(TARGET_CLASS,
- 2L);
+ ObjectIdentity identityParent = new ObjectIdentityImpl(TARGET_CLASS, 2L);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority(
- "ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL"));
- MutableAcl parentAcl = new AclImpl(identityParent, 2L,
- aclAuthorizationStrategy, new ConsoleAuditLogger());
+ new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
+ new SimpleGrantedAuthority("ROLE_GENERAL"));
+ MutableAcl parentAcl = new AclImpl(identityParent, 2L, aclAuthorizationStrategy, new ConsoleAuditLogger());
acl.setParent(parentAcl);
myCache.putInCache(acl);
@@ -233,10 +226,8 @@ public class EhCacheBasedAclCacheTests {
MutableAcl fromCache = myCache.getFromCache(acl.getId());
- assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy"))
- .isNotNull();
- assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy"))
- .isNotNull();
+ assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull();
+ assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull();
}
@Test
@@ -248,8 +239,7 @@ public class EhCacheBasedAclCacheTests {
@Test
public void getFromCacheObjectIdentityPopulatesTransient() {
- when(cache.get(acl.getObjectIdentity()))
- .thenReturn(new Element(acl.getId(), acl));
+ when(cache.get(acl.getObjectIdentity())).thenReturn(new Element(acl.getId(), acl));
myCache.putInCache(acl);
@@ -258,16 +248,13 @@ public class EhCacheBasedAclCacheTests {
MutableAcl fromCache = myCache.getFromCache(acl.getObjectIdentity());
- assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy"))
- .isNotNull();
- assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy"))
- .isNotNull();
+ assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull();
+ assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull();
}
@Test
public void evictCacheSerializable() {
- when(cache.get(acl.getObjectIdentity()))
- .thenReturn(new Element(acl.getId(), acl));
+ when(cache.get(acl.getObjectIdentity())).thenReturn(new Element(acl.getId(), acl));
myCache.evictFromCache(acl.getObjectIdentity());
@@ -284,4 +271,5 @@ public class EhCacheBasedAclCacheTests {
verify(cache).remove(acl.getId());
verify(cache).remove(acl.getObjectIdentity());
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java
index b039e4d656..2ce64f73c2 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java
@@ -41,8 +41,7 @@ import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
/**
- * Unit and Integration tests the ACL JdbcAclService using an
- * in-memory database.
+ * Unit and Integration tests the ACL JdbcAclService using an in-memory database.
*
* @author Nena Raab
*/
@@ -61,6 +60,7 @@ public class JdbcAclServiceTests {
JdbcOperations jdbcOperations;
private JdbcAclService aclServiceIntegration;
+
private JdbcAclService aclService;
@Before
@@ -72,9 +72,7 @@ public class JdbcAclServiceTests {
@Before
public void setUpEmbeddedDatabase() {
embeddedDatabase = new EmbeddedDatabaseBuilder()//
- .addScript("createAclSchemaWithAclClassIdType.sql")
- .addScript("db/sql/test_data_hierarchy.sql")
- .build();
+ .addScript("createAclSchemaWithAclClassIdType.sql").addScript("db/sql/test_data_hierarchy.sql").build();
}
@After
@@ -86,9 +84,7 @@ public class JdbcAclServiceTests {
@Test(expected = NotFoundException.class)
public void readAclByIdMissingAcl() {
Map result = new HashMap<>();
- when(
- lookupStrategy.readAclsById(anyList(),
- anyList())).thenReturn(result);
+ when(lookupStrategy.readAclsById(anyList(), anyList())).thenReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 1);
List sids = Arrays.asList(new PrincipalSid("user"));
@@ -99,10 +95,8 @@ public class JdbcAclServiceTests {
public void findOneChildren() {
List result = new ArrayList<>();
result.add(new ObjectIdentityImpl(Object.class, "5577"));
- Object[] args = {"1", "org.springframework.security.acls.jdbc.JdbcAclServiceTests$MockLongIdDomainObject"};
- when(
- jdbcOperations.query(anyString(),
- aryEq(args), any(RowMapper.class))).thenReturn(result);
+ Object[] args = { "1", "org.springframework.security.acls.jdbc.JdbcAclServiceTests$MockLongIdDomainObject" };
+ when(jdbcOperations.query(anyString(), aryEq(args), any(RowMapper.class))).thenReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L);
List objectIdentities = aclService.findChildren(objectIdentity);
@@ -170,10 +164,12 @@ public class JdbcAclServiceTests {
List objectIdentities = aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("costcenter");
- assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(UUID.fromString("25d93b3f-c3aa-4814-9d5e-c7c96ced7762"));
+ assertThat(objectIdentities.get(0).getIdentifier())
+ .isEqualTo(UUID.fromString("25d93b3f-c3aa-4814-9d5e-c7c96ced7762"));
}
private class MockLongIdDomainObject {
+
private Object id;
public Object getId() {
@@ -183,9 +179,11 @@ public class JdbcAclServiceTests {
public void setId(Object id) {
this.id = id;
}
+
}
private class MockUntypedIdDomainObject {
+
private Object id;
public Object getId() {
@@ -195,5 +193,7 @@ public class JdbcAclServiceTests {
public void setId(Object id) {
this.id = id;
}
+
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java
index 0e54ed8f58..0d80c92051 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java
@@ -62,36 +62,38 @@ import org.springframework.transaction.annotation.Transactional;
* @author Andrei Stefan
*/
@ContextConfiguration(locations = { "/jdbcMutableAclServiceTests-context.xml" })
-public class JdbcMutableAclServiceTests extends
- AbstractTransactionalJUnit4SpringContextTests {
+public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4SpringContextTests {
+
// ~ Constant fields
// ================================================================================================
private static final String TARGET_CLASS = TargetObject.class.getName();
- private final Authentication auth = new TestingAuthenticationToken("ben", "ignored",
- "ROLE_ADMINISTRATOR");
+ private final Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR");
public static final String SELECT_ALL_CLASSES = "SELECT * FROM acl_class WHERE class = ?";
// ~ Instance fields
// ================================================================================================
- private final ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS,
- 100L);
- private final ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS,
- 101L);
- private final ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS,
- 102L);
+ private final ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
+
+ private final ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101L);
+
+ private final ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L);
@Autowired
private JdbcMutableAclService jdbcMutableAclService;
+
@Autowired
private AclCache aclCache;
+
@Autowired
private LookupStrategy lookupStrategy;
+
@Autowired
private DataSource dataSource;
+
@Autowired
private JdbcTemplate jdbcTemplate;
@@ -166,8 +168,8 @@ public class JdbcMutableAclServiceTests extends
jdbcMutableAclService.updateAcl(child);
// Let's check if we can read them back correctly
- Map map = jdbcMutableAclService.readAclsById(Arrays.asList(
- getTopParentOid(), getMiddleParentOid(), getChildOid()));
+ Map map = jdbcMutableAclService
+ .readAclsById(Arrays.asList(getTopParentOid(), getMiddleParentOid(), getChildOid()));
assertThat(map).hasSize(3);
// Replace our current objects with their retrieved versions
@@ -257,8 +259,9 @@ public class JdbcMutableAclServiceTests extends
}
// Check the permissions are as they should be
- assertThat(child.isGranted(delete, pSid, true)).isFalse(); // as earlier permission
- // overrode
+ assertThat(child.isGranted(delete, pSid, true)).isFalse(); // as earlier
+ // permission
+ // overrode
assertThat(child.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue();
// Now check the first ACE (index 0) really is DELETE for our Sid and is
@@ -360,8 +363,7 @@ public class JdbcMutableAclServiceTests extends
@Transactional
public void createAclForADuplicateDomainObject() {
SecurityContextHolder.getContext().setAuthentication(auth);
- ObjectIdentity duplicateOid = new ObjectIdentityImpl(TARGET_CLASS,
- 100L);
+ ObjectIdentity duplicateOid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
jdbcMutableAclService.createAcl(duplicateOid);
// Try to add the same object second time
try {
@@ -419,11 +421,8 @@ public class JdbcMutableAclServiceTests extends
// Remove the child and check all related database rows were removed accordingly
jdbcMutableAclService.deleteAcl(getChildOid(), false);
- assertThat(
- jdbcTemplate.queryForList(SELECT_ALL_CLASSES,
- new Object[] { getTargetClass() })).hasSize(1);
- assertThat(jdbcTemplate.queryForList("select * from acl_object_identity")
- ).isEmpty();
+ assertThat(jdbcTemplate.queryForList(SELECT_ALL_CLASSES, new Object[] { getTargetClass() })).hasSize(1);
+ assertThat(jdbcTemplate.queryForList("select * from acl_object_identity")).isEmpty();
assertThat(jdbcTemplate.queryForList("select * from acl_entry")).isEmpty();
// Check the cache
@@ -439,8 +438,7 @@ public class JdbcMutableAclServiceTests extends
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 101);
jdbcMutableAclService.createAcl(oid);
- assertThat(jdbcMutableAclService.readAclById(new ObjectIdentityImpl(
- TARGET_CLASS, 101L))).isNotNull();
+ assertThat(jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 101L))).isNotNull();
}
/**
@@ -449,8 +447,7 @@ public class JdbcMutableAclServiceTests extends
@Test
@Transactional
public void childrenAreClearedFromCacheWhenParentIsUpdated() {
- Authentication auth = new TestingAuthenticationToken("ben", "ignored",
- "ROLE_ADMINISTRATOR");
+ Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
@@ -474,7 +471,8 @@ public class JdbcMutableAclServiceTests extends
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid);
parent = (MutableAcl) child.getParentAcl();
- assertThat(parent.getEntries()).hasSize(2).withFailMessage("Fails because child has a stale reference to its parent");
+ assertThat(parent.getEntries()).hasSize(2)
+ .withFailMessage("Fails because child has a stale reference to its parent");
assertThat(parent.getEntries().get(0).getPermission().getMask()).isEqualTo(1);
assertThat(parent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben"));
assertThat(parent.getEntries().get(1).getPermission().getMask()).isEqualTo(1);
@@ -487,34 +485,28 @@ public class JdbcMutableAclServiceTests extends
@Test
@Transactional
public void childrenAreClearedFromCacheWhenParentisUpdated2() {
- Authentication auth = new TestingAuthenticationToken("system", "secret",
- "ROLE_IGNORED");
+ Authentication auth = new TestingAuthenticationToken("system", "secret", "ROLE_IGNORED");
SecurityContextHolder.getContext().setAuthentication(auth);
- ObjectIdentityImpl rootObject = new ObjectIdentityImpl(TARGET_CLASS,
- 1L);
+ ObjectIdentityImpl rootObject = new ObjectIdentityImpl(TARGET_CLASS, 1L);
MutableAcl parent = jdbcMutableAclService.createAcl(rootObject);
- MutableAcl child = jdbcMutableAclService.createAcl(new ObjectIdentityImpl(
- TARGET_CLASS, 2L));
+ MutableAcl child = jdbcMutableAclService.createAcl(new ObjectIdentityImpl(TARGET_CLASS, 2L));
child.setParent(parent);
jdbcMutableAclService.updateAcl(child);
- parent.insertAce(0, BasePermission.ADMINISTRATION, new GrantedAuthoritySid(
- "ROLE_ADMINISTRATOR"), true);
+ parent.insertAce(0, BasePermission.ADMINISTRATION, new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true);
jdbcMutableAclService.updateAcl(parent);
parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true);
jdbcMutableAclService.updateAcl(parent);
- child = (MutableAcl) jdbcMutableAclService.readAclById(new ObjectIdentityImpl(
- TARGET_CLASS, 2L));
+ child = (MutableAcl) jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 2L));
parent = (MutableAcl) child.getParentAcl();
assertThat(parent.getEntries()).hasSize(2);
assertThat(parent.getEntries().get(0).getPermission().getMask()).isEqualTo(16);
- assertThat(parent.getEntries()
- .get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"));
+ assertThat(parent.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"));
assertThat(parent.getEntries().get(1).getPermission().getMask()).isEqualTo(8);
assertThat(parent.getEntries().get(1).getSid()).isEqualTo(new PrincipalSid("terry"));
}
@@ -522,18 +514,15 @@ public class JdbcMutableAclServiceTests extends
@Test
@Transactional
public void cumulativePermissions() {
- Authentication auth = new TestingAuthenticationToken("ben", "ignored",
- "ROLE_ADMINISTRATOR");
+ Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
- ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS,
- 110L);
+ ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 110L);
MutableAcl topParent = jdbcMutableAclService.createAcl(topParentOid);
// Add an ACE permission entry
- Permission cm = new CumulativePermission().set(BasePermission.READ).set(
- BasePermission.ADMINISTRATION);
+ Permission cm = new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION);
assertThat(cm.getMask()).isEqualTo(17);
Sid benSid = new PrincipalSid(auth);
topParent.insertAce(0, cm, benSid, true);
@@ -551,15 +540,12 @@ public class JdbcMutableAclServiceTests extends
@Test
public void testProcessingCustomSid() {
- CustomJdbcMutableAclService customJdbcMutableAclService = spy(new CustomJdbcMutableAclService(
- dataSource, lookupStrategy, aclCache));
+ CustomJdbcMutableAclService customJdbcMutableAclService = spy(
+ new CustomJdbcMutableAclService(dataSource, lookupStrategy, aclCache));
CustomSid customSid = new CustomSid("Custom sid");
- when(
- customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid",
- false, false)).thenReturn(1L);
+ when(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).thenReturn(1L);
- Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(
- customSid, false);
+ Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(customSid, false);
assertThat(new Long(1L)).isEqualTo(result);
}
@@ -570,8 +556,7 @@ public class JdbcMutableAclServiceTests extends
*/
private class CustomJdbcMutableAclService extends JdbcMutableAclService {
- private CustomJdbcMutableAclService(DataSource dataSource,
- LookupStrategy lookupStrategy, AclCache aclCache) {
+ private CustomJdbcMutableAclService(DataSource dataSource, LookupStrategy lookupStrategy, AclCache aclCache) {
super(dataSource, lookupStrategy, aclCache);
}
@@ -591,6 +576,7 @@ public class JdbcMutableAclServiceTests extends
}
return createOrRetrieveSidPrimaryKey(sidName, isPrincipal, allowCreate);
}
+
}
protected Authentication getAuth() {
@@ -600,4 +586,5 @@ public class JdbcMutableAclServiceTests extends
protected JdbcMutableAclService getJdbcMutableAclService() {
return jdbcMutableAclService;
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTestsWithAclClassId.java b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTestsWithAclClassId.java
index 1d45b033aa..397dfc4820 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTestsWithAclClassId.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTestsWithAclClassId.java
@@ -28,20 +28,21 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
- * Integration tests the ACL system using ACL class id type of UUID and using an in-memory database.
+ * Integration tests the ACL system using ACL class id type of UUID and using an in-memory
+ * database.
+ *
* @author Paul Wheeler
*/
-@ContextConfiguration(locations = {"/jdbcMutableAclServiceTestsWithAclClass-context.xml"})
+@ContextConfiguration(locations = { "/jdbcMutableAclServiceTestsWithAclClass-context.xml" })
public class JdbcMutableAclServiceTestsWithAclClassId extends JdbcMutableAclServiceTests {
private static final String TARGET_CLASS_WITH_UUID = TargetObjectWithUUID.class.getName();
- private final ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID,
- UUID.randomUUID());
- private final ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID,
- UUID.randomUUID());
- private final ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID,
- UUID.randomUUID());
+ private final ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, UUID.randomUUID());
+
+ private final ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, UUID.randomUUID());
+
+ private final ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, UUID.randomUUID());
@Override
protected String getSqlClassPathResource() {
@@ -77,7 +78,8 @@ public class JdbcMutableAclServiceTestsWithAclClassId extends JdbcMutableAclServ
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, id);
getJdbcMutableAclService().createAcl(oid);
- assertThat(getJdbcMutableAclService().readAclById(new ObjectIdentityImpl(
- TARGET_CLASS_WITH_UUID, id))).isNotNull();
+ assertThat(getJdbcMutableAclService().readAclById(new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, id)))
+ .isNotNull();
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/SpringCacheBasedAclCacheTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/SpringCacheBasedAclCacheTests.java
index 4d9de2f556..6b9368af6c 100644
--- a/acl/src/test/java/org/springframework/security/acls/jdbc/SpringCacheBasedAclCacheTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/jdbc/SpringCacheBasedAclCacheTests.java
@@ -41,6 +41,7 @@ import static org.assertj.core.api.Assertions.*;
* @author Marten Deinum
*/
public class SpringCacheBasedAclCacheTests {
+
private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject";
private static CacheManager cacheManager;
@@ -76,16 +77,14 @@ public class SpringCacheBasedAclCacheTests {
Map realCache = (Map) cache.getNativeCache();
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority(
- "ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL"));
+ new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
+ new SimpleGrantedAuthority("ROLE_GENERAL"));
AuditLogger auditLogger = new ConsoleAuditLogger();
- PermissionGrantingStrategy permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(
- auditLogger);
- SpringCacheBasedAclCache myCache = new SpringCacheBasedAclCache(cache,
- permissionGrantingStrategy, aclAuthorizationStrategy);
- MutableAcl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy,
- auditLogger);
+ PermissionGrantingStrategy permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(auditLogger);
+ SpringCacheBasedAclCache myCache = new SpringCacheBasedAclCache(cache, permissionGrantingStrategy,
+ aclAuthorizationStrategy);
+ MutableAcl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, auditLogger);
assertThat(realCache).isEmpty();
myCache.putInCache(acl);
@@ -96,8 +95,7 @@ public class SpringCacheBasedAclCacheTests {
// Put another object in cache
ObjectIdentity identity2 = new ObjectIdentityImpl(TARGET_CLASS, 101L);
- MutableAcl acl2 = new AclImpl(identity2, 2L,
- aclAuthorizationStrategy, new ConsoleAuditLogger());
+ MutableAcl acl2 = new AclImpl(identity2, 2L, aclAuthorizationStrategy, new ConsoleAuditLogger());
myCache.putInCache(acl2);
@@ -123,28 +121,23 @@ public class SpringCacheBasedAclCacheTests {
Cache cache = getCache();
Map realCache = (Map) cache.getNativeCache();
- Authentication auth = new TestingAuthenticationToken("user", "password",
- "ROLE_GENERAL");
+ Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 1L);
- ObjectIdentity identityParent = new ObjectIdentityImpl(TARGET_CLASS,
- 2L);
+ ObjectIdentity identityParent = new ObjectIdentityImpl(TARGET_CLASS, 2L);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
- new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority(
- "ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL"));
+ new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
+ new SimpleGrantedAuthority("ROLE_GENERAL"));
AuditLogger auditLogger = new ConsoleAuditLogger();
- PermissionGrantingStrategy permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(
- auditLogger);
- SpringCacheBasedAclCache myCache = new SpringCacheBasedAclCache(cache,
- permissionGrantingStrategy, aclAuthorizationStrategy);
+ PermissionGrantingStrategy permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(auditLogger);
+ SpringCacheBasedAclCache myCache = new SpringCacheBasedAclCache(cache, permissionGrantingStrategy,
+ aclAuthorizationStrategy);
- MutableAcl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy,
- auditLogger);
- MutableAcl parentAcl = new AclImpl(identityParent, 2L,
- aclAuthorizationStrategy, auditLogger);
+ MutableAcl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, auditLogger);
+ MutableAcl parentAcl = new AclImpl(identityParent, 2L, aclAuthorizationStrategy, auditLogger);
acl.setParent(parentAcl);
@@ -156,16 +149,14 @@ public class SpringCacheBasedAclCacheTests {
AclImpl aclFromCache = (AclImpl) myCache.getFromCache(1L);
assertThat(aclFromCache).isEqualTo(acl);
// SEC-951 check transient fields are set on parent
- assertThat(FieldUtils.getFieldValue(aclFromCache.getParentAcl(),
- "aclAuthorizationStrategy")).isNotNull();
- assertThat(FieldUtils.getFieldValue(aclFromCache.getParentAcl(),
- "permissionGrantingStrategy")).isNotNull();
+ assertThat(FieldUtils.getFieldValue(aclFromCache.getParentAcl(), "aclAuthorizationStrategy")).isNotNull();
+ assertThat(FieldUtils.getFieldValue(aclFromCache.getParentAcl(), "permissionGrantingStrategy")).isNotNull();
assertThat(myCache.getFromCache(identity)).isEqualTo(acl);
assertThat(FieldUtils.getFieldValue(aclFromCache, "aclAuthorizationStrategy")).isNotNull();
AclImpl parentAclFromCache = (AclImpl) myCache.getFromCache(2L);
assertThat(parentAclFromCache).isEqualTo(parentAcl);
- assertThat(FieldUtils.getFieldValue(parentAclFromCache,
- "aclAuthorizationStrategy")).isNotNull();
+ assertThat(FieldUtils.getFieldValue(parentAclFromCache, "aclAuthorizationStrategy")).isNotNull();
assertThat(myCache.getFromCache(identityParent)).isEqualTo(parentAcl);
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/sid/CustomSid.java b/acl/src/test/java/org/springframework/security/acls/sid/CustomSid.java
index 21226f1888..c872258518 100644
--- a/acl/src/test/java/org/springframework/security/acls/sid/CustomSid.java
+++ b/acl/src/test/java/org/springframework/security/acls/sid/CustomSid.java
@@ -19,6 +19,7 @@ import org.springframework.security.acls.model.Sid;
/**
* This class is example of custom {@link Sid} implementation
+ *
* @author Mikhail Stryzhonok
*/
public class CustomSid implements Sid {
@@ -36,4 +37,5 @@ public class CustomSid implements Sid {
public void setSid(String sid) {
this.sid = sid;
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/sid/SidRetrievalStrategyTests.java b/acl/src/test/java/org/springframework/security/acls/sid/SidRetrievalStrategyTests.java
index ba61b41d01..8972dfa378 100644
--- a/acl/src/test/java/org/springframework/security/acls/sid/SidRetrievalStrategyTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/sid/SidRetrievalStrategyTests.java
@@ -39,8 +39,8 @@ import org.springframework.security.core.authority.AuthorityUtils;
*/
@SuppressWarnings("unchecked")
public class SidRetrievalStrategyTests {
- Authentication authentication = new TestingAuthenticationToken("scott", "password",
- "A", "B", "C");
+
+ Authentication authentication = new TestingAuthenticationToken("scott", "password", "A", "B", "C");
// ~ Methods
// ========================================================================================================
@@ -69,8 +69,7 @@ public class SidRetrievalStrategyTests {
public void roleHierarchyIsUsedWhenSet() {
RoleHierarchy rh = mock(RoleHierarchy.class);
List rhAuthorities = AuthorityUtils.createAuthorityList("D");
- when(rh.getReachableGrantedAuthorities(anyCollection()))
- .thenReturn(rhAuthorities);
+ when(rh.getReachableGrantedAuthorities(anyCollection())).thenReturn(rhAuthorities);
SidRetrievalStrategy strat = new SidRetrievalStrategyImpl(rh);
List sids = strat.getSids(authentication);
@@ -79,4 +78,5 @@ public class SidRetrievalStrategyTests {
assertThat(sids.get(0) instanceof PrincipalSid).isTrue();
assertThat(((GrantedAuthoritySid) sids.get(1)).getGrantedAuthority()).isEqualTo("D");
}
+
}
diff --git a/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java b/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java
index b65c1cb906..fe11171182 100644
--- a/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java
+++ b/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java
@@ -67,16 +67,14 @@ public class SidTests {
}
try {
- Authentication authentication = new TestingAuthenticationToken(null,
- "password");
+ Authentication authentication = new TestingAuthenticationToken(null, "password");
new PrincipalSid(authentication);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
- Authentication authentication = new TestingAuthenticationToken("johndoe",
- "password");
+ Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
new PrincipalSid(authentication);
// throws no exception
}
@@ -140,18 +138,15 @@ public class SidTests {
@Test
public void testPrincipalSidEquals() {
- Authentication authentication = new TestingAuthenticationToken("johndoe",
- "password");
+ Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
Sid principalSid = new PrincipalSid(authentication);
assertThat(principalSid.equals(null)).isFalse();
assertThat(principalSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse();
assertThat(principalSid.equals(principalSid)).isTrue();
assertThat(principalSid.equals(new PrincipalSid(authentication))).isTrue();
- assertThat(principalSid.equals(new PrincipalSid(
- new TestingAuthenticationToken("johndoe", null)))).isTrue();
- assertThat(principalSid.equals(new PrincipalSid(
- new TestingAuthenticationToken("scott", null)))).isFalse();
+ assertThat(principalSid.equals(new PrincipalSid(new TestingAuthenticationToken("johndoe", null)))).isTrue();
+ assertThat(principalSid.equals(new PrincipalSid(new TestingAuthenticationToken("scott", null)))).isFalse();
assertThat(principalSid.equals(new PrincipalSid("johndoe"))).isTrue();
assertThat(principalSid.equals(new PrincipalSid("scott"))).isFalse();
}
@@ -165,27 +160,22 @@ public class SidTests {
assertThat(gaSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse();
assertThat(gaSid.equals(gaSid)).isTrue();
assertThat(gaSid.equals(new GrantedAuthoritySid(ga))).isTrue();
- assertThat(gaSid.equals(new GrantedAuthoritySid(
- new SimpleGrantedAuthority("ROLE_TEST")))).isTrue();
- assertThat(gaSid.equals(new GrantedAuthoritySid(
- new SimpleGrantedAuthority("ROLE_NOT_EQUAL")))).isFalse();
+ assertThat(gaSid.equals(new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST")))).isTrue();
+ assertThat(gaSid.equals(new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_NOT_EQUAL")))).isFalse();
assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_TEST"))).isTrue();
assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_NOT_EQUAL"))).isFalse();
}
@Test
public void testPrincipalSidHashCode() {
- Authentication authentication = new TestingAuthenticationToken("johndoe",
- "password");
+ Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
Sid principalSid = new PrincipalSid(authentication);
assertThat(principalSid.hashCode()).isEqualTo("johndoe".hashCode());
- assertThat(principalSid.hashCode()).isEqualTo(
- new PrincipalSid("johndoe").hashCode());
- assertThat(principalSid.hashCode()).isNotEqualTo(
- new PrincipalSid("scott").hashCode());
- assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid(
- new TestingAuthenticationToken("scott", "password")).hashCode());
+ assertThat(principalSid.hashCode()).isEqualTo(new PrincipalSid("johndoe").hashCode());
+ assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid("scott").hashCode());
+ assertThat(principalSid.hashCode())
+ .isNotEqualTo(new PrincipalSid(new TestingAuthenticationToken("scott", "password")).hashCode());
}
@Test
@@ -194,18 +184,15 @@ public class SidTests {
Sid gaSid = new GrantedAuthoritySid(ga);
assertThat(gaSid.hashCode()).isEqualTo("ROLE_TEST".hashCode());
- assertThat(gaSid.hashCode()).isEqualTo(
- new GrantedAuthoritySid("ROLE_TEST").hashCode());
- assertThat(gaSid.hashCode()).isNotEqualTo(
- new GrantedAuthoritySid("ROLE_TEST_2").hashCode());
- assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid(
- new SimpleGrantedAuthority("ROLE_TEST_2")).hashCode());
+ assertThat(gaSid.hashCode()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST").hashCode());
+ assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid("ROLE_TEST_2").hashCode());
+ assertThat(gaSid.hashCode())
+ .isNotEqualTo(new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST_2")).hashCode());
}
@Test
public void testGetters() {
- Authentication authentication = new TestingAuthenticationToken("johndoe",
- "password");
+ Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
PrincipalSid principalSid = new PrincipalSid(authentication);
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
GrantedAuthoritySid gaSid = new GrantedAuthoritySid(ga);
@@ -243,6 +230,7 @@ public class SidTests {
}
static class CustomAuthenticationToken extends AbstractAuthenticationToken {
+
private CustomToken principal;
CustomAuthenticationToken(CustomToken principal, Collection authorities) {
@@ -264,9 +252,11 @@ public class SidTests {
public String getName() {
return principal.getName();
}
+
}
static class CustomToken {
+
private String name;
CustomToken(String name) {
@@ -276,5 +266,7 @@ public class SidTests {
String getName() {
return name;
}
+
}
+
}
diff --git a/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java b/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java
index f0d7570722..90ff2b7db6 100644
--- a/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java
+++ b/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java
@@ -50,36 +50,37 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
/**
- *
* @author Luke Taylor
* @since 3.0.3
*/
public class AnnotationSecurityAspectTests {
+
private AffirmativeBased adm;
+
private @Mock AuthenticationManager authman;
- private TestingAuthenticationToken anne = new TestingAuthenticationToken("anne", "",
- "ROLE_A");
+
+ private TestingAuthenticationToken anne = new TestingAuthenticationToken("anne", "", "ROLE_A");
+
// private TestingAuthenticationToken bob = new TestingAuthenticationToken("bob", "",
// "ROLE_B");
private AspectJMethodSecurityInterceptor interceptor;
+
private SecuredImpl secured = new SecuredImpl();
+
private SecuredImplSubclass securedSub = new SecuredImplSubclass();
+
private PrePostSecured prePostSecured = new PrePostSecured();
@Before
public final void setUp() {
MockitoAnnotations.initMocks(this);
interceptor = new AspectJMethodSecurityInterceptor();
- AccessDecisionVoter[] voters = new AccessDecisionVoter[] {
- new RoleVoter(),
- new PreInvocationAuthorizationAdviceVoter(
- new ExpressionBasedPreInvocationAdvice()) };
- adm = new AffirmativeBased(
- Arrays.> asList(voters));
+ AccessDecisionVoter[] voters = new AccessDecisionVoter[] { new RoleVoter(),
+ new PreInvocationAuthorizationAdviceVoter(new ExpressionBasedPreInvocationAdvice()) };
+ adm = new AffirmativeBased(Arrays.>asList(voters));
interceptor.setAccessDecisionManager(adm);
interceptor.setAuthenticationManager(authman);
- interceptor
- .setSecurityMetadataSource(new SecuredAnnotationSecurityMetadataSource());
+ interceptor.setSecurityMetadataSource(new SecuredAnnotationSecurityMetadataSource());
AnnotationSecurityAspect secAspect = AnnotationSecurityAspect.aspectOf();
secAspect.setSecurityInterceptor(interceptor);
}
@@ -151,23 +152,25 @@ public class AnnotationSecurityAspectTests {
private void configureForElAnnotations() {
DefaultMethodSecurityExpressionHandler eh = new DefaultMethodSecurityExpressionHandler();
- interceptor
- .setSecurityMetadataSource(new PrePostAnnotationSecurityMetadataSource(
- new ExpressionBasedAnnotationAttributeFactory(eh)));
+ interceptor.setSecurityMetadataSource(
+ new PrePostAnnotationSecurityMetadataSource(new ExpressionBasedAnnotationAttributeFactory(eh)));
interceptor.setAccessDecisionManager(adm);
AfterInvocationProviderManager aim = new AfterInvocationProviderManager();
- aim.setProviders(Arrays.asList(new PostInvocationAdviceProvider(
- new ExpressionBasedPostInvocationAdvice(eh))));
+ aim.setProviders(Arrays.asList(new PostInvocationAdviceProvider(new ExpressionBasedPostInvocationAdvice(eh))));
interceptor.setAfterInvocationManager(aim);
}
+
}
interface SecuredInterface {
+
@Secured("ROLE_X")
void securedMethod();
+
}
class SecuredImpl implements SecuredInterface {
+
// Not really secured because AspectJ doesn't inherit annotations from interfaces
public void securedMethod() {
}
@@ -188,18 +191,22 @@ class SecuredImpl implements SecuredInterface {
public void publicCallsPrivate() {
privateMethod();
}
+
}
class SecuredImplSubclass extends SecuredImpl {
+
protected void protectedMethod() {
}
public void publicCallsPrivate() {
super.publicCallsPrivate();
}
+
}
class PrePostSecured {
+
@PreAuthorize("denyAll")
public void denyAllMethod() {
}
@@ -207,8 +214,8 @@ class PrePostSecured {
@PostFilter("filterObject.startsWith('a')")
public List postFilterMethod() {
ArrayList objects = new ArrayList<>();
- objects.addAll(Arrays.asList(new String[] { "apple", "banana", "aubergine",
- "orange" }));
+ objects.addAll(Arrays.asList(new String[] { "apple", "banana", "aubergine", "orange" }));
return objects;
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/SamlServiceProperties.java b/cas/src/main/java/org/springframework/security/cas/SamlServiceProperties.java
index 6be415859e..c20e352e73 100644
--- a/cas/src/main/java/org/springframework/security/cas/SamlServiceProperties.java
+++ b/cas/src/main/java/org/springframework/security/cas/SamlServiceProperties.java
@@ -32,4 +32,5 @@ public final class SamlServiceProperties extends ServiceProperties {
super.setArtifactParameter(DEFAULT_SAML_ARTIFACT_PARAMETER);
super.setServiceParameter(DEFAULT_SAML_SERVICE_PARAMETER);
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/ServiceProperties.java b/cas/src/main/java/org/springframework/security/cas/ServiceProperties.java
index e63742222c..85bab3cc0e 100644
--- a/cas/src/main/java/org/springframework/security/cas/ServiceProperties.java
+++ b/cas/src/main/java/org/springframework/security/cas/ServiceProperties.java
@@ -65,7 +65,6 @@ public class ServiceProperties implements InitializingBean {
*
- *
* @return the URL of the service the user is authenticating to
*/
public final String getService() {
@@ -81,7 +80,6 @@ public class ServiceProperties implements InitializingBean {
* ticket was generated as a consequence of an explicit login. High security
* applications would probably set this to true. Defaults to
* false, providing automated single sign on.
- *
* @return whether to send the renew parameter to CAS
*/
public final boolean isSendRenew() {
@@ -103,7 +101,6 @@ public class ServiceProperties implements InitializingBean {
/**
* Configures the Request Parameter to look for when attempting to see if a CAS ticket
* was sent from the server.
- *
* @param artifactParameter the id to use. Default is "ticket".
*/
public final void setArtifactParameter(final String artifactParameter) {
@@ -113,7 +110,6 @@ public class ServiceProperties implements InitializingBean {
/**
* Configures the Request parameter to look for when attempting to send a request to
* CAS.
- *
* @return the service parameter to use. Default is "service".
*/
public final String getServiceParameter() {
@@ -132,11 +128,10 @@ public class ServiceProperties implements InitializingBean {
* If true, then any non-null artifact (ticket) should be authenticated. Additionally,
* the service will be determined dynamically in order to ensure the service matches
* the expected value for this artifact.
- *
* @param authenticateAllArtifacts
*/
- public final void setAuthenticateAllArtifacts(
- final boolean authenticateAllArtifacts) {
+ public final void setAuthenticateAllArtifacts(final boolean authenticateAllArtifacts) {
this.authenticateAllArtifacts = authenticateAllArtifacts;
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/CasAssertionAuthenticationToken.java b/cas/src/main/java/org/springframework/security/cas/authentication/CasAssertionAuthenticationToken.java
index af82fa1183..ffc2ad4703 100644
--- a/cas/src/main/java/org/springframework/security/cas/authentication/CasAssertionAuthenticationToken.java
+++ b/cas/src/main/java/org/springframework/security/cas/authentication/CasAssertionAuthenticationToken.java
@@ -53,4 +53,5 @@ public final class CasAssertionAuthenticationToken extends AbstractAuthenticatio
public Assertion getAssertion() {
return this.assertion;
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java
index 226a786d6b..e40696fb94 100644
--- a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java
+++ b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java
@@ -54,8 +54,8 @@ import org.springframework.util.Assert;
* @author Ben Alex
* @author Scott Battaglia
*/
-public class CasAuthenticationProvider implements AuthenticationProvider,
- InitializingBean, MessageSourceAware {
+public class CasAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
+
// ~ Static fields/initializers
// =====================================================================================
@@ -67,67 +67,65 @@ public class CasAuthenticationProvider implements AuthenticationProvider,
private AuthenticationUserDetailsService authenticationUserDetailsService;
private final UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
+
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
+
private StatelessTicketCache statelessTicketCache = new NullStatelessTicketCache();
+
private String key;
+
private TicketValidator ticketValidator;
+
private ServiceProperties serviceProperties;
+
private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();
// ~ Methods
// ========================================================================================================
public void afterPropertiesSet() {
- Assert.notNull(this.authenticationUserDetailsService,
- "An authenticationUserDetailsService must be set");
+ Assert.notNull(this.authenticationUserDetailsService, "An authenticationUserDetailsService must be set");
Assert.notNull(this.ticketValidator, "A ticketValidator must be set");
Assert.notNull(this.statelessTicketCache, "A statelessTicketCache must be set");
- Assert.hasText(
- this.key,
+ Assert.hasText(this.key,
"A Key is required so CasAuthenticationProvider can identify tokens it previously authenticated");
Assert.notNull(this.messages, "A message source must be set");
}
- public Authentication authenticate(Authentication authentication)
- throws AuthenticationException {
+ public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
if (authentication instanceof UsernamePasswordAuthenticationToken
- && (!CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER
- .equals(authentication.getPrincipal().toString()) && !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER
- .equals(authentication.getPrincipal().toString()))) {
+ && (!CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER.equals(authentication.getPrincipal().toString())
+ && !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER
+ .equals(authentication.getPrincipal().toString()))) {
// UsernamePasswordAuthenticationToken not CAS related
return null;
}
// If an existing CasAuthenticationToken, just check we created it
if (authentication instanceof CasAuthenticationToken) {
- if (this.key.hashCode() == ((CasAuthenticationToken) authentication)
- .getKeyHash()) {
+ if (this.key.hashCode() == ((CasAuthenticationToken) authentication).getKeyHash()) {
return authentication;
}
else {
- throw new BadCredentialsException(
- messages.getMessage("CasAuthenticationProvider.incorrectKey",
- "The presented CasAuthenticationToken does not contain the expected key"));
+ throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.incorrectKey",
+ "The presented CasAuthenticationToken does not contain the expected key"));
}
}
// Ensure credentials are presented
- if ((authentication.getCredentials() == null)
- || "".equals(authentication.getCredentials())) {
- throw new BadCredentialsException(messages.getMessage(
- "CasAuthenticationProvider.noServiceTicket",
+ if ((authentication.getCredentials() == null) || "".equals(authentication.getCredentials())) {
+ throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.noServiceTicket",
"Failed to provide a CAS service ticket to validate"));
}
boolean stateless = false;
if (authentication instanceof UsernamePasswordAuthenticationToken
- && CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER.equals(authentication
- .getPrincipal())) {
+ && CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER.equals(authentication.getPrincipal())) {
stateless = true;
}
@@ -135,8 +133,7 @@ public class CasAuthenticationProvider implements AuthenticationProvider,
if (stateless) {
// Try to obtain from cache
- result = statelessTicketCache.getByTicketId(authentication.getCredentials()
- .toString());
+ result = statelessTicketCache.getByTicketId(authentication.getCredentials().toString());
}
if (result == null) {
@@ -152,17 +149,14 @@ public class CasAuthenticationProvider implements AuthenticationProvider,
return result;
}
- private CasAuthenticationToken authenticateNow(final Authentication authentication)
- throws AuthenticationException {
+ private CasAuthenticationToken authenticateNow(final Authentication authentication) throws AuthenticationException {
try {
- final Assertion assertion = this.ticketValidator.validate(authentication
- .getCredentials().toString(), getServiceUrl(authentication));
+ final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(),
+ getServiceUrl(authentication));
final UserDetails userDetails = loadUserByAssertion(assertion);
userDetailsChecker.check(userDetails);
- return new CasAuthenticationToken(this.key, userDetails,
- authentication.getCredentials(),
- authoritiesMapper.mapAuthorities(userDetails.getAuthorities()),
- userDetails, assertion);
+ return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(),
+ authoritiesMapper.mapAuthorities(userDetails.getAuthorities()), userDetails, assertion);
}
catch (final TicketValidationException e) {
throw new BadCredentialsException(e.getMessage(), e);
@@ -174,15 +168,13 @@ public class CasAuthenticationProvider implements AuthenticationProvider,
* {@link ServiceAuthenticationDetails}, then
* {@link ServiceAuthenticationDetails#getServiceUrl()} is used. Otherwise, the
* {@link ServiceProperties#getService()} is used.
- *
* @param authentication
* @return
*/
private String getServiceUrl(Authentication authentication) {
String serviceUrl;
if (authentication.getDetails() instanceof ServiceAuthenticationDetails) {
- serviceUrl = ((ServiceAuthenticationDetails) authentication.getDetails())
- .getServiceUrl();
+ serviceUrl = ((ServiceAuthenticationDetails) authentication.getDetails()).getServiceUrl();
}
else if (serviceProperties == null) {
throw new IllegalStateException(
@@ -205,13 +197,11 @@ public class CasAuthenticationProvider implements AuthenticationProvider,
* Template method for retrieving the UserDetails based on the assertion. Default is
* to call configured userDetailsService and pass the username. Deployers can override
* this method and retrieve the user based on any criteria they desire.
- *
* @param assertion The CAS Assertion.
* @return the UserDetails.
*/
protected UserDetails loadUserByAssertion(final Assertion assertion) {
- final CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(
- assertion, "");
+ final CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(assertion, "");
return this.authenticationUserDetailsService.loadUserDetails(token);
}
@@ -220,8 +210,7 @@ public class CasAuthenticationProvider implements AuthenticationProvider,
* Sets the UserDetailsService to use. This is a convenience method to invoke
*/
public void setUserDetailsService(final UserDetailsService userDetailsService) {
- this.authenticationUserDetailsService = new UserDetailsByNameServiceWrapper(
- userDetailsService);
+ this.authenticationUserDetailsService = new UserDetailsByNameServiceWrapper(userDetailsService);
}
public void setAuthenticationUserDetailsService(
@@ -266,10 +255,9 @@ public class CasAuthenticationProvider implements AuthenticationProvider,
}
public boolean supports(final Class> authentication) {
- return (UsernamePasswordAuthenticationToken.class
- .isAssignableFrom(authentication))
+ return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication))
|| (CasAuthenticationToken.class.isAssignableFrom(authentication))
- || (CasAssertionAuthenticationToken.class
- .isAssignableFrom(authentication));
+ || (CasAssertionAuthenticationToken.class.isAssignableFrom(authentication));
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java
index d3d0827133..3483b640cc 100644
--- a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java
+++ b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java
@@ -32,17 +32,20 @@ import org.springframework.util.Assert;
* @author Ben Alex
* @author Scott Battaglia
*/
-public class CasAuthenticationToken extends AbstractAuthenticationToken implements
- Serializable {
+public class CasAuthenticationToken extends AbstractAuthenticationToken implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
// ~ Instance fields
// ================================================================================================
private final Object credentials;
+
private final Object principal;
+
private final UserDetails userDetails;
+
private final int keyHash;
+
private final Assertion assertion;
// ~ Constructors
@@ -50,60 +53,53 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
/**
* Constructor.
- *
- * @param key to identify if this object made by a given
- * {@link CasAuthenticationProvider}
- * @param principal typically the UserDetails object (cannot be null)
+ * @param key to identify if this object made by a given
+ * {@link CasAuthenticationProvider}
+ * @param principal typically the UserDetails object (cannot be null)
* @param credentials the service/proxy ticket ID from CAS (cannot be
- * null)
+ * null)
* @param authorities the authorities granted to the user (from the
- * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
- * be null)
+ * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
+ * be null)
* @param userDetails the user details (from the
- * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
- * be null)
- * @param assertion the assertion returned from the CAS servers. It contains the
- * principal and how to obtain a proxy ticket for the user.
+ * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
+ * be null)
+ * @param assertion the assertion returned from the CAS servers. It contains the
+ * principal and how to obtain a proxy ticket for the user.
* @throws IllegalArgumentException if a null was passed
*/
- public CasAuthenticationToken(final String key, final Object principal,
- final Object credentials,
- final Collection extends GrantedAuthority> authorities,
- final UserDetails userDetails, final Assertion assertion) {
+ public CasAuthenticationToken(final String key, final Object principal, final Object credentials,
+ final Collection extends GrantedAuthority> authorities, final UserDetails userDetails,
+ final Assertion assertion) {
this(extractKeyHash(key), principal, credentials, authorities, userDetails, assertion);
}
/**
* Private constructor for Jackson Deserialization support
- *
- * @param keyHash hashCode of provided key to identify if this object made by a given
- * {@link CasAuthenticationProvider}
- * @param principal typically the UserDetails object (cannot be null)
+ * @param keyHash hashCode of provided key to identify if this object made by a given
+ * {@link CasAuthenticationProvider}
+ * @param principal typically the UserDetails object (cannot be null)
* @param credentials the service/proxy ticket ID from CAS (cannot be
- * null)
+ * null)
* @param authorities the authorities granted to the user (from the
- * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
- * be null)
+ * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
+ * be null)
* @param userDetails the user details (from the
- * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
- * be null)
- * @param assertion the assertion returned from the CAS servers. It contains the
- * principal and how to obtain a proxy ticket for the user.
+ * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
+ * be null)
+ * @param assertion the assertion returned from the CAS servers. It contains the
+ * principal and how to obtain a proxy ticket for the user.
* @throws IllegalArgumentException if a null was passed
* @since 4.2
*/
- private CasAuthenticationToken(final Integer keyHash, final Object principal,
- final Object credentials,
- final Collection extends GrantedAuthority> authorities,
- final UserDetails userDetails, final Assertion assertion) {
+ private CasAuthenticationToken(final Integer keyHash, final Object principal, final Object credentials,
+ final Collection extends GrantedAuthority> authorities, final UserDetails userDetails,
+ final Assertion assertion) {
super(authorities);
- if ((principal == null)
- || "".equals(principal) || (credentials == null)
- || "".equals(credentials) || (authorities == null)
- || (userDetails == null) || (assertion == null)) {
- throw new IllegalArgumentException(
- "Cannot pass null or empty values to constructor");
+ if ((principal == null) || "".equals(principal) || (credentials == null) || "".equals(credentials)
+ || (authorities == null) || (userDetails == null) || (assertion == null)) {
+ throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
this.keyHash = keyHash;
@@ -187,4 +183,5 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
return (sb.toString());
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java
index e424d512de..7840387422 100644
--- a/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java
+++ b/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java
@@ -25,12 +25,13 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
/**
- * Caches tickets using a Spring IoC defined EHCACHE.
+ * Caches tickets using a Spring IoC defined
+ * EHCACHE.
*
* @author Ben Alex
*/
public class EhCacheBasedTicketCache implements StatelessTicketCache, InitializingBean {
+
// ~ Static fields/initializers
// =====================================================================================
@@ -52,8 +53,7 @@ public class EhCacheBasedTicketCache implements StatelessTicketCache, Initializi
final Element element = cache.get(serviceTicket);
if (logger.isDebugEnabled()) {
- logger.debug("Cache hit: " + (element != null) + "; service ticket: "
- + serviceTicket);
+ logger.debug("Cache hit: " + (element != null) + "; service ticket: " + serviceTicket);
}
return element == null ? null : (CasAuthenticationToken) element.getValue();
@@ -88,4 +88,5 @@ public class EhCacheBasedTicketCache implements StatelessTicketCache, Initializi
public void setCache(final Ehcache cache) {
this.cache = cache;
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/NullStatelessTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/NullStatelessTicketCache.java
index b33518114b..e5aafe8235 100644
--- a/cas/src/main/java/org/springframework/security/cas/authentication/NullStatelessTicketCache.java
+++ b/cas/src/main/java/org/springframework/security/cas/authentication/NullStatelessTicketCache.java
@@ -24,7 +24,6 @@ package org.springframework.security.cas.authentication;
* are not using the stateless session management.
*
* @author Scott Battaglia
- *
* @see CasAuthenticationProvider
*/
public final class NullStatelessTicketCache implements StatelessTicketCache {
@@ -56,4 +55,5 @@ public final class NullStatelessTicketCache implements StatelessTicketCache {
public void removeTicketFromCache(final String serviceTicket) {
// nothing to do
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java
index 171792448d..01549d55bd 100644
--- a/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java
+++ b/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java
@@ -28,11 +28,11 @@ import org.springframework.util.Assert;
*
*/
public class SpringCacheBasedTicketCache implements StatelessTicketCache {
+
// ~ Static fields/initializers
// =====================================================================================
- private static final Log logger = LogFactory
- .getLog(SpringCacheBasedTicketCache.class);
+ private static final Log logger = LogFactory.getLog(SpringCacheBasedTicketCache.class);
// ~ Instance fields
// ================================================================================================
@@ -51,12 +51,10 @@ public class SpringCacheBasedTicketCache implements StatelessTicketCache {
// ========================================================================================================
public CasAuthenticationToken getByTicketId(final String serviceTicket) {
- final Cache.ValueWrapper element = serviceTicket != null ? cache
- .get(serviceTicket) : null;
+ final Cache.ValueWrapper element = serviceTicket != null ? cache.get(serviceTicket) : null;
if (logger.isDebugEnabled()) {
- logger.debug("Cache hit: " + (element != null) + "; service ticket: "
- + serviceTicket);
+ logger.debug("Cache hit: " + (element != null) + "; service ticket: " + serviceTicket);
}
return element == null ? null : (CasAuthenticationToken) element.get();
@@ -83,4 +81,5 @@ public class SpringCacheBasedTicketCache implements StatelessTicketCache {
public void removeTicketFromCache(final String serviceTicket) {
cache.evict(serviceTicket);
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/StatelessTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/StatelessTicketCache.java
index 7c848f19a4..b17fd05ae0 100644
--- a/cas/src/main/java/org/springframework/security/cas/authentication/StatelessTicketCache.java
+++ b/cas/src/main/java/org/springframework/security/cas/authentication/StatelessTicketCache.java
@@ -59,6 +59,7 @@ package org.springframework.security.cas.authentication;
* @author Ben Alex
*/
public interface StatelessTicketCache {
+
// ~ Methods ================================================================
/**
@@ -68,7 +69,6 @@ public interface StatelessTicketCache {
*
* If not found, returns a nullCasAuthenticationToken.
*
- *
* @return the fully populated authentication token
*/
CasAuthenticationToken getByTicketId(String serviceTicket);
@@ -80,7 +80,6 @@ public interface StatelessTicketCache {
* The {@link CasAuthenticationToken#getCredentials()} method is used to retrieve the
* service ticket number.
*
- *
* @param token to be added to the cache
*/
void putTicketInCache(CasAuthenticationToken token);
@@ -91,10 +90,9 @@ public interface StatelessTicketCache {
*
*
* Implementations should use {@link CasAuthenticationToken#getCredentials()} to
- * obtain the ticket and then delegate to the
- * {@link #removeTicketFromCache(String)} method.
+ * obtain the ticket and then delegate to the {@link #removeTicketFromCache(String)}
+ * method.
*
- *
* @param token to be removed
*/
void removeTicketFromCache(CasAuthenticationToken token);
@@ -107,8 +105,8 @@ public interface StatelessTicketCache {
* This is in case applications wish to provide a session termination capability for
* their stateless clients.
*
- *
* @param serviceTicket to be removed
*/
void removeTicketFromCache(String serviceTicket);
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/package-info.java b/cas/src/main/java/org/springframework/security/cas/authentication/package-info.java
index 240f124bb9..c951b0f08b 100644
--- a/cas/src/main/java/org/springframework/security/cas/authentication/package-info.java
+++ b/cas/src/main/java/org/springframework/security/cas/authentication/package-info.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
/**
- * An {@code AuthenticationProvider} that can process CAS service tickets and proxy tickets.
+ * An {@code AuthenticationProvider} that can process CAS service tickets and proxy
+ * tickets.
*/
package org.springframework.security.cas.authentication;
-
diff --git a/cas/src/main/java/org/springframework/security/cas/jackson2/AssertionImplMixin.java b/cas/src/main/java/org/springframework/security/cas/jackson2/AssertionImplMixin.java
index 3085f92d95..ae16b228c0 100644
--- a/cas/src/main/java/org/springframework/security/cas/jackson2/AssertionImplMixin.java
+++ b/cas/src/main/java/org/springframework/security/cas/jackson2/AssertionImplMixin.java
@@ -23,31 +23,32 @@ import java.util.Date;
import java.util.Map;
/**
- * Helps in jackson deserialization of class {@link org.jasig.cas.client.validation.AssertionImpl}, which is
- * used with {@link org.springframework.security.cas.authentication.CasAuthenticationToken}.
- * To use this class we need to register with {@link com.fasterxml.jackson.databind.ObjectMapper}. Type information
- * will be stored in @class property.
+ * Helps in jackson deserialization of class
+ * {@link org.jasig.cas.client.validation.AssertionImpl}, which is used with
+ * {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. To use
+ * this class we need to register with
+ * {@link com.fasterxml.jackson.databind.ObjectMapper}. Type information will be stored
+ * in @class property.
*
*
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
*
*
- *
* @author Jitendra Singh
* @see CasJackson2Module
* @see org.springframework.security.jackson2.SecurityJackson2Modules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
-@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY,
- getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
+@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
+ isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
class AssertionImplMixin {
/**
- * Mixin Constructor helps in deserialize {@link org.jasig.cas.client.validation.AssertionImpl}
- *
+ * Mixin Constructor helps in deserialize
+ * {@link org.jasig.cas.client.validation.AssertionImpl}
* @param principal the Principal to associate with the Assertion.
* @param validFromDate when the assertion is valid from.
* @param validUntilDate when the assertion is valid to.
@@ -56,7 +57,9 @@ class AssertionImplMixin {
*/
@JsonCreator
AssertionImplMixin(@JsonProperty("principal") AttributePrincipal principal,
- @JsonProperty("validFromDate") Date validFromDate, @JsonProperty("validUntilDate") Date validUntilDate,
- @JsonProperty("authenticationDate") Date authenticationDate, @JsonProperty("attributes") Map attributes){
+ @JsonProperty("validFromDate") Date validFromDate, @JsonProperty("validUntilDate") Date validUntilDate,
+ @JsonProperty("authenticationDate") Date authenticationDate,
+ @JsonProperty("attributes") Map attributes) {
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/jackson2/AttributePrincipalImplMixin.java b/cas/src/main/java/org/springframework/security/cas/jackson2/AttributePrincipalImplMixin.java
index ddc326704f..ca4e28d805 100644
--- a/cas/src/main/java/org/springframework/security/cas/jackson2/AttributePrincipalImplMixin.java
+++ b/cas/src/main/java/org/springframework/security/cas/jackson2/AttributePrincipalImplMixin.java
@@ -22,9 +22,10 @@ import org.jasig.cas.client.proxy.ProxyRetriever;
import java.util.Map;
/**
- * Helps in deserialize {@link org.jasig.cas.client.authentication.AttributePrincipalImpl} which is used with
- * {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. Type information will be stored
- * in property named @class.
+ * Helps in deserialize {@link org.jasig.cas.client.authentication.AttributePrincipalImpl}
+ * which is used with
+ * {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. Type
+ * information will be stored in property named @class.
*
*
* ObjectMapper mapper = new ObjectMapper();
@@ -43,16 +44,19 @@ import java.util.Map;
class AttributePrincipalImplMixin {
/**
- * Mixin Constructor helps in deserialize {@link org.jasig.cas.client.authentication.AttributePrincipalImpl}
- *
+ * Mixin Constructor helps in deserialize
+ * {@link org.jasig.cas.client.authentication.AttributePrincipalImpl}
* @param name the unique identifier for the principal.
* @param attributes the key/value pairs for this principal.
* @param proxyGrantingTicket the ticket associated with this principal.
- * @param proxyRetriever the ProxyRetriever implementation to call back to the CAS server.
+ * @param proxyRetriever the ProxyRetriever implementation to call back to the CAS
+ * server.
*/
@JsonCreator
- AttributePrincipalImplMixin(@JsonProperty("name") String name, @JsonProperty("attributes") Map attributes,
- @JsonProperty("proxyGrantingTicket") String proxyGrantingTicket,
- @JsonProperty("proxyRetriever") ProxyRetriever proxyRetriever) {
+ AttributePrincipalImplMixin(@JsonProperty("name") String name,
+ @JsonProperty("attributes") Map attributes,
+ @JsonProperty("proxyGrantingTicket") String proxyGrantingTicket,
+ @JsonProperty("proxyRetriever") ProxyRetriever proxyRetriever) {
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixin.java b/cas/src/main/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixin.java
index dba9e0521e..bf7dacde49 100644
--- a/cas/src/main/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixin.java
+++ b/cas/src/main/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixin.java
@@ -26,11 +26,12 @@ import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
/**
- * Mixin class which helps in deserialize {@link org.springframework.security.cas.authentication.CasAuthenticationToken}
- * using jackson. Two more dependent classes needs to register along with this mixin class.
+ * Mixin class which helps in deserialize
+ * {@link org.springframework.security.cas.authentication.CasAuthenticationToken} using
+ * jackson. Two more dependent classes needs to register along with this mixin class.
*
- *
@@ -53,7 +54,6 @@ class CasAuthenticationTokenMixin {
/**
* Mixin Constructor helps in deserialize {@link CasAuthenticationToken}
- *
* @param keyHash hashCode of provided key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be null)
@@ -70,8 +70,9 @@ class CasAuthenticationTokenMixin {
*/
@JsonCreator
CasAuthenticationTokenMixin(@JsonProperty("keyHash") Integer keyHash, @JsonProperty("principal") Object principal,
- @JsonProperty("credentials") Object credentials,
- @JsonProperty("authorities") Collection extends GrantedAuthority> authorities,
- @JsonProperty("userDetails") UserDetails userDetails, @JsonProperty("assertion") Assertion assertion) {
+ @JsonProperty("credentials") Object credentials,
+ @JsonProperty("authorities") Collection extends GrantedAuthority> authorities,
+ @JsonProperty("userDetails") UserDetails userDetails, @JsonProperty("assertion") Assertion assertion) {
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/jackson2/CasJackson2Module.java b/cas/src/main/java/org/springframework/security/cas/jackson2/CasJackson2Module.java
index 5d2e99370d..2042e967fa 100644
--- a/cas/src/main/java/org/springframework/security/cas/jackson2/CasJackson2Module.java
+++ b/cas/src/main/java/org/springframework/security/cas/jackson2/CasJackson2Module.java
@@ -24,16 +24,17 @@ import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.jackson2.SecurityJackson2Modules;
/**
- * Jackson module for spring-security-cas. This module register {@link AssertionImplMixin},
- * {@link AttributePrincipalImplMixin} and {@link CasAuthenticationTokenMixin}. If no default typing enabled by default then
- * it'll enable it because typing info is needed to properly serialize/deserialize objects. In order to use this module just
- * add this module into your ObjectMapper configuration.
+ * Jackson module for spring-security-cas. This module register
+ * {@link AssertionImplMixin}, {@link AttributePrincipalImplMixin} and
+ * {@link CasAuthenticationTokenMixin}. If no default typing enabled by default then it'll
+ * enable it because typing info is needed to properly serialize/deserialize objects. In
+ * order to use this module just add this module into your ObjectMapper configuration.
*
*
- * Note: use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get list of all security modules on the classpath.
+ *
Note: use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get list
+ * of all security modules on the classpath.
*
* @author Jitendra Singh.
* @see org.springframework.security.jackson2.SecurityJackson2Modules
@@ -52,4 +53,5 @@ public class CasJackson2Module extends SimpleModule {
context.setMixInAnnotations(AttributePrincipalImpl.class, AttributePrincipalImplMixin.class);
context.setMixInAnnotations(CasAuthenticationToken.class, CasAuthenticationTokenMixin.class);
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/package-info.java b/cas/src/main/java/org/springframework/security/cas/package-info.java
index 8ce8a88b5a..87b0b093f8 100644
--- a/cas/src/main/java/org/springframework/security/cas/package-info.java
+++ b/cas/src/main/java/org/springframework/security/cas/package-info.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
/**
- * Spring Security support for Jasig's Central Authentication Service (CAS).
+ * Spring Security support for Jasig's Central Authentication Service
+ * (CAS).
*/
package org.springframework.security.cas;
-
diff --git a/cas/src/main/java/org/springframework/security/cas/userdetails/AbstractCasAssertionUserDetailsService.java b/cas/src/main/java/org/springframework/security/cas/userdetails/AbstractCasAssertionUserDetailsService.java
index bb4770eb05..235c5fadfd 100644
--- a/cas/src/main/java/org/springframework/security/cas/userdetails/AbstractCasAssertionUserDetailsService.java
+++ b/cas/src/main/java/org/springframework/security/cas/userdetails/AbstractCasAssertionUserDetailsService.java
@@ -28,8 +28,8 @@ import org.springframework.security.core.userdetails.UserDetails;
* @author Scott Battaglia
* @since 3.0
*/
-public abstract class AbstractCasAssertionUserDetailsService implements
- AuthenticationUserDetailsService {
+public abstract class AbstractCasAssertionUserDetailsService
+ implements AuthenticationUserDetailsService {
public final UserDetails loadUserDetails(final CasAssertionAuthenticationToken token) {
return loadUserDetails(token.getAssertion());
@@ -39,10 +39,10 @@ public abstract class AbstractCasAssertionUserDetailsService implements
* Protected template method for construct a
* {@link org.springframework.security.core.userdetails.UserDetails} via the supplied
* CAS assertion.
- *
* @param assertion the assertion to use to construct the new UserDetails. CANNOT be
* NULL.
* @return the newly constructed UserDetails.
*/
protected abstract UserDetails loadUserDetails(Assertion assertion);
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsService.java b/cas/src/main/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsService.java
index 93f03eeabe..d160a6c091 100644
--- a/cas/src/main/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsService.java
+++ b/cas/src/main/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsService.java
@@ -34,8 +34,8 @@ import java.util.ArrayList;
* @author Scott Battaglia
* @since 3.0
*/
-public final class GrantedAuthorityFromAssertionAttributesUserDetailsService extends
- AbstractCasAssertionUserDetailsService {
+public final class GrantedAuthorityFromAssertionAttributesUserDetailsService
+ extends AbstractCasAssertionUserDetailsService {
private static final String NON_EXISTENT_PASSWORD_VALUE = "NO_PASSWORD";
@@ -43,11 +43,9 @@ public final class GrantedAuthorityFromAssertionAttributesUserDetailsService ext
private boolean convertToUpperCase = true;
- public GrantedAuthorityFromAssertionAttributesUserDetailsService(
- final String[] attributes) {
+ public GrantedAuthorityFromAssertionAttributesUserDetailsService(final String[] attributes) {
Assert.notNull(attributes, "attributes cannot be null.");
- Assert.isTrue(attributes.length > 0,
- "At least one attribute is required to retrieve roles from.");
+ Assert.isTrue(attributes.length > 0, "At least one attribute is required to retrieve roles from.");
this.attributes = attributes;
}
@@ -68,29 +66,27 @@ public final class GrantedAuthorityFromAssertionAttributesUserDetailsService ext
for (final Object o : list) {
grantedAuthorities.add(new SimpleGrantedAuthority(
- this.convertToUpperCase ? o.toString().toUpperCase() : o
- .toString()));
+ this.convertToUpperCase ? o.toString().toUpperCase() : o.toString()));
}
}
else {
grantedAuthorities.add(new SimpleGrantedAuthority(
- this.convertToUpperCase ? value.toString().toUpperCase() : value
- .toString()));
+ this.convertToUpperCase ? value.toString().toUpperCase() : value.toString()));
}
}
- return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE,
- true, true, true, true, grantedAuthorities);
+ return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true,
+ grantedAuthorities);
}
/**
* Converts the returned attribute values to uppercase values.
- *
* @param convertToUpperCase true if it should convert, false otherwise.
*/
public void setConvertToUpperCase(final boolean convertToUpperCase) {
this.convertToUpperCase = convertToUpperCase;
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java
index 9742fde7d5..4e8d8a63f3 100644
--- a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java
+++ b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java
@@ -42,8 +42,8 @@ import org.springframework.util.Assert;
* @author Ben Alex
* @author Scott Battaglia
*/
-public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint,
- InitializingBean {
+public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean {
+
// ~ Instance fields
// ================================================================================================
private ServiceProperties serviceProperties;
@@ -67,12 +67,10 @@ public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint,
public void afterPropertiesSet() {
Assert.hasLength(this.loginUrl, "loginUrl must be specified");
Assert.notNull(this.serviceProperties, "serviceProperties must be specified");
- Assert.notNull(this.serviceProperties.getService(),
- "serviceProperties.getService() cannot be null.");
+ Assert.notNull(this.serviceProperties.getService(), "serviceProperties.getService() cannot be null.");
}
- public final void commence(final HttpServletRequest servletRequest,
- final HttpServletResponse response,
+ public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response,
final AuthenticationException authenticationException) throws IOException {
final String urlEncodedService = createServiceUrl(servletRequest, response);
@@ -90,42 +88,34 @@ public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint,
* @param response the HttpServlet Response
* @return the constructed service url. CANNOT be NULL.
*/
- protected String createServiceUrl(final HttpServletRequest request,
- final HttpServletResponse response) {
- return CommonUtils.constructServiceUrl(null, response,
- this.serviceProperties.getService(), null,
- this.serviceProperties.getArtifactParameter(),
- this.encodeServiceUrlWithSessionId);
+ protected String createServiceUrl(final HttpServletRequest request, final HttpServletResponse response) {
+ return CommonUtils.constructServiceUrl(null, response, this.serviceProperties.getService(), null,
+ this.serviceProperties.getArtifactParameter(), this.encodeServiceUrlWithSessionId);
}
/**
* Constructs the Url for Redirection to the CAS server. Default implementation relies
* on the CAS client to do the bulk of the work.
- *
* @param serviceUrl the service url that should be included.
* @return the redirect url. CANNOT be NULL.
*/
protected String createRedirectUrl(final String serviceUrl) {
- return CommonUtils.constructRedirectUrl(this.loginUrl,
- this.serviceProperties.getServiceParameter(), serviceUrl,
+ return CommonUtils.constructRedirectUrl(this.loginUrl, this.serviceProperties.getServiceParameter(), serviceUrl,
this.serviceProperties.isSendRenew(), false);
}
/**
* Template method for you to do your own pre-processing before the redirect occurs.
- *
* @param request the HttpServletRequest
* @param response the HttpServletResponse
*/
- protected void preCommence(final HttpServletRequest request,
- final HttpServletResponse response) {
+ protected void preCommence(final HttpServletRequest request, final HttpServletResponse response) {
}
/**
* The enterprise-wide CAS login URL. Usually something like
* https://www.mycompany.com/cas/login.
- *
* @return the enterprise-wide CAS login URL
*/
public final String getLoginUrl() {
@@ -146,12 +136,10 @@ public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint,
/**
* Sets whether to encode the service url with the session id or not.
- *
* @param encodeServiceUrlWithSessionId whether to encode the service url with the
* session id or not.
*/
- public final void setEncodeServiceUrlWithSessionId(
- final boolean encodeServiceUrlWithSessionId) {
+ public final void setEncodeServiceUrlWithSessionId(final boolean encodeServiceUrlWithSessionId) {
this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId;
}
@@ -163,4 +151,5 @@ public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint,
protected boolean getEncodeServiceUrlWithSessionId() {
return this.encodeServiceUrlWithSessionId;
}
+
}
diff --git a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java
index 7ff21e2480..e88e85b0cb 100644
--- a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java
+++ b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java
@@ -45,7 +45,8 @@ import org.springframework.util.Assert;
/**
* Processes a CAS service ticket, obtains proxy granting tickets, and processes proxy
- * tickets.
*
* @see WebSecurity
- *
* @author Rob Winch
- *
* @param The object that this builder returns
* @param The type of this builder (that is returned by the base class)
*/
public abstract class AbstractConfiguredSecurityBuilder>
extends AbstractSecurityBuilder {
+
private final Log logger = LogFactory.getLog(getClass());
private final LinkedHashMap>, List>> configurers = new LinkedHashMap<>();
+
private final List> configurersAddedInInitializing = new ArrayList<>();
private final Map, Object> sharedObjects = new HashMap<>();
@@ -70,11 +70,9 @@ public abstract class AbstractConfiguredSecurityBuilder objectPostProcessor) {
+ protected AbstractConfiguredSecurityBuilder(ObjectPostProcessor objectPostProcessor) {
this(objectPostProcessor, false);
}
@@ -82,13 +80,11 @@ public abstract class AbstractConfiguredSecurityBuilder objectPostProcessor,
+ protected AbstractConfiguredSecurityBuilder(ObjectPostProcessor objectPostProcessor,
boolean allowConfigurersOfSameType) {
Assert.notNull(objectPostProcessor, "objectPostProcessor cannot be null");
this.objectPostProcessor = objectPostProcessor;
@@ -98,7 +94,6 @@ public abstract class AbstractConfiguredSecurityBuilder> C apply(C configurer)
- throws Exception {
+ public > C apply(C configurer) throws Exception {
configurer.addObjectPostProcessor(objectPostProcessor);
configurer.setBuilder((B) this);
add(configurer);
@@ -138,7 +131,6 @@ public abstract class AbstractConfiguredSecurityBuilder> configs = allowConfigurersOfSameType ? this.configurers
- .get(clazz) : null;
+ List> configs = allowConfigurersOfSameType ? this.configurers.get(clazz) : null;
if (configs == null) {
configs = new ArrayList<>(1);
}
@@ -211,7 +198,6 @@ public abstract class AbstractConfiguredSecurityBuildernull if not
* found. Note that object hierarchies are not considered.
- *
* @param clazz
* @return the {@link SecurityConfigurer} for further customizations
*/
@@ -254,8 +238,7 @@ public abstract class AbstractConfiguredSecurityBuildernull if not found. Note that object hierarchies are not considered.
- *
* @param clazz
* @return
*/
@@ -274,8 +256,7 @@ public abstract class AbstractConfiguredSecurityBuilder= CONFIGURING.order;
}
+
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/AbstractSecurityBuilder.java b/config/src/main/java/org/springframework/security/config/annotation/AbstractSecurityBuilder.java
index 2f4c4022fe..afaeebd92a 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/AbstractSecurityBuilder.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/AbstractSecurityBuilder.java
@@ -22,11 +22,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
* time.
*
* @param the type of Object that is being built
- *
* @author Rob Winch
*
*/
public abstract class AbstractSecurityBuilder implements SecurityBuilder {
+
private AtomicBoolean building = new AtomicBoolean();
private O object;
@@ -47,7 +47,6 @@ public abstract class AbstractSecurityBuilder implements SecurityBuilder {
/**
* Gets the object that was built. If it has not been built yet an Exception is
* thrown.
- *
* @return the Object that was built
*/
public final O getObject() {
@@ -59,10 +58,9 @@ public abstract class AbstractSecurityBuilder implements SecurityBuilder {
/**
* Subclasses should implement this to perform the build.
- *
* @return the object that should be returned by {@link #build()}.
- *
* @throws Exception if an error occurs
*/
protected abstract O doBuild() throws Exception;
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/AlreadyBuiltException.java b/config/src/main/java/org/springframework/security/config/annotation/AlreadyBuiltException.java
index b84bbff45e..b50484c4ea 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/AlreadyBuiltException.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/AlreadyBuiltException.java
@@ -28,4 +28,5 @@ public class AlreadyBuiltException extends IllegalStateException {
}
private static final long serialVersionUID = -5891004752785553015L;
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/ObjectPostProcessor.java b/config/src/main/java/org/springframework/security/config/annotation/ObjectPostProcessor.java
index ca07992749..4218081cdb 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/ObjectPostProcessor.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/ObjectPostProcessor.java
@@ -25,7 +25,6 @@ import org.springframework.beans.factory.InitializingBean;
* {@link DisposableBean#destroy()} has been invoked.
*
* @param the bound of the types of Objects this {@link ObjectPostProcessor} supports.
- *
* @author Rob Winch
* @since 3.2
*/
@@ -34,9 +33,9 @@ public interface ObjectPostProcessor {
/**
* Initialize the object possibly returning a modified instance that should be used
* instead.
- *
* @param object the object to initialize
* @return the initialized version of the object
*/
O postProcess(O object);
+
}
\ No newline at end of file
diff --git a/config/src/main/java/org/springframework/security/config/annotation/SecurityBuilder.java b/config/src/main/java/org/springframework/security/config/annotation/SecurityBuilder.java
index 1f097537c0..3340250675 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/SecurityBuilder.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/SecurityBuilder.java
@@ -20,16 +20,15 @@ package org.springframework.security.config.annotation;
*
* @author Rob Winch
* @since 3.2
- *
* @param The type of the Object being built
*/
public interface SecurityBuilder {
/**
* Builds the object and returns it or null.
- *
* @return the Object to be built or null if the implementation allows it.
* @throws Exception if an error occurred when building the Object
*/
O build() throws Exception;
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/SecurityConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/SecurityConfigurer.java
index 4ddba28274..13564216ea 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/SecurityConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/SecurityConfigurer.java
@@ -22,20 +22,18 @@ package org.springframework.security.config.annotation;
* {@link #configure(SecurityBuilder)} method is invoked.
*
* @see AbstractConfiguredSecurityBuilder
- *
* @author Rob Winch
- *
* @param The object being built by the {@link SecurityBuilder} B
* @param The {@link SecurityBuilder} that builds objects of type O. This is also the
* {@link SecurityBuilder} that is being configured.
*/
public interface SecurityConfigurer> {
+
/**
* Initialize the {@link SecurityBuilder}. Here only shared state should be created
* and modified, but not properties on the {@link SecurityBuilder} used for building
* the object. This ensures that the {@link #configure(SecurityBuilder)} method uses
* the correct shared objects when building. Configurers should be applied here.
- *
* @param builder
* @throws Exception
*/
@@ -44,9 +42,9 @@ public interface SecurityConfigurer> {
/**
* Configure the {@link SecurityBuilder} by setting the necessary properties on the
* {@link SecurityBuilder}.
- *
* @param builder
* @throws Exception
*/
void configure(B builder) throws Exception;
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/SecurityConfigurerAdapter.java b/config/src/main/java/org/springframework/security/config/annotation/SecurityConfigurerAdapter.java
index d5ca809c64..87e0876002 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/SecurityConfigurerAdapter.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/SecurityConfigurerAdapter.java
@@ -29,13 +29,12 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator;
*
* @author Rob Winch
* @author Wallace Wadge
- *
* @param The Object being built by B
* @param The Builder that is building O and is configured by
* {@link SecurityConfigurerAdapter}
*/
-public abstract class SecurityConfigurerAdapter>
- implements SecurityConfigurer {
+public abstract class SecurityConfigurerAdapter> implements SecurityConfigurer {
+
private B securityBuilder;
private CompositeObjectPostProcessor objectPostProcessor = new CompositeObjectPostProcessor();
@@ -49,7 +48,6 @@ public abstract class SecurityConfigurerAdapter>
/**
* Return the {@link SecurityBuilder} when done using the {@link SecurityConfigurer}.
* This is useful for method chaining.
- *
* @return the {@link SecurityBuilder} for further customizations
*/
public B and() {
@@ -58,7 +56,6 @@ public abstract class SecurityConfigurerAdapter>
/**
* Gets the {@link SecurityBuilder}. Cannot be null.
- *
* @return the {@link SecurityBuilder}
* @throws IllegalStateException if {@link SecurityBuilder} is null
*/
@@ -72,7 +69,6 @@ public abstract class SecurityConfigurerAdapter>
/**
* Performs post processing of an object. The default is to delegate to the
* {@link ObjectPostProcessor}.
- *
* @param object the Object to post process
* @return the possibly modified Object to use
*/
@@ -85,7 +81,6 @@ public abstract class SecurityConfigurerAdapter>
* Adds an {@link ObjectPostProcessor} to be used for this
* {@link SecurityConfigurerAdapter}. The default implementation does nothing to the
* object.
- *
* @param objectPostProcessor the {@link ObjectPostProcessor} to use
*/
public void addObjectPostProcessor(ObjectPostProcessor> objectPostProcessor) {
@@ -95,7 +90,6 @@ public abstract class SecurityConfigurerAdapter>
/**
* Sets the {@link SecurityBuilder} to be used. This is automatically set when using
* {@link AbstractConfiguredSecurityBuilder#apply(SecurityConfigurerAdapter)}
- *
* @param builder the {@link SecurityBuilder} to set
*/
public void setBuilder(B builder) {
@@ -108,16 +102,15 @@ public abstract class SecurityConfigurerAdapter>
*
* @author Rob Winch
*/
- private static final class CompositeObjectPostProcessor implements
- ObjectPostProcessor {
+ private static final class CompositeObjectPostProcessor implements ObjectPostProcessor {
+
private List> postProcessors = new ArrayList<>();
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object postProcess(Object object) {
for (ObjectPostProcessor opp : postProcessors) {
Class> oppClass = opp.getClass();
- Class> oppType = GenericTypeResolver.resolveTypeArgument(oppClass,
- ObjectPostProcessor.class);
+ Class> oppType = GenericTypeResolver.resolveTypeArgument(oppClass, ObjectPostProcessor.class);
if (oppType == null || oppType.isAssignableFrom(object.getClass())) {
object = opp.postProcess(object);
}
@@ -130,11 +123,12 @@ public abstract class SecurityConfigurerAdapter>
* @param objectPostProcessor the {@link ObjectPostProcessor} to add
* @return true if the {@link ObjectPostProcessor} was added, else false
*/
- private boolean addObjectPostProcessor(
- ObjectPostProcessor> objectPostProcessor) {
+ private boolean addObjectPostProcessor(ObjectPostProcessor> objectPostProcessor) {
boolean result = this.postProcessors.add(objectPostProcessor);
postProcessors.sort(AnnotationAwareOrderComparator.INSTANCE);
return result;
}
+
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/authentication/ProviderManagerBuilder.java b/config/src/main/java/org/springframework/security/config/annotation/authentication/ProviderManagerBuilder.java
index aab2e9eab6..6240d764c0 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/authentication/ProviderManagerBuilder.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/authentication/ProviderManagerBuilder.java
@@ -24,11 +24,10 @@ import org.springframework.security.config.annotation.SecurityBuilder;
* Interface for operating on a SecurityBuilder that creates a {@link ProviderManager}
*
* @author Rob Winch
- *
* @param the type of the {@link SecurityBuilder}
*/
-public interface ProviderManagerBuilder> extends
- SecurityBuilder {
+public interface ProviderManagerBuilder>
+ extends SecurityBuilder {
/**
* Add authentication based upon the custom {@link AuthenticationProvider} that is
@@ -36,10 +35,11 @@ public interface ProviderManagerBuilder> ext
* customizations must be done externally and the {@link ProviderManagerBuilder} is
* returned immediately.
*
- * Note that an Exception is thrown if an error occurs when adding the {@link AuthenticationProvider}.
- *
+ * Note that an Exception is thrown if an error occurs when adding the
+ * {@link AuthenticationProvider}.
* @return a {@link ProviderManagerBuilder} to allow further authentication to be
* provided to the {@link ProviderManagerBuilder}
*/
B authenticationProvider(AuthenticationProvider authenticationProvider);
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/authentication/builders/AuthenticationManagerBuilder.java b/config/src/main/java/org/springframework/security/config/annotation/authentication/builders/AuthenticationManagerBuilder.java
index 36b4a97a28..3052cfa2c7 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/authentication/builders/AuthenticationManagerBuilder.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/authentication/builders/AuthenticationManagerBuilder.java
@@ -48,15 +48,19 @@ import org.springframework.util.Assert;
* @since 3.2
*/
public class AuthenticationManagerBuilder
- extends
- AbstractConfiguredSecurityBuilder
+ extends AbstractConfiguredSecurityBuilder
implements ProviderManagerBuilder {
+
private final Log logger = LogFactory.getLog(getClass());
private AuthenticationManager parentAuthenticationManager;
+
private List authenticationProviders = new ArrayList<>();
+
private UserDetailsService defaultUserDetailsService;
+
private Boolean eraseCredentials;
+
private AuthenticationEventPublisher eventPublisher;
/**
@@ -71,18 +75,15 @@ public class AuthenticationManagerBuilder
* Allows providing a parent {@link AuthenticationManager} that will be tried if this
* {@link AuthenticationManager} was unable to attempt to authenticate the provided
* {@link Authentication}.
- *
* @param authenticationManager the {@link AuthenticationManager} that should be used
* if the current {@link AuthenticationManager} was unable to attempt to authenticate
* the provided {@link Authentication}.
* @return the {@link AuthenticationManagerBuilder} for further adding types of
* authentication
*/
- public AuthenticationManagerBuilder parentAuthenticationManager(
- AuthenticationManager authenticationManager) {
+ public AuthenticationManagerBuilder parentAuthenticationManager(AuthenticationManager authenticationManager) {
if (authenticationManager instanceof ProviderManager) {
- eraseCredentials(((ProviderManager) authenticationManager)
- .isEraseCredentialsAfterAuthentication());
+ eraseCredentials(((ProviderManager) authenticationManager).isEraseCredentialsAfterAuthentication());
}
this.parentAuthenticationManager = authenticationManager;
return this;
@@ -90,20 +91,16 @@ public class AuthenticationManagerBuilder
/**
* Sets the {@link AuthenticationEventPublisher}
- *
* @param eventPublisher the {@link AuthenticationEventPublisher} to use
* @return the {@link AuthenticationManagerBuilder} for further customizations
*/
- public AuthenticationManagerBuilder authenticationEventPublisher(
- AuthenticationEventPublisher eventPublisher) {
+ public AuthenticationManagerBuilder authenticationEventPublisher(AuthenticationEventPublisher eventPublisher) {
Assert.notNull(eventPublisher, "AuthenticationEventPublisher cannot be null");
this.eventPublisher = eventPublisher;
return this;
}
/**
- *
- *
* @param eraseCredentials true if {@link AuthenticationManager} should clear the
* credentials from the {@link Authentication} object after authenticating
* @return the {@link AuthenticationManagerBuilder} for further customizations
@@ -124,7 +121,6 @@ public class AuthenticationManagerBuilder
* {@link UserDetailsService}'s may override this {@link UserDetailsService} as the
* default.
*
- *
* @return a {@link InMemoryUserDetailsManagerConfigurer} to allow customization of
* the in memory authentication
* @throws Exception if an error occurs when adding the in memory authentication
@@ -141,8 +137,8 @@ public class AuthenticationManagerBuilder
*
*
* When using with a persistent data store, it is best to add users external of
- * configuration using something like Flyway or Liquibase to create the schema and adding
+ * configuration using something like Flyway or
+ * Liquibase to create the schema and adding
* users to ensure these steps are only done once and that the optimal SQL is used.
*
*
@@ -154,13 +150,11 @@ public class AuthenticationManagerBuilder
* "https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#user-schema"
* >User Schema section of the reference for the default schema.
*
- *
* @return a {@link JdbcUserDetailsManagerConfigurer} to allow customization of the
* JDBC authentication
* @throws Exception if an error occurs when adding the JDBC authentication
*/
- public JdbcUserDetailsManagerConfigurer jdbcAuthentication()
- throws Exception {
+ public JdbcUserDetailsManagerConfigurer jdbcAuthentication() throws Exception {
return apply(new JdbcUserDetailsManagerConfigurer<>());
}
@@ -175,7 +169,6 @@ public class AuthenticationManagerBuilder
* {@link UserDetailsService}'s may override this {@link UserDetailsService} as the
* default.
*
- *
* @return a {@link DaoAuthenticationConfigurer} to allow customization of the DAO
* authentication
* @throws Exception if an error occurs when adding the {@link UserDetailsService}
@@ -184,8 +177,7 @@ public class AuthenticationManagerBuilder
public DaoAuthenticationConfigurer userDetailsService(
T userDetailsService) throws Exception {
this.defaultUserDetailsService = userDetailsService;
- return apply(new DaoAuthenticationConfigurer<>(
- userDetailsService));
+ return apply(new DaoAuthenticationConfigurer<>(userDetailsService));
}
/**
@@ -196,13 +188,11 @@ public class AuthenticationManagerBuilder
*
- *
* @param roles the roles for this user (i.e. USER, ADMIN, etc). Cannot be null,
* contain null values or start with "ROLE_"
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
@@ -187,7 +180,6 @@ public class UserDetailsManagerConfigurer, C
/**
* Populates the authorities. This attribute is required.
- *
* @param authorities the authorities for this user. Cannot be null, or contain
* null values
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
@@ -201,7 +193,6 @@ public class UserDetailsManagerConfigurer, C
/**
* Populates the authorities. This attribute is required.
- *
* @param authorities the authorities for this user. Cannot be null, or contain
* null values
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
@@ -215,7 +206,6 @@ public class UserDetailsManagerConfigurer, C
/**
* Populates the authorities. This attribute is required.
- *
* @param authorities the authorities for this user (i.e. ROLE_USER, ROLE_ADMIN,
* etc). Cannot be null, or contain null values
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
@@ -229,7 +219,6 @@ public class UserDetailsManagerConfigurer, C
/**
* Defines if the account is expired or not. Default is false.
- *
* @param accountExpired true if the account is expired, false otherwise
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
* additional attributes for this user)
@@ -241,7 +230,6 @@ public class UserDetailsManagerConfigurer, C
/**
* Defines if the account is locked or not. Default is false.
- *
* @param accountLocked true if the account is locked, false otherwise
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
* additional attributes for this user)
@@ -253,7 +241,6 @@ public class UserDetailsManagerConfigurer, C
/**
* Defines if the credentials are expired or not. Default is false.
- *
* @param credentialsExpired true if the credentials are expired, false otherwise
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
* additional attributes for this user)
@@ -265,7 +252,6 @@ public class UserDetailsManagerConfigurer, C
/**
* Defines if the account is disabled or not. Default is false.
- *
* @param disabled true if the account is disabled, false otherwise
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
* additional attributes for this user)
@@ -278,5 +264,7 @@ public class UserDetailsManagerConfigurer, C
UserDetails build() {
return this.user.build();
}
+
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/userdetails/AbstractDaoAuthenticationConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/userdetails/AbstractDaoAuthenticationConfigurer.java
index 0cf004160f..ebc2fa8e36 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/userdetails/AbstractDaoAuthenticationConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/userdetails/AbstractDaoAuthenticationConfigurer.java
@@ -28,7 +28,6 @@ import org.springframework.security.core.userdetails.UserDetailsPasswordService;
*
* @author Rob Winch
* @since 3.2
- *
* @param the type of the {@link SecurityBuilder}
* @param the type of {@link AbstractDaoAuthenticationConfigurer} this is
* @param The type of {@link UserDetailsService} that is being used
@@ -36,12 +35,13 @@ import org.springframework.security.core.userdetails.UserDetailsPasswordService;
*/
abstract class AbstractDaoAuthenticationConfigurer, C extends AbstractDaoAuthenticationConfigurer, U extends UserDetailsService>
extends UserDetailsAwareConfigurer {
+
private DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
+
private final U userDetailsService;
/**
* Creates a new instance
- *
* @param userDetailsService
*/
protected AbstractDaoAuthenticationConfigurer(U userDetailsService) {
@@ -54,7 +54,6 @@ abstract class AbstractDaoAuthenticationConfigurer The type of {@link ProviderManagerBuilder} this is
* @param The type of {@link UserDetailsService} that is being used
*
*/
public class DaoAuthenticationConfigurer, U extends UserDetailsService>
- extends
- AbstractDaoAuthenticationConfigurer, U> {
+ extends AbstractDaoAuthenticationConfigurer, U> {
/**
* Creates a new instance
@@ -40,4 +38,5 @@ public class DaoAuthenticationConfigurer, U
public DaoAuthenticationConfigurer(U userDetailsService) {
super(userDetailsService);
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/userdetails/UserDetailsAwareConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/userdetails/UserDetailsAwareConfigurer.java
index 7ba27523ec..ee2dc6eac4 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/userdetails/UserDetailsAwareConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/userdetails/UserDetailsAwareConfigurer.java
@@ -26,7 +26,6 @@ import org.springframework.security.core.userdetails.UserDetailsService;
* value with {@link AuthenticationManagerBuilder}.
*
* @author Rob Winch
- *
* @param the type of the {@link ProviderManagerBuilder}
* @param the type of {@link UserDetailsService}
*/
@@ -38,4 +37,5 @@ public abstract class UserDetailsAwareConfigurer the type of the {@link ProviderManagerBuilder}
* @param the {@link UserDetailsServiceConfigurer} (or this)
* @param the type of UserDetailsService being used to allow for returning the
@@ -55,4 +54,5 @@ public class UserDetailsServiceConfigurer, C
*/
protected void initUserDetailsService() throws Exception {
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessor.java b/config/src/main/java/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessor.java
index 813e05684c..5844af0506 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessor.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessor.java
@@ -39,13 +39,16 @@ import org.springframework.util.Assert;
*/
final class AutowireBeanFactoryObjectPostProcessor
implements ObjectPostProcessor, DisposableBean, SmartInitializingSingleton {
+
private final Log logger = LogFactory.getLog(getClass());
+
private final AutowireCapableBeanFactory autowireBeanFactory;
+
private final List disposableBeans = new ArrayList<>();
+
private final List smartSingletons = new ArrayList<>();
- AutowireBeanFactoryObjectPostProcessor(
- AutowireCapableBeanFactory autowireBeanFactory) {
+ AutowireBeanFactoryObjectPostProcessor(AutowireCapableBeanFactory autowireBeanFactory) {
Assert.notNull(autowireBeanFactory, "autowireBeanFactory cannot be null");
this.autowireBeanFactory = autowireBeanFactory;
}
@@ -64,13 +67,11 @@ final class AutowireBeanFactoryObjectPostProcessor
}
T result = null;
try {
- result = (T) this.autowireBeanFactory.initializeBean(object,
- object.toString());
+ result = (T) this.autowireBeanFactory.initializeBean(object, object.toString());
}
catch (RuntimeException e) {
Class> type = object.getClass();
- throw new RuntimeException(
- "Could not postProcess " + object + " of type " + type, e);
+ throw new RuntimeException("Could not postProcess " + object + " of type " + type, e);
}
this.autowireBeanFactory.autowireBean(object);
if (result instanceof DisposableBean) {
@@ -82,8 +83,11 @@ final class AutowireBeanFactoryObjectPostProcessor
return result;
}
- /* (non-Javadoc)
- * @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.springframework.beans.factory.SmartInitializingSingleton#
+ * afterSingletonsInstantiated()
*/
@Override
public void afterSingletonsInstantiated() {
diff --git a/config/src/main/java/org/springframework/security/config/annotation/configuration/ObjectPostProcessorConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/configuration/ObjectPostProcessorConfiguration.java
index 3c61557c4c..3dcaa846b4 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/configuration/ObjectPostProcessorConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/configuration/ObjectPostProcessorConfiguration.java
@@ -31,7 +31,6 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
*
* @see EnableWebSecurity
* @see EnableGlobalMethodSecurity
- *
* @author Rob Winch
* @since 3.2
*/
@@ -41,8 +40,8 @@ public class ObjectPostProcessorConfiguration {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
- public ObjectPostProcessor objectPostProcessor(
- AutowireCapableBeanFactory beanFactory) {
+ public ObjectPostProcessor objectPostProcessor(AutowireCapableBeanFactory beanFactory) {
return new AutowireBeanFactoryObjectPostProcessor(beanFactory);
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableGlobalMethodSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableGlobalMethodSecurity.java
index 7c1fbc49d0..61d4f33609 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableGlobalMethodSecurity.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableGlobalMethodSecurity.java
@@ -28,8 +28,8 @@ import org.springframework.security.config.annotation.authentication.configurati
/**
*
- * Enables Spring Security global method security similar to the <global-method-security>
- * xml support.
+ * Enables Spring Security global method security similar to the
+ * <global-method-security> xml support.
*
*
* More advanced configurations may wish to extend
@@ -82,7 +82,6 @@ public @interface EnableGlobalMethodSecurity {
* annotation will be upgraded to subclass proxying at the same time. This approach
* has no negative impact in practice unless one is explicitly expecting one type of
* proxy vs another, e.g. in tests.
- *
* @return true if CGILIB proxies should be created instead of interface based
* proxies, else false
*/
@@ -92,7 +91,6 @@ public @interface EnableGlobalMethodSecurity {
* Indicate how security advice should be applied. The default is
* {@link AdviceMode#PROXY}.
* @see AdviceMode
- *
* @return the {@link AdviceMode} to use
*/
AdviceMode mode() default AdviceMode.PROXY;
@@ -101,8 +99,8 @@ public @interface EnableGlobalMethodSecurity {
* Indicate the ordering of the execution of the security advisor when multiple
* advices are applied at a specific joinpoint. The default is
* {@link Ordered#LOWEST_PRECEDENCE}.
- *
* @return the order the security advisor should be applied
*/
int order() default Ordered.LOWEST_PRECEDENCE;
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.java
index 3d659bc4eb..11fcf66e80 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.java
@@ -36,16 +36,18 @@ import java.lang.annotation.Target;
@Import({ ReactiveMethodSecuritySelector.class })
@Configuration
public @interface EnableReactiveMethodSecurity {
+
/**
- * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
- * to standard Java interface-based proxies. The default is {@code false}.
+ * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed to
+ * standard Java interface-based proxies. The default is {@code false}.
* Applicable only if {@link #mode()} is set to {@link AdviceMode#PROXY}.
- *
Note that setting this attribute to {@code true} will affect all
- * Spring-managed beans requiring proxying, not just those marked with {@code @Cacheable}.
- * For example, other beans marked with Spring's {@code @Transactional} annotation will
- * be upgraded to subclass proxying at the same time. This approach has no negative
- * impact in practice unless one is explicitly expecting one type of proxy vs another,
- * e.g. in tests.
+ *
+ * Note that setting this attribute to {@code true} will affect all
+ * Spring-managed beans requiring proxying, not just those marked with
+ * {@code @Cacheable}. For example, other beans marked with Spring's
+ * {@code @Transactional} annotation will be upgraded to subclass proxying at the same
+ * time. This approach has no negative impact in practice unless one is explicitly
+ * expecting one type of proxy vs another, e.g. in tests.
*/
boolean proxyTargetClass() default false;
@@ -53,7 +55,6 @@ public @interface EnableReactiveMethodSecurity {
* Indicate how security advice should be applied. The default is
* {@link AdviceMode#PROXY}.
* @see AdviceMode
- *
* @return the {@link AdviceMode} to use
*/
AdviceMode mode() default AdviceMode.PROXY;
@@ -62,8 +63,8 @@ public @interface EnableReactiveMethodSecurity {
* Indicate the ordering of the execution of the security advisor when multiple
* advices are applied at a specific joinpoint. The default is
* {@link Ordered#LOWEST_PRECEDENCE}.
- *
* @return the order the security advisor should be applied
*/
int order() default Ordered.LOWEST_PRECEDENCE;
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityAspectJAutoProxyRegistrar.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityAspectJAutoProxyRegistrar.java
index 392c58f3d8..0d2705d6f5 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityAspectJAutoProxyRegistrar.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityAspectJAutoProxyRegistrar.java
@@ -36,28 +36,24 @@ import org.springframework.core.type.AnnotationMetadata;
* @author Rob Winch
* @since 3.2
*/
-class GlobalMethodSecurityAspectJAutoProxyRegistrar implements
- ImportBeanDefinitionRegistrar {
+class GlobalMethodSecurityAspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
/**
* Register, escalate, and configure the AspectJ auto proxy creator based on the value
* of the @{@link EnableGlobalMethodSecurity#proxyTargetClass()} attribute on the
* importing {@code @Configuration} class.
*/
- public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
- BeanDefinitionRegistry registry) {
+ public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
- BeanDefinition interceptor = registry
- .getBeanDefinition("methodSecurityInterceptor");
+ BeanDefinition interceptor = registry.getBeanDefinition("methodSecurityInterceptor");
- BeanDefinitionBuilder aspect = BeanDefinitionBuilder
- .rootBeanDefinition("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect");
+ BeanDefinitionBuilder aspect = BeanDefinitionBuilder.rootBeanDefinition(
+ "org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect");
aspect.setFactoryMethod("aspectOf");
aspect.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
aspect.addPropertyValue("securityInterceptor", interceptor);
- registry.registerBeanDefinition("annotationSecurityAspect$0",
- aspect.getBeanDefinition());
+ registry.registerBeanDefinition("annotationSecurityAspect$0", aspect.getBeanDefinition());
}
}
\ No newline at end of file
diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.java
index eb3207f823..244cac59b2 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.java
@@ -82,24 +82,31 @@ import org.springframework.util.Assert;
*/
@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
-public class GlobalMethodSecurityConfiguration
- implements ImportAware, SmartInitializingSingleton, BeanFactoryAware {
- private static final Log logger = LogFactory
- .getLog(GlobalMethodSecurityConfiguration.class);
+public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInitializingSingleton, BeanFactoryAware {
+
+ private static final Log logger = LogFactory.getLog(GlobalMethodSecurityConfiguration.class);
+
private ObjectPostProcessor objectPostProcessor = new ObjectPostProcessor() {
public T postProcess(T object) {
throw new IllegalStateException(ObjectPostProcessor.class.getName()
- + " is a required bean. Ensure you have used @"
- + EnableGlobalMethodSecurity.class.getName());
+ + " is a required bean. Ensure you have used @" + EnableGlobalMethodSecurity.class.getName());
}
};
+
private DefaultMethodSecurityExpressionHandler defaultMethodExpressionHandler = new DefaultMethodSecurityExpressionHandler();
+
private AuthenticationManager authenticationManager;
+
private AuthenticationManagerBuilder auth;
+
private boolean disableAuthenticationRegistry;
+
private AnnotationAttributes enableMethodSecurity;
+
private BeanFactory context;
+
private MethodSecurityExpressionHandler expressionHandler;
+
private MethodSecurityInterceptor methodSecurityInterceptor;
/**
@@ -117,19 +124,17 @@ public class GlobalMethodSecurityConfiguration
* Subclasses can override this method to provide a different
* {@link MethodInterceptor}.
*
- * @param methodSecurityMetadataSource the default {@link MethodSecurityMetadataSource}.
- *
+ * @param methodSecurityMetadataSource the default
+ * {@link MethodSecurityMetadataSource}.
* @return the {@link MethodInterceptor}.
*/
@Bean
public MethodInterceptor methodSecurityInterceptor(MethodSecurityMetadataSource methodSecurityMetadataSource) {
- this.methodSecurityInterceptor = isAspectJ()
- ? new AspectJMethodSecurityInterceptor()
+ this.methodSecurityInterceptor = isAspectJ() ? new AspectJMethodSecurityInterceptor()
: new MethodSecurityInterceptor();
methodSecurityInterceptor.setAccessDecisionManager(accessDecisionManager());
methodSecurityInterceptor.setAfterInvocationManager(afterInvocationManager());
- methodSecurityInterceptor
- .setSecurityMetadataSource(methodSecurityMetadataSource);
+ methodSecurityInterceptor.setSecurityMetadataSource(methodSecurityMetadataSource);
RunAsManager runAsManager = runAsManager();
if (runAsManager != null) {
methodSecurityInterceptor.setRunAsManager(runAsManager);
@@ -153,11 +158,9 @@ public class GlobalMethodSecurityConfiguration
throw new RuntimeException(e);
}
- PermissionEvaluator permissionEvaluator = getSingleBeanOrNull(
- PermissionEvaluator.class);
+ PermissionEvaluator permissionEvaluator = getSingleBeanOrNull(PermissionEvaluator.class);
if (permissionEvaluator != null) {
- this.defaultMethodExpressionHandler
- .setPermissionEvaluator(permissionEvaluator);
+ this.defaultMethodExpressionHandler.setPermissionEvaluator(permissionEvaluator);
}
RoleHierarchy roleHierarchy = getSingleBeanOrNull(RoleHierarchy.class);
@@ -165,24 +168,23 @@ public class GlobalMethodSecurityConfiguration
this.defaultMethodExpressionHandler.setRoleHierarchy(roleHierarchy);
}
- AuthenticationTrustResolver trustResolver = getSingleBeanOrNull(
- AuthenticationTrustResolver.class);
+ AuthenticationTrustResolver trustResolver = getSingleBeanOrNull(AuthenticationTrustResolver.class);
if (trustResolver != null) {
this.defaultMethodExpressionHandler.setTrustResolver(trustResolver);
}
- GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull(
- GrantedAuthorityDefaults.class);
+ GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull(GrantedAuthorityDefaults.class);
if (grantedAuthorityDefaults != null) {
- this.defaultMethodExpressionHandler.setDefaultRolePrefix(
- grantedAuthorityDefaults.getRolePrefix());
+ this.defaultMethodExpressionHandler.setDefaultRolePrefix(grantedAuthorityDefaults.getRolePrefix());
}
}
private T getSingleBeanOrNull(Class type) {
try {
return context.getBean(type);
- } catch (NoSuchBeanDefinitionException e) {}
+ }
+ catch (NoSuchBeanDefinitionException e) {
+ }
return null;
}
@@ -195,14 +197,14 @@ public class GlobalMethodSecurityConfiguration
/**
* Provide a custom {@link AfterInvocationManager} for the default implementation of
- * {@link #methodSecurityInterceptor(MethodSecurityMetadataSource)}. The default is null
- * if pre post is not enabled. Otherwise, it returns a {@link AfterInvocationProviderManager}.
+ * {@link #methodSecurityInterceptor(MethodSecurityMetadataSource)}. The default is
+ * null if pre post is not enabled. Otherwise, it returns a
+ * {@link AfterInvocationProviderManager}.
*
*
* Subclasses should override this method to provide a custom
* {@link AfterInvocationManager}
*
- *
* @return the {@link AfterInvocationManager} to use
*/
protected AfterInvocationManager afterInvocationManager() {
@@ -210,8 +212,7 @@ public class GlobalMethodSecurityConfiguration
AfterInvocationProviderManager invocationProviderManager = new AfterInvocationProviderManager();
ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice(
getExpressionHandler());
- PostInvocationAdviceProvider postInvocationAdviceProvider = new PostInvocationAdviceProvider(
- postAdvice);
+ PostInvocationAdviceProvider postInvocationAdviceProvider = new PostInvocationAdviceProvider(postAdvice);
List afterInvocationProviders = new ArrayList<>();
afterInvocationProviders.add(postInvocationAdviceProvider);
invocationProviderManager.setProviders(afterInvocationProviders);
@@ -222,8 +223,8 @@ public class GlobalMethodSecurityConfiguration
/**
* Provide a custom {@link RunAsManager} for the default implementation of
- * {@link #methodSecurityInterceptor(MethodSecurityMetadataSource)}. The default is null.
- *
+ * {@link #methodSecurityInterceptor(MethodSecurityMetadataSource)}. The default is
+ * null.
* @return the {@link RunAsManager} to use
*/
protected RunAsManager runAsManager() {
@@ -239,24 +240,20 @@ public class GlobalMethodSecurityConfiguration
*
{@link RoleVoter}
*
{@link AuthenticatedVoter}
*
- *
* @return the {@link AccessDecisionManager} to use
*/
protected AccessDecisionManager accessDecisionManager() {
List> decisionVoters = new ArrayList<>();
if (prePostEnabled()) {
- ExpressionBasedPreInvocationAdvice expressionAdvice =
- new ExpressionBasedPreInvocationAdvice();
+ ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice();
expressionAdvice.setExpressionHandler(getExpressionHandler());
- decisionVoters
- .add(new PreInvocationAuthorizationAdviceVoter(expressionAdvice));
+ decisionVoters.add(new PreInvocationAuthorizationAdviceVoter(expressionAdvice));
}
if (jsr250Enabled()) {
decisionVoters.add(new Jsr250Voter());
}
RoleVoter roleVoter = new RoleVoter();
- GrantedAuthorityDefaults grantedAuthorityDefaults =
- getSingleBeanOrNull(GrantedAuthorityDefaults.class);
+ GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull(GrantedAuthorityDefaults.class);
if (grantedAuthorityDefaults != null) {
roleVoter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix());
}
@@ -275,7 +272,6 @@ public class GlobalMethodSecurityConfiguration
* Subclasses may override this method to provide a custom
* {@link MethodSecurityExpressionHandler}
*
- *
* @return the {@link MethodSecurityExpressionHandler} to use
*/
protected MethodSecurityExpressionHandler createExpressionHandler() {
@@ -285,7 +281,6 @@ public class GlobalMethodSecurityConfiguration
/**
* Gets the {@link MethodSecurityExpressionHandler} or creates it using
* {@link #expressionHandler}.
- *
* @return a non {@code null} {@link MethodSecurityExpressionHandler}
*/
protected final MethodSecurityExpressionHandler getExpressionHandler() {
@@ -298,7 +293,6 @@ public class GlobalMethodSecurityConfiguration
/**
* Provides a custom {@link MethodSecurityMetadataSource} that is registered with the
* {@link #methodSecurityMetadataSource()}. Default is null.
- *
* @return a custom {@link MethodSecurityMetadataSource} that is registered with the
* {@link #methodSecurityMetadataSource()}
*/
@@ -312,7 +306,6 @@ public class GlobalMethodSecurityConfiguration
* {@link #configure(AuthenticationManagerBuilder)}. If
* {@link #configure(AuthenticationManagerBuilder)} was not overridden, then an
* {@link AuthenticationManager} is attempted to be autowired by type.
- *
* @return the {@link AuthenticationManager} to use
*/
protected AuthenticationManager authenticationManager() throws Exception {
@@ -323,8 +316,7 @@ public class GlobalMethodSecurityConfiguration
auth.authenticationEventPublisher(eventPublisher);
configure(auth);
if (disableAuthenticationRegistry) {
- authenticationManager = getAuthenticationConfiguration()
- .getAuthenticationManager();
+ authenticationManager = getAuthenticationConfiguration().getAuthenticationManager();
}
else {
authenticationManager = auth.build();
@@ -337,7 +329,6 @@ public class GlobalMethodSecurityConfiguration
* Sub classes can override this method to register different types of authentication.
* If not overridden, {@link #configure(AuthenticationManagerBuilder)} will attempt to
* autowire by type.
- *
* @param auth the {@link AuthenticationManagerBuilder} used to register different
* authentication mechanisms for the global method security.
* @throws Exception
@@ -351,7 +342,6 @@ public class GlobalMethodSecurityConfiguration
* creates a {@link DelegatingMethodSecurityMetadataSource} based upon
* {@link #customMethodSecurityMetadataSource()} and the attributes on
* {@link EnableGlobalMethodSecurity}.
- *
* @return the {@link MethodSecurityMetadataSource}
*/
@Bean
@@ -370,8 +360,8 @@ public class GlobalMethodSecurityConfiguration
boolean isJsr250Enabled = jsr250Enabled();
if (!isPrePostEnabled && !isSecuredEnabled && !isJsr250Enabled && !hasCustom) {
- throw new IllegalStateException("In the composition of all global method configuration, " +
- "no annotation support was actually activated");
+ throw new IllegalStateException("In the composition of all global method configuration, "
+ + "no annotation support was actually activated");
}
if (isPrePostEnabled) {
@@ -381,12 +371,11 @@ public class GlobalMethodSecurityConfiguration
sources.add(new SecuredAnnotationSecurityMetadataSource());
}
if (isJsr250Enabled) {
- GrantedAuthorityDefaults grantedAuthorityDefaults =
- getSingleBeanOrNull(GrantedAuthorityDefaults.class);
- Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource = this.context.getBean(Jsr250MethodSecurityMetadataSource.class);
+ GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull(GrantedAuthorityDefaults.class);
+ Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource = this.context
+ .getBean(Jsr250MethodSecurityMetadataSource.class);
if (grantedAuthorityDefaults != null) {
- jsr250MethodSecurityMetadataSource.setDefaultRolePrefix(
- grantedAuthorityDefaults.getRolePrefix());
+ jsr250MethodSecurityMetadataSource.setDefaultRolePrefix(grantedAuthorityDefaults.getRolePrefix());
}
sources.add(jsr250MethodSecurityMetadataSource);
}
@@ -396,7 +385,6 @@ public class GlobalMethodSecurityConfiguration
/**
* Creates the {@link PreInvocationAuthorizationAdvice} to be used. The default is
* {@link ExpressionBasedPreInvocationAdvice}.
- *
* @return the {@link PreInvocationAuthorizationAdvice}
*/
@Bean
@@ -419,16 +407,13 @@ public class GlobalMethodSecurityConfiguration
@Autowired(required = false)
public void setObjectPostProcessor(ObjectPostProcessor objectPostProcessor) {
this.objectPostProcessor = objectPostProcessor;
- this.defaultMethodExpressionHandler = objectPostProcessor
- .postProcess(defaultMethodExpressionHandler);
+ this.defaultMethodExpressionHandler = objectPostProcessor.postProcess(defaultMethodExpressionHandler);
}
@Autowired(required = false)
- public void setMethodSecurityExpressionHandler(
- List handlers) {
+ public void setMethodSecurityExpressionHandler(List handlers) {
if (handlers.size() != 1) {
- logger.debug("Not autowiring MethodSecurityExpressionHandler since size != 1. Got "
- + handlers);
+ logger.debug("Not autowiring MethodSecurityExpressionHandler since size != 1. Got " + handlers);
return;
}
this.expressionHandler = handlers.get(0);
@@ -466,14 +451,13 @@ public class GlobalMethodSecurityConfiguration
private AnnotationAttributes enableMethodSecurity() {
if (enableMethodSecurity == null) {
// if it is null look at this instance (i.e. a subclass was used)
- EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils
- .findAnnotation(getClass(), EnableGlobalMethodSecurity.class);
- Assert.notNull(methodSecurityAnnotation,
- () -> EnableGlobalMethodSecurity.class.getName() + " is required");
- Map methodSecurityAttrs = AnnotationUtils
- .getAnnotationAttributes(methodSecurityAnnotation);
+ EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(),
+ EnableGlobalMethodSecurity.class);
+ Assert.notNull(methodSecurityAnnotation, () -> EnableGlobalMethodSecurity.class.getName() + " is required");
+ Map methodSecurityAttrs = AnnotationUtils.getAnnotationAttributes(methodSecurityAnnotation);
this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs);
}
return this.enableMethodSecurity;
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecuritySelector.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecuritySelector.java
index 1ffa8256a2..da6bf1537f 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecuritySelector.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecuritySelector.java
@@ -38,26 +38,22 @@ final class GlobalMethodSecuritySelector implements ImportSelector {
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
Class annoType = EnableGlobalMethodSecurity.class;
- Map annotationAttributes = importingClassMetadata
- .getAnnotationAttributes(annoType.getName(), false);
- AnnotationAttributes attributes = AnnotationAttributes
- .fromMap(annotationAttributes);
- Assert.notNull(attributes, () -> String.format(
- "@%s is not present on importing class '%s' as expected",
+ Map annotationAttributes = importingClassMetadata.getAnnotationAttributes(annoType.getName(),
+ false);
+ AnnotationAttributes attributes = AnnotationAttributes.fromMap(annotationAttributes);
+ Assert.notNull(attributes, () -> String.format("@%s is not present on importing class '%s' as expected",
annoType.getSimpleName(), importingClassMetadata.getClassName()));
// TODO would be nice if could use BeanClassLoaderAware (does not work)
- Class> importingClass = ClassUtils
- .resolveClassName(importingClassMetadata.getClassName(),
- ClassUtils.getDefaultClassLoader());
+ Class> importingClass = ClassUtils.resolveClassName(importingClassMetadata.getClassName(),
+ ClassUtils.getDefaultClassLoader());
boolean skipMethodSecurityConfiguration = GlobalMethodSecurityConfiguration.class
.isAssignableFrom(importingClass);
AdviceMode mode = attributes.getEnum("mode");
boolean isProxy = AdviceMode.PROXY == mode;
- String autoProxyClassName = isProxy ? AutoProxyRegistrar.class
- .getName() : GlobalMethodSecurityAspectJAutoProxyRegistrar.class
- .getName();
+ String autoProxyClassName = isProxy ? AutoProxyRegistrar.class.getName()
+ : GlobalMethodSecurityAspectJAutoProxyRegistrar.class.getName();
boolean jsr250Enabled = attributes.getBoolean("jsr250Enabled");
@@ -78,4 +74,5 @@ final class GlobalMethodSecuritySelector implements ImportSelector {
return classNames.toArray(new String[0]);
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/Jsr250MetadataSourceConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/Jsr250MetadataSourceConfiguration.java
index 5c98bf48fe..b2b534d0aa 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/Jsr250MetadataSourceConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/Jsr250MetadataSourceConfiguration.java
@@ -30,4 +30,5 @@ class Jsr250MetadataSourceConfiguration {
public Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource() {
return new Jsr250MethodSecurityMetadataSource();
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityMetadataSourceAdvisorRegistrar.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityMetadataSourceAdvisorRegistrar.java
index 8ef8f1e4af..a000487b95 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityMetadataSourceAdvisorRegistrar.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityMetadataSourceAdvisorRegistrar.java
@@ -24,24 +24,22 @@ import org.springframework.security.access.intercept.aopalliance.MethodSecurityM
import org.springframework.util.MultiValueMap;
/**
- * Creates Spring Security's MethodSecurityMetadataSourceAdvisor only when
- * using proxy based method security (i.e. do not do it when using ASPECTJ).
- * The conditional logic is controlled through {@link GlobalMethodSecuritySelector}.
+ * Creates Spring Security's MethodSecurityMetadataSourceAdvisor only when using proxy
+ * based method security (i.e. do not do it when using ASPECTJ). The conditional logic is
+ * controlled through {@link GlobalMethodSecuritySelector}.
*
* @author Rob Winch
* @since 4.0.2
* @see GlobalMethodSecuritySelector
*/
-class MethodSecurityMetadataSourceAdvisorRegistrar implements
- ImportBeanDefinitionRegistrar {
+class MethodSecurityMetadataSourceAdvisorRegistrar implements ImportBeanDefinitionRegistrar {
/**
* Register, escalate, and configure the AspectJ auto proxy creator based on the value
* of the @{@link EnableGlobalMethodSecurity#proxyTargetClass()} attribute on the
* importing {@code @Configuration} class.
*/
- public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
- BeanDefinitionRegistry registry) {
+ public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
BeanDefinitionBuilder advisor = BeanDefinitionBuilder
.rootBeanDefinition(MethodSecurityMetadataSourceAdvisor.class);
@@ -50,13 +48,14 @@ class MethodSecurityMetadataSourceAdvisorRegistrar implements
advisor.addConstructorArgReference("methodSecurityMetadataSource");
advisor.addConstructorArgValue("methodSecurityMetadataSource");
- MultiValueMap attributes = importingClassMetadata.getAllAnnotationAttributes(EnableGlobalMethodSecurity.class.getName());
+ MultiValueMap attributes = importingClassMetadata
+ .getAllAnnotationAttributes(EnableGlobalMethodSecurity.class.getName());
Integer order = (Integer) attributes.getFirst("order");
if (order != null) {
advisor.addPropertyValue("order", order);
}
- registry.registerBeanDefinition("metaDataSourceAdvisor",
- advisor.getBeanDefinition());
+ registry.registerBeanDefinition("metaDataSourceAdvisor", advisor.getBeanDefinition());
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecurityConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecurityConfiguration.java
index b1ba9ae5d8..ab77dab8af 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecurityConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecurityConfiguration.java
@@ -40,6 +40,7 @@ import java.util.Arrays;
*/
@Configuration(proxyBeanMethods = false)
class ReactiveMethodSecurityConfiguration implements ImportAware {
+
private int advisorOrder;
private GrantedAuthorityDefaults grantedAuthorityDefaults;
@@ -48,26 +49,27 @@ class ReactiveMethodSecurityConfiguration implements ImportAware {
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public MethodSecurityMetadataSourceAdvisor methodSecurityInterceptor(AbstractMethodSecurityMetadataSource source) {
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
- "securityMethodInterceptor", source, "methodMetadataSource");
+ "securityMethodInterceptor", source, "methodMetadataSource");
advisor.setOrder(advisorOrder);
return advisor;
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
- public DelegatingMethodSecurityMetadataSource methodMetadataSource(MethodSecurityExpressionHandler methodSecurityExpressionHandler) {
+ public DelegatingMethodSecurityMetadataSource methodMetadataSource(
+ MethodSecurityExpressionHandler methodSecurityExpressionHandler) {
ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory(
methodSecurityExpressionHandler);
PrePostAnnotationSecurityMetadataSource prePostSource = new PrePostAnnotationSecurityMetadataSource(
- attributeFactory);
+ attributeFactory);
return new DelegatingMethodSecurityMetadataSource(Arrays.asList(prePostSource));
}
@Bean
- public PrePostAdviceReactiveMethodInterceptor securityMethodInterceptor(AbstractMethodSecurityMetadataSource source, MethodSecurityExpressionHandler handler) {
+ public PrePostAdviceReactiveMethodInterceptor securityMethodInterceptor(AbstractMethodSecurityMetadataSource source,
+ MethodSecurityExpressionHandler handler) {
- ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice(
- handler);
+ ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice(handler);
ExpressionBasedPreInvocationAdvice preAdvice = new ExpressionBasedPreInvocationAdvice();
preAdvice.setExpressionHandler(handler);
@@ -86,7 +88,8 @@ class ReactiveMethodSecurityConfiguration implements ImportAware {
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
- this.advisorOrder = (int) importMetadata.getAnnotationAttributes(EnableReactiveMethodSecurity.class.getName()).get("order");
+ this.advisorOrder = (int) importMetadata.getAnnotationAttributes(EnableReactiveMethodSecurity.class.getName())
+ .get("order");
}
@Autowired(required = false)
diff --git a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecuritySelector.java b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecuritySelector.java
index 612432215e..43b7fd85a8 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecuritySelector.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/method/configuration/ReactiveMethodSecuritySelector.java
@@ -27,22 +27,23 @@ import java.util.List;
* @author Rob Winch
* @since 5.0
*/
-class ReactiveMethodSecuritySelector extends
- AdviceModeImportSelector {
+class ReactiveMethodSecuritySelector extends AdviceModeImportSelector {
@Override
protected String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
- case PROXY:
- return getProxyImports();
- default:
- throw new IllegalStateException("AdviceMode " + adviceMode + " is not supported");
+ case PROXY:
+ return getProxyImports();
+ default:
+ throw new IllegalStateException("AdviceMode " + adviceMode + " is not supported");
}
}
/**
- * Return the imports to use if the {@link AdviceMode} is set to {@link AdviceMode#PROXY}.
- *
Take care of adding the necessary JSR-107 import if it is available.
+ * Return the imports to use if the {@link AdviceMode} is set to
+ * {@link AdviceMode#PROXY}.
+ *
+ * Take care of adding the necessary JSR-107 import if it is available.
*/
private String[] getProxyImports() {
List result = new ArrayList<>();
@@ -50,4 +51,5 @@ class ReactiveMethodSecuritySelector extends
result.add(ReactiveMethodSecurityConfiguration.class.getName());
return result.toArray(new String[0]);
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/rsocket/EnableRSocketSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/rsocket/EnableRSocketSecurity.java
index 440186090f..a44636e121 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/rsocket/EnableRSocketSecurity.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/rsocket/EnableRSocketSecurity.java
@@ -36,4 +36,6 @@ import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import({ RSocketSecurityConfiguration.class, SecuritySocketAcceptorInterceptorConfiguration.class })
-public @interface EnableRSocketSecurity { }
+public @interface EnableRSocketSecurity {
+
+}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/rsocket/PayloadInterceptorOrder.java b/config/src/main/java/org/springframework/security/config/annotation/rsocket/PayloadInterceptorOrder.java
index eba69bd9c5..f21d5b71eb 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/rsocket/PayloadInterceptorOrder.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/rsocket/PayloadInterceptorOrder.java
@@ -21,14 +21,15 @@ import org.springframework.security.config.Customizer;
import org.springframework.security.rsocket.api.PayloadInterceptor;
/**
- * The standard order for {@link PayloadInterceptor} to be
- * sorted. The actual values might change, so users should use the {@link #getOrder()} method to
- * calculate the position dynamically rather than copy values.
+ * The standard order for {@link PayloadInterceptor} to be sorted. The actual values might
+ * change, so users should use the {@link #getOrder()} method to calculate the position
+ * dynamically rather than copy values.
*
* @author Rob Winch
* @since 5.2
*/
public enum PayloadInterceptorOrder implements Ordered {
+
/**
* Where basic authentication is placed.
* @see RSocketSecurity#basicAuthentication(Customizer)
@@ -65,4 +66,5 @@ public enum PayloadInterceptorOrder implements Ordered {
public int getOrder() {
return this.order;
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurity.java
index d36acdbc44..1428f0015a 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurity.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurity.java
@@ -99,6 +99,7 @@ import java.util.List;
* }
* }
*
+ *
* @author Rob Winch
* @author Jesús Ascama Arias
* @author Luis Felipe Vega
@@ -123,12 +124,12 @@ public class RSocketSecurity {
private ReactiveAuthenticationManager authenticationManager;
/**
- * Adds a {@link PayloadInterceptor} to be used. This is typically only used
- * when using the DSL does not meet a users needs. In order to ensure the
- * {@link PayloadInterceptor} is done in the proper order the {@link PayloadInterceptor} should
- * either implement {@link org.springframework.core.Ordered} or be annotated with
+ * Adds a {@link PayloadInterceptor} to be used. This is typically only used when
+ * using the DSL does not meet a users needs. In order to ensure the
+ * {@link PayloadInterceptor} is done in the proper order the
+ * {@link PayloadInterceptor} should either implement
+ * {@link org.springframework.core.Ordered} or be annotated with
* {@link org.springframework.core.annotation.Order}.
- *
* @param interceptor
* @return the builder for additional customizations
* @see PayloadInterceptorOrder
@@ -144,8 +145,9 @@ public class RSocketSecurity {
}
/**
- * Adds support for validating a username and password using
- * Simple Authentication
+ * Adds support for validating a username and password using Simple
+ * Authentication
* @param simple a customizer
* @return RSocketSecurity for additional configuration
* @since 5.3
@@ -162,6 +164,7 @@ public class RSocketSecurity {
* @since 5.3
*/
public class SimpleAuthenticationSpec {
+
private ReactiveAuthenticationManager authenticationManager;
public SimpleAuthenticationSpec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
@@ -184,12 +187,13 @@ public class RSocketSecurity {
return result;
}
- private SimpleAuthenticationSpec() {}
+ private SimpleAuthenticationSpec() {
+ }
+
}
/**
* Adds authentication with BasicAuthenticationPayloadExchangeConverter.
- *
* @param basic
* @return
* @deprecated Use {@link #simpleAuthentication(Customizer)}
@@ -204,6 +208,7 @@ public class RSocketSecurity {
}
public class BasicAuthenticationSpec {
+
private ReactiveAuthenticationManager authenticationManager;
public BasicAuthenticationSpec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
@@ -225,7 +230,9 @@ public class RSocketSecurity {
return result;
}
- private BasicAuthenticationSpec() {}
+ private BasicAuthenticationSpec() {
+ }
+
}
public RSocketSecurity jwt(Customizer jwt) {
@@ -237,6 +244,7 @@ public class RSocketSecurity {
}
public class JwtSpec {
+
private ReactiveAuthenticationManager authenticationManager;
public JwtSpec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
@@ -269,7 +277,9 @@ public class RSocketSecurity {
return Arrays.asList(standard, legacy);
}
- private JwtSpec() {}
+ private JwtSpec() {
+ }
+
}
public RSocketSecurity authorizePayload(Customizer authorize) {
@@ -281,8 +291,7 @@ public class RSocketSecurity {
}
public PayloadSocketAcceptorInterceptor build() {
- PayloadSocketAcceptorInterceptor interceptor = new PayloadSocketAcceptorInterceptor(
- payloadInterceptors());
+ PayloadSocketAcceptorInterceptor interceptor = new PayloadSocketAcceptorInterceptor(payloadInterceptors());
RSocketMessageHandler handler = getBean(RSocketMessageHandler.class);
interceptor.setDefaultDataMimeType(handler.getDefaultDataMimeType());
interceptor.setDefaultMetadataMimeType(handler.getDefaultMetadataMimeType());
@@ -318,16 +327,17 @@ public class RSocketSecurity {
public class AuthorizePayloadsSpec {
- private PayloadExchangeMatcherReactiveAuthorizationManager.Builder authzBuilder =
- PayloadExchangeMatcherReactiveAuthorizationManager.builder();
+ private PayloadExchangeMatcherReactiveAuthorizationManager.Builder authzBuilder = PayloadExchangeMatcherReactiveAuthorizationManager
+ .builder();
public Access setup() {
return matcher(PayloadExchangeMatchers.setup());
}
/**
- * Matches if {@link org.springframework.security.rsocket.api.PayloadExchangeType#isRequest()} is true, else
- * not a match
+ * Matches if
+ * {@link org.springframework.security.rsocket.api.PayloadExchangeType#isRequest()}
+ * is true, else not a match
* @return the Access to set up the authorization rule.
*/
public Access anyRequest() {
@@ -350,10 +360,8 @@ public class RSocketSecurity {
public Access route(String pattern) {
RSocketMessageHandler handler = getBean(RSocketMessageHandler.class);
- PayloadExchangeMatcher matcher = new RoutePayloadExchangeMatcher(
- handler.getMetadataExtractor(),
- handler.getRouteMatcher(),
- pattern);
+ PayloadExchangeMatcher matcher = new RoutePayloadExchangeMatcher(handler.getMetadataExtractor(),
+ handler.getRouteMatcher(), pattern);
return matcher(matcher);
}
@@ -386,8 +394,7 @@ public class RSocketSecurity {
}
public AuthorizePayloadsSpec permitAll() {
- return access((a, ctx) -> Mono
- .just(new AuthorizationDecision(true)));
+ return access((a, ctx) -> Mono.just(new AuthorizationDecision(true)));
}
public AuthorizePayloadsSpec hasAnyAuthority(String... authorities) {
@@ -396,15 +403,17 @@ public class RSocketSecurity {
public AuthorizePayloadsSpec access(
ReactiveAuthorizationManager authorization) {
- AuthorizePayloadsSpec.this.authzBuilder.add(new PayloadExchangeMatcherEntry<>(this.matcher, authorization));
+ AuthorizePayloadsSpec.this.authzBuilder
+ .add(new PayloadExchangeMatcherEntry<>(this.matcher, authorization));
return AuthorizePayloadsSpec.this;
}
public AuthorizePayloadsSpec denyAll() {
- return access((a, ctx) -> Mono
- .just(new AuthorizationDecision(false)));
+ return access((a, ctx) -> Mono.just(new AuthorizationDecision(false)));
}
+
}
+
}
private T getBean(Class beanClass) {
@@ -422,15 +431,15 @@ public class RSocketSecurity {
if (this.context == null) {
return null;
}
- String[] names = this.context.getBeanNamesForType(type);
+ String[] names = this.context.getBeanNamesForType(type);
if (names.length == 1) {
return (T) this.context.getBean(names[0]);
}
return null;
}
- protected void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
+ protected void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurityConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurityConfiguration.java
index fdf9bd31bc..9e6cfcb73d 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurityConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/rsocket/RSocketSecurityConfiguration.java
@@ -34,6 +34,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
class RSocketSecurityConfiguration {
private static final String BEAN_NAME_PREFIX = "org.springframework.security.config.annotation.rsocket.RSocketSecurityConfiguration.";
+
private static final String RSOCKET_SECURITY_BEAN_NAME = BEAN_NAME_PREFIX + "rsocketSecurity";
private ReactiveAuthenticationManager authenticationManager;
@@ -43,8 +44,7 @@ class RSocketSecurityConfiguration {
private PasswordEncoder passwordEncoder;
@Autowired(required = false)
- void setAuthenticationManager(
- ReactiveAuthenticationManager authenticationManager) {
+ void setAuthenticationManager(ReactiveAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@@ -61,8 +61,7 @@ class RSocketSecurityConfiguration {
@Bean(name = RSOCKET_SECURITY_BEAN_NAME)
@Scope("prototype")
public RSocketSecurity rsocketSecurity(ApplicationContext context) {
- RSocketSecurity security = new RSocketSecurity()
- .authenticationManager(authenticationManager());
+ RSocketSecurity security = new RSocketSecurity().authenticationManager(authenticationManager());
security.setApplicationContext(context);
return security;
}
@@ -72,8 +71,8 @@ class RSocketSecurityConfiguration {
return this.authenticationManager;
}
if (this.reactiveUserDetailsService != null) {
- UserDetailsRepositoryReactiveAuthenticationManager manager =
- new UserDetailsRepositoryReactiveAuthenticationManager(this.reactiveUserDetailsService);
+ UserDetailsRepositoryReactiveAuthenticationManager manager = new UserDetailsRepositoryReactiveAuthenticationManager(
+ this.reactiveUserDetailsService);
if (this.passwordEncoder != null) {
manager.setPasswordEncoder(this.passwordEncoder);
}
@@ -81,4 +80,5 @@ class RSocketSecurityConfiguration {
}
return null;
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/rsocket/SecuritySocketAcceptorInterceptorConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/rsocket/SecuritySocketAcceptorInterceptorConfiguration.java
index cdd007d61e..57804f171f 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/rsocket/SecuritySocketAcceptorInterceptorConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/rsocket/SecuritySocketAcceptorInterceptorConfiguration.java
@@ -31,29 +31,25 @@ import org.springframework.security.rsocket.util.matcher.PayloadExchangeMatcher.
*/
@Configuration(proxyBeanMethods = false)
class SecuritySocketAcceptorInterceptorConfiguration {
+
@Bean
SecuritySocketAcceptorInterceptor securitySocketAcceptorInterceptor(
- ObjectProvider rsocketInterceptor, ObjectProvider rsocketSecurity) {
+ ObjectProvider rsocketInterceptor,
+ ObjectProvider rsocketSecurity) {
PayloadSocketAcceptorInterceptor delegate = rsocketInterceptor
.getIfAvailable(() -> defaultInterceptor(rsocketSecurity));
return new SecuritySocketAcceptorInterceptor(delegate);
}
- private PayloadSocketAcceptorInterceptor defaultInterceptor(
- ObjectProvider rsocketSecurity) {
+ private PayloadSocketAcceptorInterceptor defaultInterceptor(ObjectProvider rsocketSecurity) {
RSocketSecurity rsocket = rsocketSecurity.getIfAvailable();
if (rsocket == null) {
throw new NoSuchBeanDefinitionException("No RSocketSecurity defined");
}
- rsocket
- .basicAuthentication(Customizer.withDefaults())
- .simpleAuthentication(Customizer.withDefaults())
- .authorizePayload(authz ->
- authz
- .setup().authenticated()
- .anyRequest().authenticated()
- .matcher(e -> MatchResult.match()).permitAll()
- );
+ rsocket.basicAuthentication(Customizer.withDefaults()).simpleAuthentication(Customizer.withDefaults())
+ .authorizePayload(authz -> authz.setup().authenticated().anyRequest().authenticated()
+ .matcher(e -> MatchResult.match()).permitAll());
return rsocket.build();
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.java b/config/src/main/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.java
index 268c0e4a54..01956cfe07 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.java
@@ -36,14 +36,13 @@ import java.util.List;
* A base class for registering {@link RequestMatcher}'s. For example, it might allow for
* specifying which {@link RequestMatcher} require a certain level of authorization.
*
- *
* @param The object that is returned or Chained after creating the RequestMatcher
- *
* @author Rob Winch
* @author Ankur Pathak
* @since 3.2
*/
public abstract class AbstractRequestMatcherRegistry {
+
private static final String HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME = "mvcHandlerMappingIntrospector";
private static final RequestMatcher ANY_REQUEST = AnyRequestMatcher.INSTANCE;
@@ -58,7 +57,6 @@ public abstract class AbstractRequestMatcherRegistry {
/**
* Gets the {@link ApplicationContext}
- *
* @return the {@link ApplicationContext}
*/
protected final ApplicationContext getApplicationContext() {
@@ -67,7 +65,6 @@ public abstract class AbstractRequestMatcherRegistry {
/**
* Maps any request.
- *
* @return the object that is chained after creating the {@link RequestMatcher}
*/
public C anyRequest() {
@@ -81,10 +78,7 @@ public abstract class AbstractRequestMatcherRegistry {
* Maps a {@link List} of
* {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher}
* instances.
- *
- * @param method the {@link HttpMethod} to use for any
- * {@link HttpMethod}.
- *
+ * @param method the {@link HttpMethod} to use for any {@link HttpMethod}.
* @return the object that is chained after creating the {@link RequestMatcher}
*/
public C antMatchers(HttpMethod method) {
@@ -95,12 +89,11 @@ public abstract class AbstractRequestMatcherRegistry {
* Maps a {@link List} of
* {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher}
* instances.
- *
* @param method the {@link HttpMethod} to use or {@code null} for any
* {@link HttpMethod}.
- * @param antPatterns the ant patterns to create. If {@code null} or empty, then matches on nothing.
+ * @param antPatterns the ant patterns to create. If {@code null} or empty, then
+ * matches on nothing.
* {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher} from
- *
* @return the object that is chained after creating the {@link RequestMatcher}
*/
public C antMatchers(HttpMethod method, String... antPatterns) {
@@ -112,10 +105,8 @@ public abstract class AbstractRequestMatcherRegistry {
* Maps a {@link List} of
* {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher}
* instances that do not care which {@link HttpMethod} is used.
- *
* @param antPatterns the ant patterns to create
* {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher} from
- *
* @return the object that is chained after creating the {@link RequestMatcher}
*/
public C antMatchers(String... antPatterns) {
@@ -134,7 +125,6 @@ public abstract class AbstractRequestMatcherRegistry {
* If the current request will not be processed by Spring MVC, a reasonable default
* using the pattern as a ant pattern will be used.
*
- *
* @param mvcPatterns the patterns to match on. The rules for matching are defined by
* Spring MVC
* @return the object that is chained after creating the {@link RequestMatcher}.
@@ -152,7 +142,6 @@ public abstract class AbstractRequestMatcherRegistry {
* If the current request will not be processed by Spring MVC, a reasonable default
* using the pattern as a ant pattern will be used.
*
- *
* @param method the HTTP method to match on
* @param mvcPatterns the patterns to match on. The rules for matching are defined by
* Spring MVC
@@ -162,23 +151,21 @@ public abstract class AbstractRequestMatcherRegistry {
/**
* Creates {@link MvcRequestMatcher} instances for the method and patterns passed in
- *
* @param method the HTTP method to use or null if any should be used
* @param mvcPatterns the Spring MVC patterns to match on
* @return a List of {@link MvcRequestMatcher} instances
*/
- protected final List createMvcMatchers(HttpMethod method,
- String... mvcPatterns) {
+ protected final List createMvcMatchers(HttpMethod method, String... mvcPatterns) {
Assert.state(!this.anyRequestConfigured, "Can't configure mvcMatchers after anyRequest");
ObjectPostProcessor opp = this.context.getBean(ObjectPostProcessor.class);
if (!this.context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) {
- throw new NoSuchBeanDefinitionException("A Bean named " + HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME +" of type " + HandlerMappingIntrospector.class.getName()
- + " is required to use MvcRequestMatcher. Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext.");
+ throw new NoSuchBeanDefinitionException("A Bean named " + HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME
+ + " of type " + HandlerMappingIntrospector.class.getName()
+ + " is required to use MvcRequestMatcher. Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext.");
}
HandlerMappingIntrospector introspector = this.context.getBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME,
- HandlerMappingIntrospector.class);
- List matchers = new ArrayList<>(
- mvcPatterns.length);
+ HandlerMappingIntrospector.class);
+ List matchers = new ArrayList<>(mvcPatterns.length);
for (String mvcPattern : mvcPatterns) {
MvcRequestMatcher matcher = new MvcRequestMatcher(introspector, mvcPattern);
opp.postProcess(matcher);
@@ -195,12 +182,10 @@ public abstract class AbstractRequestMatcherRegistry {
* Maps a {@link List} of
* {@link org.springframework.security.web.util.matcher.RegexRequestMatcher}
* instances.
- *
* @param method the {@link HttpMethod} to use or {@code null} for any
* {@link HttpMethod}.
* @param regexPatterns the regular expressions to create
* {@link org.springframework.security.web.util.matcher.RegexRequestMatcher} from
- *
* @return the object that is chained after creating the {@link RequestMatcher}
*/
public C regexMatchers(HttpMethod method, String... regexPatterns) {
@@ -212,10 +197,8 @@ public abstract class AbstractRequestMatcherRegistry {
* Create a {@link List} of
* {@link org.springframework.security.web.util.matcher.RegexRequestMatcher} instances
* that do not specify an {@link HttpMethod}.
- *
* @param regexPatterns the regular expressions to create
* {@link org.springframework.security.web.util.matcher.RegexRequestMatcher} from
- *
* @return the object that is chained after creating the {@link RequestMatcher}
*/
public C regexMatchers(String... regexPatterns) {
@@ -226,9 +209,7 @@ public abstract class AbstractRequestMatcherRegistry {
/**
* Associates a list of {@link RequestMatcher} instances with the
* {@link AbstractConfigAttributeRequestMatcherRegistry}
- *
* @param requestMatchers the {@link RequestMatcher} instances
- *
* @return the object that is chained after creating the {@link RequestMatcher}
*/
public C requestMatchers(RequestMatcher... requestMatchers) {
@@ -239,7 +220,6 @@ public abstract class AbstractRequestMatcherRegistry {
/**
* Subclasses should implement this method for returning the object that is chained to
* the creation of the {@link RequestMatcher} instances.
- *
* @param requestMatchers the {@link RequestMatcher} instances that were created
* @return the chained Object for the subclass which allows association of something
* else to the {@link RequestMatcher}
@@ -256,16 +236,13 @@ public abstract class AbstractRequestMatcherRegistry {
/**
* Create a {@link List} of {@link AntPathRequestMatcher} instances.
- *
* @param httpMethod the {@link HttpMethod} to use or {@code null} for any
* {@link HttpMethod}.
* @param antPatterns the ant patterns to create {@link AntPathRequestMatcher}
* from
- *
* @return a {@link List} of {@link AntPathRequestMatcher} instances
*/
- public static List antMatchers(HttpMethod httpMethod,
- String... antPatterns) {
+ public static List antMatchers(HttpMethod httpMethod, String... antPatterns) {
String method = httpMethod == null ? null : httpMethod.toString();
List matchers = new ArrayList<>();
for (String pattern : antPatterns) {
@@ -277,10 +254,8 @@ public abstract class AbstractRequestMatcherRegistry {
/**
* Create a {@link List} of {@link AntPathRequestMatcher} instances that do not
* specify an {@link HttpMethod}.
- *
* @param antPatterns the ant patterns to create {@link AntPathRequestMatcher}
* from
- *
* @return a {@link List} of {@link AntPathRequestMatcher} instances
*/
public static List antMatchers(String... antPatterns) {
@@ -289,16 +264,13 @@ public abstract class AbstractRequestMatcherRegistry {
/**
* Create a {@link List} of {@link RegexRequestMatcher} instances.
- *
* @param httpMethod the {@link HttpMethod} to use or {@code null} for any
* {@link HttpMethod}.
* @param regexPatterns the regular expressions to create
* {@link RegexRequestMatcher} from
- *
* @return a {@link List} of {@link RegexRequestMatcher} instances
*/
- public static List regexMatchers(HttpMethod httpMethod,
- String... regexPatterns) {
+ public static List regexMatchers(HttpMethod httpMethod, String... regexPatterns) {
String method = httpMethod == null ? null : httpMethod.toString();
List matchers = new ArrayList<>();
for (String pattern : regexPatterns) {
@@ -310,10 +282,8 @@ public abstract class AbstractRequestMatcherRegistry {
/**
* Create a {@link List} of {@link RegexRequestMatcher} instances that do not
* specify an {@link HttpMethod}.
- *
* @param regexPatterns the regular expressions to create
* {@link RegexRequestMatcher} from
- *
* @return a {@link List} of {@link RegexRequestMatcher} instances
*/
public static List regexMatchers(String... regexPatterns) {
@@ -322,6 +292,7 @@ public abstract class AbstractRequestMatcherRegistry {
private RequestMatchers() {
}
+
}
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java b/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java
index 510f40cba6..61d69ad820 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java
@@ -44,36 +44,29 @@ import org.springframework.security.web.session.ConcurrentSessionFilter;
import org.springframework.security.web.session.SessionManagementFilter;
/**
- *
* @author Rob Winch
- *
* @param
*/
-public interface HttpSecurityBuilder> extends
- SecurityBuilder {
+public interface HttpSecurityBuilder>
+ extends SecurityBuilder {
/**
* Gets the {@link SecurityConfigurer} by its class name or null if not
* found. Note that object hierarchies are not considered.
- *
* @param clazz the Class of the {@link SecurityConfigurer} to attempt to get.
*/
- > C getConfigurer(
- Class clazz);
+ > C getConfigurer(Class clazz);
/**
* Removes the {@link SecurityConfigurer} by its class name or null if
* not found. Note that object hierarchies are not considered.
- *
* @param clazz the Class of the {@link SecurityConfigurer} to attempt to remove.
* @return the {@link SecurityConfigurer} that was removed or null if not found
*/
- > C removeConfigurer(
- Class clazz);
+ > C removeConfigurer(Class clazz);
/**
* Sets an object that is shared by multiple {@link SecurityConfigurer}.
- *
* @param sharedType the Class to key the shared object by.
* @param object the Object to store
*/
@@ -81,7 +74,6 @@ public interface HttpSecurityBuilder> extends
/**
* Gets a shared Object. Note that object heirarchies are not considered.
- *
* @param sharedType the type of the shared Object
* @return the shared Object or null if it is not found
*/
@@ -89,7 +81,6 @@ public interface HttpSecurityBuilder> extends
/**
* Allows adding an additional {@link AuthenticationProvider} to be used
- *
* @param authenticationProvider the {@link AuthenticationProvider} to be added
* @return the {@link HttpSecurity} for further customizations
*/
@@ -97,7 +88,6 @@ public interface HttpSecurityBuilder> extends
/**
* Allows adding an additional {@link UserDetailsService} to be used
- *
* @param userDetailsService the {@link UserDetailsService} to be added
* @return the {@link HttpSecurity} for further customizations
*/
@@ -108,7 +98,6 @@ public interface HttpSecurityBuilder> extends
* known {@link Filter} instances are either a {@link Filter} listed in
* {@link #addFilter(Filter)} or a {@link Filter} that has already been added using
* {@link #addFilterAfter(Filter, Class)} or {@link #addFilterBefore(Filter, Class)}.
- *
* @param filter the {@link Filter} to register after the type {@code afterFilter}
* @param afterFilter the Class of the known {@link Filter}.
* @return the {@link HttpSecurity} for further customizations
@@ -120,7 +109,6 @@ public interface HttpSecurityBuilder> extends
* known {@link Filter} instances are either a {@link Filter} listed in
* {@link #addFilter(Filter)} or a {@link Filter} that has already been added using
* {@link #addFilterAfter(Filter, Class)} or {@link #addFilterBefore(Filter, Class)}.
- *
* @param filter the {@link Filter} to register before the type {@code beforeFilter}
* @param beforeFilter the Class of the known {@link Filter}.
* @return the {@link HttpSecurity} for further customizations
@@ -140,7 +128,8 @@ public interface HttpSecurityBuilder> extends
*
@@ -159,9 +148,9 @@ public interface HttpSecurityBuilder> extends
*
{@link FilterSecurityInterceptor}
*
{@link SwitchUserFilter}
*
- *
* @param filter the {@link Filter} to add
* @return the {@link HttpSecurity} for further customizations
*/
H addFilter(Filter filter);
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/WebSecurityConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/WebSecurityConfigurer.java
index e97f2cf4da..68da8c63e9 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/WebSecurityConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/WebSecurityConfigurer.java
@@ -28,17 +28,15 @@ import org.springframework.security.web.SecurityFilterChain;
/**
* Allows customization to the {@link WebSecurity}. In most instances users will use
* {@link EnableWebSecurity} and either create a {@link Configuration} that extends
- * {@link WebSecurityConfigurerAdapter} or expose a {@link SecurityFilterChain} bean.
- * Both will automatically be applied to the {@link WebSecurity} by the
+ * {@link WebSecurityConfigurerAdapter} or expose a {@link SecurityFilterChain} bean. Both
+ * will automatically be applied to the {@link WebSecurity} by the
* {@link EnableWebSecurity} annotation.
*
* @see WebSecurityConfigurerAdapter
* @see SecurityFilterChain
- *
* @author Rob Winch
* @since 3.2
*/
-public interface WebSecurityConfigurer> extends
- SecurityConfigurer {
+public interface WebSecurityConfigurer> extends SecurityConfigurer {
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterComparator.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterComparator.java
index 4b96267a59..f62ce4bafc 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterComparator.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterComparator.java
@@ -56,8 +56,11 @@ import org.springframework.web.filter.CorsFilter;
@SuppressWarnings("serial")
final class FilterComparator implements Comparator, Serializable {
+
private static final int INITIAL_ORDER = 100;
+
private static final int ORDER_STEP = 100;
+
private final Map filterToOrder = new HashMap<>();
FilterComparator() {
@@ -70,40 +73,35 @@ final class FilterComparator implements Comparator, Serializable {
put(CorsFilter.class, order.next());
put(CsrfFilter.class, order.next());
put(LogoutFilter.class, order.next());
- filterToOrder.put(
- "org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter",
+ filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter",
order.next());
filterToOrder.put(
"org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationRequestFilter",
order.next());
put(X509AuthenticationFilter.class, order.next());
put(AbstractPreAuthenticatedProcessingFilter.class, order.next());
- filterToOrder.put("org.springframework.security.cas.web.CasAuthenticationFilter",
- order.next());
- filterToOrder.put(
- "org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter",
+ filterToOrder.put("org.springframework.security.cas.web.CasAuthenticationFilter", order.next());
+ filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter",
order.next());
filterToOrder.put(
"org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter",
order.next());
put(UsernamePasswordAuthenticationFilter.class, order.next());
order.next(); // gh-8105
- filterToOrder.put(
- "org.springframework.security.openid.OpenIDAuthenticationFilter", order.next());
+ filterToOrder.put("org.springframework.security.openid.OpenIDAuthenticationFilter", order.next());
put(DefaultLoginPageGeneratingFilter.class, order.next());
put(DefaultLogoutPageGeneratingFilter.class, order.next());
put(ConcurrentSessionFilter.class, order.next());
put(DigestAuthenticationFilter.class, order.next());
- filterToOrder.put(
- "org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter", order.next());
+ filterToOrder.put("org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter",
+ order.next());
put(BasicAuthenticationFilter.class, order.next());
put(RequestCacheAwareFilter.class, order.next());
put(SecurityContextHolderAwareRequestFilter.class, order.next());
put(JaasApiIntegrationFilter.class, order.next());
put(RememberMeAuthenticationFilter.class, order.next());
put(AnonymousAuthenticationFilter.class, order.next());
- filterToOrder.put(
- "org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter",
+ filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter",
order.next());
put(SessionManagementFilter.class, order.next());
put(ExceptionTranslationFilter.class, order.next());
@@ -119,7 +117,6 @@ final class FilterComparator implements Comparator, Serializable {
/**
* Determines if a particular {@link Filter} is registered to be sorted
- *
* @param filter
* @return
*/
@@ -134,12 +131,10 @@ final class FilterComparator implements Comparator, Serializable {
* @param afterFilter the {@link Filter} that is already registered and that
* {@code filter} should be placed after.
*/
- public void registerAfter(Class extends Filter> filter,
- Class extends Filter> afterFilter) {
+ public void registerAfter(Class extends Filter> filter, Class extends Filter> afterFilter) {
Integer position = getOrder(afterFilter);
if (position == null) {
- throw new IllegalArgumentException(
- "Cannot register after unregistered Filter " + afterFilter);
+ throw new IllegalArgumentException("Cannot register after unregistered Filter " + afterFilter);
}
put(filter, position + 1);
@@ -151,12 +146,10 @@ final class FilterComparator implements Comparator, Serializable {
* @param atFilter the {@link Filter} that is already registered and that
* {@code filter} should be placed at.
*/
- public void registerAt(Class extends Filter> filter,
- Class extends Filter> atFilter) {
+ public void registerAt(Class extends Filter> filter, Class extends Filter> atFilter) {
Integer position = getOrder(atFilter);
if (position == null) {
- throw new IllegalArgumentException(
- "Cannot register after unregistered Filter " + atFilter);
+ throw new IllegalArgumentException("Cannot register after unregistered Filter " + atFilter);
}
put(filter, position);
@@ -169,12 +162,10 @@ final class FilterComparator implements Comparator, Serializable {
* @param beforeFilter the {@link Filter} that is already registered and that
* {@code filter} should be placed before.
*/
- public void registerBefore(Class extends Filter> filter,
- Class extends Filter> beforeFilter) {
+ public void registerBefore(Class extends Filter> filter, Class extends Filter> beforeFilter) {
Integer position = getOrder(beforeFilter);
if (position == null) {
- throw new IllegalArgumentException(
- "Cannot register after unregistered Filter " + beforeFilter);
+ throw new IllegalArgumentException("Cannot register after unregistered Filter " + beforeFilter);
}
put(filter, position - 1);
@@ -188,7 +179,6 @@ final class FilterComparator implements Comparator, Serializable {
/**
* Gets the order of a particular {@link Filter} class taking into consideration
* superclasses.
- *
* @param clazz the {@link Filter} class to determine the sort order
* @return the sort order or null if not defined
*/
@@ -206,6 +196,7 @@ final class FilterComparator implements Comparator, Serializable {
private static class Step {
private int value;
+
private final int stepSize;
Step(int initialValue, int stepSize) {
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java
index b056bdc898..e082f1fb57 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java
@@ -120,13 +120,15 @@ import javax.servlet.http.HttpServletRequest;
* @since 3.2
* @see EnableWebSecurity
*/
-public final class HttpSecurity extends
- AbstractConfiguredSecurityBuilder
- implements SecurityBuilder,
- HttpSecurityBuilder {
+public final class HttpSecurity extends AbstractConfiguredSecurityBuilder
+ implements SecurityBuilder, HttpSecurityBuilder {
+
private final RequestMatcherConfigurer requestMatcherConfigurer;
+
private List filters = new ArrayList<>();
+
private RequestMatcher requestMatcher = AnyRequestMatcher.INSTANCE;
+
private FilterComparator comparator = new FilterComparator();
/**
@@ -139,17 +141,14 @@ public final class HttpSecurity extends
*/
@SuppressWarnings("unchecked")
public HttpSecurity(ObjectPostProcessor objectPostProcessor,
- AuthenticationManagerBuilder authenticationBuilder,
- Map, Object> sharedObjects) {
+ AuthenticationManagerBuilder authenticationBuilder, Map, Object> sharedObjects) {
super(objectPostProcessor);
Assert.notNull(authenticationBuilder, "authenticationBuilder cannot be null");
setSharedObject(AuthenticationManagerBuilder.class, authenticationBuilder);
- for (Map.Entry, Object> entry : sharedObjects
- .entrySet()) {
+ for (Map.Entry, Object> entry : sharedObjects.entrySet()) {
setSharedObject((Class) entry.getKey(), entry.getValue());
}
- ApplicationContext context = (ApplicationContext) sharedObjects
- .get(ApplicationContext.class);
+ ApplicationContext context = (ApplicationContext) sharedObjects.get(ApplicationContext.class);
this.requestMatcherConfigurer = new RequestMatcherConfigurer(context);
}
@@ -231,11 +230,11 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link OpenIDLoginConfigurer} for further customizations.
* @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are
- * encouraged to migrate
- * to OpenID Connect, which is supported by spring-security-oauth2.
+ * encouraged to
+ * migrate to OpenID Connect, which is
+ * supported by spring-security-oauth2.
* @throws Exception
* @see OpenIDLoginConfigurer
*/
@@ -354,24 +353,25 @@ public final class HttpSecurity extends
*
*
* @see OpenIDLoginConfigurer
- *
- * @param openidLoginCustomizer the {@link Customizer} to provide more options for
- * the {@link OpenIDLoginConfigurer}
+ * @param openidLoginCustomizer the {@link Customizer} to provide more options for the
+ * {@link OpenIDLoginConfigurer}
* @deprecated The OpenID 1.0 and 2.0 protocols have been deprecated and users are
- * encouraged to migrate
- * to OpenID Connect, which is supported by spring-security-oauth2.
+ * encouraged to
+ * migrate to OpenID Connect, which is
+ * supported by spring-security-oauth2.
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity openidLogin(Customizer> openidLoginCustomizer) throws Exception {
+ public HttpSecurity openidLogin(Customizer> openidLoginCustomizer)
+ throws Exception {
openidLoginCustomizer.customize(getOrApply(new OpenIDLoginConfigurer<>()));
return HttpSecurity.this;
}
/**
* Adds the Security headers to the response. This is activated by default when using
- * {@link WebSecurityConfigurerAdapter}'s default constructor. Accepting the
- * default provided by {@link WebSecurityConfigurerAdapter} or only invoking
+ * {@link WebSecurityConfigurerAdapter}'s default constructor. Accepting the default
+ * provided by {@link WebSecurityConfigurerAdapter} or only invoking
* {@link #headers()} without invoking additional methods on it, is the equivalent of:
*
*
@@ -415,9 +415,9 @@ public final class HttpSecurity extends
*
*
* You can enable only a few of the headers by first invoking
- * {@link HeadersConfigurer#defaultsDisabled()}
- * and then invoking the appropriate methods on the {@link #headers()} result.
- * For example, the following will enable {@link HeadersConfigurer#cacheControl()} and
+ * {@link HeadersConfigurer#defaultsDisabled()} and then invoking the appropriate
+ * methods on the {@link #headers()} result. For example, the following will enable
+ * {@link HeadersConfigurer#cacheControl()} and
* {@link HeadersConfigurer#frameOptions()} only.
*
*
@@ -439,8 +439,8 @@ public final class HttpSecurity extends
* }
*
*
- * You can also choose to keep the defaults but explicitly disable a subset of headers.
- * For example, the following will enable all the default headers except
+ * You can also choose to keep the defaults but explicitly disable a subset of
+ * headers. For example, the following will enable all the default headers except
* {@link HeadersConfigurer#frameOptions()}.
*
*
@@ -459,7 +459,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link HeadersConfigurer} for further customizations
* @throws Exception
* @see HeadersConfigurer
@@ -474,8 +473,9 @@ public final class HttpSecurity extends
*
*
Example Configurations
*
- * Accepting the default provided by {@link WebSecurityConfigurerAdapter} or only invoking
- * {@link #headers()} without invoking additional methods on it, is the equivalent of:
+ * Accepting the default provided by {@link WebSecurityConfigurerAdapter} or only
+ * invoking {@link #headers()} without invoking additional methods on it, is the
+ * equivalent of:
*
*
* @Configuration
@@ -513,9 +513,9 @@ public final class HttpSecurity extends
*
*
* You can enable only a few of the headers by first invoking
- * {@link HeadersConfigurer#defaultsDisabled()}
- * and then invoking the appropriate methods on the {@link #headers()} result.
- * For example, the following will enable {@link HeadersConfigurer#cacheControl()} and
+ * {@link HeadersConfigurer#defaultsDisabled()} and then invoking the appropriate
+ * methods on the {@link #headers()} result. For example, the following will enable
+ * {@link HeadersConfigurer#cacheControl()} and
* {@link HeadersConfigurer#frameOptions()} only.
*
*
@@ -536,8 +536,8 @@ public final class HttpSecurity extends
* }
*
*
- * You can also choose to keep the defaults but explicitly disable a subset of headers.
- * For example, the following will enable all the default headers except
+ * You can also choose to keep the defaults but explicitly disable a subset of
+ * headers. For example, the following will enable all the default headers except
* {@link HeadersConfigurer#frameOptions()}.
*
*
@@ -554,9 +554,8 @@ public final class HttpSecurity extends
* );
* }
*
- *
- * @param headersCustomizer the {@link Customizer} to provide more options for
- * the {@link HeadersConfigurer}
+ * @param headersCustomizer the {@link Customizer} to provide more options for the
+ * {@link HeadersConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
@@ -570,7 +569,6 @@ public final class HttpSecurity extends
* provided, that {@link CorsFilter} is used. Else if corsConfigurationSource is
* defined, then that {@link CorsConfiguration} is used. Otherwise, if Spring MVC is
* on the classpath a {@link HandlerMappingIntrospector} is used.
- *
* @return the {@link CorsConfigurer} for customizations
* @throws Exception
*/
@@ -582,8 +580,8 @@ public final class HttpSecurity extends
* Adds a {@link CorsFilter} to be used. If a bean by the name of corsFilter is
* provided, that {@link CorsFilter} is used. Else if corsConfigurationSource is
* defined, then that {@link CorsConfiguration} is used. Otherwise, if Spring MVC is
- * on the classpath a {@link HandlerMappingIntrospector} is used.
- * You can enable CORS using:
+ * on the classpath a {@link HandlerMappingIntrospector} is used. You can enable CORS
+ * using:
*
*
* @Configuration
@@ -597,9 +595,8 @@ public final class HttpSecurity extends
* }
* }
*
- *
- * @param corsCustomizer the {@link Customizer} to provide more options for
- * the {@link CorsConfigurer}
+ * @param corsCustomizer the {@link Customizer} to provide more options for the
+ * {@link CorsConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
@@ -652,7 +649,6 @@ public final class HttpSecurity extends
* Alternatively,
* {@link AbstractSecurityWebApplicationInitializer#enableHttpSessionEventPublisher()}
* could return true.
- *
* @return the {@link SessionManagementConfigurer} for further customizations
* @throws Exception
*/
@@ -713,13 +709,13 @@ public final class HttpSecurity extends
* Alternatively,
* {@link AbstractSecurityWebApplicationInitializer#enableHttpSessionEventPublisher()}
* could return true.
- *
- * @param sessionManagementCustomizer the {@link Customizer} to provide more options for
- * the {@link SessionManagementConfigurer}
+ * @param sessionManagementCustomizer the {@link Customizer} to provide more options
+ * for the {@link SessionManagementConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity sessionManagement(Customizer> sessionManagementCustomizer) throws Exception {
+ public HttpSecurity sessionManagement(
+ Customizer> sessionManagementCustomizer) throws Exception {
sessionManagementCustomizer.customize(getOrApply(new SessionManagementConfigurer<>()));
return HttpSecurity.this;
}
@@ -758,7 +754,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link PortMapperConfigurer} for further customizations
* @throws Exception
* @see #requiresChannel()
@@ -804,19 +799,20 @@ public final class HttpSecurity extends
*
*
* @see #requiresChannel()
- * @param portMapperCustomizer the {@link Customizer} to provide more options for
- * the {@link PortMapperConfigurer}
+ * @param portMapperCustomizer the {@link Customizer} to provide more options for the
+ * {@link PortMapperConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity portMapper(Customizer> portMapperCustomizer) throws Exception {
+ public HttpSecurity portMapper(Customizer> portMapperCustomizer)
+ throws Exception {
portMapperCustomizer.customize(getOrApply(new PortMapperConfigurer<>()));
return HttpSecurity.this;
}
/**
- * Configures container based pre authentication. In this case, authentication
- * is managed by the Servlet Container.
+ * Configures container based pre authentication. In this case, authentication is
+ * managed by the Servlet Container.
*
*
Example Configuration
*
@@ -878,7 +874,6 @@ public final class HttpSecurity extends
* Last you will need to configure your container to contain the user with the correct
* roles. This configuration is specific to the Servlet Container, so consult your
* Servlet Container's documentation.
- *
* @return the {@link JeeConfigurer} for further customizations
* @throws Exception
*/
@@ -887,8 +882,8 @@ public final class HttpSecurity extends
}
/**
- * Configures container based pre authentication. In this case, authentication
- * is managed by the Servlet Container.
+ * Configures container based pre authentication. In this case, authentication is
+ * managed by the Servlet Container.
*
*
Example Configuration
*
@@ -956,9 +951,8 @@ public final class HttpSecurity extends
* Last you will need to configure your container to contain the user with the correct
* roles. This configuration is specific to the Servlet Container, so consult your
* Servlet Container's documentation.
- *
- * @param jeeCustomizer the {@link Customizer} to provide more options for
- * the {@link JeeConfigurer}
+ * @param jeeCustomizer the {@link Customizer} to provide more options for the
+ * {@link JeeConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
@@ -989,7 +983,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link X509Configurer} for further customizations
* @throws Exception
*/
@@ -1022,9 +1015,8 @@ public final class HttpSecurity extends
* }
* }
*
- *
- * @param x509Customizer the {@link Customizer} to provide more options for
- * the {@link X509Configurer}
+ * @param x509Customizer the {@link Customizer} to provide more options for the
+ * {@link X509Configurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
@@ -1062,7 +1054,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link RememberMeConfigurer} for further customizations
* @throws Exception
*/
@@ -1097,13 +1088,13 @@ public final class HttpSecurity extends
* }
* }
*
- *
- * @param rememberMeCustomizer the {@link Customizer} to provide more options for
- * the {@link RememberMeConfigurer}
+ * @param rememberMeCustomizer the {@link Customizer} to provide more options for the
+ * {@link RememberMeConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity rememberMe(Customizer> rememberMeCustomizer) throws Exception {
+ public HttpSecurity rememberMe(Customizer> rememberMeCustomizer)
+ throws Exception {
rememberMeCustomizer.customize(getOrApply(new RememberMeConfigurer<>()));
return HttpSecurity.this;
}
@@ -1169,15 +1160,13 @@ public final class HttpSecurity extends
*
*
* @see #requestMatcher(RequestMatcher)
- *
* @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations
* @throws Exception
*/
public ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry authorizeRequests()
throws Exception {
ApplicationContext context = getContext();
- return getOrApply(new ExpressionUrlAuthorizationConfigurer<>(context))
- .getRegistry();
+ return getOrApply(new ExpressionUrlAuthorizationConfigurer<>(context)).getRegistry();
}
/**
@@ -1251,17 +1240,17 @@ public final class HttpSecurity extends
*
*
* @see #requestMatcher(RequestMatcher)
- *
- * @param authorizeRequestsCustomizer the {@link Customizer} to provide more options for
- * the {@link ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry}
+ * @param authorizeRequestsCustomizer the {@link Customizer} to provide more options
+ * for the {@link ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity authorizeRequests(Customizer.ExpressionInterceptUrlRegistry> authorizeRequestsCustomizer)
+ public HttpSecurity authorizeRequests(
+ Customizer.ExpressionInterceptUrlRegistry> authorizeRequestsCustomizer)
throws Exception {
ApplicationContext context = getContext();
- authorizeRequestsCustomizer.customize(getOrApply(new ExpressionUrlAuthorizationConfigurer<>(context))
- .getRegistry());
+ authorizeRequestsCustomizer
+ .customize(getOrApply(new ExpressionUrlAuthorizationConfigurer<>(context)).getRegistry());
return HttpSecurity.this;
}
@@ -1271,7 +1260,6 @@ public final class HttpSecurity extends
* a login page. After authentication, Spring Security will redirect the user to the
* originally requested protected page (/protected). This is automatically applied
* when using {@link WebSecurityConfigurerAdapter}.
- *
* @return the {@link RequestCacheConfigurer} for further customizations
* @throws Exception
*/
@@ -1308,7 +1296,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @param requestCacheCustomizer the {@link Customizer} to provide more options for
* the {@link RequestCacheConfigurer}
* @return the {@link HttpSecurity} for further customizations
@@ -1323,7 +1310,6 @@ public final class HttpSecurity extends
/**
* Allows configuring exception handling. This is automatically applied when using
* {@link WebSecurityConfigurerAdapter}.
- *
* @return the {@link ExceptionHandlingConfigurer} for further customizations
* @throws Exception
*/
@@ -1337,8 +1323,8 @@ public final class HttpSecurity extends
*
*
Example Custom Configuration
*
- * The following customization will ensure that users who are denied access are forwarded
- * to the page "/errors/access-denied".
+ * The following customization will ensure that users who are denied access are
+ * forwarded to the page "/errors/access-denied".
*
*
* @Configuration
@@ -1360,13 +1346,13 @@ public final class HttpSecurity extends
* }
* }
*
- *
- * @param exceptionHandlingCustomizer the {@link Customizer} to provide more options for
- * the {@link ExceptionHandlingConfigurer}
+ * @param exceptionHandlingCustomizer the {@link Customizer} to provide more options
+ * for the {@link ExceptionHandlingConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity exceptionHandling(Customizer> exceptionHandlingCustomizer) throws Exception {
+ public HttpSecurity exceptionHandling(
+ Customizer> exceptionHandlingCustomizer) throws Exception {
exceptionHandlingCustomizer.customize(getOrApply(new ExceptionHandlingConfigurer<>()));
return HttpSecurity.this;
}
@@ -1375,7 +1361,6 @@ public final class HttpSecurity extends
* Sets up management of the {@link SecurityContext} on the
* {@link SecurityContextHolder} between {@link HttpServletRequest}'s. This is
* automatically applied when using {@link WebSecurityConfigurerAdapter}.
- *
* @return the {@link SecurityContextConfigurer} for further customizations
* @throws Exception
*/
@@ -1405,13 +1390,13 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @param securityContextCustomizer the {@link Customizer} to provide more options for
* the {@link SecurityContextConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity securityContext(Customizer> securityContextCustomizer) throws Exception {
+ public HttpSecurity securityContext(Customizer> securityContextCustomizer)
+ throws Exception {
securityContextCustomizer.customize(getOrApply(new SecurityContextConfigurer<>()));
return HttpSecurity.this;
}
@@ -1420,7 +1405,6 @@ public final class HttpSecurity extends
* Integrates the {@link HttpServletRequest} methods with the values found on the
* {@link SecurityContext}. This is automatically applied when using
* {@link WebSecurityConfigurerAdapter}.
- *
* @return the {@link ServletApiConfigurer} for further customizations
* @throws Exception
*/
@@ -1447,13 +1431,13 @@ public final class HttpSecurity extends
* }
* }
*
- *
- * @param servletApiCustomizer the {@link Customizer} to provide more options for
- * the {@link ServletApiConfigurer}
+ * @param servletApiCustomizer the {@link Customizer} to provide more options for the
+ * {@link ServletApiConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity servletApi(Customizer> servletApiCustomizer) throws Exception {
+ public HttpSecurity servletApi(Customizer> servletApiCustomizer)
+ throws Exception {
servletApiCustomizer.customize(getOrApply(new ServletApiConfigurer<>()));
return HttpSecurity.this;
}
@@ -1476,7 +1460,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link CsrfConfigurer} for further customizations
* @throws Exception
*/
@@ -1502,9 +1485,8 @@ public final class HttpSecurity extends
* }
* }
*
- *
- * @param csrfCustomizer the {@link Customizer} to provide more options for
- * the {@link CsrfConfigurer}
+ * @param csrfCustomizer the {@link Customizer} to provide more options for the
+ * {@link CsrfConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
@@ -1547,7 +1529,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link LogoutConfigurer} for further customizations
* @throws Exception
*/
@@ -1591,9 +1572,8 @@ public final class HttpSecurity extends
* }
* }
*
- *
- * @param logoutCustomizer the {@link Customizer} to provide more options for
- * the {@link LogoutConfigurer}
+ * @param logoutCustomizer the {@link Customizer} to provide more options for the
+ * {@link LogoutConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
@@ -1665,7 +1645,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link AnonymousConfigurer} for further customizations
* @throws Exception
*/
@@ -1736,9 +1715,8 @@ public final class HttpSecurity extends
* }
* }
*
- *
- * @param anonymousCustomizer the {@link Customizer} to provide more options for
- * the {@link AnonymousConfigurer}
+ * @param anonymousCustomizer the {@link Customizer} to provide more options for the
+ * {@link AnonymousConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
@@ -1747,7 +1725,6 @@ public final class HttpSecurity extends
return HttpSecurity.this;
}
-
/**
* Specifies to support form based authentication. If
* {@link FormLoginConfigurer#loginPage(String)} is not specified a default login page
@@ -1804,7 +1781,6 @@ public final class HttpSecurity extends
*
*
* @see FormLoginConfigurer#loginPage(String)
- *
* @return the {@link FormLoginConfigurer} for further customizations
* @throws Exception
*/
@@ -1868,9 +1844,8 @@ public final class HttpSecurity extends
*
*
* @see FormLoginConfigurer#loginPage(String)
- *
- * @param formLoginCustomizer the {@link Customizer} to provide more options for
- * the {@link FormLoginConfigurer}
+ * @param formLoginCustomizer the {@link Customizer} to provide more options for the
+ * {@link FormLoginConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
@@ -1880,40 +1855,39 @@ public final class HttpSecurity extends
}
/**
- * Configures authentication support using an SAML 2.0 Service Provider.
- *
+ * Configures authentication support using an SAML 2.0 Service Provider.
*
*
- * The "authentication flow" is implemented using the Web Browser SSO Profile, using POST and REDIRECT bindings,
- * as documented in the SAML V2.0 Core,Profiles and Bindings
- * specifications.
- *
+ * The "authentication flow" is implemented using the Web Browser SSO
+ * Profile, using POST and REDIRECT bindings, as documented in the
+ * SAML V2.0
+ * Core,Profiles and Bindings specifications.
*
*
- * As a prerequisite to using this feature, is that you have a SAML v2.0 Identity Provider to provide an assertion.
- * The representation of the Service Provider, the relying party, and the remote Identity Provider, the asserting party
- * is contained within {@link RelyingPartyRegistration}.
- *
+ * As a prerequisite to using this feature, is that you have a SAML v2.0 Identity
+ * Provider to provide an assertion. The representation of the Service Provider, the
+ * relying party, and the remote Identity Provider, the asserting party is contained
+ * within {@link RelyingPartyRegistration}.
*
*
* {@link RelyingPartyRegistration}(s) are composed within a
- * {@link RelyingPartyRegistrationRepository},
- * which is required and must be registered with the {@link ApplicationContext} or
- * configured via saml2Login().relyingPartyRegistrationRepository(..).
- *
+ * {@link RelyingPartyRegistrationRepository}, which is required and must be
+ * registered with the {@link ApplicationContext} or configured via
+ * saml2Login().relyingPartyRegistrationRepository(..).
*
*
- * The default configuration provides an auto-generated login page at "/login" and
- * redirects to "/login?error" when an authentication error occurs.
- * The login page will display each of the identity providers with a link
- * that is capable of initiating the "authentication flow".
- *
+ * The default configuration provides an auto-generated login page at
+ * "/login" and redirects to
+ * "/login?error" when an authentication error occurs. The
+ * login page will display each of the identity providers with a link that is capable
+ * of initiating the "authentication flow".
*
*
*
*
Example Configuration
*
- * The following example shows the minimal configuration required, using SimpleSamlPhp as the Authentication Provider.
+ * The following example shows the minimal configuration required, using SimpleSamlPhp
+ * as the Authentication Provider.
*
*
* @Configuration
@@ -1971,40 +1945,39 @@ public final class HttpSecurity extends
}
/**
- * Configures authentication support using an SAML 2.0 Service Provider.
- *
+ * Configures authentication support using an SAML 2.0 Service Provider.
*
*
- * The "authentication flow" is implemented using the Web Browser SSO Profile, using POST and REDIRECT bindings,
- * as documented in the SAML V2.0 Core,Profiles and Bindings
- * specifications.
- *
+ * The "authentication flow" is implemented using the Web Browser SSO
+ * Profile, using POST and REDIRECT bindings, as documented in the
+ * SAML V2.0
+ * Core,Profiles and Bindings specifications.
*
*
- * As a prerequisite to using this feature, is that you have a SAML v2.0 Identity Provider to provide an assertion.
- * The representation of the Service Provider, the relying party, and the remote Identity Provider, the asserting party
- * is contained within {@link RelyingPartyRegistration}.
- *
+ * As a prerequisite to using this feature, is that you have a SAML v2.0 Identity
+ * Provider to provide an assertion. The representation of the Service Provider, the
+ * relying party, and the remote Identity Provider, the asserting party is contained
+ * within {@link RelyingPartyRegistration}.
*
*
* {@link RelyingPartyRegistration}(s) are composed within a
- * {@link RelyingPartyRegistrationRepository},
- * which is required and must be registered with the {@link ApplicationContext} or
- * configured via saml2Login().relyingPartyRegistrationRepository(..).
- *
+ * {@link RelyingPartyRegistrationRepository}, which is required and must be
+ * registered with the {@link ApplicationContext} or configured via
+ * saml2Login().relyingPartyRegistrationRepository(..).
*
*
- * The default configuration provides an auto-generated login page at "/login" and
- * redirects to "/login?error" when an authentication error occurs.
- * The login page will display each of the identity providers with a link
- * that is capable of initiating the "authentication flow".
- *
+ * The default configuration provides an auto-generated login page at
+ * "/login" and redirects to
+ * "/login?error" when an authentication error occurs. The
+ * login page will display each of the identity providers with a link that is capable
+ * of initiating the "authentication flow".
*
*
*
*
Example Configuration
*
- * The following example shows the minimal configuration required, using SimpleSamlPhp as the Authentication Provider.
+ * The following example shows the minimal configuration required, using SimpleSamlPhp
+ * as the Authentication Provider.
*
*
* @Configuration
@@ -2054,53 +2027,57 @@ public final class HttpSecurity extends
*
*
* @since 5.2
- * @param saml2LoginCustomizer the {@link Customizer} to provide more options for
- * the {@link Saml2LoginConfigurer}
+ * @param saml2LoginCustomizer the {@link Customizer} to provide more options for the
+ * {@link Saml2LoginConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity saml2Login(Customizer> saml2LoginCustomizer) throws Exception {
+ public HttpSecurity saml2Login(Customizer> saml2LoginCustomizer)
+ throws Exception {
saml2LoginCustomizer.customize(getOrApply(new Saml2LoginConfigurer<>()));
return HttpSecurity.this;
}
/**
- * Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.
- *
+ * Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0
+ * Provider.
*
*
- * The "authentication flow" is implemented using the Authorization Code Grant, as specified in the
- * OAuth 2.0 Authorization Framework
- * and OpenID Connect Core 1.0
- * specification.
- *
+ * The "authentication flow" is implemented using the Authorization Code
+ * Grant, as specified in the
+ * OAuth 2.0
+ * Authorization Framework and OpenID Connect
+ * Core 1.0 specification.
*
*
- * As a prerequisite to using this feature, you must register a client with a provider.
- * The client registration information may than be used for configuring
- * a {@link org.springframework.security.oauth2.client.registration.ClientRegistration} using a
+ * As a prerequisite to using this feature, you must register a client with a
+ * provider. The client registration information may than be used for configuring a
+ * {@link org.springframework.security.oauth2.client.registration.ClientRegistration}
+ * using a
* {@link org.springframework.security.oauth2.client.registration.ClientRegistration.Builder}.
*
*
*
- * {@link org.springframework.security.oauth2.client.registration.ClientRegistration}(s) are composed within a
+ * {@link org.springframework.security.oauth2.client.registration.ClientRegistration}(s)
+ * are composed within a
* {@link org.springframework.security.oauth2.client.registration.ClientRegistrationRepository},
- * which is required and must be registered with the {@link ApplicationContext} or
- * configured via oauth2Login().clientRegistrationRepository(..).
- *
+ * which is required and must be registered with the {@link ApplicationContext}
+ * or configured via oauth2Login().clientRegistrationRepository(..).
*
*
- * The default configuration provides an auto-generated login page at "/login" and
- * redirects to "/login?error" when an authentication error occurs.
- * The login page will display each of the clients with a link
- * that is capable of initiating the "authentication flow".
- *
+ * The default configuration provides an auto-generated login page at
+ * "/login" and redirects to
+ * "/login?error" when an authentication error occurs. The
+ * login page will display each of the clients with a link that is capable of
+ * initiating the "authentication flow".
*
*
*
*
Example Configuration
*
- * The following example shows the minimal configuration required, using Google as the Authentication Provider.
+ * The following example shows the minimal configuration required, using Google as the
+ * Authentication Provider.
*
*
* @Configuration
@@ -2143,11 +2120,16 @@ public final class HttpSecurity extends
*
*
*
- * For more advanced configuration, see {@link OAuth2LoginConfigurer} for available options to customize the defaults.
+ * For more advanced configuration, see {@link OAuth2LoginConfigurer} for available
+ * options to customize the defaults.
*
* @since 5.0
- * @see Section 4.1 Authorization Code Grant
- * @see Section 3.1 Authorization Code Flow
+ * @see Section 4.1 Authorization Code
+ * Grant
+ * @see Section 3.1
+ * Authorization Code Flow
* @see org.springframework.security.oauth2.client.registration.ClientRegistration
* @see org.springframework.security.oauth2.client.registration.ClientRegistrationRepository
* @return the {@link OAuth2LoginConfigurer} for further customizations
@@ -2158,42 +2140,45 @@ public final class HttpSecurity extends
}
/**
- * Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.
- *
+ * Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0
+ * Provider.
*
*
- * The "authentication flow" is implemented using the Authorization Code Grant, as specified in the
- * OAuth 2.0 Authorization Framework
- * and OpenID Connect Core 1.0
- * specification.
- *
+ * The "authentication flow" is implemented using the Authorization Code
+ * Grant, as specified in the
+ * OAuth 2.0
+ * Authorization Framework and OpenID Connect
+ * Core 1.0 specification.
*
*
- * As a prerequisite to using this feature, you must register a client with a provider.
- * The client registration information may than be used for configuring
- * a {@link org.springframework.security.oauth2.client.registration.ClientRegistration} using a
+ * As a prerequisite to using this feature, you must register a client with a
+ * provider. The client registration information may than be used for configuring a
+ * {@link org.springframework.security.oauth2.client.registration.ClientRegistration}
+ * using a
* {@link org.springframework.security.oauth2.client.registration.ClientRegistration.Builder}.
*
*
*
- * {@link org.springframework.security.oauth2.client.registration.ClientRegistration}(s) are composed within a
+ * {@link org.springframework.security.oauth2.client.registration.ClientRegistration}(s)
+ * are composed within a
* {@link org.springframework.security.oauth2.client.registration.ClientRegistrationRepository},
- * which is required and must be registered with the {@link ApplicationContext} or
- * configured via oauth2Login().clientRegistrationRepository(..).
- *
+ * which is required and must be registered with the {@link ApplicationContext}
+ * or configured via oauth2Login().clientRegistrationRepository(..).
*
*
- * The default configuration provides an auto-generated login page at "/login" and
- * redirects to "/login?error" when an authentication error occurs.
- * The login page will display each of the clients with a link
- * that is capable of initiating the "authentication flow".
- *
+ * The default configuration provides an auto-generated login page at
+ * "/login" and redirects to
+ * "/login?error" when an authentication error occurs. The
+ * login page will display each of the clients with a link that is capable of
+ * initiating the "authentication flow".
*
*
*
*
Example Configuration
*
- * The following example shows the minimal configuration required, using Google as the Authentication Provider.
+ * The following example shows the minimal configuration required, using Google as the
+ * Authentication Provider.
*
*
* @Configuration
@@ -2237,19 +2222,24 @@ public final class HttpSecurity extends
*
*
*
- * For more advanced configuration, see {@link OAuth2LoginConfigurer} for available options to customize the defaults.
+ * For more advanced configuration, see {@link OAuth2LoginConfigurer} for available
+ * options to customize the defaults.
*
- * @see Section 4.1 Authorization Code Grant
- * @see Section 3.1 Authorization Code Flow
+ * @see Section 4.1 Authorization Code
+ * Grant
+ * @see Section 3.1
+ * Authorization Code Flow
* @see org.springframework.security.oauth2.client.registration.ClientRegistration
* @see org.springframework.security.oauth2.client.registration.ClientRegistrationRepository
- *
- * @param oauth2LoginCustomizer the {@link Customizer} to provide more options for
- * the {@link OAuth2LoginConfigurer}
+ * @param oauth2LoginCustomizer the {@link Customizer} to provide more options for the
+ * {@link OAuth2LoginConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity oauth2Login(Customizer> oauth2LoginCustomizer) throws Exception {
+ public HttpSecurity oauth2Login(Customizer> oauth2LoginCustomizer)
+ throws Exception {
oauth2LoginCustomizer.customize(getOrApply(new OAuth2LoginConfigurer<>()));
return HttpSecurity.this;
}
@@ -2258,7 +2248,9 @@ public final class HttpSecurity extends
* Configures OAuth 2.0 Client support.
*
* @since 5.1
- * @see OAuth 2.0 Authorization Framework
+ * @see OAuth 2.0 Authorization
+ * Framework
* @return the {@link OAuth2ClientConfigurer} for further customizations
* @throws Exception
*/
@@ -2273,7 +2265,8 @@ public final class HttpSecurity extends
*
*
Example Configuration
*
- * The following example demonstrates how to enable OAuth 2.0 Client support for all endpoints.
+ * The following example demonstrates how to enable OAuth 2.0 Client support for all
+ * endpoints.
*
*
* @Configuration
@@ -2291,14 +2284,16 @@ public final class HttpSecurity extends
* }
*
*
- * @see OAuth 2.0 Authorization Framework
- *
+ * @see OAuth 2.0 Authorization
+ * Framework
* @param oauth2ClientCustomizer the {@link Customizer} to provide more options for
* the {@link OAuth2ClientConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity oauth2Client(Customizer> oauth2ClientCustomizer) throws Exception {
+ public HttpSecurity oauth2Client(Customizer> oauth2ClientCustomizer)
+ throws Exception {
oauth2ClientCustomizer.customize(getOrApply(new OAuth2ClientConfigurer<>()));
return HttpSecurity.this;
}
@@ -2307,12 +2302,15 @@ public final class HttpSecurity extends
* Configures OAuth 2.0 Resource Server support.
*
* @since 5.1
- * @see OAuth 2.0 Authorization Framework
+ * @see OAuth 2.0 Authorization
+ * Framework
* @return the {@link OAuth2ResourceServerConfigurer} for further customizations
* @throws Exception
*/
public OAuth2ResourceServerConfigurer oauth2ResourceServer() throws Exception {
- OAuth2ResourceServerConfigurer configurer = getOrApply(new OAuth2ResourceServerConfigurer<>(getContext()));
+ OAuth2ResourceServerConfigurer configurer = getOrApply(
+ new OAuth2ResourceServerConfigurer<>(getContext()));
this.postProcess(configurer);
return configurer;
}
@@ -2322,7 +2320,8 @@ public final class HttpSecurity extends
*
*
Example Configuration
*
- * The following example demonstrates how to configure a custom JWT authentication converter.
+ * The following example demonstrates how to configure a custom JWT authentication
+ * converter.
*
*
* @Configuration
@@ -2355,16 +2354,18 @@ public final class HttpSecurity extends
* }
*
*
- * @see OAuth 2.0 Authorization Framework
- *
- * @param oauth2ResourceServerCustomizer the {@link Customizer} to provide more options for
- * the {@link OAuth2ResourceServerConfigurer}
+ * @see OAuth 2.0 Authorization
+ * Framework
+ * @param oauth2ResourceServerCustomizer the {@link Customizer} to provide more
+ * options for the {@link OAuth2ResourceServerConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity oauth2ResourceServer(Customizer> oauth2ResourceServerCustomizer)
- throws Exception {
- OAuth2ResourceServerConfigurer configurer = getOrApply(new OAuth2ResourceServerConfigurer<>(getContext()));
+ public HttpSecurity oauth2ResourceServer(
+ Customizer> oauth2ResourceServerCustomizer) throws Exception {
+ OAuth2ResourceServerConfigurer configurer = getOrApply(
+ new OAuth2ResourceServerConfigurer<>(getContext()));
this.postProcess(configurer);
oauth2ResourceServerCustomizer.customize(configurer);
return HttpSecurity.this;
@@ -2379,8 +2380,8 @@ public final class HttpSecurity extends
* The example below demonstrates how to require HTTPs for every request. Only
* requiring HTTPS for some requests is supported, but not recommended since an
* application that allows for HTTP introduces many security vulnerabilities. For one
- * such example, read about Firesheep.
+ * such example, read about
+ * Firesheep.
*
*
* @Configuration
@@ -2399,16 +2400,12 @@ public final class HttpSecurity extends
* }
* }
*
- *
- *
* @return the {@link ChannelSecurityConfigurer} for further customizations
* @throws Exception
*/
- public ChannelSecurityConfigurer.ChannelRequestMatcherRegistry requiresChannel()
- throws Exception {
+ public ChannelSecurityConfigurer.ChannelRequestMatcherRegistry requiresChannel() throws Exception {
ApplicationContext context = getContext();
- return getOrApply(new ChannelSecurityConfigurer<>(context))
- .getRegistry();
+ return getOrApply(new ChannelSecurityConfigurer<>(context)).getRegistry();
}
/**
@@ -2420,8 +2417,8 @@ public final class HttpSecurity extends
* The example below demonstrates how to require HTTPs for every request. Only
* requiring HTTPS for some requests is supported, but not recommended since an
* application that allows for HTTP introduces many security vulnerabilities. For one
- * such example, read about Firesheep.
+ * such example, read about
+ * Firesheep.
*
*
* @Configuration
@@ -2443,17 +2440,16 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @param requiresChannelCustomizer the {@link Customizer} to provide more options for
* the {@link ChannelSecurityConfigurer.ChannelRequestMatcherRegistry}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
- public HttpSecurity requiresChannel(Customizer.ChannelRequestMatcherRegistry> requiresChannelCustomizer)
+ public HttpSecurity requiresChannel(
+ Customizer.ChannelRequestMatcherRegistry> requiresChannelCustomizer)
throws Exception {
ApplicationContext context = getContext();
- requiresChannelCustomizer.customize(getOrApply(new ChannelSecurityConfigurer<>(context))
- .getRegistry());
+ requiresChannelCustomizer.customize(getOrApply(new ChannelSecurityConfigurer<>(context)).getRegistry());
return HttpSecurity.this;
}
@@ -2463,8 +2459,8 @@ public final class HttpSecurity extends
*
Example Configuration
*
* The example below demonstrates how to configure HTTP Basic authentication for an
- * application. The default realm is "Realm", but can be
- * customized using {@link HttpBasicConfigurer#realmName(String)}.
+ * application. The default realm is "Realm", but can be customized using
+ * {@link HttpBasicConfigurer#realmName(String)}.
*
*
* @Configuration
@@ -2482,7 +2478,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link HttpBasicConfigurer} for further customizations
* @throws Exception
*/
@@ -2496,8 +2491,8 @@ public final class HttpSecurity extends
*
Example Configuration
*
* The example below demonstrates how to configure HTTP Basic authentication for an
- * application. The default realm is "Realm", but can be
- * customized using {@link HttpBasicConfigurer#realmName(String)}.
+ * application. The default realm is "Realm", but can be customized using
+ * {@link HttpBasicConfigurer#realmName(String)}.
*
*
* @Configuration
@@ -2515,9 +2510,8 @@ public final class HttpSecurity extends
* }
* }
*
- *
- * @param httpBasicCustomizer the {@link Customizer} to provide more options for
- * the {@link HttpBasicConfigurer}
+ * @param httpBasicCustomizer the {@link Customizer} to provide more options for the
+ * {@link HttpBasicConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
@@ -2544,12 +2538,11 @@ public final class HttpSecurity extends
/*
* (non-Javadoc)
*
- * @see
- * org.springframework.security.config.annotation.web.HttpSecurityBuilder#authenticationProvider
+ * @see org.springframework.security.config.annotation.web.HttpSecurityBuilder#
+ * authenticationProvider
* (org.springframework.security.authentication.AuthenticationProvider)
*/
- public HttpSecurity authenticationProvider(
- AuthenticationProvider authenticationProvider) {
+ public HttpSecurity authenticationProvider(AuthenticationProvider authenticationProvider) {
getAuthenticationRegistry().authenticationProvider(authenticationProvider);
return this;
}
@@ -2557,12 +2550,11 @@ public final class HttpSecurity extends
/*
* (non-Javadoc)
*
- * @see
- * org.springframework.security.config.annotation.web.HttpSecurityBuilder#userDetailsService
+ * @see org.springframework.security.config.annotation.web.HttpSecurityBuilder#
+ * userDetailsService
* (org.springframework.security.core.userdetails.UserDetailsService)
*/
- public HttpSecurity userDetailsService(UserDetailsService userDetailsService)
- throws Exception {
+ public HttpSecurity userDetailsService(UserDetailsService userDetailsService) throws Exception {
getAuthenticationRegistry().userDetailsService(userDetailsService);
return this;
}
@@ -2574,9 +2566,8 @@ public final class HttpSecurity extends
/*
* (non-Javadoc)
*
- * @see
- * org.springframework.security.config.annotation.web.HttpSecurityBuilder#addFilterAfter(javax
- * .servlet.Filter, java.lang.Class)
+ * @see org.springframework.security.config.annotation.web.HttpSecurityBuilder#
+ * addFilterAfter(javax .servlet.Filter, java.lang.Class)
*/
public HttpSecurity addFilterAfter(Filter filter, Class extends Filter> afterFilter) {
comparator.registerAfter(filter.getClass(), afterFilter);
@@ -2586,12 +2577,10 @@ public final class HttpSecurity extends
/*
* (non-Javadoc)
*
- * @see
- * org.springframework.security.config.annotation.web.HttpSecurityBuilder#addFilterBefore(
- * javax.servlet.Filter, java.lang.Class)
+ * @see org.springframework.security.config.annotation.web.HttpSecurityBuilder#
+ * addFilterBefore( javax.servlet.Filter, java.lang.Class)
*/
- public HttpSecurity addFilterBefore(Filter filter,
- Class extends Filter> beforeFilter) {
+ public HttpSecurity addFilterBefore(Filter filter, Class extends Filter> beforeFilter) {
comparator.registerBefore(filter.getClass(), beforeFilter);
return addFilter(filter);
}
@@ -2600,16 +2589,14 @@ public final class HttpSecurity extends
* (non-Javadoc)
*
* @see
- * org.springframework.security.config.annotation.web.HttpSecurityBuilder#addFilter(javax.
- * servlet.Filter)
+ * org.springframework.security.config.annotation.web.HttpSecurityBuilder#addFilter(
+ * javax. servlet.Filter)
*/
public HttpSecurity addFilter(Filter filter) {
Class extends Filter> filterClass = filter.getClass();
if (!comparator.isRegistered(filterClass)) {
- throw new IllegalArgumentException(
- "The Filter class "
- + filterClass.getName()
- + " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.");
+ throw new IllegalArgumentException("The Filter class " + filterClass.getName()
+ + " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.");
}
this.filters.add(filter);
return this;
@@ -2628,7 +2615,6 @@ public final class HttpSecurity extends
* deterministic. More concretely, registering multiple Filters in the same location
* does not override existing Filters. Instead, do not register Filters you do not
* want to use.
- *
* @param filter the Filter to register
* @param atFilter the location of another {@link Filter} that is already registered
* (i.e. known) with Spring Security.
@@ -2643,14 +2629,15 @@ public final class HttpSecurity extends
* Allows specifying which {@link HttpServletRequest} instances this
* {@link HttpSecurity} will be invoked on. This method allows for easily invoking the
* {@link HttpSecurity} for multiple different {@link RequestMatcher} instances. If
- * only a single {@link RequestMatcher} is necessary consider using {@link #mvcMatcher(String)},
- * {@link #antMatcher(String)}, {@link #regexMatcher(String)}, or
- * {@link #requestMatcher(RequestMatcher)}.
+ * only a single {@link RequestMatcher} is necessary consider using
+ * {@link #mvcMatcher(String)}, {@link #antMatcher(String)},
+ * {@link #regexMatcher(String)}, or {@link #requestMatcher(RequestMatcher)}.
*
*
- * Invoking {@link #requestMatchers()} will not override previous invocations of {@link #mvcMatcher(String)}},
- * {@link #requestMatchers()}, {@link #antMatcher(String)},
- * {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
+ * Invoking {@link #requestMatchers()} will not override previous invocations of
+ * {@link #mvcMatcher(String)}}, {@link #requestMatchers()},
+ * {@link #antMatcher(String)}, {@link #regexMatcher(String)}, and
+ * {@link #requestMatcher(RequestMatcher)}.
*
*
*
Example Configurations
@@ -2743,7 +2730,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @return the {@link RequestMatcherConfigurer} for further customizations
*/
public RequestMatcherConfigurer requestMatchers() {
@@ -2754,14 +2740,15 @@ public final class HttpSecurity extends
* Allows specifying which {@link HttpServletRequest} instances this
* {@link HttpSecurity} will be invoked on. This method allows for easily invoking the
* {@link HttpSecurity} for multiple different {@link RequestMatcher} instances. If
- * only a single {@link RequestMatcher} is necessary consider using {@link #mvcMatcher(String)},
- * {@link #antMatcher(String)}, {@link #regexMatcher(String)}, or
- * {@link #requestMatcher(RequestMatcher)}.
+ * only a single {@link RequestMatcher} is necessary consider using
+ * {@link #mvcMatcher(String)}, {@link #antMatcher(String)},
+ * {@link #regexMatcher(String)}, or {@link #requestMatcher(RequestMatcher)}.
*
*
- * Invoking {@link #requestMatchers()} will not override previous invocations of {@link #mvcMatcher(String)}},
- * {@link #requestMatchers()}, {@link #antMatcher(String)},
- * {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
+ * Invoking {@link #requestMatchers()} will not override previous invocations of
+ * {@link #mvcMatcher(String)}}, {@link #requestMatchers()},
+ * {@link #antMatcher(String)}, {@link #regexMatcher(String)}, and
+ * {@link #requestMatcher(RequestMatcher)}.
*
*
*
Example Configurations
@@ -2840,7 +2827,6 @@ public final class HttpSecurity extends
* }
* }
*
- *
* @param requestMatcherCustomizer the {@link Customizer} to provide more options for
* the {@link RequestMatcherConfigurer}
* @return the {@link HttpSecurity} for further customizations
@@ -2857,10 +2843,10 @@ public final class HttpSecurity extends
*
*
* Invoking {@link #requestMatcher(RequestMatcher)} will override previous invocations
- * of {@link #requestMatchers()}, {@link #mvcMatcher(String)}, {@link #antMatcher(String)},
- * {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
+ * of {@link #requestMatchers()}, {@link #mvcMatcher(String)},
+ * {@link #antMatcher(String)}, {@link #regexMatcher(String)}, and
+ * {@link #requestMatcher(RequestMatcher)}.
*
- *
* @param requestMatcher the {@link RequestMatcher} to use (i.e. new
* AntPathRequestMatcher("/admin/**","GET") )
* @return the {@link HttpSecurity} for further customizations
@@ -2879,11 +2865,11 @@ public final class HttpSecurity extends
* {@link #requestMatchers()} or {@link #requestMatcher(RequestMatcher)}.
*
*
- * Invoking {@link #antMatcher(String)} will override previous invocations of {@link #mvcMatcher(String)}},
- * {@link #requestMatchers()}, {@link #antMatcher(String)},
- * {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
+ * Invoking {@link #antMatcher(String)} will override previous invocations of
+ * {@link #mvcMatcher(String)}}, {@link #requestMatchers()},
+ * {@link #antMatcher(String)}, {@link #regexMatcher(String)}, and
+ * {@link #requestMatcher(RequestMatcher)}.
*
- *
* @param antPattern the Ant Pattern to match on (i.e. "/admin/**")
* @return the {@link HttpSecurity} for further customizations
* @see AntPathRequestMatcher
@@ -2894,15 +2880,15 @@ public final class HttpSecurity extends
/**
* Allows configuring the {@link HttpSecurity} to only be invoked when matching the
- * provided Spring MVC pattern. If more advanced configuration is necessary, consider using
- * {@link #requestMatchers()} or {@link #requestMatcher(RequestMatcher)}.
+ * provided Spring MVC pattern. If more advanced configuration is necessary, consider
+ * using {@link #requestMatchers()} or {@link #requestMatcher(RequestMatcher)}.
*
*
- * Invoking {@link #mvcMatcher(String)} will override previous invocations of {@link #mvcMatcher(String)}},
- * {@link #requestMatchers()}, {@link #antMatcher(String)},
- * {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
+ * Invoking {@link #mvcMatcher(String)} will override previous invocations of
+ * {@link #mvcMatcher(String)}}, {@link #requestMatchers()},
+ * {@link #antMatcher(String)}, {@link #regexMatcher(String)}, and
+ * {@link #requestMatcher(RequestMatcher)}.
*
- *
* @param mvcPattern the Spring MVC Pattern to match on (i.e. "/admin/**")
* @return the {@link HttpSecurity} for further customizations
* @see MvcRequestMatcher
@@ -2918,11 +2904,11 @@ public final class HttpSecurity extends
* {@link #requestMatchers()} or {@link #requestMatcher(RequestMatcher)}.
*
*
- * Invoking {@link #regexMatcher(String)} will override previous invocations of {@link #mvcMatcher(String)}},
- * {@link #requestMatchers()}, {@link #antMatcher(String)},
- * {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
+ * Invoking {@link #regexMatcher(String)} will override previous invocations of
+ * {@link #mvcMatcher(String)}}, {@link #requestMatchers()},
+ * {@link #antMatcher(String)}, {@link #regexMatcher(String)}, and
+ * {@link #requestMatcher(RequestMatcher)}.
*
- *
* @param pattern the Regular Expression to match on (i.e. "/admin/.+")
* @return the {@link HttpSecurity} for further customizations
* @see RegexRequestMatcher
@@ -2945,8 +2931,7 @@ public final class HttpSecurity extends
* @param matchers the {@link MvcRequestMatcher} instances to set the servlet path
* on if {@link #servletPath(String)} is set.
*/
- private MvcMatchersRequestMatcherConfigurer(ApplicationContext context,
- List matchers) {
+ private MvcMatchersRequestMatcherConfigurer(ApplicationContext context, List matchers) {
super(context);
this.matchers = new ArrayList<>(matchers);
}
@@ -2966,8 +2951,7 @@ public final class HttpSecurity extends
* @author Rob Winch
* @since 3.2
*/
- public class RequestMatcherConfigurer
- extends AbstractRequestMatcherRegistry {
+ public class RequestMatcherConfigurer extends AbstractRequestMatcherRegistry {
protected List matchers = new ArrayList<>();
@@ -2979,8 +2963,7 @@ public final class HttpSecurity extends
}
@Override
- public MvcMatchersRequestMatcherConfigurer mvcMatchers(HttpMethod method,
- String... mvcPatterns) {
+ public MvcMatchersRequestMatcherConfigurer mvcMatchers(HttpMethod method, String... mvcPatterns) {
List mvcMatchers = createMvcMatchers(method, mvcPatterns);
setMatchers(mvcMatchers);
return new MvcMatchersRequestMatcherConfigurer(getContext(), mvcMatchers);
@@ -2992,8 +2975,7 @@ public final class HttpSecurity extends
}
@Override
- protected RequestMatcherConfigurer chainRequestMatchers(
- List requestMatchers) {
+ protected RequestMatcherConfigurer chainRequestMatchers(List requestMatchers) {
setMatchers(requestMatchers);
return this;
}
@@ -3005,7 +2987,6 @@ public final class HttpSecurity extends
/**
* Return the {@link HttpSecurity} for further customizations
- *
* @return the {@link HttpSecurity} for further customizations
*/
public HttpSecurity and() {
@@ -3017,19 +2998,19 @@ public final class HttpSecurity extends
/**
* If the {@link SecurityConfigurer} has already been specified get the original,
* otherwise apply the new {@link SecurityConfigurerAdapter}.
- *
* @param configurer the {@link SecurityConfigurer} to apply if one is not found for
* this {@link SecurityConfigurer} class.
* @return the current {@link SecurityConfigurer} for the configurer passed in
* @throws Exception
*/
@SuppressWarnings("unchecked")
- private > C getOrApply(
- C configurer) throws Exception {
+ private > C getOrApply(C configurer)
+ throws Exception {
C existingConfig = (C) getConfigurer(configurer.getClass());
if (existingConfig != null) {
return existingConfig;
}
return apply(configurer);
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java
index 251556fcaf..1adc9465ec 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java
@@ -74,14 +74,13 @@ import org.springframework.web.filter.DelegatingFilterProxy;
*
* @see EnableWebSecurity
* @see WebSecurityConfiguration
- *
* @author Rob Winch
* @author Evgeniy Cheban
* @since 3.2
*/
-public final class WebSecurity extends
- AbstractConfiguredSecurityBuilder implements
- SecurityBuilder, ApplicationContextAware {
+public final class WebSecurity extends AbstractConfiguredSecurityBuilder
+ implements SecurityBuilder, ApplicationContextAware {
+
private final Log logger = LogFactory.getLog(getClass());
private final List ignoredRequests = new ArrayList<>();
@@ -118,12 +117,11 @@ public final class WebSecurity extends
/**
*
- * Allows adding {@link RequestMatcher} instances that Spring Security
- * should ignore. Web Security provided by Spring Security (including the
- * {@link SecurityContext}) will not be available on {@link HttpServletRequest} that
- * match. Typically the requests that are registered should be that of only static
- * resources. For requests that are dynamic, consider mapping the request to allow all
- * users instead.
+ * Allows adding {@link RequestMatcher} instances that Spring Security should ignore.
+ * Web Security provided by Spring Security (including the {@link SecurityContext})
+ * will not be available on {@link HttpServletRequest} that match. Typically the
+ * requests that are registered should be that of only static resources. For requests
+ * that are dynamic, consider mapping the request to allow all users instead.
*
*
* Example Usage:
@@ -154,7 +152,6 @@ public final class WebSecurity extends
* .antMatchers("/static/**");
* // now both URLs that start with /resources/ and /static/ will be ignored
*
- *
* @return the {@link IgnoredRequestConfigurer} to use for registering request that
* should be ignored
*/
@@ -165,7 +162,6 @@ public final class WebSecurity extends
/**
* Allows customizing the {@link HttpFirewall}. The default is
* {@link StrictHttpFirewall}.
- *
* @param httpFirewall the custom {@link HttpFirewall}
* @return the {@link WebSecurity} for further customizations
*/
@@ -176,10 +172,8 @@ public final class WebSecurity extends
/**
* Controls debugging support for Spring Security.
- *
* @param debugEnabled if true, enables debug support with Spring Security. Default is
* false.
- *
* @return the {@link WebSecurity} for further customization.
* @see EnableWebSecurity#debug()
*/
@@ -197,7 +191,6 @@ public final class WebSecurity extends
* Typically this method is invoked automatically within the framework from
* {@link WebSecurityConfigurerAdapter#init(WebSecurity)}
*
- *
* @param securityFilterChainBuilder the builder to use to create the
* {@link SecurityFilterChain} instances
* @return the {@link WebSecurity} for further customizations
@@ -209,15 +202,13 @@ public final class WebSecurity extends
}
/**
- * Set the {@link WebInvocationPrivilegeEvaluator} to be used. If this is not specified,
- * then a {@link DefaultWebInvocationPrivilegeEvaluator} will be created when
- * {@link #securityInterceptor(FilterSecurityInterceptor)} is non null.
- *
+ * Set the {@link WebInvocationPrivilegeEvaluator} to be used. If this is not
+ * specified, then a {@link DefaultWebInvocationPrivilegeEvaluator} will be created
+ * when {@link #securityInterceptor(FilterSecurityInterceptor)} is non null.
* @param privilegeEvaluator the {@link WebInvocationPrivilegeEvaluator} to use
* @return the {@link WebSecurity} for further customizations
*/
- public WebSecurity privilegeEvaluator(
- WebInvocationPrivilegeEvaluator privilegeEvaluator) {
+ public WebSecurity privilegeEvaluator(WebInvocationPrivilegeEvaluator privilegeEvaluator) {
this.privilegeEvaluator = privilegeEvaluator;
return this;
}
@@ -225,12 +216,10 @@ public final class WebSecurity extends
/**
* Set the {@link SecurityExpressionHandler} to be used. If this is not specified,
* then a {@link DefaultWebSecurityExpressionHandler} will be used.
- *
* @param expressionHandler the {@link SecurityExpressionHandler} to use
* @return the {@link WebSecurity} for further customizations
*/
- public WebSecurity expressionHandler(
- SecurityExpressionHandler expressionHandler) {
+ public WebSecurity expressionHandler(SecurityExpressionHandler expressionHandler) {
Assert.notNull(expressionHandler, "expressionHandler cannot be null");
this.expressionHandler = expressionHandler;
return this;
@@ -269,7 +258,6 @@ public final class WebSecurity extends
/**
* Executes the Runnable immediately after the build takes place
- *
* @param postBuildAction
* @return the {@link WebSecurity} for further customizations
*/
@@ -280,17 +268,14 @@ public final class WebSecurity extends
@Override
protected Filter performBuild() throws Exception {
- Assert.state(
- !securityFilterChainBuilders.isEmpty(),
+ Assert.state(!securityFilterChainBuilders.isEmpty(),
() -> "At least one SecurityBuilder extends SecurityFilterChain> needs to be specified. "
+ "Typically this is done by exposing a SecurityFilterChain bean "
+ "or by adding a @Configuration that extends WebSecurityConfigurerAdapter. "
- + "More advanced users can invoke "
- + WebSecurity.class.getSimpleName()
+ + "More advanced users can invoke " + WebSecurity.class.getSimpleName()
+ ".addSecurityFilterChainBuilder directly");
int chainSize = ignoredRequests.size() + securityFilterChainBuilders.size();
- List securityFilterChains = new ArrayList<>(
- chainSize);
+ List securityFilterChains = new ArrayList<>(chainSize);
for (RequestMatcher ignoredRequest : ignoredRequests) {
securityFilterChains.add(new DefaultSecurityFilterChain(ignoredRequest));
}
@@ -308,8 +293,7 @@ public final class WebSecurity extends
Filter result = filterChainProxy;
if (debugEnabled) {
- logger.warn("\n\n"
- + "********************************************************************\n"
+ logger.warn("\n\n" + "********************************************************************\n"
+ "********** Security debugging is enabled. *************\n"
+ "********** This may include sensitive information. *************\n"
+ "********** Do not use in a production system! *************\n"
@@ -326,12 +310,11 @@ public final class WebSecurity extends
*
* @author Rob Winch
*/
- public final class MvcMatchersIgnoredRequestConfigurer
- extends IgnoredRequestConfigurer {
+ public final class MvcMatchersIgnoredRequestConfigurer extends IgnoredRequestConfigurer {
+
private final List mvcMatchers;
- private MvcMatchersIgnoredRequestConfigurer(ApplicationContext context,
- List mvcMatchers) {
+ private MvcMatchersIgnoredRequestConfigurer(ApplicationContext context, List mvcMatchers) {
super(context);
this.mvcMatchers = mvcMatchers;
}
@@ -342,6 +325,7 @@ public final class WebSecurity extends
}
return this;
}
+
}
/**
@@ -351,20 +335,17 @@ public final class WebSecurity extends
* @author Rob Winch
* @since 3.2
*/
- public class IgnoredRequestConfigurer
- extends AbstractRequestMatcherRegistry {
+ public class IgnoredRequestConfigurer extends AbstractRequestMatcherRegistry {
private IgnoredRequestConfigurer(ApplicationContext context) {
setApplicationContext(context);
}
@Override
- public MvcMatchersIgnoredRequestConfigurer mvcMatchers(HttpMethod method,
- String... mvcPatterns) {
+ public MvcMatchersIgnoredRequestConfigurer mvcMatchers(HttpMethod method, String... mvcPatterns) {
List mvcMatchers = createMvcMatchers(method, mvcPatterns);
WebSecurity.this.ignoredRequests.addAll(mvcMatchers);
- return new MvcMatchersIgnoredRequestConfigurer(getApplicationContext(),
- mvcMatchers);
+ return new MvcMatchersIgnoredRequestConfigurer(getApplicationContext(), mvcMatchers);
}
@Override
@@ -373,8 +354,7 @@ public final class WebSecurity extends
}
@Override
- protected IgnoredRequestConfigurer chainRequestMatchers(
- List requestMatchers) {
+ protected IgnoredRequestConfigurer chainRequestMatchers(List requestMatchers) {
WebSecurity.this.ignoredRequests.addAll(requestMatchers);
return this;
}
@@ -385,29 +365,37 @@ public final class WebSecurity extends
public WebSecurity and() {
return WebSecurity.this;
}
+
}
@Override
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- this.defaultWebSecurityExpressionHandler
- .setApplicationContext(applicationContext);
+ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
+ this.defaultWebSecurityExpressionHandler.setApplicationContext(applicationContext);
try {
this.defaultWebSecurityExpressionHandler.setRoleHierarchy(applicationContext.getBean(RoleHierarchy.class));
- } catch (NoSuchBeanDefinitionException e) {}
+ }
+ catch (NoSuchBeanDefinitionException e) {
+ }
try {
- this.defaultWebSecurityExpressionHandler.setPermissionEvaluator(applicationContext.getBean(
- PermissionEvaluator.class));
- } catch(NoSuchBeanDefinitionException e) {}
+ this.defaultWebSecurityExpressionHandler
+ .setPermissionEvaluator(applicationContext.getBean(PermissionEvaluator.class));
+ }
+ catch (NoSuchBeanDefinitionException e) {
+ }
this.ignoredRequestRegistry = new IgnoredRequestConfigurer(applicationContext);
try {
this.httpFirewall = applicationContext.getBean(HttpFirewall.class);
- } catch(NoSuchBeanDefinitionException e) {}
+ }
+ catch (NoSuchBeanDefinitionException e) {
+ }
try {
this.requestRejectedHandler = applicationContext.getBean(RequestRejectedHandler.class);
- } catch(NoSuchBeanDefinitionException e) {}
+ }
+ catch (NoSuchBeanDefinitionException e) {
+ }
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/AutowiredWebSecurityConfigurersIgnoreParents.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/AutowiredWebSecurityConfigurersIgnoreParents.java
index 9195060ef1..012c0fec66 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/AutowiredWebSecurityConfigurersIgnoreParents.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/AutowiredWebSecurityConfigurersIgnoreParents.java
@@ -40,8 +40,7 @@ final class AutowiredWebSecurityConfigurersIgnoreParents {
private final ConfigurableListableBeanFactory beanFactory;
- AutowiredWebSecurityConfigurersIgnoreParents(
- ConfigurableListableBeanFactory beanFactory) {
+ AutowiredWebSecurityConfigurersIgnoreParents(ConfigurableListableBeanFactory beanFactory) {
Assert.notNull(beanFactory, "beanFactory cannot be null");
this.beanFactory = beanFactory;
}
@@ -49,11 +48,11 @@ final class AutowiredWebSecurityConfigurersIgnoreParents {
@SuppressWarnings({ "rawtypes", "unchecked" })
public List> getWebSecurityConfigurers() {
List> webSecurityConfigurers = new ArrayList<>();
- Map beansOfType = beanFactory
- .getBeansOfType(WebSecurityConfigurer.class);
+ Map beansOfType = beanFactory.getBeansOfType(WebSecurityConfigurer.class);
for (Entry entry : beansOfType.entrySet()) {
webSecurityConfigurers.add(entry.getValue());
}
return webSecurityConfigurers;
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurity.java
index 9b6ccdbfa5..217ae581a3 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurity.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurity.java
@@ -72,10 +72,8 @@ import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
-@Import({ WebSecurityConfiguration.class,
- SpringWebMvcImportSelector.class,
- OAuth2ImportSelector.class,
- HttpSecurityConfiguration.class})
+@Import({ WebSecurityConfiguration.class, SpringWebMvcImportSelector.class, OAuth2ImportSelector.class,
+ HttpSecurityConfiguration.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
@@ -85,4 +83,5 @@ public @interface EnableWebSecurity {
* @return if true, enables debug support with Spring Security
*/
boolean debug() default false;
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.java
index 0b4ea90061..456f436ce1 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.java
@@ -42,7 +42,9 @@ import static org.springframework.security.config.Customizer.withDefaults;
*/
@Configuration(proxyBeanMethods = false)
class HttpSecurityConfiguration {
+
private static final String BEAN_NAME_PREFIX = "org.springframework.security.config.annotation.web.configuration.HttpSecurityConfiguration.";
+
private static final String HTTPSECURITY_BEAN_NAME = BEAN_NAME_PREFIX + "httpSecurity";
private ObjectPostProcessor objectPostProcessor;
@@ -64,8 +66,7 @@ class HttpSecurityConfiguration {
}
@Autowired
- public void setAuthenticationConfiguration(
- AuthenticationConfiguration authenticationConfiguration) {
+ public void setAuthenticationConfiguration(AuthenticationConfiguration authenticationConfiguration) {
this.authenticationConfiguration = authenticationConfiguration;
}
@@ -77,26 +78,18 @@ class HttpSecurityConfiguration {
@Bean(HTTPSECURITY_BEAN_NAME)
@Scope("prototype")
public HttpSecurity httpSecurity() throws Exception {
- WebSecurityConfigurerAdapter.LazyPasswordEncoder passwordEncoder =
- new WebSecurityConfigurerAdapter.LazyPasswordEncoder(this.context);
+ WebSecurityConfigurerAdapter.LazyPasswordEncoder passwordEncoder = new WebSecurityConfigurerAdapter.LazyPasswordEncoder(
+ this.context);
- AuthenticationManagerBuilder authenticationBuilder =
- new WebSecurityConfigurerAdapter.DefaultPasswordEncoderAuthenticationManagerBuilder(this.objectPostProcessor, passwordEncoder);
+ AuthenticationManagerBuilder authenticationBuilder = new WebSecurityConfigurerAdapter.DefaultPasswordEncoderAuthenticationManagerBuilder(
+ this.objectPostProcessor, passwordEncoder);
authenticationBuilder.parentAuthenticationManager(authenticationManager());
HttpSecurity http = new HttpSecurity(objectPostProcessor, authenticationBuilder, createSharedObjects());
- http
- .csrf(withDefaults())
- .addFilter(new WebAsyncManagerIntegrationFilter())
- .exceptionHandling(withDefaults())
- .headers(withDefaults())
- .sessionManagement(withDefaults())
- .securityContext(withDefaults())
- .requestCache(withDefaults())
- .anonymous(withDefaults())
- .servletApi(withDefaults())
- .logout(withDefaults())
- .apply(new DefaultLoginPageConfigurer<>());
+ http.csrf(withDefaults()).addFilter(new WebAsyncManagerIntegrationFilter()).exceptionHandling(withDefaults())
+ .headers(withDefaults()).sessionManagement(withDefaults()).securityContext(withDefaults())
+ .requestCache(withDefaults()).anonymous(withDefaults()).servletApi(withDefaults())
+ .logout(withDefaults()).apply(new DefaultLoginPageConfigurer<>());
return http;
}
@@ -104,7 +97,8 @@ class HttpSecurityConfiguration {
private AuthenticationManager authenticationManager() throws Exception {
if (this.authenticationManager != null) {
return this.authenticationManager;
- } else {
+ }
+ else {
return this.authenticationConfiguration.getAuthenticationManager();
}
}
@@ -114,4 +108,5 @@ class HttpSecurityConfiguration {
sharedObjects.put(ApplicationContext.class, context);
return sharedObjects;
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfiguration.java
index 892fb394f0..09d5681d9d 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfiguration.java
@@ -53,20 +53,25 @@ final class OAuth2ClientConfiguration {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
- boolean webmvcPresent = ClassUtils.isPresent(
- "org.springframework.web.servlet.DispatcherServlet", getClass().getClassLoader());
+ boolean webmvcPresent = ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet",
+ getClass().getClassLoader());
- return webmvcPresent ?
- new String[] { "org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration.OAuth2ClientWebMvcSecurityConfiguration" } :
- new String[] {};
+ return webmvcPresent ? new String[] {
+ "org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration.OAuth2ClientWebMvcSecurityConfiguration" }
+ : new String[] {};
}
+
}
@Configuration(proxyBeanMethods = false)
static class OAuth2ClientWebMvcSecurityConfiguration implements WebMvcConfigurer {
+
private ClientRegistrationRepository clientRegistrationRepository;
+
private OAuth2AuthorizedClientRepository authorizedClientRepository;
+
private OAuth2AccessTokenResponseClient accessTokenResponseClient;
+
private OAuth2AuthorizedClientManager authorizedClientManager;
@Override
@@ -92,7 +97,8 @@ final class OAuth2ClientConfiguration {
}
@Autowired(required = false)
- void setAccessTokenResponseClient(OAuth2AccessTokenResponseClient accessTokenResponseClient) {
+ void setAccessTokenResponseClient(
+ OAuth2AccessTokenResponseClient accessTokenResponseClient) {
this.accessTokenResponseClient = accessTokenResponseClient;
}
@@ -111,25 +117,24 @@ final class OAuth2ClientConfiguration {
OAuth2AuthorizedClientManager authorizedClientManager = null;
if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) {
if (this.accessTokenResponseClient != null) {
- OAuth2AuthorizedClientProvider authorizedClientProvider =
- OAuth2AuthorizedClientProviderBuilder.builder()
- .authorizationCode()
- .refreshToken()
- .clientCredentials(configurer ->
- configurer.accessTokenResponseClient(this.accessTokenResponseClient))
- .password()
- .build();
- DefaultOAuth2AuthorizedClientManager defaultAuthorizedClientManager =
- new DefaultOAuth2AuthorizedClientManager(
- this.clientRegistrationRepository, this.authorizedClientRepository);
+ OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder
+ .builder().authorizationCode().refreshToken()
+ .clientCredentials(
+ configurer -> configurer.accessTokenResponseClient(this.accessTokenResponseClient))
+ .password().build();
+ DefaultOAuth2AuthorizedClientManager defaultAuthorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
+ this.clientRegistrationRepository, this.authorizedClientRepository);
defaultAuthorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
authorizedClientManager = defaultAuthorizedClientManager;
- } else {
+ }
+ else {
authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientRepository);
}
}
return authorizedClientManager;
}
+
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/OAuth2ImportSelector.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/OAuth2ImportSelector.java
index a999d5c7f8..863cf03dca 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/OAuth2ImportSelector.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/OAuth2ImportSelector.java
@@ -26,10 +26,11 @@ import org.springframework.util.ClassUtils;
* Used by {@link EnableWebSecurity} to conditionally import:
*
*
- *
{@link OAuth2ClientConfiguration} when the {@code spring-security-oauth2-client} module is present on the classpath
- *
{@link SecurityReactorContextConfiguration} when either the {@code spring-security-oauth2-client} or
- * {@code spring-security-oauth2-resource-server} module as well as the {@code spring-webflux} module
- * are present on the classpath
+ *
{@link OAuth2ClientConfiguration} when the {@code spring-security-oauth2-client}
+ * module is present on the classpath
+ *
{@link SecurityReactorContextConfiguration} when either the
+ * {@code spring-security-oauth2-client} or {@code spring-security-oauth2-resource-server}
+ * module as well as the {@code spring-webflux} module are present on the classpath
*
*
* @author Joe Grandja
@@ -45,7 +46,8 @@ final class OAuth2ImportSelector implements ImportSelector {
Set imports = new LinkedHashSet<>();
boolean oauth2ClientPresent = ClassUtils.isPresent(
- "org.springframework.security.oauth2.client.registration.ClientRegistration", getClass().getClassLoader());
+ "org.springframework.security.oauth2.client.registration.ClientRegistration",
+ getClass().getClassLoader());
if (oauth2ClientPresent) {
imports.add("org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration");
}
@@ -53,15 +55,18 @@ final class OAuth2ImportSelector implements ImportSelector {
boolean webfluxPresent = ClassUtils.isPresent(
"org.springframework.web.reactive.function.client.ExchangeFilterFunction", getClass().getClassLoader());
if (webfluxPresent && oauth2ClientPresent) {
- imports.add("org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration");
+ imports.add(
+ "org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration");
}
boolean oauth2ResourceServerPresent = ClassUtils.isPresent(
"org.springframework.security.oauth2.server.resource.BearerTokenError", getClass().getClassLoader());
if (webfluxPresent && oauth2ResourceServerPresent) {
- imports.add("org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration");
+ imports.add(
+ "org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration");
}
return imports.toArray(new String[0]);
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java
index 8d76982c80..667ca07881 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java
@@ -41,13 +41,13 @@ import java.util.function.Function;
import static org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration.SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES;
/**
- * {@link Configuration} that (potentially) adds a "decorating" {@code Publisher}
- * for the last operator created in every {@code Mono} or {@code Flux}.
+ * {@link Configuration} that (potentially) adds a "decorating" {@code Publisher} for the
+ * last operator created in every {@code Mono} or {@code Flux}.
*
*
- * The {@code Publisher} is solely responsible for adding
- * the current {@code HttpServletRequest}, {@code HttpServletResponse} and {@code Authentication}
- * to the Reactor {@code Context} so that it's accessible in every flow, if required.
+ * The {@code Publisher} is solely responsible for adding the current
+ * {@code HttpServletRequest}, {@code HttpServletResponse} and {@code Authentication} to
+ * the Reactor {@code Context} so that it's accessible in every flow, if required.
*
* @author Joe Grandja
* @author Roman Matiushchenko
@@ -63,12 +63,13 @@ class SecurityReactorContextConfiguration {
}
static class SecurityReactorContextSubscriberRegistrar implements InitializingBean, DisposableBean {
+
private static final String SECURITY_REACTOR_CONTEXT_OPERATOR_KEY = "org.springframework.security.SECURITY_REACTOR_CONTEXT_OPERATOR";
@Override
public void afterPropertiesSet() throws Exception {
- Function super Publisher, ? extends Publisher> lifter =
- Operators.liftPublisher((pub, sub) -> createSubscriberIfNecessary(sub));
+ Function super Publisher, ? extends Publisher> lifter = Operators
+ .liftPublisher((pub, sub) -> createSubscriberIfNecessary(sub));
Hooks.onLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY, pub -> {
if (!contextAttributesAvailable()) {
@@ -93,8 +94,8 @@ class SecurityReactorContextConfiguration {
}
private static boolean contextAttributesAvailable() {
- return SecurityContextHolder.getContext().getAuthentication() != null ||
- RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes;
+ return SecurityContextHolder.getContext().getAuthentication() != null
+ || RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes;
}
private static Map getContextAttributes() {
@@ -104,7 +105,7 @@ class SecurityReactorContextConfiguration {
if (requestAttributes instanceof ServletRequestAttributes) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
servletRequest = servletRequestAttributes.getRequest();
- servletResponse = servletRequestAttributes.getResponse(); // possible null
+ servletResponse = servletRequestAttributes.getResponse(); // possible null
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null && servletRequest == null) {
@@ -124,11 +125,15 @@ class SecurityReactorContextConfiguration {
return contextAttributes;
}
+
}
static class SecurityReactorContextSubscriber implements CoreSubscriber {
+
static final String SECURITY_CONTEXT_ATTRIBUTES = "org.springframework.security.SECURITY_CONTEXT_ATTRIBUTES";
+
private final CoreSubscriber delegate;
+
private final Context context;
SecurityReactorContextSubscriber(CoreSubscriber delegate, Map attributes) {
@@ -137,7 +142,8 @@ class SecurityReactorContextConfiguration {
Context context;
if (currentContext.hasKey(SECURITY_CONTEXT_ATTRIBUTES)) {
context = currentContext;
- } else {
+ }
+ else {
context = currentContext.put(SECURITY_CONTEXT_ATTRIBUTES, attributes);
}
this.context = context;
@@ -167,5 +173,7 @@ class SecurityReactorContextConfiguration {
public void onComplete() {
this.delegate.onComplete();
}
+
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.java
index 1516a3e3f0..93aa8279c5 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.java
@@ -36,12 +36,12 @@ class SpringWebMvcImportSelector implements ImportSelector {
* springframework .core.type.AnnotationMetadata)
*/
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
- boolean webmvcPresent = ClassUtils.isPresent(
- "org.springframework.web.servlet.DispatcherServlet",
+ boolean webmvcPresent = ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet",
getClass().getClassLoader());
return webmvcPresent
? new String[] {
"org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration" }
: new String[] {};
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebMvcSecurityConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebMvcSecurityConfiguration.java
index 312a1b170e..10751a034a 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebMvcSecurityConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebMvcSecurityConfiguration.java
@@ -35,8 +35,10 @@ import java.util.List;
/**
* Used to add a {@link RequestDataValueProcessor} for Spring MVC and Spring Security CSRF
* integration. This configuration is added whenever {@link EnableWebMvc} is added by
- * SpringWebMvcImportSelector and the DispatcherServlet is present on the
- * classpath. It also adds the {@link AuthenticationPrincipalArgumentResolver} as a
+ * SpringWebMvcImportSelector
+ * and the DispatcherServlet is present on the classpath. It also adds the
+ * {@link AuthenticationPrincipalArgumentResolver} as a
* {@link HandlerMethodArgumentResolver}.
*
* @author Rob Winch
@@ -44,6 +46,7 @@ import java.util.List;
* @since 3.2
*/
class WebMvcSecurityConfiguration implements WebMvcConfigurer, ApplicationContextAware {
+
private BeanResolver beanResolver;
@Override
@@ -70,4 +73,5 @@ class WebMvcSecurityConfiguration implements WebMvcConfigurer, ApplicationContex
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.beanResolver = new BeanFactoryResolver(applicationContext.getAutowireCapableBeanFactory());
}
+
}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.java
index 31e5e9f6ea..dc854bc4d7 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.java
@@ -49,7 +49,6 @@ import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
-
/**
* Uses a {@link WebSecurity} to create the {@link FilterChainProxy} that performs the web
* based security for Spring Security. It then exports the necessary beans. Customizations
@@ -60,13 +59,13 @@ import org.springframework.security.web.context.AbstractSecurityWebApplicationIn
*
* @see EnableWebSecurity
* @see WebSecurity
- *
* @author Rob Winch
* @author Keesun Baik
* @since 3.2
*/
@Configuration(proxyBeanMethods = false)
public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAware {
+
private WebSecurity webSecurity;
private Boolean debugEnabled;
@@ -98,13 +97,11 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
*/
@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
public Filter springSecurityFilterChain() throws Exception {
- boolean hasConfigurers = webSecurityConfigurers != null
- && !webSecurityConfigurers.isEmpty();
+ boolean hasConfigurers = webSecurityConfigurers != null && !webSecurityConfigurers.isEmpty();
boolean hasFilterChain = !securityFilterChains.isEmpty();
if (hasConfigurers && hasFilterChain) {
throw new IllegalStateException(
- "Found WebSecurityConfigurerAdapter as well as SecurityFilterChain." +
- "Please select just one.");
+ "Found WebSecurityConfigurerAdapter as well as SecurityFilterChain." + "Please select just one.");
}
if (!hasConfigurers && !hasFilterChain) {
WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor
@@ -138,7 +135,6 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
/**
* Sets the {@code }
* instances used to create the web configuration.
- *
* @param objectPostProcessor the {@link ObjectPostProcessor} used to create a
* {@link WebSecurity} instance
* @param webSecurityConfigurers the
@@ -147,12 +143,10 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
* @throws Exception
*/
@Autowired(required = false)
- public void setFilterChainProxySecurityConfigurer(
- ObjectPostProcessor objectPostProcessor,
+ public void setFilterChainProxySecurityConfigurer(ObjectPostProcessor objectPostProcessor,
@Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List