1
0
mirror of synced 2026-07-11 22:00:04 +00:00

Compare commits

..

58 Commits

Author SHA1 Message Date
Spring Buildmaster 59bb10ef81 Release version 3.2.4.RELEASE 2014-05-21 14:27:27 -07:00
Rob Winch 08ec5797db SEC-2607: CAS Server logouts out synchronously 2014-05-21 15:43:05 -05:00
Rob Winch b20438562d SEC-2579: Ignore springio props in release checks 2014-05-21 14:04:18 -05:00
Rob Winch d4e26864d9 SEC-2606: ApacheDSServerIntegrationTests scan for available port 2014-05-21 06:49:00 -05:00
Rob Winch 519d85877c SEC-2603: Fix config groovy integration tests 2014-05-20 23:14:11 -05:00
Rob Winch f31a5c5411 SEC-2472: Support LDAP crypto PasswordEncoder 2014-05-20 23:13:07 -05:00
Rob Winch 77b9209640 SEC-2579: Remove duplicate snapshot repo and dependencies closure 2014-05-19 15:58:04 -05:00
Rob Winch ae39a4dcdd SEC-2579: Polish so that platformVersion has a default 2014-05-19 15:33:30 -05:00
Andy Wilkinson f37e414442 SEC-2579: Update Spring IO plugin configuration
- Upgrade to 0.0.3.RELEASE of the plugin
- Declare a dependency in the springIoVersions configuration on the
  Platform’s platform-versions artifact. An external property is used to
  provide the version of this artifact. This means that the build script
  does not need to refer to a snapshot artifact (the only version
  available at the time of writing) and also breaks a circular
  dependency between Spring Security (a project that’s part of the
  Platform) and the Platform itself.
- The plugin applied and the libs-snapshot repository is added only
  if the external property is specified. This removes the possibility
  of a release or milestone being shipped with a snapshot dependency
  (unless the release build is performed with -PplatformVersion=foo).
2014-05-19 15:25:57 -05:00
Andy Wilkinson be687d6a84 SEC-2600: Remove unused import 2014-05-19 12:28:05 -05:00
Rob Winch d6b81abcf2 SEC-2578: HttpSessionSecurityContextRepository traverses HttpServletResponseWrapper 2014-05-02 15:06:28 -05:00
Rob Winch bf918df7a3 SEC-2543: Logout with CSRF enabled requires POST by default 2014-05-02 11:17:57 -05:00
Rob Winch dc7a3b30ea SEC-2581: Update to propdeps-plugin:0.0.6 2014-04-30 16:41:51 -05:00
Rob Winch 3be2f375f6 SEC-2580: Include ApacheDS in samples/ldap-xml 2014-04-30 16:39:23 -05:00
Rob Winch 9146345673 Fix warnings in itest-web.gradle 2014-04-30 08:52:39 -05:00
Rob Winch fb2cf96fa4 SEC-2579: Fix acl tests to work w/ newer ehcache versions 2014-04-30 08:52:29 -05:00
Rob Winch 9a27f9f778 SEC-2579: Add springio-platform plugin 2014-04-29 16:59:32 -05:00
Alexander Grüneberg e0b4945fad SEC-2577: Add missing whitespace in reference 2014-04-28 16:25:38 -05:00
Rob Winch d6f540fdee SEC-2532: Add disclaimer about jdbcAuthentication() with persistent data stores 2014-04-28 14:45:51 -05:00
Rob Winch 3f24210a2a SEC-2537: Add nekohtml to openid module 2014-04-25 13:51:00 -05:00
Rob Winch 13c5750f5d SEC-2571: Improve wording of UsernamePasswordAuthenticationToken#setAuthenticated() error 2014-04-24 17:03:34 -05:00
Rob Winch 414289d466 SEC-2571: Failure in UserDetailsService->InternalAuthenticationServiceException 2014-04-24 16:35:58 -05:00
Rob Winch 5e88ebef2e SEC-2549: Remove LazyBean marker interface 2014-04-24 13:55:25 -05:00
Mattias Severson c074493f24 SEC-2573: RequestHeaderRequestMatcher constructor argument name has typo 2014-04-23 09:41:43 -05:00
Rob Winch 1337f99843 SEC-2560: Remove samples from .gitignore and add missing sample files 2014-04-16 21:16:34 -05:00
Rob Winch cf721afc29 SEC-2558: Fix failing ApacheDSContainerTests when port is taken 2014-04-15 13:39:03 -05:00
Rob Winch 9133491da9 Revert "SEC-2547: Consistent CAS client version"
This reverts commit d9e87d8222.
2014-04-15 10:16:51 -05:00
Rob Winch 3632564972 Revert "SEC-2547: Fix sample after updating CAS client version"
This reverts commit 7ea0d3d42f.
2014-04-15 10:16:49 -05:00
Rob Winch 7ea0d3d42f SEC-2547: Fix sample after updating CAS client version 2014-04-15 07:49:34 -05:00
Hans-Joachim Kliemeck d9e87d8222 SEC-2547: Consistent CAS client version 2014-04-14 22:45:18 -05:00
Grzegorz Rożniecki 3954e0b2c1 SEC-2556: Fix @Import example in manual 2014-04-14 22:38:41 -05:00
Rob Winch 79fa1c70eb SEC-2542: Polish dependency exclusions
This cleans up exclusions so the pom.xml are not as cluttered.
2014-04-02 08:49:25 -05:00
Rob Winch fd6f9da184 SEC-2542: Use exclusions to remove duplicate dependencies
A number of projects had duplicate dependencies on their classpaths
as a result of the same classes being available in more than one
artifact, each with different Maven coordinates. Typically this only
affected the tests, but meant that the actual classes that were
loaded was somewhat unpredictable and had the potential to vary
between an IDE and the command line depending on the order in which
the aritfacts appeared on the classpath. This commit adds a number of
exclusions to remove such duplicates.

In addition to the new exclusions, notable other changes are:

 - Spring Data JPA has been updated to 1.4.1. This brings its
   transitive dependency upon spring-data-commons into line with
   Spring LDAP's and prevents both spring-data-commons-core and
   spring-data-commons from being on the classpath
 - All Servlet API dependencies have been updated to use the official
   artifact with all transitive dependencies on unofficial servlet API
   artifacts being excluded.
 - In places, groovy has been replaced with groovy-all. This removes
   some duplicates caused by groovy's transitive dependencies.
 - JUnit has been updated to 4.11 which brings its transitive Hamcrest
   dependency into line with other components.

There appears to be a bug in Gradle which means that some exclusions
applied to an artifact do not work reliably. To work around this
problem it has been necessary to apply some exclusions at the
configuration level

Conflicts:
	samples/messages-jc/pom.xml
2014-04-02 08:48:55 -05:00
Rob Winch ea0466d666 Next developmenet version in pom.xml 2014-04-02 08:44:06 -05:00
Spring Buildmaster 2cc0d94481 Next development version 2014-03-25 12:05:00 -07:00
Rob Winch 32c767a30d SEC-2533: Global AuthenticationManagerBuilder disables clearing child credentials 2014-03-25 13:00:42 -05:00
Rob Winch a11746a8d1 SEC-2498: RequestCache allows POST when CSRF is disabled 2014-03-25 10:44:34 -05:00
Rob Winch a18265a163 SEC-2531: AuthenticationConfiguration#lazyBean should use BeanClassLoader 2014-03-24 14:54:02 -05:00
Rob Winch d7a2c0a98c SEC-2177: Polish 2014-03-18 15:49:20 -05:00
Maciej Zasada 9057fbe0ed SEC-2177: Striping off all leading schemes
Striping off all leading schemes in the DefaultRedirectStrategy, so it
will be less vulnerable to open redirect phishing attacks. More info can
be found at SEC-2177 JIRA issue.
2014-03-18 15:49:20 -05:00
Julien Dubois 537d8f974f SEC-2519: RememberMeAuthenticationException supports root cause
Added a constructor which keeps the root cause of the exception, and
added some documentation
2014-03-11 16:13:03 -05:00
Alexander Kjäll 783af4012b SEC-2518: UserDetailsService javadoc repeats "insensitive"
Typo in javadoc, "case insensitive" was repeated twice.
2014-03-11 15:38:28 -05:00
Spring Buildmaster 5f5b8052d8 Next development version 2014-03-10 15:24:45 -07:00
Rob Winch 7dbb8e777e SEC-2500: Prevent anonymous bind for ActiveDirectoryLdapAuthenticator 2014-03-10 14:21:32 -05:00
Rob Winch bb563967cc SEC-2507: WebExpressionVoter.supports support subclasses of FilterInvocation 2014-03-10 14:21:07 -05:00
Rob Winch 974105ed19 SEC-2515: Detect object cycle for AuthenticationManager configuration 2014-03-10 14:04:10 -05:00
Rob Winch 2cad2f401b SEC-2325: Polish CSRF Tag support
- Rename csrfField to csrfInput
- Make AbstractCsrfTag package scope
- rename FormFieldTag to CsrfInputTag
- rename MetaTagsTag to CsrfMetaTagsTag
- removed whitespace from tag output so output is
  minimized & improving browser performance
- Update @since
- changed test names to be more meaningful
2014-03-07 15:25:57 -06:00
beamerblvd 3048e2c6e7 SEC-2325 Added JSP tags for CSRF meta tags and form fields 2014-03-07 13:18:46 -06:00
beamerblvd 561f284718 SEC-2335 Added ACL schema files for MySQL, SQL Server, Oracle 2014-03-07 13:10:03 -06:00
John Tims afc6a6ee0d SEC-2514: Fix typo in hellomvc.asc
packags -> packages
2014-03-07 10:26:31 -06:00
John Tims fa05e9c590 SEC-2513: Add link to SpringSource CLA form 2014-03-07 10:22:36 -06:00
Manimaran Selvan 818be86d46 SEC-2512: Fix typo in reference`
udates -> updates
2014-03-06 22:21:22 -06:00
Rob Winch 60704eb50e SEC-2511: Remove double ALLOW-FROM in X-Frame-Options header 2014-03-06 22:00:09 -06:00
getvictor f02b77794f SEC-2511: Remove double ALLOW-FROM from X-Frame-Options header.
The interface documentation for getAllowFromValue states: Gets the value for ALLOW-FROM excluding the ALLOW-FROM.
2014-03-06 21:59:46 -06:00
Rob Winch 1172d44397 SEC-2499: Allow MethodSecurityExpressionHandler in parent context
Previously a NoSuchBeanDefintionException was thrown when the
MethodSecurityExpressionHandler was defined in the parent context. This
happened due to trying to work around ordering issues related to SEC-2136

This commit resolves this by not marking the
MethodSecurityExpressionHandler bean as lazy unless it exists.
2014-03-06 20:51:24 -06:00
Rob Winch 49738e4588 SEC-2508: Passivity test for SEC-2357 2014-03-06 15:13:34 -06:00
Rob Winch 3b13c1fdf4 SEC-2495: CSRF disables logout on GET 2014-02-20 09:33:30 -06:00
Spring Buildmaster 8f6450ede1 Next development version 2014-02-19 10:52:05 -06:00
277 changed files with 1120 additions and 14043 deletions
+11 -17
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>spring-security-acl</name>
<description>spring-security-acl</description>
<url>http://spring.io/spring-security</url>
@@ -42,12 +42,6 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>aopalliance</groupId>
@@ -58,25 +52,25 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -88,13 +82,13 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -107,7 +101,7 @@
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.5</version>
<version>1.7.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@@ -150,19 +144,19 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -1,6 +1,5 @@
package org.springframework.security.acls.jdbc;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import static org.fest.assertions.Assertions.*;
@@ -12,17 +11,12 @@ import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
@@ -43,7 +37,6 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.util.FieldUtils;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ReflectionUtils;
/**
* Tests {@link EhCacheBasedAclCache}
+24
View File
@@ -0,0 +1,24 @@
Implementation-Title: org.springframework.security.acls
Implementation-Version: ${version}
Bundle-SymbolicName: org.springframework.security.acls
Bundle-Name: Spring Security Acls
Bundle-Vendor: SpringSource
Bundle-Version: ${version}
Bundle-ManifestVersion: 2
Ignored-Existing-Headers:
Import-Package,
Export-Package
Import-Template:
org.aopalliance.*;version="${aopAllianceRange}",
org.apache.commons.logging.*;version="${cloggingRange}",
org.springframework.cache.*;version="${springRange}";resolution:=optional,
org.springframework.security.core.*;version="${secRange}",
org.springframework.security.access.*;version="${secRange}",
org.springframework.security.util.*;version="${secRange}",
org.springframework.context.*;version="${springRange}";resolution:=optional,
org.springframework.dao.*;version="${springRange}";resolution:=optional,
org.springframework.jdbc.core.*;version="${springRange}";resolution:=optional,
org.springframework.transaction.support.*;version="${springRange}";resolution:=optional,
org.springframework.util.*;version="${springRange}";resolution:=optional,
net.sf.ehcache.*;version="${ehcacheRange}";resolution:=optional,
javax.sql.*;version="0";resolution:=optional
+7 -13
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-aspects</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>spring-security-aspects</name>
<description>spring-security-aspects</description>
<url>http://spring.io/spring-security</url>
@@ -42,35 +42,29 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -132,13 +126,13 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
+16
View File
@@ -0,0 +1,16 @@
Implementation-Title: org.springframework.security.aspects
Implementation-Version: ${version}
Bundle-SymbolicName: org.springframework.security.aspects
Bundle-Name: Spring Security Aspects
Bundle-Vendor: SpringSource
Bundle-ManifestVersion: 2
Bundle-Version: ${version}
Ignored-Existing-Headers:
Import-Package,
Export-Package
Import-Template:
org.aspectj.*;version="${aspectjRange}";resolution:=optional,
org.apache.commons.logging.*;version="${cloggingRange}",
org.springframework.security.core.*;version="${secRange}",
org.springframework.security.access.intercept.aspectj;version="${secRange}",
org.springframework.beans.factory;version="${springRange}"
+16 -9
View File
@@ -6,8 +6,9 @@ buildscript {
}
dependencies {
classpath("org.springframework.build.gradle:propdeps-plugin:0.0.6")
classpath("org.springframework.build.gradle:bundlor-plugin:0.1.2")
classpath("org.springframework.build.gradle:spring-io-plugin:0.0.3.RELEASE")
classpath("org.gradle.api.plugins:gradle-tomcat-plugin:1.2.3")
classpath("org.gradle.api.plugins:gradle-tomcat-plugin:0.9.8")
classpath('me.champeau.gradle:gradle-javadoc-hotfix-plugin:0.1')
classpath('org.asciidoctor:asciidoctor-gradle-plugin:0.7.0')
classpath('org.asciidoctor:asciidoctor-java-integration:0.1.4.preview.1')
@@ -25,8 +26,10 @@ allprojects {
ext.releaseBuild = version.endsWith('RELEASE')
ext.snapshotBuild = version.endsWith('SNAPSHOT')
ext.springVersion = '4.1.0.RC2'
ext.springLdapVersion = '2.0.1.RELEASE'
ext.springVersion = '3.2.8.RELEASE'
ext.spring4Version = '4.0.2.RELEASE'
ext.springLdapVersion = '1.3.2.RELEASE'
ext.springLdap2Version = '2.0.1.RELEASE'
group = 'org.springframework.security'
@@ -37,7 +40,7 @@ allprojects {
maven { url "http://repo.terracotta.org/maven2/" }
}
eclipse.project.name = "${project.name}-4.0.x"
eclipse.project.name = "${project.name}-3.2.x"
}
sonarRunner {
@@ -59,7 +62,7 @@ ext.javaProjects = subprojects.findAll { project -> project.name != 'docs' && pr
ext.sampleProjects = subprojects.findAll { project -> project.name.startsWith('spring-security-samples') }
ext.itestProjects = subprojects.findAll { project -> project.name.startsWith('itest') }
ext.coreModuleProjects = javaProjects - sampleProjects - itestProjects
ext.aspectjProjects = [project(':spring-security-aspects'), project(':spring-security-samples-aspectj-xml'), project(':spring-security-samples-aspectj-jc')]
ext.aspectjProjects = [project(':spring-security-aspects'), project(':spring-security-samples-aspectj-xml')]
configure(allprojects - javaProjects) {
task afterEclipseImport {
@@ -96,18 +99,22 @@ configure(javaProjects) {
}
configure(coreModuleProjects) {
apply plugin: 'bundlor'
apply plugin: 'emma'
apply plugin: 'spring-io'
ext.springIoVersion = project.hasProperty('platformVersion') ? platformVersion : '1.1.0.BUILD-SNAPSHOT'
ext.springIoVersion = project.hasProperty('platformVersion') ? platformVersion : '1.0.0.BUILD-SNAPSHOT'
bundlor.doFirst {
def templateText = file("template.mf").text
bundlor.manifestTemplate = new SimpleTemplateEngine().createTemplate(templateText).make(bundlorProperties).toString()
}
configurations {
jacoco //Configuration Group used by Sonar to provide Code Coverage using JaCoCo
}
dependencies {
springIoVersions "io.spring.platform:platform-versions:${springIoVersion}@properties"
jacoco "org.jacoco:org.jacoco.agent:0.6.2.201302030002:runtime"
springIoVersions "io.spring.platform:platform-versions:${springIoVersion}@properties"
}
test {
jvmArgs "-javaagent:${configurations.jacoco.asPath}=destfile=${buildDir}/jacoco.exec,includes=${project.group}.*"
@@ -166,5 +173,5 @@ artifacts {
}
task wrapper(type: Wrapper) {
gradleVersion = '1.12'
gradleVersion = '1.10-rc-2'
}
+1 -1
View File
@@ -5,7 +5,7 @@ dependencies {
"org.springframework:spring-context:$springVersion",
"org.springframework:spring-beans:$springVersion",
"org.springframework:spring-web:$springVersion",
"org.jasig.cas.client:cas-client-core:3.3.3"
"org.jasig.cas.client:cas-client-core:3.2.1"
optional "net.sf.ehcache:ehcache-core:$ehcacheVersion"
+10 -16
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>spring-security-cas</name>
<description>spring-security-cas</description>
<url>http://spring.io/spring-security</url>
@@ -42,47 +42,41 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.3.3</version>
<version>3.2.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -94,7 +88,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -107,7 +101,7 @@
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.5</version>
<version>1.7.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@@ -150,7 +144,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -49,7 +49,9 @@ public class ServiceProperties implements InitializingBean {
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.hasLength(this.service, "service cannot be empty.");
if(!authenticateAllArtifacts) {
Assert.hasLength(this.service, "service must be specified unless authenticateAllArtifacts is true.");
}
Assert.hasLength(this.artifactParameter, "artifactParameter cannot be empty.");
Assert.hasLength(this.serviceParameter, "serviceParameter cannot be empty.");
}
@@ -15,8 +15,6 @@
*/
package org.springframework.security.cas.web.authentication;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
@@ -52,13 +50,11 @@ final class DefaultServiceAuthenticationDetails extends WebAuthenticationDetails
* string from containing the artifact name and value. This can
* be created using {@link #createArtifactPattern(String)}.
*/
DefaultServiceAuthenticationDetails(String casService, HttpServletRequest request, Pattern artifactPattern) throws MalformedURLException {
DefaultServiceAuthenticationDetails(HttpServletRequest request, Pattern artifactPattern) {
super(request);
URL casServiceUrl = new URL(casService);
int port = getServicePort(casServiceUrl);
final String query = getQueryString(request,artifactPattern);
this.serviceUrl = UrlUtils.buildFullRequestUrl(casServiceUrl.getProtocol(),
casServiceUrl.getHost(), port,
this.serviceUrl = UrlUtils.buildFullRequestUrl(request.getScheme(),
request.getServerName(), request.getServerPort(),
request.getRequestURI(), query);
}
@@ -132,17 +128,4 @@ final class DefaultServiceAuthenticationDetails extends WebAuthenticationDetails
Assert.hasLength(artifactParameterName);
return Pattern.compile("&?"+Pattern.quote(artifactParameterName)+"=[^&]*");
}
/**
* Gets the port from the casServiceURL ensuring to return the proper value if the default port is being used.
* @param casServiceUrl the casServerUrl to be used (i.e. "https://example.com/context/j_spring_security_cas_check")
* @return the port that is configured for the casServerUrl
*/
private static int getServicePort(URL casServiceUrl) {
int port = casServiceUrl.getPort();
if(port == -1) {
port = casServiceUrl.getDefaultPort();
}
return port;
}
}
@@ -15,18 +15,12 @@
*/
package org.springframework.security.cas.web.authentication;
import java.net.MalformedURLException;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.util.Assert;
/**
* The {@code AuthenticationDetailsSource} that is set on the
@@ -39,33 +33,20 @@ import org.springframework.util.Assert;
* @author Rob Winch
*/
public class ServiceAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest,
ServiceAuthenticationDetails>, ApplicationContextAware {
ServiceAuthenticationDetails> {
//~ Instance fields ================================================================================================
private final Pattern artifactPattern;
private ServiceProperties serviceProperties;
//~ Constructors ===================================================================================================
/**
* Creates an implementation that uses the default CAS artifactParameterName.
* @deprecated Use ServiceAuthenticationDetailsSource(ServiceProperties)
*/
@Deprecated
public ServiceAuthenticationDetailsSource() {
this(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER);
}
/**
* Creates an implementation that uses the specified ServiceProperites and the default CAS artifactParameterName.
*
* @param serviceProperties The ServiceProperties to use to construct the serviceUrl.
*/
public ServiceAuthenticationDetailsSource(ServiceProperties serviceProperties) {
this(serviceProperties,ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER);
}
/**
* Creates an implementation that uses the specified artifactParameterName
*
@@ -73,27 +54,11 @@ public class ServiceAuthenticationDetailsSource implements AuthenticationDetails
* the artifactParameterName that is removed from the current
* URL. The result becomes the service url. Cannot be null and
* cannot be an empty String.
* @deprecated Use ServiceAuthenticationDetailsSource(ServiceProperties,String)
*/
public ServiceAuthenticationDetailsSource(final String artifactParameterName) {
this.artifactPattern = DefaultServiceAuthenticationDetails.createArtifactPattern(artifactParameterName);
}
/**
* Creates an implementation that uses the specified artifactParameterName
*
* @param serviceProperties The ServiceProperties to use to construct the serviceUrl.
* @param artifactParameterName
* the artifactParameterName that is removed from the current
* URL. The result becomes the service url. Cannot be null and
* cannot be an empty String.
*/
public ServiceAuthenticationDetailsSource(ServiceProperties serviceProperties, String artifactParameterName) {
Assert.notNull(serviceProperties, "serviceProperties cannot be null");
this.serviceProperties = serviceProperties;
this.artifactPattern = DefaultServiceAuthenticationDetails.createArtifactPattern(artifactParameterName);
}
//~ Methods ========================================================================================================
/**
@@ -101,17 +66,6 @@ public class ServiceAuthenticationDetailsSource implements AuthenticationDetails
* @return the {@code ServiceAuthenticationDetails} containing information about the current request
*/
public ServiceAuthenticationDetails buildDetails(HttpServletRequest context) {
try {
return new DefaultServiceAuthenticationDetails(serviceProperties.getService(),context,artifactPattern);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(serviceProperties == null) {
serviceProperties = applicationContext.getBean(ServiceProperties.class);
}
return new DefaultServiceAuthenticationDetails(context,artifactPattern);
}
}
@@ -36,13 +36,10 @@ public class ServicePropertiesTests {
}
@Test
public void nullServiceWhenAuthenticateAllTokens() throws Exception {
public void allowNullServiceWhenAuthenticateAllTokens() throws Exception {
ServiceProperties sp = new ServiceProperties();
sp.setAuthenticateAllArtifacts(true);
try {
sp.afterPropertiesSet();
fail("Expected Exception");
}catch(IllegalArgumentException success) {}
sp.afterPropertiesSet();
sp.setAuthenticateAllArtifacts(false);
try {
sp.afterPropertiesSet();
@@ -18,21 +18,11 @@ import static org.junit.Assert.assertEquals;
import java.util.regex.Pattern;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*
@@ -42,13 +32,9 @@ public class DefaultServiceAuthenticationDetailsTests {
private DefaultServiceAuthenticationDetails details;
private MockHttpServletRequest request;
private Pattern artifactPattern;
private String casServiceUrl;
private ConfigurableApplicationContext context;
@Before
public void setUp() {
casServiceUrl = "https://localhost:8443/j_spring_security_cas";
request = new MockHttpServletRequest();
request.setScheme("https");
request.setServerName("localhost");
@@ -58,82 +44,45 @@ public class DefaultServiceAuthenticationDetailsTests {
}
@After
public void cleanup() {
if(context != null) {
context.close();
}
}
@Test
public void getServiceUrlNullQuery() throws Exception {
details = new DefaultServiceAuthenticationDetails(casServiceUrl, request,artifactPattern);
assertEquals(UrlUtils.buildFullRequestUrl(request), details.getServiceUrl());
details = new DefaultServiceAuthenticationDetails(request,artifactPattern);
assertEquals(UrlUtils.buildFullRequestUrl(request),details.getServiceUrl());
}
@Test
public void getServiceUrlTicketOnlyParam() throws Exception {
public void getServiceUrlTicketOnlyParam() {
request.setQueryString("ticket=123");
details = new DefaultServiceAuthenticationDetails(casServiceUrl,request,artifactPattern);
details = new DefaultServiceAuthenticationDetails(request,artifactPattern);
String serviceUrl = details.getServiceUrl();
request.setQueryString(null);
assertEquals(UrlUtils.buildFullRequestUrl(request),serviceUrl);
}
@Test
public void getServiceUrlTicketFirstMultiParam() throws Exception {
public void getServiceUrlTicketFirstMultiParam() {
request.setQueryString("ticket=123&other=value");
details = new DefaultServiceAuthenticationDetails(casServiceUrl, request,artifactPattern);
details = new DefaultServiceAuthenticationDetails(request,artifactPattern);
String serviceUrl = details.getServiceUrl();
request.setQueryString("other=value");
assertEquals(UrlUtils.buildFullRequestUrl(request),serviceUrl);
}
@Test
public void getServiceUrlTicketLastMultiParam() throws Exception {
public void getServiceUrlTicketLastMultiParam() {
request.setQueryString("other=value&ticket=123");
details = new DefaultServiceAuthenticationDetails(casServiceUrl,request,artifactPattern);
details = new DefaultServiceAuthenticationDetails(request,artifactPattern);
String serviceUrl = details.getServiceUrl();
request.setQueryString("other=value");
assertEquals(UrlUtils.buildFullRequestUrl(request),serviceUrl);
}
@Test
public void getServiceUrlTicketMiddleMultiParam() throws Exception {
public void getServiceUrlTicketMiddleMultiParam() {
request.setQueryString("other=value&ticket=123&last=this");
details = new DefaultServiceAuthenticationDetails(casServiceUrl,request,artifactPattern);
details = new DefaultServiceAuthenticationDetails(request,artifactPattern);
String serviceUrl = details.getServiceUrl();
request.setQueryString("other=value&last=this");
assertEquals(UrlUtils.buildFullRequestUrl(request),serviceUrl);
}
@Test
public void getServiceUrlDoesNotUseHostHeader() throws Exception {
casServiceUrl = "https://example.com/j_spring_security_cas";
request.setServerName("evil.com");
details = new DefaultServiceAuthenticationDetails(casServiceUrl, request,artifactPattern);
assertEquals("https://example.com/cas-sample/secure/",details.getServiceUrl());
}
@Test
public void getServiceUrlDoesNotUseHostHeaderPassivity() {
casServiceUrl = "https://example.com/j_spring_security_cas";
request.setServerName("evil.com");
ServiceAuthenticationDetails details = loadServiceAuthenticationDetails("defaultserviceauthenticationdetails-passivity.xml");
assertEquals("https://example.com/cas-sample/secure/", details.getServiceUrl());
}
@Test
public void getServiceUrlDoesNotUseHostHeaderExplicit() {
casServiceUrl = "https://example.com/j_spring_security_cas";
request.setServerName("evil.com");
ServiceAuthenticationDetails details = loadServiceAuthenticationDetails("defaultserviceauthenticationdetails-explicit.xml");
assertEquals("https://example.com/cas-sample/secure/", details.getServiceUrl());
}
private ServiceAuthenticationDetails loadServiceAuthenticationDetails(String resourceName) {
context = new GenericXmlApplicationContext(getClass(), resourceName);
ServiceAuthenticationDetailsSource source = context.getBean(ServiceAuthenticationDetailsSource.class);
return source.buildDetails(request);
}
}
@@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="serviceProperties"
class="org.springframework.security.cas.ServiceProperties">
<property name="service"
value="https://example.com/j_spring_security_cas"/>
<property name="sendRenew" value="false"/>
</bean>
<bean id="serviceProperties2"
class="org.springframework.security.cas.ServiceProperties">
<property name="service"
value="https://example2.com/j_spring_security_cas"/>
<property name="sendRenew" value="false"/>
</bean>
<bean class="org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource">
<constructor-arg ref="serviceProperties"/>
</bean>
</beans>
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="serviceProperties"
class="org.springframework.security.cas.ServiceProperties">
<property name="service"
value="https://example.com/j_spring_security_cas"/>
<property name="sendRenew" value="false"/>
</bean>
<bean class="org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource"/>
</beans>
+23
View File
@@ -0,0 +1,23 @@
Implementation-Title: org.springframework.security.cas
Implementation-Version: ${version}
Bundle-SymbolicName: org.springframework.security.cas
Bundle-Name: Spring Security CAS
Bundle-Vendor: SpringSource
Bundle-Version: ${version}
Bundle-ManifestVersion: 2
Ignored-Existing-Headers:
Import-Package,
Export-Package
Import-Template:
org.apache.commons.logging.*;version="${cloggingRange}",
org.jasig.cas.client.*;version="${casRange}",
org.springframework.security.core.*;version="${secRange}",
org.springframework.security.authentication.*;version="${secRange}",
org.springframework.security.web.*;version="${secRange}",
org.springframework.beans.factory;version="${springRange}",
org.springframework.cache.*;version="${springRange}";resolution:=optional,
org.springframework.context.*;version="${springRange}",
org.springframework.dao;version="${springRange}",
org.springframework.util;version="${springRange}",
net.sf.ehcache.*;version="${ehcacheRange}";resolution:=optional,
javax.servlet.*;version="0"
+2 -5
View File
@@ -18,9 +18,7 @@ dependencies {
optional project(':spring-security-web'),
project(':spring-security-ldap'),
project(':spring-security-openid'),
project(':spring-security-messaging'),
"org.springframework:spring-web:$springVersion",
"org.springframework:spring-websocket:$springVersion",
"org.springframework:spring-web:$springVersion",
"org.springframework:spring-webmvc:$springVersion",
"org.aspectj:aspectjweaver:$aspectjVersion",
"org.springframework:spring-jdbc:$springVersion",
@@ -30,7 +28,6 @@ dependencies {
testCompile project(':spring-security-cas'),
project(':spring-security-core').sourceSets.test.output,
project(':spring-security-aspects'),
'javax.annotation:jsr250-api:1.0',
"org.springframework.ldap:spring-ldap-core:$springLdapVersion",
"org.springframework:spring-expression:$springVersion",
@@ -56,7 +53,7 @@ dependencies {
testCompile('org.openid4java:openid4java-nodeps:0.9.6') {
exclude group: 'com.google.code.guice', module: 'guice'
}
testCompile("org.springframework.data:spring-data-jpa:$springDataJpaVersion") {
testCompile('org.springframework.data:spring-data-jpa:1.4.1.RELEASE') {
exclude group: 'org.aspectj', module: 'aspectjrt'
}
+19 -45
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>spring-security-config</name>
<description>spring-security-config</description>
<url>http://spring.io/spring-security</url>
@@ -42,12 +42,6 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>aopalliance</groupId>
@@ -58,31 +52,31 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -108,63 +102,49 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>4.0.0.M2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-openid</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.0.RC2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@@ -375,7 +355,7 @@
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.7.0.RC1</version>
<version>1.4.1.RELEASE</version>
<scope>test</scope>
<exclusions>
<exclusion>
@@ -387,37 +367,31 @@
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.0.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-aspects</artifactId>
<version>4.0.0.M2</version>
<version>1.3.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -1,61 +0,0 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.authentication.ldap
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.authentication.ldap.NamespaceLdapAuthenticationProviderTestsConfigs.LdapAuthenticationProviderConfig
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider
import org.springframework.security.ldap.authentication.PasswordComparisonAuthenticator
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator
import org.springframework.security.ldap.userdetails.PersonContextMapper
import org.springframework.test.util.ReflectionTestUtils
import static org.springframework.security.config.annotation.authentication.ldap.NamespaceLdapAuthenticationProviderTestsConfigs.*
/**
*
* @author Rob Winch
*
*/
class LdapAuthenticationProviderConfigurerTests extends BaseSpringSpec {
def "authentication-manager support multiple default ldap contexts (ports dynamically allocated)"() {
when:
loadConfig(MultiLdapAuthenticationProvidersConfig)
then:
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("bob","bobspassword"))
}
@EnableWebSecurity
@Configuration
static class MultiLdapAuthenticationProvidersConfig extends WebSecurityConfigurerAdapter {
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.groupSearchBase("ou=groups")
.userDnPatterns("uid={0},ou=people")
.and()
.ldapAuthentication()
.groupSearchBase("ou=groups")
.userDnPatterns("uid={0},ou=people")
}
}
}
@@ -15,12 +15,10 @@
*/
package org.springframework.security.config.annotation.authentication.ldap
import org.springframework.beans.factory.config.AutowireCapableBeanFactory
import org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import org.springframework.security.authentication.AuthenticationManager
@@ -29,12 +27,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.authentication.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication
import org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor
import org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessorTests
import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
@@ -65,7 +58,6 @@ class LdapAuthenticationProviderBuilderSecurityBuilderTests extends BaseSpringSp
auth
.ldapAuthentication()
.contextSource(contextSource())
.userDnPatterns("uid={0},ou=people")
}
}
@@ -83,7 +75,6 @@ class LdapAuthenticationProviderBuilderSecurityBuilderTests extends BaseSpringSp
auth
.ldapAuthentication()
.contextSource(contextSource())
.userDnPatterns("uid={0},ou=people")
.groupRoleAttribute("group")
}
}
@@ -102,7 +93,6 @@ class LdapAuthenticationProviderBuilderSecurityBuilderTests extends BaseSpringSp
auth
.ldapAuthentication()
.contextSource(contextSource())
.userDnPatterns("uid={0},ou=people")
.groupSearchFilter("ou=groupName");
}
}
@@ -121,7 +111,6 @@ class LdapAuthenticationProviderBuilderSecurityBuilderTests extends BaseSpringSp
auth
.ldapAuthentication()
.contextSource(contextSource())
.userDnPatterns("uid={0},ou=people")
.rolePrefix("role_")
}
}
@@ -132,7 +121,7 @@ class LdapAuthenticationProviderBuilderSecurityBuilderTests extends BaseSpringSp
AuthenticationManager auth = context.getBean(AuthenticationManager)
then:
auth
auth.authenticate(new UsernamePasswordAuthenticationToken("bob","bobspassword")).authorities.collect { it.authority }.sort() == ["ROLE_DEVELOPERS"]
auth.authenticate(new UsernamePasswordAuthenticationToken("admin","password")).authorities.collect { it.authority }.sort() == ["ROLE_ADMIN","ROLE_USER"]
}
@Configuration
@@ -142,29 +131,30 @@ class LdapAuthenticationProviderBuilderSecurityBuilderTests extends BaseSpringSp
.ldapAuthentication()
.contextSource(contextSource())
.groupSearchBase("ou=groups")
.groupSearchFilter("(member={0})")
.userDnPatterns("uid={0},ou=people");
}
}
def "SEC-2472: Can use crypto PasswordEncoder"() {
setup:
PasswordEncoderConfig.PE = Mock(PasswordEncoder)
loadConfig(PasswordEncoderConfig)
when:
AuthenticationManager auth = context.getBean(AuthenticationManager)
then:
auth.authenticate(new UsernamePasswordAuthenticationToken("bcrypt","password")).authorities.collect { it.authority }.sort() == ["ROLE_DEVELOPERS"]
auth.authenticate(new UsernamePasswordAuthenticationToken("admin","password")).authorities.collect { it.authority }.sort() == ["ROLE_ADMIN","ROLE_USER"]
PasswordEncoderConfig.PE.matches(_, _) << true
}
@Configuration
static class PasswordEncoderConfig extends BaseLdapServerConfig {
static PasswordEncoder PE
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.contextSource(contextSource())
.passwordEncoder(new BCryptPasswordEncoder())
.passwordEncoder(PE)
.groupSearchBase("ou=groups")
.groupSearchFilter("(member={0})")
.userDnPatterns("uid={0},ou=people");
}
}
@@ -177,44 +167,23 @@ class LdapAuthenticationProviderBuilderSecurityBuilderTests extends BaseSpringSp
static abstract class BaseLdapServerConfig extends BaseLdapProviderConfig {
@Bean
public ApacheDSContainer ldapServer() throws Exception {
ApacheDSContainer apacheDSContainer = new ApacheDSContainer("dc=springframework,dc=org", "classpath:/test-server.ldif");
apacheDSContainer.setPort(getPort());
ApacheDSContainer apacheDSContainer = new ApacheDSContainer("dc=springframework,dc=org", "classpath:/users.ldif");
apacheDSContainer.setPort(33389);
return apacheDSContainer;
}
}
@Configuration
@EnableGlobalAuthentication
@Import(ObjectPostProcessorConfiguration)
static abstract class BaseLdapProviderConfig {
@Bean
public BaseLdapPathContextSource contextSource() throws Exception {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(
"ldap://127.0.0.1:"+ getPort() + "/dc=springframework,dc=org")
"ldap://127.0.0.1:33389/dc=springframework,dc=org")
contextSource.userDn = "uid=admin,ou=system"
contextSource.password = "secret"
contextSource.afterPropertiesSet()
contextSource.afterPropertiesSet();
return contextSource;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationManagerBuilder auth) {
configure(auth)
auth.build()
}
abstract protected void configure(AuthenticationManagerBuilder auth)
}
static Integer port;
static int getPort() {
if(port == null) {
ServerSocket socket = new ServerSocket(0)
port = socket.localPort
socket.close()
}
port
}
}
@@ -40,7 +40,7 @@ class NamespaceLdapAuthenticationProviderTests extends BaseSpringSpec {
when:
loadConfig(LdapAuthenticationProviderConfig)
then:
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("bob","bobspassword"))
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user","password")).authorities*.authority.sort() == ['ROLE_USER']
}
def "ldap-authentication-provider custom"() {
@@ -75,6 +75,6 @@ class NamespaceLdapAuthenticationProviderTests extends BaseSpringSpec {
LdapAuthenticationProvider provider = findAuthenticationProvider(LdapAuthenticationProvider)
then:
provider.authenticator instanceof PasswordComparisonAuthenticator
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("bob","bobspassword"))
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user","password")).authorities*.authority.sort() == ['ROLE_USER']
}
}
@@ -56,7 +56,7 @@ public class NamespaceLdapAuthenticationProviderTestsConfigs {
.userSearchFilter("(uid={0})") // ldap-authentication-provider@user-search-filter
// .contextSource(contextSource) // ldap-authentication-provider@server-ref
.contextSource()
.ldif("classpath:users.xldif") // ldap-server@ldif
.ldif("classpath:user.ldif") // ldap-server@ldif
.managerDn("uid=admin,ou=system") // ldap-server@manager-dn
.managerPassword("secret") // ldap-server@manager-password
.port(33399) // ldap-server@port
@@ -68,22 +68,11 @@ sn: Mouse
uid: jerry
userPassword: jerryspassword
dn: uid=bcrypt,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: BCrypt user
sn: BCrypt
uid: bcrypt
userPassword: $2a$10$lDa0YFNHAt63MjIzK/wUqeM0qjIhzPhp3RNI/MLUQEAUbzhB/SnnS
dn: cn=developers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: developers
ou: developer
member: uid=bcrypt,ou=people,dc=springframework,dc=org
member: uid=ben,ou=people,dc=springframework,dc=org
member: uid=bob,ou=people,dc=springframework,dc=org
@@ -0,0 +1,42 @@
dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups
dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people
dn: uid=admin,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Rod Johnson
sn: Johnson
uid: admin
userPassword: password
dn: uid=user,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Dianne Emu
sn: Emu
uid: user
userPassword: password
dn: cn=user,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: user
uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
uniqueMember: uid=user,ou=people,dc=springframework,dc=org
dn: cn=admin,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: admin
uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
@@ -1,92 +0,0 @@
dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups
dn: ou=subgroups,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: subgroups
dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people
dn: ou=otherpeople,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: otherpeople
dn: uid=ben,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Ben Alex
sn: Alex
uid: ben
userPassword: {SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=
dn: uid=bcrypt,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: BCrypt user
sn: BCrypt
uid: bcrypt
userPassword: $2a$10$lDa0YFNHAt63MjIzK/wUqeM0qjIhzPhp3RNI/MLUQEAUbzhB/SnnS
dn: uid=bob,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Bob Hamilton
sn: Hamilton
uid: bob
userPassword: bobspassword
dn: uid=joe,ou=otherpeople,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Joe Smeth
sn: Smeth
uid: joe
userPassword: joespassword
dn: cn=mouse\, jerry,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Mouse, Jerry
sn: Mouse
uid: jerry
userPassword: jerryspassword
dn: cn=developers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: developers
ou: developer
member: uid=ben,ou=people,dc=springframework,dc=org
member: uid=bob,ou=people,dc=springframework,dc=org
dn: cn=managers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: managers
ou: manager
member: uid=ben,ou=people,dc=springframework,dc=org
member: cn=mouse\, jerry,ou=people,dc=springframework,dc=org
dn: cn=submanagers,ou=subgroups,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: submanagers
ou: submanager
member: uid=ben,ou=people,dc=springframework,dc=org
@@ -42,9 +42,6 @@ import org.springframework.security.ldap.userdetails.PersonContextMapper;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
import org.springframework.util.Assert;
import java.io.IOException;
import java.net.ServerSocket;
/**
* Configures LDAP {@link AuthenticationProvider} in the {@link ProviderManagerBuilder}.
*
@@ -64,7 +61,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
private BaseLdapPathContextSource contextSource;
private ContextSourceBuilder contextSourceBuilder = new ContextSourceBuilder();
private UserDetailsContextMapper userDetailsContextMapper;
private Object passwordEncoder;
private PasswordEncoder passwordEncoder;
private String passwordAttribute;
private LdapAuthoritiesPopulator ldapAuthoritiesPopulator;
@@ -153,9 +150,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
*/
private PasswordComparisonAuthenticator createPasswordCompareAuthenticator(BaseLdapPathContextSource contextSource) {
PasswordComparisonAuthenticator ldapAuthenticator = new PasswordComparisonAuthenticator(contextSource);
if(passwordAttribute != null) {
ldapAuthenticator.setPasswordAttributeName(passwordAttribute);
}
ldapAuthenticator.setPasswordAttributeName(passwordAttribute);
ldapAuthenticator.setPasswordEncoder(passwordEncoder);
return ldapAuthenticator;
}
@@ -226,7 +221,21 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
*/
public LdapAuthenticationProviderConfigurer<B> passwordEncoder(final org.springframework.security.crypto.password.PasswordEncoder passwordEncoder) {
Assert.notNull(passwordEncoder, "passwordEncoder must not be null.");
this.passwordEncoder = passwordEncoder;
passwordEncoder(new PasswordEncoder() {
public String encodePassword(String rawPass, Object salt) {
checkSalt(salt);
return passwordEncoder.encode(rawPass);
}
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
checkSalt(salt);
return passwordEncoder.matches(rawPass, encPass);
}
private void checkSalt(Object salt) {
Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");
}
});
return this;
}
@@ -393,8 +402,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
private String ldif = "classpath*:*.ldif";
private String managerPassword;
private String managerDn;
private Integer port;
private static final int DEFAULT_PORT = 33389;
private int port = 33389;
private String root = "dc=springframework,dc=org";
private String url;
@@ -439,7 +447,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
}
/**
* The port to connect to LDAP to (the default is 33389 or random available port if unavailable).
* The port to connect to LDAP to (the default is 33389).
* @param port the port to connect to
* @return the {@link ContextSourceBuilder} for further customization
*/
@@ -499,43 +507,14 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
return contextSource;
}
ApacheDSContainer apacheDsContainer = new ApacheDSContainer(root, ldif);
apacheDsContainer.setPort(getPort());
apacheDsContainer.setPort(port);
postProcess(apacheDsContainer);
return contextSource;
}
private int getPort() {
if(port == null) {
port = getDefaultPort();
}
return port;
}
private int getDefaultPort() {
ServerSocket serverSocket = null;
try {
try {
serverSocket = new ServerSocket(DEFAULT_PORT);
} catch (IOException e) {
try {
serverSocket = new ServerSocket(0);
} catch(IOException e2) {
return DEFAULT_PORT;
}
}
return serverSocket.getLocalPort();
} finally {
if(serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {}
}
}
}
private String getProviderUrl() {
if(url == null) {
return "ldap://127.0.0.1:" + getPort() + "/" + root;
return "ldap://127.0.0.1:" + port + "/" + root;
}
return url;
}
@@ -18,8 +18,6 @@ package org.springframework.security.config.annotation.method.configuration;
import java.util.Map;
import org.springframework.aop.config.AopConfigUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
@@ -52,15 +50,18 @@ class GlobalMethodSecurityAspectJAutoProxyRegistrar implements
AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
BeanDefinition interceptor = registry.getBeanDefinition("methodSecurityInterceptor");
AopConfigUtils
.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
BeanDefinitionBuilder aspect =
BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect");
aspect.setFactoryMethod("aspectOf");
aspect.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
aspect.addPropertyValue("securityInterceptor", interceptor);
Map<String, Object> annotationAttributes = importingClassMetadata
.getAnnotationAttributes(EnableGlobalMethodSecurity.class
.getName());
AnnotationAttributes enableAJAutoProxy = AnnotationAttributes
.fromMap(annotationAttributes);
registry.registerBeanDefinition("annotationSecurityAspect$0", aspect.getBeanDefinition());
if (enableAJAutoProxy.getBoolean("proxyTargetClass")) {
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
}
}
}
@@ -24,7 +24,10 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.context.annotation.Role;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.AnnotationMetadata;
@@ -45,7 +48,6 @@ import org.springframework.security.access.intercept.AfterInvocationProviderMana
import org.springframework.security.access.intercept.RunAsManager;
import org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor;
import org.springframework.security.access.intercept.aopalliance.MethodSecurityMetadataSourceAdvisor;
import org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor;
import org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource;
import org.springframework.security.access.method.MethodSecurityMetadataSource;
import org.springframework.security.access.prepost.PostInvocationAdviceProvider;
@@ -109,7 +111,7 @@ public class GlobalMethodSecurityConfiguration implements ImportAware {
*/
@Bean
public MethodInterceptor methodSecurityInterceptor() throws Exception {
MethodSecurityInterceptor methodSecurityInterceptor = isAspectJ() ? new AspectJMethodSecurityInterceptor() : new MethodSecurityInterceptor();
MethodSecurityInterceptor methodSecurityInterceptor = new MethodSecurityInterceptor();
methodSecurityInterceptor
.setAccessDecisionManager(accessDecisionManager());
methodSecurityInterceptor
@@ -377,10 +379,6 @@ public class GlobalMethodSecurityConfiguration implements ImportAware {
return (Integer) enableMethodSecurity().get("order");
}
private boolean isAspectJ() {
return enableMethodSecurity().getEnum("mode") == AdviceMode.ASPECTJ;
}
private AnnotationAttributes enableMethodSecurity() {
if (enableMethodSecurity == null) {
// if it is null look at this instance (i.e. a subclass was used)
@@ -1000,7 +1000,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
* .and()
* .formLogin()
* .and()
* .requiresChannel()
* .channelSecurity()
* .anyRequest().requiresSecure();
* }
*
@@ -1,303 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.config.annotation.web.messaging;
import org.springframework.messaging.Message;
import org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer;
import org.springframework.security.messaging.access.expression.ExpressionBasedMessageSecurityMetadataSourceFactory;
import org.springframework.security.messaging.access.intercept.MessageSecurityMetadataSource;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import java.util.*;
/**
* Allows mapping security constraints using {@link MessageMatcher} to the security expressions.
*
* @since 4.0
* @author Rob Winch
*/
public class MessageSecurityMetadataSourceRegistry {
private static final String permitAll = "permitAll";
private static final String denyAll = "denyAll";
private static final String anonymous = "anonymous";
private static final String authenticated = "authenticated";
private static final String fullyAuthenticated = "fullyAuthenticated";
private static final String rememberMe = "rememberMe";
private final LinkedHashMap<MatcherBuilder,String> matcherToExpression = new LinkedHashMap<MatcherBuilder,String>();
private PathMatcher pathMatcher = new AntPathMatcher();
/**
* Maps any {@link Message} to a security expression.
*
* @return the Expression to associate
*/
public Constraint anyMessage() {
return matchers(MessageMatcher.ANY_MESSAGE);
}
/**
* Maps a {@link List} of {@link org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher} instances.
*
* @param patterns the patterns to create {@link org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher}
* from. Uses {@link MessageSecurityMetadataSourceRegistry#pathMatcher(PathMatcher)}.
*
* @return the {@link Constraint} that is associated to the {@link MessageMatcher}
* @see {@link MessageSecurityMetadataSourceRegistry#pathMatcher(PathMatcher)}
*/
public Constraint destinationMatchers(String... patterns) {
List<MatcherBuilder> matchers = new ArrayList<MatcherBuilder>(patterns.length);
for(String pattern : patterns) {
matchers.add(new PathMatcherMessageMatcherBuilder(pattern));
}
return new Constraint(matchers);
}
/**
* The {@link PathMatcher} to be used with the {@link MessageSecurityMetadataSourceRegistry#destinationMatchers(String...)}.
* The default is to use the default constructor of {@link AntPathMatcher}.
*
* @param pathMatcher the {@link PathMatcher} to use. Cannot be null.
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization.
*/
public MessageSecurityMetadataSourceRegistry pathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "pathMatcher cannot be null");
this.pathMatcher = pathMatcher;
return this;
}
/**
* Maps a {@link List} of {@link MessageMatcher} instances to a security expression.
*
* @param matchers the {@link MessageMatcher} instances to map.
* @return The {@link Constraint} that is associated to the {@link MessageMatcher} instances
*/
public Constraint matchers(MessageMatcher<?>... matchers) {
List<MatcherBuilder> builders = new ArrayList<MatcherBuilder>(matchers.length);
for(MessageMatcher<?> matcher : matchers) {
builders.add(new PreBuiltMatcherBuilder(matcher));
}
return new Constraint(builders);
}
/**
* Allows subclasses to create creating a {@link MessageSecurityMetadataSource}.
*
* <p>This is not exposed so as not to confuse users of the API, which should never invoke this method.</p>
*
* @return the {@link MessageSecurityMetadataSource} to use
*/
protected MessageSecurityMetadataSource createMetadataSource() {
LinkedHashMap<MessageMatcher<?>,String> matcherToExpression = new LinkedHashMap<MessageMatcher<?>,String>();
for(Map.Entry<MatcherBuilder,String> entry : this.matcherToExpression.entrySet()) {
matcherToExpression.put(entry.getKey().build(), entry.getValue());
}
return ExpressionBasedMessageSecurityMetadataSourceFactory.createExpressionMessageMetadataSource(matcherToExpression);
}
/**
* Represents the security constraint to be applied to the {@link MessageMatcher} instances.
*/
public class Constraint {
private final List<MatcherBuilder> messageMatchers;
/**
* Creates a new instance
*
* @param messageMatchers the {@link MessageMatcher} instances to map to this constraint
*/
private Constraint(List<MatcherBuilder> messageMatchers) {
Assert.notEmpty(messageMatchers, "messageMatchers cannot be null or empty");
this.messageMatchers = messageMatchers;
}
/**
* Shortcut for specifying {@link Message} instances require a particular role. If you do not want to have "ROLE_" automatically
* inserted see {@link #hasAuthority(String)}.
*
* @param role the role to require (i.e. USER, ADMIN, etc). Note, it should not start with "ROLE_" as
* this is automatically inserted.
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
*/
public MessageSecurityMetadataSourceRegistry hasRole(String role) {
return access(MessageSecurityMetadataSourceRegistry.hasRole(role));
}
/**
* Shortcut for specifying {@link Message} instances require any of a number of roles. If you
* do not want to have "ROLE_" automatically inserted see
* {@link #hasAnyAuthority(String...)}
*
* @param roles
* the roles to require (i.e. USER, ADMIN, etc). Note, it
* should not start with "ROLE_" as this is automatically
* inserted.
* @return the {@link MessageSecurityMetadataSourceRegistry} for further
* customization
*/
public MessageSecurityMetadataSourceRegistry hasAnyRole(String... roles) {
return access(MessageSecurityMetadataSourceRegistry.hasAnyRole(roles));
}
/**
* Specify that {@link Message} instances require a particular authority.
*
* @param authority the authority to require (i.e. ROLE_USER, ROLE_ADMIN, etc).
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
*/
public MessageSecurityMetadataSourceRegistry hasAuthority(String authority) {
return access(MessageSecurityMetadataSourceRegistry.hasAuthority(authority));
}
/**
* Specify that {@link Message} instances requires any of a number authorities.
*
* @param authorities the requests require at least one of the authorities (i.e. "ROLE_USER","ROLE_ADMIN" would
* mean either "ROLE_USER" or "ROLE_ADMIN" is required).
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
*/
public MessageSecurityMetadataSourceRegistry hasAnyAuthority(String... authorities) {
return access(MessageSecurityMetadataSourceRegistry.hasAnyAuthority(authorities));
}
/**
* Specify that Messages are allowed by anyone.
*
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
*/
public MessageSecurityMetadataSourceRegistry permitAll() {
return access(permitAll);
}
/**
* Specify that Messages are allowed by anonymous users.
*
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
*/
public MessageSecurityMetadataSourceRegistry anonymous() {
return access(anonymous);
}
/**
* Specify that Messages are allowed by users that have been remembered.
*
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
* @see {@link RememberMeConfigurer}
*/
public MessageSecurityMetadataSourceRegistry rememberMe() {
return access(rememberMe);
}
/**
* Specify that Messages are not allowed by anyone.
*
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
*/
public MessageSecurityMetadataSourceRegistry denyAll() {
return access(denyAll);
}
/**
* Specify that Messages are allowed by any authenticated user.
*
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
*/
public MessageSecurityMetadataSourceRegistry authenticated() {
return access(authenticated);
}
/**
* Specify that Messages are allowed by users who have authenticated and were not "remembered".
*
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
* @see {@link RememberMeConfigurer}
*/
public MessageSecurityMetadataSourceRegistry fullyAuthenticated() {
return access(fullyAuthenticated);
}
/**
* Allows specifying that Messages are secured by an arbitrary expression
*
* @param attribute the expression to secure the URLs (i.e. "hasRole('ROLE_USER') and hasRole('ROLE_SUPER')")
* @return the {@link MessageSecurityMetadataSourceRegistry} for further customization
*/
public MessageSecurityMetadataSourceRegistry access(String attribute) {
for(MatcherBuilder messageMatcher : messageMatchers) {
matcherToExpression.put(messageMatcher, attribute);
}
return MessageSecurityMetadataSourceRegistry.this;
}
}
private static String hasAnyRole(String... authorities) {
String anyAuthorities = StringUtils.arrayToDelimitedString(authorities, "','ROLE_");
return "hasAnyRole('ROLE_" + anyAuthorities + "')";
}
private static String hasRole(String role) {
Assert.notNull(role, "role cannot be null");
if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException("role should not start with 'ROLE_' since it is automatically inserted. Got '" + role + "'");
}
return "hasRole('ROLE_" + role + "')";
}
private static String hasAuthority(String authority) {
return "hasAuthority('" + authority + "')";
}
private static String hasAnyAuthority(String... authorities) {
String anyAuthorities = StringUtils.arrayToDelimitedString(authorities, "','");
return "hasAnyAuthority('" + anyAuthorities + "')";
}
private class PreBuiltMatcherBuilder implements MatcherBuilder {
private MessageMatcher<?> matcher;
private PreBuiltMatcherBuilder(MessageMatcher<?> matcher) {
this.matcher = matcher;
}
@Override
public MessageMatcher<?> build() {
return matcher;
}
}
private class PathMatcherMessageMatcherBuilder implements MatcherBuilder {
private final String pattern;
private PathMatcherMessageMatcherBuilder(String pattern) {
this.pattern = pattern;
}
@Override
public MessageMatcher<?> build() {
return new SimpDestinationMessageMatcher(pattern, pathMatcher);
}
}
private interface MatcherBuilder {
MessageMatcher<?> build();
}
}
@@ -1,112 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.config.annotation.web.socket;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry;
import org.springframework.security.messaging.access.expression.ExpressionBasedMessageSecurityMetadataSourceFactory;
import org.springframework.security.messaging.access.expression.MessageExpressionVoter;
import org.springframework.security.messaging.access.intercept.ChannelSecurityInterceptor;
import org.springframework.security.messaging.access.intercept.MessageSecurityMetadataSource;
import org.springframework.security.messaging.context.SecurityContextChannelInterceptor;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
/**
* Allows configuring WebSocket Authorization.
*
* <p>For example:</p>
*
* <pre>
* @Configuration
* public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
*
* @Override
* protected void configure(MessageSecurityMetadataSourceRegistry messages) {
* messages
* .destinationMatchers("/user/queue/errors").permitAll()
* .destinationMatchers("/admin/**").hasRole("ADMIN")
* .anyMessage().authenticated();
* }
* }
* </pre>
*
*
* @since 4.0
* @author Rob Winch
*/
@Order(Ordered.HIGHEST_PRECEDENCE + 100)
public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(securityContextChannelInterceptor(),channelSecurity());
}
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.setInterceptors(securityContextChannelInterceptor(),channelSecurity());
}
@Bean
public ChannelSecurityInterceptor channelSecurity() {
ChannelSecurityInterceptor channelSecurityInterceptor = new ChannelSecurityInterceptor(metadataSource());
List<AccessDecisionVoter> voters = new ArrayList<AccessDecisionVoter>();
voters.add(new MessageExpressionVoter());
AffirmativeBased manager = new AffirmativeBased(voters);
channelSecurityInterceptor.setAccessDecisionManager(manager);
return channelSecurityInterceptor;
}
@Bean
public SecurityContextChannelInterceptor securityContextChannelInterceptor() {
return new SecurityContextChannelInterceptor();
}
@Bean
public MessageSecurityMetadataSource metadataSource() {
WebSocketMessageSecurityMetadataSourceRegistry registry = new WebSocketMessageSecurityMetadataSourceRegistry();
configure(registry);
return registry.createMetadataSource();
}
/**
*
* @param messages
*/
protected abstract void configure(MessageSecurityMetadataSourceRegistry messages);
private class WebSocketMessageSecurityMetadataSourceRegistry extends MessageSecurityMetadataSourceRegistry {
@Override
public MessageSecurityMetadataSource createMetadataSource() {
return super.createMetadataSource();
}
}
}
@@ -208,7 +208,7 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
}
String fromParameter = getAttribute(frameElt, ATT_FROM_PARAMETER, "from");
allowFromStrategy.addPropertyValue("allowFromParameterName", fromParameter);
builder.addConstructorArgValue(allowFromStrategy.getBeanDefinition());
builder.addConstructorArgValue(allowFromStrategy);
}
} else {
parserContext.getReaderContext().error("One of 'strategy' and 'strategy-ref' must be set.",
@@ -15,14 +15,11 @@
*/
package org.springframework.security.config.annotation.method.configuration
import org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor
import static org.fest.assertions.Assertions.assertThat
import static org.junit.Assert.fail
import java.lang.reflect.Method
import org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
import org.springframework.beans.factory.BeanCreationException
import org.springframework.context.ConfigurableApplicationContext
@@ -191,8 +188,8 @@ public class NamespaceGlobalMethodSecurityTests extends BaseSpringSpec {
when:
context = new AnnotationConfigApplicationContext(AspectJModeConfig)
then:
context.getBean(AnnotationSecurityAspect)
context.getBean(AspectJMethodSecurityInterceptor)
AnnotationAwareAspectJAutoProxyCreator autoProxyCreator = context.getBean(AnnotationAwareAspectJAutoProxyCreator)
autoProxyCreator.proxyTargetClass == true
}
@Configuration
@@ -204,8 +201,8 @@ public class NamespaceGlobalMethodSecurityTests extends BaseSpringSpec {
when:
context = new AnnotationConfigApplicationContext(BaseMethodConfig,AspectJModeExtendsGMSCConfig)
then:
context.getBean(AnnotationSecurityAspect)
context.getBean(AspectJMethodSecurityInterceptor)
AnnotationAwareAspectJAutoProxyCreator autoProxyCreator = context.getBean(AnnotationAwareAspectJAutoProxyCreator)
autoProxyCreator.proxyTargetClass == false
}
@Configuration
@@ -172,26 +172,6 @@ class HttpHeadersConfigTests extends AbstractHttpConfigTests {
assertHeaders(response, ['X-Frame-Options':'ALLOW-FROM https://example.com'])
}
def 'http headers frame-options ALLOW-FROM with whitelist strategy'() {
when:
httpAutoConfig {
'headers'() {
'frame-options'(policy : 'ALLOW-FROM', strategy: 'whitelist', value : 'https://example.com')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
def request = new MockHttpServletRequest()
request.setParameter("from", "https://example.com");
hf.doFilter(request, response, new MockFilterChain())
then:
assertHeaders(response, ['X-Frame-Options':'ALLOW-FROM https://example.com'])
}
def 'http headers header a=b'() {
when:
httpAutoConfig {
@@ -0,0 +1,34 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:org/springframework/security/config/sec-2508.xml" )
public class Sec2508Tests {
@Autowired
private AuthenticationEntryPoint ep;
@Test
public void loads() {}
}
@@ -1,231 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.config.annotation.web.messaging;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.messaging.access.intercept.MessageSecurityMetadataSource;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.util.AntPathMatcher;
import java.util.Collection;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MessageSecurityMetadataSourceRegistryTests {
@Mock
private MessageMatcher<Object> matcher;
private MessageSecurityMetadataSourceRegistry messages;
private Message<String> message;
@Before
public void setup() {
messages = new MessageSecurityMetadataSourceRegistry();
message = MessageBuilder
.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "location")
.build();
}
// See https://github.com/spring-projects/spring-security/commit/3f30529039c76facf335d6ca69d18d8ae287f3f9#commitcomment-7412712
// https://jira.spring.io/browse/SPR-11660
@Test
public void destinationMatcherCustom() {
message = MessageBuilder
.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2")
.build();
messages
.pathMatcher(new AntPathMatcher("."))
.destinationMatchers("price.stock.*").permitAll();
assertThat(getAttribute()).isNull();
message = MessageBuilder
.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2")
.build();
messages
.pathMatcher(new AntPathMatcher("."))
.destinationMatchers("price.stock.**").permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void destinationMatcherCustomSetAfterMatchersDoesNotMatter() {
message = MessageBuilder
.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2")
.build();
messages
.destinationMatchers("price.stock.*").permitAll()
.pathMatcher(new AntPathMatcher("."));
assertThat(getAttribute()).isNull();
message = MessageBuilder
.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2")
.build();
messages
.destinationMatchers("price.stock.**").permitAll()
.pathMatcher(new AntPathMatcher("."));
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test(expected = IllegalArgumentException.class)
public void pathMatcherNull() {
messages.pathMatcher(null);
}
@Test
public void matchersFalse() {
messages
.matchers(matcher).permitAll();
assertThat(getAttribute()).isNull();
}
@Test
public void matchersTrue() {
when(matcher.matches(message)).thenReturn(true);
messages
.matchers(matcher).permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void destinationMatcherExact() {
messages
.destinationMatchers("location").permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void destinationMatcherMulti() {
messages
.destinationMatchers("admin/**","api/**").hasRole("ADMIN")
.destinationMatchers("location").permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void destinationMatcherRole() {
messages
.destinationMatchers("admin/**","location/**").hasRole("ADMIN")
.anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("hasRole('ROLE_ADMIN')");
}
@Test
public void destinationMatcherAnyRole() {
messages
.destinationMatchers("admin/**","location/**").hasAnyRole("ADMIN", "ROOT")
.anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("hasAnyRole('ROLE_ADMIN','ROLE_ROOT')");
}
@Test
public void destinationMatcherAuthority() {
messages
.destinationMatchers("admin/**","location/**").hasAuthority("ROLE_ADMIN")
.anyMessage().fullyAuthenticated();
assertThat(getAttribute()).isEqualTo("hasAuthority('ROLE_ADMIN')");
}
@Test
public void destinationMatcherAccess() {
String expected = "hasRole('ROLE_ADMIN') and fullyAuthenticated";
messages
.destinationMatchers("admin/**","location/**").access(expected)
.anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo(expected);
}
@Test
public void destinationMatcherAnyAuthority() {
messages
.destinationMatchers("admin/**","location/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_ROOT")
.anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("hasAnyAuthority('ROLE_ADMIN','ROLE_ROOT')");
}
@Test
public void destinationMatcherRememberMe() {
messages
.destinationMatchers("admin/**","location/**").rememberMe()
.anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("rememberMe");
}
@Test
public void destinationMatcherAnonymous() {
messages
.destinationMatchers("admin/**","location/**").anonymous()
.anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("anonymous");
}
@Test
public void destinationMatcherFullyAuthenticated() {
messages
.destinationMatchers("admin/**","location/**").fullyAuthenticated()
.anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("fullyAuthenticated");
}
@Test
public void destinationMatcherDenyAll() {
messages
.destinationMatchers("admin/**","location/**").denyAll()
.anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
private String getAttribute() {
MessageSecurityMetadataSource source = messages.createMetadataSource();
Collection<ConfigAttribute> attrs = source.getAttributes(message);
if(attrs == null) {
return null;
}
assertThat(attrs.size()).isEqualTo(1);
return attrs.iterator().next().toString();
}
}
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint">
<constructor-arg>
<map>
<entry>
<key>
<bean class="org.springframework.security.web.util.AntPathRequestMatcher">
<constructor-arg value="/**"/>
</bean>
</key>
<bean class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>
</entry>
</map>
</constructor-arg>
<property name="defaultEntryPoint">
<bean class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>
</property>
</bean>
</beans>
+46
View File
@@ -0,0 +1,46 @@
Implementation-Title: org.springframework.security.config
Implementation-Version: ${version}
Bundle-SymbolicName: org.springframework.security.config
Bundle-Name: Spring Security Namespace Configuration
Bundle-Vendor: SpringSource
Bundle-Version: ${version}
Bundle-ManifestVersion: 2
Ignored-Existing-Headers:
Import-Package,
Export-Package
Import-Template:
org.aopalliance.*;version="${aopAllianceRange}",
org.apache.commons.logging.*;version="${cloggingRange}",
org.aopalliance.*;version="${aopAllianceRange}";resolution:=optional,
org.aspectj.*;version="${aspectjRange}";resolution:=optional,
org.openid4java.*;version="${openid4javaRange}";resolution:=optional,
org.springframework.security.access.*;version="${secRange}",
org.springframework.security.authentication.*;version="${secRange}",
org.springframework.security.core.*;version="${secRange}",
org.springframework.security.crypto.bcrypt.*;version="${secRange}",
org.springframework.security.crypto.password.*;version="${secRange}",
org.springframework.security.crypto.*;version="${secRange}",
org.springframework.security.util;version="${secRange}",
org.springframework.security.provisioning;version="${secRange}",
org.springframework.security.ldap.*;version="${secRange}",
org.springframework.security.openid.*;version="${secRange}";resolution:=optional,
org.springframework.security.web.*;version="${secRange}";resolution:=optional,
org.springframework.security.ldap.*;version="${secRange}";resolution:=optional,
org.springframework.security.openid.*;version="${secRange}";resolution:=optional,
org.springframework.ldap.*;version="${springLdapRange}";resolution:=optional,
org.springframework.aop.*;version="${springRange}";resolution:=optional,
org.springframework.jdbc.*;version="${springRange}";resolution:=optional,
org.springframework.http.*;version="${springRange}";resolution:=optional,
org.springframework.beans.*;version="${springRange}",
org.springframework.context.*;version="${springRange}",
org.springframework.core.*;version="${springRange}",
org.springframework.http.*;version="${springRange}",
org.springframework.ldap.*;version="${springLdapRange}",
org.springframework.jdbc.*;version="${springRange}",
org.springframework.web.*;version="${springRange}",
org.springframework.util.*;version="${springRange}",
javax.servlet.*;version="0";resolution:=optional,
org.openid4java.*;version="${openid4javaRange}",
javax.sql.*;version="0";resolution:=optional,
javax.naming.directory;version="0";resolution:=optional,
org.w3c.dom;version="0";resolution:=optional
+10 -16
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>spring-security-core</name>
<description>spring-security-core</description>
<url>http://spring.io/spring-security</url>
@@ -42,12 +42,6 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>aopalliance</groupId>
@@ -58,25 +52,25 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -88,7 +82,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -108,7 +102,7 @@
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.5</version>
<version>1.7.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@@ -122,14 +116,14 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@@ -280,7 +274,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
<exclusions>
<exclusion>
@@ -38,9 +38,7 @@ import org.springframework.security.access.event.AuthorizedEvent;
import org.springframework.security.access.event.PublicInvocationEvent;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -107,7 +105,7 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
private ApplicationEventPublisher eventPublisher;
private AccessDecisionManager accessDecisionManager;
private AfterInvocationManager afterInvocationManager;
private AuthenticationManager authenticationManager = new NoOpAuthenticationManager();
private AuthenticationManager authenticationManager;
private RunAsManager runAsManager = new NullRunAsManager();
private boolean alwaysReauthenticate = false;
@@ -462,12 +460,4 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
this.eventPublisher.publishEvent(event);
}
}
private static class NoOpAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
throw new AuthenticationServiceException("Cannot authenticate " + authentication);
}
}
}
@@ -85,7 +85,7 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
"Once created you cannot set this token to authenticated. Create a new instance using the constructor which takes a GrantedAuthority list will mark this as authenticated.");
}
super.setAuthenticated(false);
@@ -52,14 +52,4 @@ public class SystemWideSaltSource implements SaltSource, InitializingBean {
public void setSystemWideSalt(String systemWideSalt) {
this.systemWideSalt = systemWideSalt;
}
/**
* Displays the system wide salt
* @since 4.0
* @return
*/
@Override
public String toString() {
return systemWideSalt;
}
}
@@ -1,469 +0,0 @@
package org.springframework.security.core;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Properties;
import java.util.Stack;
/**
* Generic implementation of version comparison.
*
* NOTE: This is a copy from https://svn.apache.org/repos/asf/maven/maven-3/tags/maven-3.1.0/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java
*
* <p>Features:
* <ul>
* <li>mixing of '<code>-</code>' (dash) and '<code>.</code>' (dot) separators,</li>
* <li>transition between characters and digits also constitutes a separator:
* <code>1.0alpha1 =&gt; [1, 0, alpha, 1]</code></li>
* <li>unlimited number of version components,</li>
* <li>version components in the text can be digits or strings,</li>
* <li>strings are checked for well-known qualifiers and the qualifier ordering is used for version ordering.
* Well-known qualifiers (case insensitive) are:<ul>
* <li><code>alpha</code> or <code>a</code></li>
* <li><code>beta</code> or <code>b</code></li>
* <li><code>milestone</code> or <code>m</code></li>
* <li><code>rc</code> or <code>cr</code></li>
* <li><code>snapshot</code></li>
* <li><code>(the empty string)</code> or <code>ga</code> or <code>final</code></li>
* <li><code>sp</code></li>
* </ul>
* Unknown qualifiers are considered after known qualifiers, with lexical order (always case insensitive),
* </li>
* <li>a dash usually precedes a qualifier, and is always less important than something preceded with a dot.</li>
* </ul></p>
*
* @see <a href="https://cwiki.apache.org/confluence/display/MAVENOLD/Versioning">"Versioning" on Maven Wiki</a>
* @author <a href="mailto:kenney@apache.org">Kenney Westerhof</a>
* @author <a href="mailto:hboutemy@apache.org">Hervé Boutemy</a>
*/
class ComparableVersion
implements Comparable<ComparableVersion>
{
private String value;
private String canonical;
private ListItem items;
private interface Item
{
final int INTEGER_ITEM = 0;
final int STRING_ITEM = 1;
final int LIST_ITEM = 2;
int compareTo( Item item );
int getType();
boolean isNull();
}
/**
* Represents a numeric item in the version item list.
*/
private static class IntegerItem
implements Item
{
private static final BigInteger BigInteger_ZERO = new BigInteger( "0" );
private final BigInteger value;
public static final IntegerItem ZERO = new IntegerItem();
private IntegerItem()
{
this.value = BigInteger_ZERO;
}
public IntegerItem( String str )
{
this.value = new BigInteger( str );
}
public int getType()
{
return INTEGER_ITEM;
}
public boolean isNull()
{
return BigInteger_ZERO.equals( value );
}
public int compareTo( Item item )
{
if ( item == null )
{
return BigInteger_ZERO.equals( value ) ? 0 : 1; // 1.0 == 1, 1.1 > 1
}
switch ( item.getType() )
{
case INTEGER_ITEM:
return value.compareTo( ( (IntegerItem) item ).value );
case STRING_ITEM:
return 1; // 1.1 > 1-sp
case LIST_ITEM:
return 1; // 1.1 > 1-1
default:
throw new RuntimeException( "invalid item: " + item.getClass() );
}
}
public String toString()
{
return value.toString();
}
}
/**
* Represents a string in the version item list, usually a qualifier.
*/
private static class StringItem
implements Item
{
private static final String[] QUALIFIERS = { "alpha", "beta", "milestone", "rc", "snapshot", "", "sp" };
private static final List<String> _QUALIFIERS = Arrays.asList( QUALIFIERS );
private static final Properties ALIASES = new Properties();
static
{
ALIASES.put( "ga", "" );
ALIASES.put( "final", "" );
ALIASES.put( "cr", "rc" );
}
/**
* A comparable value for the empty-string qualifier. This one is used to determine if a given qualifier makes
* the version older than one without a qualifier, or more recent.
*/
private static final String RELEASE_VERSION_INDEX = String.valueOf( _QUALIFIERS.indexOf( "" ) );
private String value;
public StringItem( String value, boolean followedByDigit )
{
if ( followedByDigit && value.length() == 1 )
{
// a1 = alpha-1, b1 = beta-1, m1 = milestone-1
switch ( value.charAt( 0 ) )
{
case 'a':
value = "alpha";
break;
case 'b':
value = "beta";
break;
case 'm':
value = "milestone";
break;
}
}
this.value = ALIASES.getProperty( value , value );
}
public int getType()
{
return STRING_ITEM;
}
public boolean isNull()
{
return ( comparableQualifier( value ).compareTo( RELEASE_VERSION_INDEX ) == 0 );
}
/**
* Returns a comparable value for a qualifier.
*
* This method takes into account the ordering of known qualifiers then unknown qualifiers with lexical ordering.
*
* just returning an Integer with the index here is faster, but requires a lot of if/then/else to check for -1
* or QUALIFIERS.size and then resort to lexical ordering. Most comparisons are decided by the first character,
* so this is still fast. If more characters are needed then it requires a lexical sort anyway.
*
* @param qualifier
* @return an equivalent value that can be used with lexical comparison
*/
public static String comparableQualifier( String qualifier )
{
int i = _QUALIFIERS.indexOf( qualifier );
return i == -1 ? ( _QUALIFIERS.size() + "-" + qualifier ) : String.valueOf( i );
}
public int compareTo( Item item )
{
if ( item == null )
{
// 1-rc < 1, 1-ga > 1
return comparableQualifier( value ).compareTo( RELEASE_VERSION_INDEX );
}
switch ( item.getType() )
{
case INTEGER_ITEM:
return -1; // 1.any < 1.1 ?
case STRING_ITEM:
return comparableQualifier( value ).compareTo( comparableQualifier( ( (StringItem) item ).value ) );
case LIST_ITEM:
return -1; // 1.any < 1-1
default:
throw new RuntimeException( "invalid item: " + item.getClass() );
}
}
public String toString()
{
return value;
}
}
/**
* Represents a version list item. This class is used both for the global item list and for sub-lists (which start
* with '-(number)' in the version specification).
*/
private static class ListItem
extends ArrayList<Item>
implements Item
{
public int getType()
{
return LIST_ITEM;
}
public boolean isNull()
{
return ( size() == 0 );
}
void normalize()
{
for( ListIterator<Item> iterator = listIterator( size() ); iterator.hasPrevious(); )
{
Item item = iterator.previous();
if ( item.isNull() )
{
iterator.remove(); // remove null trailing items: 0, "", empty list
}
else
{
break;
}
}
}
public int compareTo( Item item )
{
if ( item == null )
{
if ( size() == 0 )
{
return 0; // 1-0 = 1- (normalize) = 1
}
Item first = get( 0 );
return first.compareTo( null );
}
switch ( item.getType() )
{
case INTEGER_ITEM:
return -1; // 1-1 < 1.0.x
case STRING_ITEM:
return 1; // 1-1 > 1-sp
case LIST_ITEM:
Iterator<Item> left = iterator();
Iterator<Item> right = ( (ListItem) item ).iterator();
while ( left.hasNext() || right.hasNext() )
{
Item l = left.hasNext() ? left.next() : null;
Item r = right.hasNext() ? right.next() : null;
// if this is shorter, then invert the compare and mul with -1
int result = l == null ? -1 * r.compareTo( l ) : l.compareTo( r );
if ( result != 0 )
{
return result;
}
}
return 0;
default:
throw new RuntimeException( "invalid item: " + item.getClass() );
}
}
public String toString()
{
StringBuilder buffer = new StringBuilder( "(" );
for( Iterator<Item> iter = iterator(); iter.hasNext(); )
{
buffer.append( iter.next() );
if ( iter.hasNext() )
{
buffer.append( ',' );
}
}
buffer.append( ')' );
return buffer.toString();
}
}
public ComparableVersion( String version )
{
parseVersion( version );
}
public final void parseVersion( String version )
{
this.value = version;
items = new ListItem();
version = version.toLowerCase( Locale.ENGLISH );
ListItem list = items;
Stack<Item> stack = new Stack<Item>();
stack.push( list );
boolean isDigit = false;
int startIndex = 0;
for ( int i = 0; i < version.length(); i++ )
{
char c = version.charAt( i );
if ( c == '.' )
{
if ( i == startIndex )
{
list.add( IntegerItem.ZERO );
}
else
{
list.add( parseItem( isDigit, version.substring( startIndex, i ) ) );
}
startIndex = i + 1;
}
else if ( c == '-' )
{
if ( i == startIndex )
{
list.add( IntegerItem.ZERO );
}
else
{
list.add( parseItem( isDigit, version.substring( startIndex, i ) ) );
}
startIndex = i + 1;
if ( isDigit )
{
list.normalize(); // 1.0-* = 1-*
if ( ( i + 1 < version.length() ) && Character.isDigit( version.charAt( i + 1 ) ) )
{
// new ListItem only if previous were digits and new char is a digit,
// ie need to differentiate only 1.1 from 1-1
list.add( list = new ListItem() );
stack.push( list );
}
}
}
else if ( Character.isDigit( c ) )
{
if ( !isDigit && i > startIndex )
{
list.add( new StringItem( version.substring( startIndex, i ), true ) );
startIndex = i;
}
isDigit = true;
}
else
{
if ( isDigit && i > startIndex )
{
list.add( parseItem( true, version.substring( startIndex, i ) ) );
startIndex = i;
}
isDigit = false;
}
}
if ( version.length() > startIndex )
{
list.add( parseItem( isDigit, version.substring( startIndex ) ) );
}
while ( !stack.isEmpty() )
{
list = (ListItem) stack.pop();
list.normalize();
}
canonical = items.toString();
}
private static Item parseItem( boolean isDigit, String buf )
{
return isDigit ? new IntegerItem( buf ) : new StringItem( buf, false );
}
public int compareTo( ComparableVersion o )
{
return items.compareTo( o.items );
}
public String toString()
{
return value;
}
public boolean equals( Object o )
{
return ( o instanceof ComparableVersion ) && canonical.equals( ( (ComparableVersion) o ).canonical );
}
public int hashCode()
{
return canonical.hashCode();
}
}
@@ -21,9 +21,9 @@ public class SpringSecurityCoreVersion {
* N.B. Classes are not intended to be serializable between different versions.
* See SEC-1709 for why we still need a serial version.
*/
public static final long SERIAL_VERSION_UID = 400L;
public static final long SERIAL_VERSION_UID = 320L;
static final String MIN_SPRING_VERSION = "4.1.0.RC2";
static final String MIN_SPRING_VERSION = "3.2.8.RELEASE";
static {
performVersionChecks();
@@ -38,15 +38,6 @@ public class SpringSecurityCoreVersion {
* Performs version checks
*/
private static void performVersionChecks() {
performVersionChecks(MIN_SPRING_VERSION);
}
/**
* Perform version checks with specific min Spring Version
*
* @param minSpringVersion
*/
private static void performVersionChecks(String minSpringVersion) {
// Check Spring Compatibility
String springVersion = SpringVersion.getVersion();
String version = getVersion();
@@ -56,8 +47,8 @@ public class SpringSecurityCoreVersion {
}
logger.info("You are running with Spring Security Core " + version);
if (new ComparableVersion(springVersion).compareTo(new ComparableVersion(minSpringVersion)) < 0) {
logger.warn("**** You are advised to use Spring " + minSpringVersion +
if (springVersion.compareTo(MIN_SPRING_VERSION) < 0) {
logger.warn("**** You are advised to use Spring " + MIN_SPRING_VERSION +
" or later with this version. You are running: " + springVersion);
}
}
@@ -1,47 +1,47 @@
AbstractAccessDecisionManager.accessDenied = \uc811\uadfc\uc774 \uac70\ubd80\ub418\uc5c8\uc2b5\ub2c8\ub2e4.
AbstractLdapAuthenticationProvider.emptyPassword = \ube44\ubc00\ubc88\ud638\uac00 \ub9de\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.
AbstractSecurityInterceptor.authenticationNotFound = SecurityContext\uc5d0\uc11c Authentication \uac1d\uccb4\ub97c \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.
AbstractUserDetailsAuthenticationProvider.badCredentials = \uc790\uaca9 \uc99d\uba85\uc5d0 \uc2e4\ud328\ud558\uc600\uc2b5\ub2c8\ub2e4.
AbstractUserDetailsAuthenticationProvider.credentialsExpired = \uc790\uaca9 \uc99d\uba85 \uc720\ud6a8 \uae30\uac04\uc774 \ub9cc\ub8cc\ub418\uc5c8\uc2b5\ub2c8\ub2e4.
AbstractUserDetailsAuthenticationProvider.disabled = \uc720\ud6a8\ud558\uc9c0 \uc54a\uc740 \uc0ac\uc6a9\uc790\uc785\ub2c8\ub2e4.
AbstractUserDetailsAuthenticationProvider.expired = \uc0ac\uc6a9\uc790 \uacc4\uc815\uc758 \uc720\ud6a8 \uae30\uac04\uc774 \ub9cc\ub8cc \ub418\uc5c8\uc2b5\ub2c8\ub2e4.
AbstractUserDetailsAuthenticationProvider.locked = \uc0ac\uc6a9\uc790 \uacc4\uc815\uc774 \uc7a0\uaca8 \uc788\uc2b5\ub2c8\ub2e4.
AbstractUserDetailsAuthenticationProvider.onlySupports = UsernamePasswordAuthenticationToken\ub9cc \uc9c0\uc6d0\ud569\ub2c8\ub2e4.
AccountStatusUserDetailsChecker.credentialsExpired = \uc790\uaca9 \uc99d\uba85 \uc720\ud6a8 \uae30\uac04\uc774 \ub9cc\ub8cc\ub418\uc5c8\uc2b5\ub2c8\ub2e4.
AccountStatusUserDetailsChecker.disabled = \uc720\ud6a8\ud558\uc9c0 \uc54a\uc740 \uc0ac\uc6a9\uc790\uc785\ub2c8\ub2e4.
AccountStatusUserDetailsChecker.expired = \uc0ac\uc6a9\uc790 \uacc4\uc815\uc758 \uc720\ud6a8 \uae30\uac04\uc774 \ub9cc\ub8cc \ub418\uc5c8\uc2b5\ub2c8\ub2e4.
AccountStatusUserDetailsChecker.locked = \uc0ac\uc6a9\uc790 \uacc4\uc815\uc774 \uc7a0\uaca8 \uc788\uc2b5\ub2c8\ub2e4.
AclEntryAfterInvocationProvider.noPermission = domain object {1}\uc5d0 \ub300\ud55c \uad8c\ud55c\uc774 Authentication {0}\uc5d0 \uc5c6\uc2b5\ub2c8\ub2e4.
AnonymousAuthenticationProvider.incorrectKey = \uc81c\uacf5\ub41c AnonymousAuthenticationToken\uc5d0\ub294 \ud544\uc694\ub85c\ud558\ub294 key\uac00 \uc5c6\uc2b5\ub2c8\ub2e4.
BindAuthenticator.badCredentials = \uc790\uaca9 \uc99d\uba85\uc5d0 \uc2e4\ud328\ud558\uc600\uc2b5\ub2c8\ub2e4.
BindAuthenticator.emptyPassword = \ube44\ubc00\ubc88\ud638 \ud56d\ubaa9\uc774 \ube44\uc5b4 \uc788\uc2b5\ub2c8\ub2e4.
CasAuthenticationProvider.incorrectKey = \uc81c\uacf5\ub41c CasAuthenticationToken\uc5d0\ub294 \ud544\uc694\ub85c \ud558\ub294 key\uac00 \uc5c6\uc2b5\ub2c8\ub2e4.
CasAuthenticationProvider.noServiceTicket = \uac80\uc99d\uc744 \uc704\ud55c CAS \uc11c\ube44\uc2a4 \ud2f0\ucf13\uc744 \uc81c\uacf5\ud560 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.
ConcurrentSessionControlStrategy.exceededAllowed = \ucd5c\ub300 \uc138\uc158 \ud5c8\uc6a9 \uc218 {0}\uac1c\ub97c \ucd08\uacfc\ud558\uc600\uc2b5\ub2c8\ub2e4.
DigestAuthenticationFilter.incorrectRealm = \uc751\ub2f5 realm \uc774\ub984 {0}\uacfc \uc2dc\uc2a4\ud15c realm \uc774\ub984 {1}\uc774 \uc77c\uce58\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.
DigestAuthenticationFilter.incorrectResponse = \uc751\ub2f5\uc774 \uc815\ud655\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.
DigestAuthenticationFilter.missingAuth = 'auth' QOP(quality of protection)\ub97c \uc704\ud55c digest \uac12\uc740 \ud544\uc218 \ud56d\ubaa9\uc785\ub2c8\ub2e4. \ud604\uc7ac header \uac12\uc740 {0}\uc785\ub2c8\ub2e4.
DigestAuthenticationFilter.missingMandatory = digest \uac12\uc740 \ud544\uc218 \ud56d\ubaa9\uc785\ub2c8\ub2e4. \ud604\uc7ac header \uac12\uc740 {0}\uc785\ub2c8\ub2e4.
DigestAuthenticationFilter.nonceCompromised = Nonce \ud1a0\ud070\uc774 \uc190\uc0c1\ub418\uc5c8\uc2b5\ub2c8\ub2e4. \ud604\uc7ac nonce \uac12\uc740 {0}\uc785\ub2c8\ub2e4.
DigestAuthenticationFilter.nonceEncoding = Nonce \uac12\uc774 Base64\ub85c \uc778\ucf54\ub529 \ub418\uc5b4\uc788\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4. \ud604\uc7ac nonce \uac12\uc740 {0}\uc785\ub2c8\ub2e4.
DigestAuthenticationFilter.nonceExpired = Nonce\uc758 \uc720\ud6a8 \uae30\uac04\uc774 \ub9cc\ub8cc\ub418\uc5c8\uac70\ub098 \uc2dc\uac04\uc774 \ucd08\uacfc\ub418\uc5c8\uc2b5\ub2c8\ub2e4.
DigestAuthenticationFilter.nonceNotNumeric = Nonce \ud1a0\ud070\uc758 \uccab \uae00\uc790\ub294 \uc22b\uc790\ub85c \uc2dc\uc791\ud574\uc57c \ud569\ub2c8\ub2e4. \ud604\uc7ac nonce \uac12\uc740 {0}\uc785\ub2c8\ub2e4.
DigestAuthenticationFilter.nonceNotTwoTokens = Nonce\ub294 \ub450 \uac1c\uc758 \ud1a0\ud070\uc744 \ub9cc\ub4e4\uc5b4\uc57c \ud569\ub2c8\ub2e4. \ud604\uc7ac nonce \uac12\uc740 {0}\uc785\ub2c8\ub2e4.
DigestAuthenticationFilter.usernameNotFound = {0} ID\ub97c \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.
JdbcDaoImpl.noAuthority = {0} \uc0ac\uc6a9\uc790\ub294 \uad8c\ud55c\uc774 \uc5c6\uc2b5\ub2c8\ub2e4.
JdbcDaoImpl.notFound = {0} \uc0ac\uc6a9\uc790\ub97c \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.
LdapAuthenticationProvider.badCredentials = \uc790\uaca9 \uc99d\uba85\uc5d0 \uc2e4\ud328\ud558\uc600\uc2b5\ub2c8\ub2e4.
LdapAuthenticationProvider.credentialsExpired = \uc790\uaca9 \uc99d\uba85 \uc720\ud6a8 \uae30\uac04\uc774 \ub9cc\ub8cc\ub418\uc5c8\uc2b5\ub2c8\ub2e4.
LdapAuthenticationProvider.disabled = \uc720\ud6a8\ud558\uc9c0 \uc54a\uc740 \uc0ac\uc6a9\uc790\uc785\ub2c8\ub2e4.
LdapAuthenticationProvider.expired = \uc0ac\uc6a9\uc790 \uacc4\uc815\uc758 \uc720\ud6a8 \uae30\uac04\uc774 \ub9cc\ub8cc \ub418\uc5c8\uc2b5\ub2c8\ub2e4.
LdapAuthenticationProvider.locked = \uc0ac\uc6a9\uc790 \uacc4\uc815\uc774 \uc7a0\uaca8 \uc788\uc2b5\ub2c8\ub2e4.
LdapAuthenticationProvider.emptyUsername = ID\uc5d0 \uacf5\ubc31\uc740 \ud5c8\uc6a9\ub418\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.
LdapAuthenticationProvider.onlySupports = UsernamePasswordAuthenticationToken\ub9cc \uc9c0\uc6d0\ud569\ub2c8\ub2e4.
PasswordComparisonAuthenticator.badCredentials = \uc790\uaca9 \uc99d\uba85\uc5d0 \uc2e4\ud328\ud558\uc600\uc2b5\ub2c8\ub2e4.
PersistentTokenBasedRememberMeServices.cookieStolen = \ub85c\uadf8\uc778 \uc0c1\ud0dc \uc720\uc9c0\ub97c \uc704\ud55c \ud1a0\ud070\uc774 \uc77c\uce58\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4. \uc774\uc804\uc5d0 \uc0ac\uc6a9\ud55c \ud1a0\ud070\uc774 \ud0c0\uc778\uc73c\ub85c\ubd80\ud130 \ud0c8\ucde8 \ub2f9\ud588\uc744 \uc218 \uc788\uc2b5\ub2c8\ub2e4.
ProviderManager.providerNotFound = {0}\uc744 \uc704\ud55c AuthenticationProvider\ub97c \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.
RememberMeAuthenticationProvider.incorrectKey = \uc81c\uacf5\ub41c RememberMeAuthenticationToken\uc5d0\ub294 \ud544\uc694\ub85c \ud558\ub294 key\uac00 \uc5c6\uc2b5\ub2c8\ub2e4.
RunAsImplAuthenticationProvider.incorrectKey = \uc81c\uacf5\ub41c RunAsUserToken\uc5d0\ub294 \ud544\uc694\ub85c \ud558\ub294 key\uac00 \uc5c6\uc2b5\ub2c8\ub2e4.
SubjectDnX509PrincipalExtractor.noMatching = subjectDN\: {0} \ub0b4\uc5d0 \ub9e4\uce6d\ub418\ub294 \ud328\ud134\uc774 \uc5c6\uc2b5\ub2c8\ub2e4.
SwitchUserFilter.noCurrentUser = \uc694\uccad\ud55c \uc0ac\uc6a9\uc790\ub97c \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.
SwitchUserFilter.noOriginalAuthentication = Authentication \uac1d\uccb4\uc758 \uc6d0\ubcf8\uc744 \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.
AbstractAccessDecisionManager.accessDenied=\uC811\uADFC\uC774 \uAC70\uBD80\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
AbstractLdapAuthenticationProvider.badCredentials=\uBE44\uBC00\uBC88\uD638\uAC00 \uB9DE\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
AbstractSecurityInterceptor.authenticationNotFound=SecurityContext\uC5D0\uC11C Authentication \uAC1D\uCCB4\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
AbstractUserDetailsAuthenticationProvider.badCredentials=\uBE44\uBC00\uBC88\uD638(credential)\uAC00 \uB9DE\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
AbstractUserDetailsAuthenticationProvider.credentialsExpired=\uBE44\uBC00\uBC88\uD638(credential)\uC758 \uC720\uD6A8 \uAE30\uAC04\uC774 \uB9CC\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
AbstractUserDetailsAuthenticationProvider.disabled=\uC874\uC7AC\uD558\uC9C0 \uC54A\uB294 \uC0AC\uC6A9\uC790 \uC785\uB2C8\uB2E4.
AbstractUserDetailsAuthenticationProvider.expired=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC758 \uC720\uD6A8 \uAE30\uAC04\uC774 \uB9CC\uB8CC \uB418\uC5C8\uC2B5\uB2C8\uB2E4.
AbstractUserDetailsAuthenticationProvider.locked=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC774 \uC7A0\uACA8 \uC788\uC2B5\uB2C8\uB2E4.
AbstractUserDetailsAuthenticationProvider.onlySupports=UsernamePasswordAuthenticationToken\uB9CC \uC9C0\uC6D0\uD569\uB2C8\uB2E4.
AccountStatusUserDetailsChecker.credentialsExpired=\uBE44\uBC00\uBC88\uD638\uC758 \uC720\uD6A8 \uAE30\uAC04\uC774 \uB9CC\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
AccountStatusUserDetailsChecker.disabled=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC744 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
AccountStatusUserDetailsChecker.expired=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC758 \uC720\uD6A8 \uAE30\uAC04\uC774 \uB9CC\uB8CC \uB418\uC5C8\uC2B5\uB2C8\uB2E4.
AccountStatusUserDetailsChecker.locked=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC774 \uC7A0\uACA8 \uC788\uC2B5\uB2C8\uB2E4.
AclEntryAfterInvocationProvider.noPermission=Authentication {0}\uC740/\uB294 domain object {1}\uC5D0 \uB300\uD55C \uAD8C\uD55C\uC774 \uC5C6\uC2B5\uB2C8\uB2E4.
AnonymousAuthenticationProvider.incorrectKey=\uC81C\uACF5\uB41C AnonymousAuthenticationToken\uC5D0\uB294 \uCC3E\uB294 key\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.
BindAuthenticator.badCredentials=\uBE44\uBC00\uBC88\uD638\uAC00 \uB9DE\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
BindAuthenticator.emptyPassword=\uBE44\uBC00\uBC88\uD638(credential)\uAC00 \uB9DE\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
CasAuthenticationProvider.incorrectKey=\uC81C\uACF5\uB41C CasAuthenticationToken\uC5D0\uB294 \uCC3E\uB294 key\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.
CasAuthenticationProvider.noServiceTicket=\uAC80\uC99D\uC744 \uC704\uD55C CAS \uC11C\uBE44\uC2A4 \uD2F0\uCF13\uC744 \uC81C\uACF5\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
ConcurrentSessionControlStrategy.exceededAllowed={0}\uC758 \uCD5C\uB300 \uC138\uC158 \uD5C8\uC6A9 \uC218\uB97C \uCD08\uACFC\uD558\uC600\uC2B5\uB2C8\uB2E4.
DigestAuthenticationFilter.incorrectRealm=\uC751\uB2F5 realm \uC774\uB984 {0}\uC774 \uC2DC\uC2A4\uD15C realm \uC774\uB984 {1}\uACFC \uC77C\uCE58 \uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
DigestAuthenticationFilter.incorrectResponse=\uC751\uB2F5\uC774 \uC815\uD655\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
DigestAuthenticationFilter.missingAuth='auth' QOP\uB97C \uC704\uD55C \uD544\uC218 digest \uD30C\uB77C\uBBF8\uD130 \uAC12\uC774 \uB204\uB77D\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uD604\uC7AC header\uB294 {0}\uC785\uB2C8\uB2E4.
DigestAuthenticationFilter.missingMandatory=\uD544\uC218 digest \uD30C\uB77C\uBBF8\uD130 \uAC12\uC774 \uB204\uB77D\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uD604\uC7AC header\uB294 {0}\uC785\uB2C8\uB2E4.
DigestAuthenticationFilter.nonceCompromised=Nonce \uD1A0\uD070\uC774 \uD6FC\uC190\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uD604\uC7AC nonce\uB294 {0}\uC785\uB2C8\uB2E4.
DigestAuthenticationFilter.nonceEncoding=Nonce\uAC00 Base64\uB85C \uC778\uCF54\uB529 \uB418\uC5B4\uC788\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uD604\uC7AC nonce\uB294 {0}\uC785\uB2C8\uB2E4.
DigestAuthenticationFilter.nonceExpired=Nonce\uC758 \uC720\uD6A8 \uAE30\uAC04\uC774 \uB9CC\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
DigestAuthenticationFilter.nonceNotNumeric=Nonce \uD1A0\uD070\uC758 \uCCAB \uAE00\uC790\uB294 \uC22B\uC790\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4. \uD604\uC7AC nonce\uB294 {0}\uC785\uB2C8\uB2E4.
DigestAuthenticationFilter.nonceNotTwoTokens=Nonce\uB294 2\uAC1C\uC758 \uD1A0\uD070\uC744 \uB9CC\uB4E4\uC5B4\uC57C \uD569\uB2C8\uB2E4. \uD604\uC7AC nonce\uB294 {0}\uC785\uB2C8\uB2E4.
DigestAuthenticationFilter.usernameNotFound=\uC0AC\uC6A9\uC790 {0}\uC744/\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
JdbcDaoImpl.noAuthority=\uC0AC\uC6A9\uC790 {0}\uC740/\uB294 \uAD8C\uD55C\uC774 \uC5C6\uC2B5\uB2C8\uB2E4.
JdbcDaoImpl.notFound=\uC0AC\uC6A9\uC790 {0}\uC744/\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
LdapAuthenticationProvider.badCredentials=\uBE44\uBC00\uBC88\uD638\uAC00 \uB9DE\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
LdapAuthenticationProvider.credentialsExpired=\uBE44\uBC00\uBC88\uD638(credential)\uC758 \uC720\uD6A8 \uAE30\uAC04\uC774 \uB9CC\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
LdapAuthenticationProvider.disabled=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC744 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
LdapAuthenticationProvider.expired=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC758 \uC720\uD6A8 \uAE30\uAC04\uC774 \uB9CC\uB8CC \uB418\uC5C8\uC2B5\uB2C8\uB2E4.
LdapAuthenticationProvider.locked=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC774 \uC7A0\uACA8 \uC788\uC2B5\uB2C8\uB2E4.
LdapAuthenticationProvider.emptyUsername=\uC0AC\uC6A9\uC790\uBA85(username)\uC5D0 \uACF5\uBC31\uC740 \uD5C8\uC6A9\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
LdapAuthenticationProvider.onlySupports=UsernamePasswordAuthenticationToken\uB9CC \uC9C0\uC6D0\uD569\uB2C8\uB2E4.
PasswordComparisonAuthenticator.badCredentials=\uBE44\uBC00\uBC88\uD638\uAC00 \uB9DE\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
#PersistentTokenBasedRememberMeServices.cookieStolen=Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack.
ProviderManager.providerNotFound={0}\uC744 \uC704\uD55C AuthenticationProvider\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
RememberMeAuthenticationProvider.incorrectKey=\uC81C\uACF5\uB41C RememberMeAuthenticationToken\uC5D0\uB294 \uCC3E\uB294 key\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.
RunAsImplAuthenticationProvider.incorrectKey=\uC81C\uACF5\uB41C RunAsUserToken\uC5D0\uB294 \uCC3E\uB294 key\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.
SubjectDnX509PrincipalExtractor.noMatching=subjectDN\: {0}\uC5D0\uC11C \uB9E4\uCE6D\uB418\uB294 \uD328\uD134\uC774 \uC5C6\uC2B5\uB2C8\uB2E4.
SwitchUserFilter.noCurrentUser=\uC0AC\uC6A9\uC790\uAC00 \uC874\uC7AC\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
SwitchUserFilter.noOriginalAuthentication=Authentication\uC758 \uC6D0\uBCF8\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
@@ -15,6 +15,7 @@
package org.springframework.security.authentication;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -58,6 +59,8 @@ public class UsernamePasswordAuthenticationTokenTests {
token.setAuthenticated(true);
fail("Should have prohibited setAuthenticated(true)");
} catch (IllegalArgumentException expected) {
// SEC-2540
assertThat(expected).hasMessage("Once created you cannot set this token to authenticated. Create a new instance using the constructor which takes a GrantedAuthority list will mark this as authenticated.");
}
}
@@ -15,8 +15,6 @@
package org.springframework.security.authentication.dao.salt;
import static org.fest.assertions.Assertions.assertThat;
import org.springframework.security.authentication.dao.SystemWideSaltSource;
import junit.framework.TestCase;
@@ -71,12 +69,4 @@ public class SystemWideSaltSourceTests extends TestCase {
saltSource.afterPropertiesSet();
assertEquals("helloWorld", saltSource.getSalt(null));
}
// SEC-2173
public void testToString() {
String systemWideSalt = "helloWorld";
SystemWideSaltSource saltSource = new SystemWideSaltSource();
saltSource.setSystemWideSalt(systemWideSalt);
assertThat(saltSource.toString()).isEqualTo(systemWideSalt);
}
}
@@ -34,7 +34,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import org.springframework.core.SpringVersion;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Checks that the embedded version information is up to date.
@@ -121,7 +120,7 @@ public class SpringSecurityCoreVersionTests {
public void noWarnIfSpringVersionLarger() throws Exception {
spy(SpringSecurityCoreVersion.class);
spy(SpringVersion.class);
when(SpringSecurityCoreVersion.getVersion()).thenReturn("4.0.0.RELEASE");
when(SpringSecurityCoreVersion.getVersion()).thenReturn("3.2.0.RELEASE");
when(SpringVersion.getVersion()).thenReturn("4.0.0.RELEASE");
performChecks();
@@ -129,20 +128,6 @@ public class SpringSecurityCoreVersionTests {
verify(logger, never()).warn(any());
}
// SEC-2697
@Test
public void noWarnIfSpringPatchVersionDoubleDigits() throws Exception {
String minSpringVersion = "3.2.8.RELEASE";
spy(SpringSecurityCoreVersion.class);
spy(SpringVersion.class);
when(SpringSecurityCoreVersion.getVersion()).thenReturn("3.2.0.RELEASE");
when(SpringVersion.getVersion()).thenReturn("3.2.10.RELEASE");
performChecks(minSpringVersion);
verify(logger, never()).warn(any());
}
@Test
public void noLoggingIfPropertySet() throws Exception {
spy(SpringSecurityCoreVersion.class);
@@ -164,7 +149,4 @@ public class SpringSecurityCoreVersionTests {
Whitebox.invokeMethod(SpringSecurityCoreVersion.class, "performVersionChecks");
}
private void performChecks(String minSpringVersion) throws Exception {
Whitebox.invokeMethod(SpringSecurityCoreVersion.class, "performVersionChecks", minSpringVersion);
}
}
+30
View File
@@ -0,0 +1,30 @@
Implementation-Title: org.springframework.security.core
Implementation-Version: ${version}
Bundle-SymbolicName: org.springframework.security.core
Bundle-Name: Spring Security Core
Bundle-Vendor: SpringSource
Bundle-Version: ${version}
Bundle-ManifestVersion: 2
Ignored-Existing-Headers:
Import-Package,
Export-Package
Import-Template:
org.aopalliance.*;version="${aopAllianceRange}",
org.aspectj.*;version="${aspectjRange}";resolution:=optional,
org.apache.commons.logging.*;version="${cloggingRange}",
org.springframework.aop.*;version="${springRange}";resolution:=optional,
org.springframework.beans.*;version="${springRange}",
org.springframework.cache.*;version="${springRange}";resolution:=optional,
org.springframework.context.*;version="${springRange}",
org.springframework.core.*;version="${springRange}",
org.springframework.expression.*;version="${springRange}";resolution:=optional,
org.springframework.dao.*;version="${springRange}";resolution:=optional,
org.springframework.jdbc.*;version="${springRange}";resolution:=optional,
org.springframework.scheduling.*;version="${springRange}";resolution:=optional,
org.springframework.transaction.*;version="${springRange}";resolution:=optional,
org.springframework.util;version="${springRange}",
net.sf.ehcache.*;version="${ehcacheRange}";resolution:=optional,
javax.annotation.security.*;version="0";resolution:=optional,
javax.crypto.*;version="0";resolution:=optional,
javax.security.auth.*;version="0";resolution:=optional,
javax.naming.*;version="0";resolution:=optional
+3 -9
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>spring-security-crypto</name>
<description>spring-security-crypto</description>
<url>http://spring.io/spring-security</url>
@@ -42,17 +42,11 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -101,7 +95,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
+13
View File
@@ -0,0 +1,13 @@
Implementation-Title: org.springframework.security.crypto
Implementation-Version: ${version}
Bundle-SymbolicName: org.springframework.security.crypto
Bundle-Name: Spring Security Crypto
Bundle-Vendor: SpringSource
Bundle-Version: ${version}
Bundle-ManifestVersion: 2
Ignored-Existing-Headers:
Import-Package,
Export-Package
Import-Template:
org.apache.commons.logging.*;version="${cloggingRange}",
javax.crypto.*;version="0"
-5
View File
@@ -1,5 +0,0 @@
dependencies {
compile project(':spring-security-core'),
"org.springframework.data:spring-data-commons:$springDataCommonsVersion"
}
-120
View File
@@ -1,120 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
<version>4.0.0.M2</version>
<name>spring-security-data</name>
<description>spring-security-data</description>
<url>http://spring.io/spring-security</url>
<organization>
<name>spring.io</name>
<url>http://spring.io/</url>
</organization>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rwinch</id>
<name>Rob Winch</name>
<email>rwinch@gopivotal.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/spring-projects/spring-security</connection>
<developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>
<url>https://github.com/spring-projects/spring-security</url>
</scm>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.9.0.RC1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.29</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<version>1.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -1,117 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.data.repository.query;
import org.springframework.data.repository.query.spi.EvaluationContextExtension;
import org.springframework.data.repository.query.spi.EvaluationContextExtensionSupport;
import org.springframework.data.repository.query.spi.Function;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Map;
/**
* <p>
* By defining this object as a Bean, Spring Security is exposed as SpEL expressions for creating Spring Data
* queries.
* </p>
*
* <p>With Java based configuration, we can define the bean using the following:</p>
*
* <p>For example, if you return a UserDetails that extends the following User object:</p>
*
* <pre>
* @Entity
* public class User {
* @GeneratedValue(strategy = GenerationType.AUTO)
* @Id
* private Long id;
*
* ...
* </pre>
*
* <p>And you have a Message object that looks like the following:</p>
*
* <pre>
* @Entity
* public class Message {
* @Id
* @GeneratedValue(strategy = GenerationType.AUTO)
* private Long id;
*
* @OneToOne
* private User to;
*
* ...
* </pre>
*
* You can use the following {@code Query} annotation to search for only messages that are to the current user:
*
* <pre>
* @Repository
* public interface SecurityMessageRepository extends MessageRepository {
*
* @Query("select m from Message m where m.to.id = ?#{ principal?.id }")
* List<Message> findAll();
* }
* </pre>
*
* This works because the principal in this instance is a User which has an id field on it.
*
* @since 4.0
* @author Rob Winch
*/
public class SecurityEvaluationContextExtension extends EvaluationContextExtensionSupport {
private Authentication authentication;
/**
* Creates a new instance that uses the current {@link Authentication} found on the
* {@link org.springframework.security.core.context.SecurityContextHolder}.
*/
public SecurityEvaluationContextExtension() {
}
/**
* Creates a new instance that always uses the same {@link Authentication} object.
*
* @param authentication the {@link Authentication} to use
*/
public SecurityEvaluationContextExtension(Authentication authentication) {
this.authentication = authentication;
}
@Override
public String getExtensionId() {
return "security";
}
@Override
public Object getRootObject() {
Authentication authentication = getAuthentication();
return new SecurityExpressionRoot(authentication) {};
}
private Authentication getAuthentication() {
if(authentication != null) {
return authentication;
}
SecurityContext context = SecurityContextHolder.getContext();
return context.getAuthentication();
}
}
@@ -1,75 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.data.repository.query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.fest.assertions.Assertions.assertThat;
public class SecurityEvaluationContextExtensionTests {
SecurityEvaluationContextExtension securityExtension;
@Before
public void setup() {
securityExtension = new SecurityEvaluationContextExtension();
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test(expected = IllegalArgumentException.class)
public void getRootObjectSecurityContextHolderAuthenticationNull() {
getRoot().getAuthentication();
}
@Test
public void getRootObjectSecurityContextHolderAuthentication() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authentication);
assertThat(getRoot().getAuthentication()).isSameAs(authentication);
}
@Test
public void getRootObjectExplicitAuthenticationOverridesSecurityContextHolder() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
securityExtension = new SecurityEvaluationContextExtension(explicit);
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authentication);
assertThat(getRoot().getAuthentication()).isSameAs(explicit);
}
@Test
public void getRootObjectExplicitAuthentication() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
securityExtension = new SecurityEvaluationContextExtension(explicit);
assertThat(getRoot().getAuthentication()).isSameAs(explicit);
}
private SecurityExpressionRoot getRoot() {
return (SecurityExpressionRoot) securityExtension.getRootObject();
}
}
+1
View File
@@ -26,6 +26,7 @@ project('manual') {
numbered: '',
'spring-security-version' : project.version,
'spring-version' : springVersion,
'spring4-version' : spring4Version,
revnumber : project.version
]
]
+14 -16
View File
@@ -198,9 +198,9 @@ If you are using a milestone or release candidate version, you will need to ensu
----
[[maven-bom]]
===== Spring Framework Bom
===== Using Spring 4 and Maven
Spring Security builds against Spring Framework {spring-version}, but should work with 4.0.x. The problem that many users will have is that Spring Security's transitive dependencies resolve Spring Framework {spring-version} which can cause strange classpath problems.
Spring Security builds against Spring Framework {spring-version}, but is also tested against Spring Framework {spring4-version}. This means you can use Spring Security {spring-security-version} with Spring Framework {spring4-version}. The problem that many users will have is that Spring Security's transitive dependencies resolve Spring Framework {spring-version} causing all sorts of strange classpath problems.
One (tedious) way to circumvent this issue would be to include all the Spring Framework modules in a http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management[<dependencyManagement>] section of your pom. An alternative approach is to include the `spring-framework-bom` within your `<dependencyManagement>` section of your `pom.xml` as shown below:
@@ -213,7 +213,7 @@ One (tedious) way to circumvent this issue would be to include all the Spring Fr
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>{spring-version}</version>
<version>{spring4-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -221,7 +221,7 @@ One (tedious) way to circumvent this issue would be to include all the Spring Fr
</dependencyManagement>
----
This will ensure that all the transitive dependencies of Spring Security use the Spring {spring-version} modules.
This will ensure that all the transitive dependencies of Spring Security use the Spring {spring4-version} modules.
NOTE: This approach uses Maven's "bill of materials" (BOM) concept and is only available in Maven 2.0.9+. For additional details about how dependencies are resolved refer to http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html[Maven's Introduction to the Dependency Mechanism documentation].
@@ -274,9 +274,9 @@ repositories {
----
[[gradle-resolutionStrategy]]
===== Using Spring 4.0.x and Gradle
===== Using Spring 4 and Gradle
By default Gradle will use the newest version when resolving transitive versions. This means that often times no additional work is necessary when running Spring Security {spring-security-version} with Spring Framework {spring-version}. However, at times there can be issues that come up so it is best to mitigate this using http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html[Gradle's ResolutionStrategy] as shown below:
By default Gradle will use the newest version when resolving transitive versions. This means that often times no additional work is necessary when running Spring Security {spring-security-version} with Spring Framework {spring4-version}. However, at times there can be issues that come up so it is best to mitigate this using http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html[Gradle's ResolutionStrategy] as shown below:
.build.gradle
[source,groovy]
@@ -285,13 +285,13 @@ By default Gradle will use the newest version when resolving transitive versions
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'org.springframework') {
details.useVersion '{spring-version}'
details.useVersion '{spring4-version}'
}
}
}
----
This will ensure that all the transitive dependencies of Spring Security use the Spring {spring-version} modules.
This will ensure that all the transitive dependencies of Spring Security use the Spring {spring4-version} modules.
NOTE: This example uses Gradle 1.9, but may need modifications to work in future versions of Gradle since this is an incubating feature within Gradle.
@@ -691,7 +691,7 @@ public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
==== LDAP Authentication
You can find the updates to suppport LDAP based authentication. The https://github.com/spring-projects/spring-security/tree/master/samples/ldap-jc[ldap-jc sample] provides a complete example of using LDAP based authentication.
You can find the updates to suppport LDAP based authentication. The https://github.com/spring-projects/spring-security/tree/master/samples/lda-jc[ldap-jc sample] provides a complete example of using LDAP based authentication.
[source,java]
----
@@ -809,7 +809,7 @@ public class MultiHttpSecurityConfig {
[[jc-method]]
=== Method Security
From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the frameworks original @Secured annotation. From 3.0 you can also make use of new <<el-access,expression-based annotations>>. You can apply security to a single bean, using the intercept-methods element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts.
From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the frameworks original @Secured annotation. From 3.0 you can also make use of new <<el-access,expression-based annotations>>. You can apply security to a single bean, using the intercept-methods element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts.
==== EnableGlobalMethodSecurity
@@ -824,7 +824,7 @@ public class MethodSecurityConfig {
}
----
Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly. Spring Securitys native annotation support defines a set of attributes for the method. These will be passed to the AccessDecisionManager for it to make the actual decision:
Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly. Spring Securitys native annotation support defines a set of attributes for the method. These will be passed to the AccessDecisionManager for it to make the actual decision:
[source,java]
----
@@ -852,7 +852,7 @@ public class MethodSecurityConfig {
}
----
These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Securitys native annotations. To use the new expression-based syntax, you would use
These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Securitys native annotations. To use the new expression-based syntax, you would use
[source,java]
----
@@ -2936,7 +2936,7 @@ The beans required in an application context to enable remember-me services are
</bean>
<bean id="rememberMeAuthenticationProvider" class=
"org.springframework.security.authentication.RememberMeAuthenticationProvider">
"org.springframework.security.authentication.rememberme.RememberMeAuthenticationProvider">
<property name="key" value="springRocks"/>
</bean>
----
@@ -5559,9 +5559,7 @@ The next step is to specify `serviceProperties` and the `authenticationDetailsSo
<property name="serviceProperties" ref="serviceProperties"/>
<property name="authenticationDetailsSource">
<bean class=
"org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource">
<constructor-arg ref="serviceProperties"/>
</bean>
"org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource"/>
</property>
</bean>
----
+1 -1
View File
@@ -1 +1 @@
version=4.0.0.M2
version=3.2.4.RELEASE
+18 -21
View File
@@ -12,7 +12,7 @@ apply plugin: 'propdeps-eclipse'
sourceCompatibility = 1.5
targetCompatibility = 1.5
ext.ehcacheVersion = '2.6.5'
ext.ehcacheVersion = '1.7.2'
ext.aspectjVersion = '1.6.10'
ext.apacheDsVersion = '1.5.5'
ext.jstlVersion = '1.2.1'
@@ -27,9 +27,7 @@ ext.seleniumVersion = '2.33.0'
ext.groovyVersion = '2.0.5'
ext.spockVersion = '0.7-groovy-2.0'
ext.gebVersion = '0.9.0'
ext.thymeleafVersion = '2.1.3.RELEASE'
ext.springDataJpaVersion = '1.7.0.RC1'
ext.springDataCommonsVersion = '1.9.0.RC1'
ext.thymeleafVersion = '2.1.2.RELEASE'
ext.spockDependencies = [
dependencies.create("org.spockframework:spock-spring:$spockVersion") {
@@ -40,13 +38,6 @@ ext.spockDependencies = [
}
]
ext.gebDependencies = spockDependencies + [
"org.seleniumhq.selenium:selenium-htmlunit-driver:$seleniumVersion",
"org.gebish:geb-spock:$gebVersion",
'commons-httpclient:commons-httpclient:3.1',
"org.codehaus.groovy:groovy:$groovyVersion"
]
ext.powerMockDependencies = [
"org.powermock:powermock-core:$powerMockVersion",
"org.powermock:powermock-api-support:$powerMockVersion",
@@ -58,11 +49,6 @@ ext.powerMockDependencies = [
"org.powermock:powermock-reflect:$powerMockVersion"
]
ext.jstlDependencies = [
"javax.servlet.jsp.jstl:javax.servlet.jsp.jstl-api:$jstlVersion",
"org.apache.taglibs:taglibs-standard-jstlel:1.2.1"
]
ext.apachedsDependencies = [
"org.apache.directory.server:apacheds-core:$apacheDsVersion",
"org.apache.directory.server:apacheds-core-entry:$apacheDsVersion",
@@ -72,6 +58,22 @@ ext.apachedsDependencies = [
'org.apache.directory.shared:shared-ldap:0.9.15'
]
ext.bundlorProperties = [
version: version,
secRange: "[$version, 3.3.0)",
springRange: "[$springVersion, 3.3.0)",
aspectjRange: '[1.6.0, 1.8.0)',
casRange: '[3.1.1, 3.2.0)',
cloggingRange: '[1.0.4, 2.0.0)',
ehcacheRange: '[1.4.1, 2.5.0)',
openid4javaRange: '[0.9.5, 1.0.0)',
springLdapRange: '[1.3.0,1.4.0)',
apacheDSRange: '[1.5.5, 1.6)',
apacheDSSharedRange: '[0.9.15, 1.0)',
ldapSdkRange: '[4.1, 5.0)',
aopAllianceRange: '[1.0.0, 2.0.0)'
]
// Integration test setup
configurations {
integrationTestCompile {
@@ -214,11 +216,6 @@ project.eclipseClasspath.doFirst {
}
}
project.idea.module {
scopes.TEST.plus += [project.configurations.integrationTestRuntime]
testSourceDirs += sourceSets.integrationTest.resources.srcDirs
}
task javadocJar(type: Jar) {
classifier = 'javadoc'
from javadoc
+1 -58
View File
@@ -1,67 +1,10 @@
buildscript {
repositories {
maven { url "https://repo.spring.io/plugins-release" }
}
dependencies {
classpath("org.gradle.api.plugins:gradle-tomcat-plugin:1.2.3")
}
}
apply plugin: 'tomcat'
dependencies {
def tomcatVersion = '7.0.54'
def tomcatVersion = '7.0.42'
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
"org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}"
tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}") {
exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
}
}
task integrationTomcatRun(type: org.gradle.api.plugins.tomcat.tasks.TomcatRun) {
onlyIf { !sourceSets.integrationTest.allSource.empty }
buildscriptClasspath = tomcatRun.buildscriptClasspath
contextPath = tomcatRun.contextPath
daemon = true
tomcatClasspath = tomcatRun.tomcatClasspath
webAppClasspath = tomcatRun.webAppClasspath
webAppSourceDirectory = tomcatRun.webAppSourceDirectory
doFirst {
def mainOutputDir = project.sourceSets.main.output.classesDir
if(mainOutputDir) {
classesDirectory = mainOutputDir
}
// delay reserving ports to ensure they are still available
def ports = reservePorts(3)
httpPort = ports[0]
ajpPort = ports[1]
stopPort = ports[2]
}
}
task integrationTomcatStop(type: org.gradle.api.plugins.tomcat.tasks.TomcatStop) {
onlyIf { !sourceSets.integrationTest.allSource.empty }
doFirst {
stopPort = integrationTomcatRun.stopPort
}
}
integrationTest {
dependsOn integrationTomcatRun
doFirst {
def host = 'localhost:' + integrationTomcatRun.httpPort
systemProperties['geb.build.baseUrl'] = 'http://'+host+'/' + integrationTomcatRun.contextPath + '/'
systemProperties['geb.build.reportsDir'] = 'build/geb-reports'
}
finalizedBy integrationTomcatStop
}
def reservePorts(int count) {
def sockets = []
for(int i in 1..count) {
sockets << new ServerSocket(0)
}
def result = sockets*.localPort
sockets*.close()
result
}
Binary file not shown.
+2 -2
View File
@@ -1,6 +1,6 @@
#Fri Jun 13 11:14:37 CDT 2014
#Wed Dec 11 17:49:08 CST 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.12-all.zip
distributionUrl=http\://services.gradle.org/distributions/gradle-1.10-rc-2-bin.zip
+11 -17
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>itest-context</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>itest-context</name>
<description>itest-context</description>
<url>http://spring.io/spring-security</url>
@@ -42,12 +42,6 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>aopalliance</groupId>
@@ -64,31 +58,31 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -100,7 +94,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -155,25 +149,25 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
+2 -4
View File
@@ -30,9 +30,7 @@ dependencies {
integrationTest {
useTestNG();
options {
jvmArgs = ["-ea", '-Xms128m', '-Xmx500m']
systemProperties = ['webapp.dir': "$projectDir/src/main/webapp"]
}
jvmArgs = ["-ea", '-Xms128m', '-Xmx500m']
systemProperty 'webapp.dir', "$projectDir/src/main/webapp"
maxParallelForks = 1
}
+12 -18
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>itest-web</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>itest-web</name>
<description>itest-web</description>
<url>http://spring.io/spring-security</url>
@@ -42,23 +42,17 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -70,7 +64,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -171,49 +165,49 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
-1
View File
@@ -19,7 +19,6 @@ dependencies {
exclude(group: 'org.springframework', module: 'spring-core')
exclude(group: 'org.springframework', module: 'spring-tx')
exclude(group: 'org.springframework', module: 'spring-beans')
exclude(group: 'org.springframework.data', module: 'spring-data-commons')
}
testCompile "org.slf4j:slf4j-api:$slf4jVersion",
+8 -18
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>spring-security-ldap</name>
<description>spring-security-ldap</description>
<url>http://spring.io/spring-security</url>
@@ -42,17 +42,11 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.0.1.RELEASE</version>
<version>1.3.2.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -63,10 +57,6 @@
<artifactId>spring-core</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-data-commons</artifactId>
<groupId>org.springframework.data</groupId>
</exclusion>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
@@ -80,25 +70,25 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -110,7 +100,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -208,7 +198,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -17,8 +17,6 @@ package org.springframework.security.ldap;
import static org.junit.Assert.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.naming.Context;
@@ -101,69 +99,6 @@ public class SpringSecurityLdapTemplateITests extends AbstractLdapIntegrationTes
assertTrue(values.contains("submanager"));
}
@Test
public void testMultiAttributeRetrievalWithNullAttributeNames() {
Set<Map<String, List<String>>> values =
template.searchForMultipleAttributeValues(
"ou=people",
"(uid={0})",
new String[]{"bob"},
null);
assertEquals(1, values.size());
Map<String, List<String>> record = values.iterator().next();
assertAttributeValue(record, "uid", "bob");
assertAttributeValue(record, "objectclass", "top", "person", "organizationalPerson", "inetOrgPerson");
assertAttributeValue(record, "cn", "Bob Hamilton");
assertAttributeValue(record, "sn", "Hamilton");
assertFalse(record.containsKey("userPassword"));
}
@Test
public void testMultiAttributeRetrievalWithZeroLengthAttributeNames() {
Set<Map<String, List<String>>> values =
template.searchForMultipleAttributeValues(
"ou=people",
"(uid={0})",
new String[]{"bob"},
new String[0]);
assertEquals(1, values.size());
Map<String, List<String>> record = values.iterator().next();
assertAttributeValue(record, "uid", "bob");
assertAttributeValue(record, "objectclass", "top", "person", "organizationalPerson", "inetOrgPerson");
assertAttributeValue(record, "cn", "Bob Hamilton");
assertAttributeValue(record, "sn", "Hamilton");
assertFalse(record.containsKey("userPassword"));
}
@Test
public void testMultiAttributeRetrievalWithSpecifiedAttributeNames() {
Set<Map<String, List<String>>> values =
template.searchForMultipleAttributeValues(
"ou=people",
"(uid={0})",
new String[]{"bob"},
new String[]{
"uid",
"cn",
"sn"
});
assertEquals(1, values.size());
Map<String, List<String>> record = values.iterator().next();
assertAttributeValue(record, "uid", "bob");
assertAttributeValue(record, "cn", "Bob Hamilton");
assertAttributeValue(record, "sn", "Hamilton");
assertFalse(record.containsKey("userPassword"));
assertFalse(record.containsKey("objectclass"));
}
protected void assertAttributeValue(Map<String, List<String>> record, String attributeName, String... values) {
assertTrue(record.containsKey(attributeName));
assertEquals(values.length, record.get(attributeName).size());
for (int i = 0; i < values.length; i++) {
assertEquals(values[i], record.get(attributeName).get(i));
}
}
@Test
public void testRoleSearchForMissingAttributeFailsGracefully() {
String param = "uid=ben,ou=people,dc=springframework,dc=org";
@@ -15,13 +15,12 @@
package org.springframework.security.ldap.search;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.*;
import javax.naming.ldap.LdapName;
import org.junit.Test;
import org.junit.*;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.AbstractLdapIntegrationTests;
@@ -33,7 +32,7 @@ import org.springframework.security.ldap.AbstractLdapIntegrationTests;
public class FilterBasedLdapUserSearchTests extends AbstractLdapIntegrationTests {
@Test
public void basicSearchSucceeds() throws Exception {
public void basicSearchSucceeds() {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(uid={0})", getContextSource());
locator.setSearchSubtree(false);
locator.setSearchTimeLimit(0);
@@ -42,25 +41,25 @@ public class FilterBasedLdapUserSearchTests extends AbstractLdapIntegrationTests
DirContextOperations bob = locator.searchForUser("bob");
assertEquals("bob", bob.getStringAttribute("uid"));
assertEquals(new LdapName("uid=bob,ou=people"), bob.getDn());
assertEquals(new DistinguishedName("uid=bob,ou=people"), bob.getDn());
}
@Test
public void searchForNameWithCommaSucceeds() throws Exception {
public void searchForNameWithCommaSucceeds() {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(uid={0})", getContextSource());
locator.setSearchSubtree(false);
DirContextOperations jerry = locator.searchForUser("jerry");
assertEquals("jerry", jerry.getStringAttribute("uid"));
assertEquals(new LdapName("cn=mouse\\, jerry,ou=people"), jerry.getDn());
assertEquals(new DistinguishedName("cn=mouse\\, jerry,ou=people"), jerry.getDn());
}
// Try some funny business with filters.
@Test
public void extraFilterPartToExcludeBob() throws Exception {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people",
"(&(cn=*)(!(|(uid={0})(uid=rod)(uid=jerry)(uid=slashguy)(uid=javadude)(uid=groovydude)(uid=closuredude)(uid=scaladude))))", getContextSource());
"(&(cn=*)(!(|(uid={0})(uid=rod)(uid=jerry)(uid=slashguy))))", getContextSource());
// Search for bob, get back ben...
DirContextOperations ben = locator.searchForUser("bob");
@@ -80,7 +79,7 @@ public class FilterBasedLdapUserSearchTests extends AbstractLdapIntegrationTests
}
@Test
public void subTreeSearchSucceeds() throws Exception {
public void subTreeSearchSucceeds() {
// Don't set the searchBase, so search from the root.
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("", "(cn={0})", getContextSource());
locator.setSearchSubtree(true);
@@ -88,7 +87,7 @@ public class FilterBasedLdapUserSearchTests extends AbstractLdapIntegrationTests
DirContextOperations ben = locator.searchForUser("Ben Alex");
assertEquals("ben", ben.getStringAttribute("uid"));
assertEquals(new LdapName("uid=ben,ou=people"), ben.getDn());
assertEquals(new DistinguishedName("uid=ben,ou=people"), ben.getDn());
}
@Test
@@ -1,131 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.ldap.userdetails;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.ldap.AbstractLdapIntegrationTests;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import static org.junit.Assert.*;
/**
* @author Filip Hanik
*/
public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegrationTests {
private NestedLdapAuthoritiesPopulator populator;
private LdapAuthority javaDevelopers;
private LdapAuthority groovyDevelopers;
private LdapAuthority scalaDevelopers;
private LdapAuthority closureDevelopers;
private LdapAuthority jDevelopers;
private LdapAuthority circularJavaDevelopers;
//~ Methods ========================================================================================================
@Before
public void setUp() throws Exception {
populator = new NestedLdapAuthoritiesPopulator(getContextSource(), "ou=jdeveloper");
populator.setGroupSearchFilter("(member={0})");
populator.setIgnorePartialResultException(false);
populator.setRolePrefix("");
populator.setSearchSubtree(true);
populator.setConvertToUpperCase(false);
jDevelopers = new LdapAuthority("j-developers", "cn=j-developers,ou=jdeveloper,dc=springframework,dc=org");
javaDevelopers = new LdapAuthority("java-developers", "cn=java-developers,ou=jdeveloper,dc=springframework,dc=org");
groovyDevelopers = new LdapAuthority("groovy-developers", "cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org");
scalaDevelopers = new LdapAuthority("scala-developers", "cn=scala-developers,ou=jdeveloper,dc=springframework,dc=org");
closureDevelopers = new LdapAuthority("closure-developers", "cn=closure-developers,ou=jdeveloper,dc=springframework,dc=org");
circularJavaDevelopers = new LdapAuthority("circular-java-developers", "cn=circular-java-developers,ou=jdeveloper,dc=springframework,dc=org");
}
@Test
public void testScalaDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "scaladude");
assertEquals(5, authorities.size());
assertEquals(Arrays.asList(javaDevelopers, scalaDevelopers, circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities);
}
@Test
public void testJavaDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter("uid=javadude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "javadude");
assertEquals(3, authorities.size());
assertEquals(Arrays.asList(javaDevelopers, circularJavaDevelopers, jDevelopers), authorities);
}
@Test
public void testScalaDudeJDevelopersAuthoritiesWithSearchLimit() {
populator.setMaxSearchDepth(1);
DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "scaladude");
assertEquals(1, authorities.size());
assertEquals(Arrays.asList(scalaDevelopers), authorities);
}
@Test
public void testGroovyDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter("uid=groovydude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "groovydude");
assertEquals(4, authorities.size());
assertEquals(Arrays.asList(javaDevelopers, circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities);
}
@Test
public void testClosureDudeJDevelopersWithMembershipAsAttributeValues() {
populator.setAttributeNames(new HashSet(Arrays.asList("member")));
DirContextAdapter ctx = new DirContextAdapter("uid=closuredude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "closuredude");
assertEquals(5, authorities.size());
assertEquals(Arrays.asList(closureDevelopers, javaDevelopers, circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities);
LdapAuthority[] ldapAuthorities = authorities.toArray(new LdapAuthority[0]);
assertEquals(5, ldapAuthorities.length);
//closure group
assertTrue(ldapAuthorities[0].getAttributes().containsKey("member"));
assertNotNull(ldapAuthorities[0].getAttributes().get("member"));
assertEquals(1, ldapAuthorities[0].getAttributes().get("member").size());
assertEquals("uid=closuredude,ou=people,dc=springframework,dc=org", ldapAuthorities[0].getFirstAttributeValue("member"));
//java group
assertTrue(ldapAuthorities[1].getAttributes().containsKey("member"));
assertNotNull(ldapAuthorities[1].getAttributes().get("member"));
assertEquals(3, ldapAuthorities[1].getAttributes().get("member").size());
assertEquals(groovyDevelopers.getDn(), ldapAuthorities[1].getFirstAttributeValue("member"));
assertEquals(
new String[]{
groovyDevelopers.getDn(),
scalaDevelopers.getDn(),
"uid=javadude,ou=people,dc=springframework,dc=org"
},
ldapAuthorities[1].getAttributes().get("member")
);
//test non existent attribute
assertNull(ldapAuthorities[2].getFirstAttributeValue("test"));
assertNotNull(ldapAuthorities[2].getAttributeValues("test"));
assertEquals(0, ldapAuthorities[2].getAttributeValues("test").size());
//test role name
assertEquals(jDevelopers.getAuthority(), ldapAuthorities[3].getAuthority());
}
}
@@ -122,109 +122,3 @@ objectclass: groupOfNames
cn: submanagers
ou: submanager
member: uid=ben,ou=people,dc=springframework,dc=org
#Nested groups data
###################
dn: ou=jdeveloper,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: jdeveloper
# javadude is part of (in a nested search)
# circular-java-developers, java-developers, j-developers
dn: uid=javadude,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Java Dude
sn: Dude
uid: javadude
userPassword: javadudespassword
# groovydude is part of (in a nested search)
# groovy-developers, java-developers, circular-java-developers, j-developers
dn: uid=groovydude,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Groovy Dude
sn: Dude
uid: groovydude
userPassword: groovydudespassword
# closuredude is part of (in a nested search)
# closure-developers, groovy-developers, java-developers, circular-java-developers, j-developers
dn: uid=closuredude,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Closure Dude
sn: Dude
uid: closuredude
userPassword: closuredudespassword
# scaladude is part of (in a nested search)
# scala-developers, groovy-developers, java-developers, circular-java-developers, j-developers
dn: uid=scaladude,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Scala Dude
sn: Dude
uid: scaladude
userPassword: scaladudespassword
dn: cn=j-developers,ou=jdeveloper,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: j-developers
ou: jdeveloper
member: cn=java-developers,ou=jdeveloper,dc=springframework,dc=org
dn: cn=java-developers,ou=jdeveloper,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: java-developers
ou: jdeveloper
member: cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org
member: cn=scala-developers,ou=jdeveloper,dc=springframework,dc=org
member: uid=javadude,ou=people,dc=springframework,dc=org
dn: cn=circular-java-developers,ou=jdeveloper,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: circular-java-developers
ou: jdeveloper
member: cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org
member: cn=scala-developers,ou=jdeveloper,dc=springframework,dc=org
member: uid=javadude,ou=people,dc=springframework,dc=org
dn: cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: groovy-developers
ou: jdeveloper
member: cn=closure-developers,ou=jdeveloper,dc=springframework,dc=org
member: uid=groovydude,ou=people,dc=springframework,dc=org
member: cn=circular-java-developers,ou=jdeveloper,dc=springframework,dc=org
dn: cn=closure-developers,ou=jdeveloper,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: closure-developers
ou: jdeveloper
member: uid=closuredude,ou=people,dc=springframework,dc=org
dn: cn=scala-developers,ou=jdeveloper,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: scala-developers
ou: jdeveloper
member: uid=scaladude,ou=people,dc=springframework,dc=org
@@ -30,18 +30,13 @@ import org.springframework.util.Assert;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.PartialResultException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -50,7 +45,6 @@ import java.util.Set;
*
* @author Ben Alex
* @author Luke Taylor
* @author Filip Hanik
* @since 2.0
*/
public class SpringSecurityLdapTemplate extends LdapTemplate {
@@ -58,13 +52,6 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
private static final Log logger = LogFactory.getLog(SpringSecurityLdapTemplate.class);
public static final String[] NO_ATTRS = new String[0];
/**
* Every search results where a record is defined by a Map&lt;String,String[]&gt;
* contains at least this key - the DN of the record itself.
*/
public static final String DN_KEY = "spring.security.ldap.dn";
private static final boolean RETURN_OBJECT = true;
//~ Instance fields ================================================================================================
@@ -152,124 +139,40 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
*/
public Set<String> searchForSingleAttributeValues(final String base, final String filter, final Object[] params,
final String attributeName) {
String[] attributeNames = new String[]{attributeName};
Set<Map<String, List<String>>> multipleAttributeValues = searchForMultipleAttributeValues(base, filter, params, attributeNames);
Set<String> result = new HashSet<String>();
for (Map<String, List<String>> map : multipleAttributeValues) {
List<String> values = map.get(attributeName);
if (values != null) {
result.addAll(values);
}
}
return result;
}
/**
* Performs a search using the supplied filter and returns the values of each named attribute
* found in all entries matched by the search. Note that one directory entry may have several values for the
* attribute. Intended for role searches and similar scenarios.
*
* @param base the DN to search in
* @param filter search filter to use
* @param params the parameters to substitute in the search filter
* @param attributeNames the attributes' values that are to be retrieved.
*
* @return the set of String values for each attribute found in all the matching entries.
* The attribute name is the key for each set of values. In addition each map contains the DN as a String
* with the key predefined key {@link #DN_KEY}.
*/
public Set<Map<String, List<String>>> searchForMultipleAttributeValues(final String base, final String filter, final Object[] params,
final String[] attributeNames) {
// Escape the params acording to RFC2254
Object[] encodedParams = new String[params.length];
for (int i = 0; i < params.length; i++) {
for (int i=0; i < params.length; i++) {
encodedParams[i] = LdapEncoder.filterEncode(params[i].toString());
}
String formattedFilter = MessageFormat.format(filter, encodedParams);
logger.debug("Using filter: " + formattedFilter);
final HashSet<Map<String, List<String>>> set = new HashSet<Map<String, List<String>>>();
final HashSet<String> set = new HashSet<String>();
ContextMapper roleMapper = new ContextMapper() {
public Object mapFromContext(Object ctx) {
DirContextAdapter adapter = (DirContextAdapter) ctx;
Map<String, List<String>> record = new HashMap<String, List<String>>();
if (attributeNames == null || attributeNames.length == 0) {
try {
for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae.hasMore(); ) {
Attribute attr = (Attribute) ae.next();
extractStringAttributeValues(adapter, record, attr.getID());
}
} catch (NamingException x) {
org.springframework.ldap.support.LdapUtils.convertLdapException(x);
}
String[] values = adapter.getStringAttributes(attributeName);
if (values == null || values.length == 0) {
logger.debug("No attribute value found for '" + attributeName + "'");
} else {
for (String attributeName : attributeNames) {
extractStringAttributeValues(adapter, record, attributeName);
}
set.addAll(Arrays.asList(values));
}
record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter)));
set.add(record);
return null;
}
};
SearchControls ctls = new SearchControls();
ctls.setSearchScope(searchControls.getSearchScope());
ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null);
ctls.setReturningAttributes(new String[] {attributeName});
search(base, formattedFilter, ctls, roleMapper);
return set;
}
/**
* Returns the DN for the context representing this LDAP record.
* By default this is using {@link javax.naming.Context#getNameInNamespace()}
* instead of {@link org.springframework.ldap.core.DirContextAdapter#getDn()} since the
* latter returns a partial DN if a base has been specified.
* @param adapter - the Context to extract the DN from
* @return - the String representing the full DN
*/
private String getAdapterDN(DirContextAdapter adapter) {
//returns the full DN rather than the sub DN if a base is specified
return adapter.getNameInNamespace();
}
/**
* Extracts String values for a specified attribute name and places them in the map representing the ldap record If
* a value is not of type String, it will derive it's value from the {@link Object#toString()}
*
* @param adapter - the adapter that contains the values
* @param record - the map holding the attribute names and values
* @param attributeName - the name for which to fetch the values from
*/
private void extractStringAttributeValues(DirContextAdapter adapter, Map<String, List<String>> record, String attributeName) {
Object[] values = adapter.getObjectAttributes(attributeName);
if (values == null || values.length == 0) {
if(logger.isDebugEnabled()) {
logger.debug("No attribute value found for '" + attributeName + "'");
}
return;
}
List<String> svalues = new ArrayList<String>();
for (Object o : values) {
if (o != null) {
if (String.class.isAssignableFrom(o.getClass())) {
svalues.add((String) o);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Attribute:" + attributeName + " contains a non string value of type[" + o.getClass() + "]");
}
svalues.add(o.toString());
}
}
}
record.put(attributeName, svalues);
}
/**
* Performs a search, with the requirement that the search shall return a single directory entry, and uses
* the supplied mapper to create the object from that entry.
@@ -18,7 +18,6 @@ package org.springframework.security.ldap.server;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
@@ -127,7 +126,6 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
server = new LdapServer();
server.setDirectoryService(service);
// AbstractLdapIntegrationTests assume IPv4, so we specify the same here
server.setTransports(new TcpTransport(port));
start();
}
@@ -206,7 +204,7 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
try {
importLdifs();
} catch (Exception e) {
throw new RuntimeException("Failed to import LDIF file(s)", e);
logger.error("Failed to import LDIF file(s)", e);
}
}
@@ -264,7 +262,7 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
LdifFileLoader loader = new LdifFileLoader(service.getAdminSession(), ldifFile);
loader.execute();
} else {
throw new IllegalArgumentException("More than one LDIF resource found with the supplied pattern:" + ldifResources+ " Got " + Arrays.toString(ldifs));
throw new IllegalArgumentException("More than one LDIF resource found with the supplied pattern:" + ldifResources);
}
}
@@ -92,7 +92,6 @@ import java.util.Set;
* a search of the entire subtree under <tt>groupSearchBase</tt>.
*
* @author Luke Taylor
* @author Filip Hanik
*/
public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {
//~ Static fields/initializers =====================================================================================
@@ -106,9 +105,6 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
*/
private GrantedAuthority defaultRole;
/**
* Template that will be used for searching
*/
private final SpringSecurityLdapTemplate ldapTemplate;
/**
@@ -131,13 +127,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* The pattern to be used for the user search. {0} is the user's DN
*/
private String groupSearchFilter = "(member={0})";
/**
* The role prefix that will be prepended to each role name
*/
private String rolePrefix = "ROLE_";
/**
* Should we convert the role name to uppercase
*/
private boolean convertToUpperCase = true;
//~ Constructors ===================================================================================================
@@ -153,7 +143,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
public DefaultLdapAuthoritiesPopulator(ContextSource contextSource, String groupSearchBase) {
Assert.notNull(contextSource, "contextSource must not be null");
ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
getLdapTemplate().setSearchControls(getSearchControls());
ldapTemplate.setSearchControls(searchControls);
this.groupSearchBase = groupSearchBase;
if (groupSearchBase == null) {
@@ -222,8 +212,8 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
+ groupSearchFilter + " in search base '" + getGroupSearchBase() + "'");
}
Set<String> userRoles = getLdapTemplate().searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter,
new String[]{userDn, username}, groupRoleAttribute);
Set<String> userRoles = ldapTemplate.searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter,
new String[]{userDn, username}, groupRoleAttribute);
if (logger.isDebugEnabled()) {
logger.debug("Roles from search: " + userRoles);
@@ -242,7 +232,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
}
protected ContextSource getContextSource() {
return getLdapTemplate().getContextSource();
return ldapTemplate.getContextSource();
}
protected String getGroupSearchBase() {
@@ -307,75 +297,6 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @see LdapTemplate#setIgnoreNameNotFoundException(boolean)
*/
public void setIgnorePartialResultException(boolean ignore) {
getLdapTemplate().setIgnorePartialResultException(ignore);
}
/**
* Returns the current LDAP template.
* Method available so that classes extending this can override the template used
* @return the LDAP template
* @see {@link org.springframework.security.ldap.SpringSecurityLdapTemplate}
*/
protected SpringSecurityLdapTemplate getLdapTemplate() {
return ldapTemplate;
}
/**
* Returns the attribute name of the LDAP attribute that will be mapped to the role name
* Method available so that classes extending this can override
* @return the attribute name used for role mapping
* @see {@link #setGroupRoleAttribute(String)}
*/
protected final String getGroupRoleAttribute() {
return groupRoleAttribute;
}
/**
* Returns the search filter configured for this populator
* Method available so that classes extending this can override
* @return the search filter
* @see {@link #setGroupSearchFilter(String)}
*/
protected final String getGroupSearchFilter() {
return groupSearchFilter;
}
/**
* Returns the role prefix used by this populator
* Method available so that classes extending this can override
* @return the role prefix
* @see {@link #setRolePrefix(String)}
*/
protected final String getRolePrefix() {
return rolePrefix;
}
/**
* Returns true if role names are converted to uppercase
* Method available so that classes extending this can override
* @return true if role names are converted to uppercase.
* @see {@link #setConvertToUpperCase(boolean)}
*/
protected final boolean isConvertToUpperCase() {
return convertToUpperCase;
}
/**
* Returns the default role
* Method available so that classes extending this can override
* @return the default role used
* @see {@link #setDefaultRole(String)}
*/
private GrantedAuthority getDefaultRole() {
return defaultRole;
}
/**
* Returns the search controls
* Method available so that classes extending this can override the search controls used
* @return the search controls
*/
private SearchControls getSearchControls() {
return searchControls;
ldapTemplate.setIgnorePartialResultException(ignore);
}
}
@@ -1,156 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.ldap.userdetails;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* An authority that contains at least a DN and a role name for an LDAP entry but can also contain other desired
* attributes to be fetched during an LDAP authority search.
*
* @author Filip Hanik
*/
public class LdapAuthority implements GrantedAuthority {
private String dn;
private String role;
private Map<String, List<String>> attributes;
/**
* Constructs an LdapAuthority that has a role and a DN but no other attributes
*
* @param role
* @param dn
*/
public LdapAuthority(String role, String dn) {
this(role, dn, null);
}
/**
* Constructs an LdapAuthority with the given role, DN and other LDAP attributes
*
* @param role
* @param dn
* @param attributes
*/
public LdapAuthority(String role, String dn, Map<String, List<String>> attributes) {
Assert.notNull(role, "role can not be null");
Assert.notNull(dn, "dn can not be null");
this.role = role;
this.dn = dn;
this.attributes = attributes;
}
/**
* Returns the LDAP attributes
*
* @return the LDAP attributes, map can be null
*/
public Map<String, List<String>> getAttributes() {
return attributes;
}
/**
* Returns the DN for this LDAP authority
*
* @return
*/
public String getDn() {
return dn;
}
/**
* Returns the values for a specific attribute
*
* @param name the attribute name
* @return a String array, never null but may be zero length
*/
public List<String> getAttributeValues(String name) {
List<String> result = null;
if (attributes != null) {
result = attributes.get(name);
}
if (result == null) {
result = Collections.emptyList();
}
return result;
}
/**
* Returns the first attribute value for a specified attribute
*
* @param name
* @return the first attribute value for a specified attribute, may be null
*/
public String getFirstAttributeValue(String name) {
List<String> result = getAttributeValues(name);
if (result.isEmpty()) {
return null;
} else {
return result.get(0);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getAuthority() {
return role;
}
/**
* Compares the LdapAuthority based on {@link #getAuthority()} and {@link #getDn()} values {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof LdapAuthority)) {
return false;
}
LdapAuthority that = (LdapAuthority) o;
if (!dn.equals(that.dn)) {
return false;
}
return role.equals(that.role);
}
@Override
public int hashCode() {
int result = dn.hashCode();
result = 31 * result + (role != null ? role.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "LdapAuthority{" +
"dn='" + dn + '\'' +
", role='" + role + '\'' +
'}';
}
}
@@ -1,258 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.ldap.userdetails;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ldap.core.ContextSource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import org.springframework.util.StringUtils;
import java.util.*;
/**
* A LDAP authority populator that can recursively search static nested groups. <p>An example of nested groups can be
* <pre>
* #Nested groups data
*
* dn: uid=javadude,ou=people,dc=springframework,dc=org
* objectclass: top
* objectclass: person
* objectclass: organizationalPerson
* objectclass: inetOrgPerson
* cn: Java Dude
* sn: Dude
* uid: javadude
* userPassword: javadudespassword
*
* dn: uid=groovydude,ou=people,dc=springframework,dc=org
* objectclass: top
* objectclass: person
* objectclass: organizationalPerson
* objectclass: inetOrgPerson
* cn: Groovy Dude
* sn: Dude
* uid: groovydude
* userPassword: groovydudespassword
*
* dn: uid=closuredude,ou=people,dc=springframework,dc=org
* objectclass: top
* objectclass: person
* objectclass: organizationalPerson
* objectclass: inetOrgPerson
* cn: Closure Dude
* sn: Dude
* uid: closuredude
* userPassword: closuredudespassword
*
* dn: uid=scaladude,ou=people,dc=springframework,dc=org
* objectclass: top
* objectclass: person
* objectclass: organizationalPerson
* objectclass: inetOrgPerson
* cn: Scala Dude
* sn: Dude
* uid: scaladude
* userPassword: scaladudespassword
*
* dn: cn=j-developers,ou=jdeveloper,dc=springframework,dc=org
* objectclass: top
* objectclass: groupOfNames
* cn: j-developers
* ou: jdeveloper
* member: cn=java-developers,ou=groups,dc=springframework,dc=org
*
* dn: cn=java-developers,ou=jdeveloper,dc=springframework,dc=org
* objectclass: top
* objectclass: groupOfNames
* cn: java-developers
* ou: jdeveloper
* member: cn=groovy-developers,ou=groups,dc=springframework,dc=org
* member: cn=scala-developers,ou=groups,dc=springframework,dc=org
* member: uid=javadude,ou=people,dc=springframework,dc=org
*
* dn: cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org
* objectclass: top
* objectclass: groupOfNames
* cn: java-developers
* ou: jdeveloper
* member: cn=closure-developers,ou=groups,dc=springframework,dc=org
* member: uid=groovydude,ou=people,dc=springframework,dc=org
*
* dn: cn=closure-developers,ou=jdeveloper,dc=springframework,dc=org
* objectclass: top
* objectclass: groupOfNames
* cn: java-developers
* ou: jdeveloper
* member: uid=closuredude,ou=people,dc=springframework,dc=org
*
* dn: cn=scala-developers,ou=jdeveloper,dc=springframework,dc=org
* objectclass: top
* objectclass: groupOfNames
* cn: java-developers
* ou: jdeveloper
* member: uid=scaladude,ou=people,dc=springframework,dc=org * </pre>
* </pre>
* </p>
*
* @author Filip Hanik
*/
public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopulator {
private static final Log logger = LogFactory.getLog(NestedLdapAuthoritiesPopulator.class);
/**
* The attribute names to retrieve for each LDAP group
*/
private Set<String> attributeNames;
/**
* Maximum search depth - represents the number of recursive searches performed
*/
private int maxSearchDepth = 10;
/**
* Constructor for group search scenarios. <tt>userRoleAttributes</tt> may still be set as a property.
*
* @param contextSource supplies the contexts used to search for user roles.
* @param groupSearchBase if this is an empty string the search will be performed from the root DN of the
*/
public NestedLdapAuthoritiesPopulator(ContextSource contextSource, String groupSearchBase) {
super(contextSource, groupSearchBase);
}
/**
* {@inheritDoc}
*/
@Override
public Set<GrantedAuthority> getGroupMembershipRoles(String userDn, String username) {
if (getGroupSearchBase() == null) {
return new HashSet<GrantedAuthority>();
}
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
performNestedSearch(userDn, username, authorities, getMaxSearchDepth());
return authorities;
}
/**
* Performs the nested group search
*
* @param userDn - the userDN to search for, will become the group DN for subsequent searches
* @param username - the username of the user
* @param authorities - the authorities set that will be populated, must not be null
* @param depth - the depth remaining, when 0 recursion will end
*/
private void performNestedSearch(String userDn, String username, Set<GrantedAuthority> authorities, int depth) {
if (depth == 0) {
//back out of recursion
if (logger.isDebugEnabled()) {
logger.debug("Search aborted, max depth reached," +
" for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter "
+ getGroupSearchFilter() + " in search base '" + getGroupSearchBase() + "'");
}
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Searching for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter "
+ getGroupSearchFilter() + " in search base '" + getGroupSearchBase() + "'");
}
if (getAttributeNames() == null) {
setAttributeNames(new HashSet<String>());
}
if (StringUtils.hasText(getGroupRoleAttribute()) && !getAttributeNames().contains(getGroupRoleAttribute())) {
getAttributeNames().add(getGroupRoleAttribute());
}
Set<Map<String, List<String>>> userRoles = getLdapTemplate().searchForMultipleAttributeValues(
getGroupSearchBase(),
getGroupSearchFilter(),
new String[]{userDn, username},
getAttributeNames().toArray(new String[getAttributeNames().size()]));
if (logger.isDebugEnabled()) {
logger.debug("Roles from search: " + userRoles);
}
for (Map<String, List<String>> record : userRoles) {
boolean circular = false;
String dn = record.get(SpringSecurityLdapTemplate.DN_KEY).get(0);
List<String> roleValues = record.get(getGroupRoleAttribute());
Set<String> roles = new HashSet<String>();
if(roleValues != null) {
roles.addAll(roleValues);
}
for (String role : roles) {
if (isConvertToUpperCase()) {
role = role.toUpperCase();
}
role = getRolePrefix() + role;
//if the group already exist, we will not search for it's parents again.
//this prevents a forever loop for a misconfigured ldap directory
circular = circular | (!authorities.add(new LdapAuthority(role, dn, record)));
}
String roleName = roles.size() > 0 ? roles.iterator().next() : dn;
if (!circular) {
performNestedSearch(dn, roleName, authorities, (depth - 1));
}
}
}
/**
* Returns the attribute names that this populator has been configured to retrieve Value can be null, represents
* fetch all attributes
*
* @return the attribute names or null for all
*/
private Set<String> getAttributeNames() {
return attributeNames;
}
/**
* Sets the attribute names to retrieve for each ldap groups. Null means retrieve all
*
* @param attributeNames - the names of the LDAP attributes to retrieve
*/
public void setAttributeNames(Set<String> attributeNames) {
this.attributeNames = attributeNames;
}
/**
* How far should a nested search go. Depth is calculated in the number of levels we search up for parent groups.
*
* @return the max search depth, default is 10
*/
private int getMaxSearchDepth() {
return maxSearchDepth;
}
/**
* How far should a nested search go. Depth is calculated in the number of levels we search up for parent groups.
*
* @param maxSearchDepth the max search depth
*/
public void setMaxSearchDepth(int maxSearchDepth) {
this.maxSearchDepth = maxSearchDepth;
}
}
@@ -1,54 +0,0 @@
package org.springframework.security.ldap.userdetails;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Filip Hanik
*/
public class LdapAuthorityTests {
public static final String DN = "cn=filip,ou=Users,dc=test,dc=com";
LdapAuthority authority;
@Before
public void setUp() {
Map<String, List<String>> attributes = new HashMap<String, List<String>>();
attributes.put(SpringSecurityLdapTemplate.DN_KEY, Arrays.asList(DN));
attributes.put("mail", Arrays.asList("filip@ldap.test.org", "filip@ldap.test2.org"));
authority = new LdapAuthority("testRole", DN, attributes);
}
@Test
public void testGetDn() throws Exception {
assertEquals(DN, authority.getDn());
assertNotNull(authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY));
assertEquals(1, authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY).size());
assertEquals(DN, authority.getFirstAttributeValue(SpringSecurityLdapTemplate.DN_KEY));
}
@Test
public void testGetAttributes() throws Exception {
assertNotNull(authority.getAttributes());
assertNotNull(authority.getAttributeValues("mail"));
assertEquals(2, authority.getAttributeValues("mail").size());
assertEquals("filip@ldap.test.org", authority.getFirstAttributeValue("mail"));
assertEquals("filip@ldap.test.org", authority.getAttributeValues("mail").get(0));
assertEquals("filip@ldap.test2.org", authority.getAttributeValues("mail").get(1));
}
@Test
public void testGetAuthority() throws Exception {
assertNotNull(authority.getAuthority());
assertEquals("testRole", authority.getAuthority());
}
}
+27
View File
@@ -0,0 +1,27 @@
Implementation-Title: org.springframework.security.ldap
Implementation-Version: ${version}
Bundle-SymbolicName: org.springframework.security.ldap
Bundle-Name: Spring Security LDAP
Bundle-Vendor: SpringSource
Bundle-Version: ${version}
Bundle-ManifestVersion: 2
Ignored-Existing-Headers:
Import-Package,
Export-Package
Import-Template:
org.apache.commons.logging.*;version="${cloggingRange}",
org.apache.directory.server.*;version="${apacheDSRange}";resolution:=optional,
org.apache.directory.shared.ldap.*;version="${apacheDSSharedRange}";resolution:=optional,
org.springframework.ldap.*;version="${springLdapRange}",
org.springframework.security.core.*;version="${secRange}",
org.springframework.security.crypto.*;version="${secRange}",
org.springframework.security.authentication.*;version="${secRange}",
org.springframework.security.provisioning.*;version="${secRange}",
org.springframework.security.util;version="${secRange}",
org.springframework.beans.*;version="${springRange}",
org.springframework.context.*;version="${springRange}",
org.springframework.core.io.*;version="${springRange}",
org.springframework.dao.*;version="${springRange}";resolution:=optional,
org.springframework.util.*;version="${springRange}",
javax.naming.*;version="0";resolution:=optional,
netscape.ldap.ber.stream;version="${ldapSdkRange}";resolution:=optional
-19
View File
@@ -1,19 +0,0 @@
apply plugin: 'groovy'
dependencies {
compile project(':spring-security-core'),
'aopalliance:aopalliance:1.0',
"org.springframework:spring-beans:$springVersion",
"org.springframework:spring-context:$springVersion",
"org.springframework:spring-expression:$springVersion",
"org.springframework:spring-messaging:$springVersion"
testCompile project(':spring-security-core').sourceSets.test.output,
'commons-codec:commons-codec:1.3',
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
"org.codehaus.groovy:groovy-all:$groovyVersion",
powerMockDependencies,
spockDependencies
testRuntime "org.hsqldb:hsqldb:$hsqlVersion"
}
-228
View File
@@ -1,228 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
<version>4.0.0.M2</version>
<name>spring-security-messaging</name>
<description>spring-security-messaging</description>
<url>http://spring.io/spring-security</url>
<organization>
<name>spring.io</name>
<url>http://spring.io/</url>
</organization>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rwinch</id>
<name>Rob Winch</name>
<email>rwinch@gopivotal.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/spring-projects/spring-security</connection>
<developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>
<url>https://github.com/spring-projects/spring-security</url>
</scm>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.0.RC2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.1.0.RC2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.29</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.0.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<version>1.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.1</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>mockito-all</artifactId>
<groupId>org.mockito</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-support</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-common</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-reflect</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>0.7-groovy-2.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>junit-dep</artifactId>
<groupId>junit</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-spring</artifactId>
<version>0.7-groovy-2.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>junit-dep</artifactId>
<groupId>junit</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -1,37 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.expression;
import org.springframework.messaging.Message;
import org.springframework.security.access.expression.AbstractSecurityExpressionHandler;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.access.expression.SecurityExpressionOperations;
import org.springframework.security.core.Authentication;
/**
* The default implementation of {@link SecurityExpressionHandler} which uses a {@link MessageSecurityExpressionRoot}.
*
* @since 4.0
*
* @author Rob Winch
*/
public class DefaultMessageSecurityExpressionHandler<T> extends AbstractSecurityExpressionHandler<Message<T>> {
@Override
protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, Message<T> invocation) {
return new MessageSecurityExpressionRoot(authentication,invocation);
}
}
@@ -1,84 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.expression;
import org.springframework.expression.Expression;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.messaging.access.intercept.DefaultMessageSecurityMetadataSource;
import org.springframework.security.messaging.access.intercept.MessageSecurityMetadataSource;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A class used to create a {@link MessageSecurityMetadataSource} that uses {@link MessageMatcher} mapped to Spring
* Expressions.
*
* @since 4.0
* @author Rob Winch
*/
public final class ExpressionBasedMessageSecurityMetadataSourceFactory {
/**
* Create a {@link MessageSecurityMetadataSource} that uses {@link MessageMatcher} mapped to Spring
* Expressions. Each entry is considered in order and only the first match is used.
*
* For example:
*
* <pre>
* LinkedHashMap<MessageMatcher<?> matcherToExpression = new LinkedHashMap<MessageMatcher<Object>();
* matcherToExpression.put(new SimDestinationMessageMatcher("/public/**"), "permitAll");
* matcherToExpression.put(new SimDestinationMessageMatcher("/admin/**"), "hasRole('ROLE_ADMIN')");
* matcherToExpression.put(new SimDestinationMessageMatcher("/**"), "authenticated");
*
* MessageSecurityMetadataSource metadataSource = createExpressionMessageMetadataSource(matcherToExpression);
* </pre>
*
* <p>
* If our destination is "/public/hello", it would match on "/public/**" and on "/**". However, only "/public/**"
* would be used since it is the first entry. That means that a destination of "/public/hello" will be mapped to
* "permitAll".
* </p>
*
* <p>
* For a complete listing of expressions see {@link MessageSecurityExpressionRoot}
* </p>
*
* @param matcherToExpression an ordered mapping of {@link MessageMatcher} to Strings that are turned into an
* Expression using {@link DefaultMessageSecurityExpressionHandler#getExpressionParser()}
* @return the {@link MessageSecurityMetadataSource} to use. Cannot be null.
*/
public static MessageSecurityMetadataSource createExpressionMessageMetadataSource(LinkedHashMap<MessageMatcher<?>,String> matcherToExpression) {
DefaultMessageSecurityExpressionHandler handler = new DefaultMessageSecurityExpressionHandler();
LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>> matcherToAttrs = new LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>>();
for(Map.Entry<MessageMatcher<?>,String> entry : matcherToExpression.entrySet()) {
MessageMatcher<?> matcher = entry.getKey();
String rawExpression = entry.getValue();
Expression expression = handler.getExpressionParser().parseExpression(rawExpression);
ConfigAttribute attribute = new MessageExpressionConfigAttribute(expression);
matcherToAttrs.put(matcher, Arrays.asList(attribute));
}
return new DefaultMessageSecurityMetadataSource(matcherToAttrs);
}
private ExpressionBasedMessageSecurityMetadataSourceFactory() {}
}
@@ -1,55 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.expression;
import org.springframework.expression.Expression;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.util.Assert;
/**
* Simple expression configuration attribute for use in {@link Message} authorizations.
*
* @since 4.0
* @author Rob Winch
*/
class MessageExpressionConfigAttribute implements ConfigAttribute {
private final Expression authorizeExpression;
/**
* Creates a new instance
*
* @param authorizeExpression the {@link Expression} to use. Cannot be null
*/
public MessageExpressionConfigAttribute(Expression authorizeExpression) {
Assert.notNull(authorizeExpression, "authorizeExpression cannot be null");
this.authorizeExpression = authorizeExpression;
}
Expression getAuthorizeExpression() {
return authorizeExpression;
}
public String getAttribute() {
return null;
}
@Override
public String toString() {
return authorizeExpression.getExpressionString();
}
}
@@ -1,78 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.expression;
import org.springframework.expression.EvaluationContext;
import org.springframework.messaging.Message;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.expression.ExpressionUtils;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import java.util.Collection;
/**
* Voter which handles {@link Message} authorisation decisions. If a {@link MessageExpressionConfigAttribute} is found,
* then its expression is evaluated. If true, {@code ACCESS_GRANTED} is returned. If false, {@code ACCESS_DENIED} is
* returned. If no {@code MessageExpressionConfigAttribute} is found, then {@code ACCESS_ABSTAIN} is returned.
*
* @since 4.0
* @author Rob Winch
*/
public class MessageExpressionVoter<T> implements AccessDecisionVoter<Message<T>> {
private SecurityExpressionHandler<Message<T>> expressionHandler = new DefaultMessageSecurityExpressionHandler();
public int vote(Authentication authentication, Message<T> message, Collection<ConfigAttribute> attributes) {
assert authentication != null;
assert message != null;
assert attributes != null;
MessageExpressionConfigAttribute attr = findConfigAttribute(attributes);
if (attr == null) {
return ACCESS_ABSTAIN;
}
EvaluationContext ctx = expressionHandler.createEvaluationContext(authentication, message);
return ExpressionUtils.evaluateAsBoolean(attr.getAuthorizeExpression(), ctx) ?
ACCESS_GRANTED : ACCESS_DENIED;
}
private MessageExpressionConfigAttribute findConfigAttribute(Collection<ConfigAttribute> attributes) {
for (ConfigAttribute attribute : attributes) {
if (attribute instanceof MessageExpressionConfigAttribute) {
return (MessageExpressionConfigAttribute)attribute;
}
}
return null;
}
public boolean supports(ConfigAttribute attribute) {
return attribute instanceof MessageExpressionConfigAttribute;
}
public boolean supports(Class<?> clazz) {
return Message.class.isAssignableFrom(clazz);
}
public void setExpressionHandler(SecurityExpressionHandler<Message<T>> expressionHandler) {
Assert.notNull(expressionHandler, "expressionHandler cannot be null");
this.expressionHandler = expressionHandler;
}
}
@@ -1,33 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.expression;
import org.springframework.messaging.Message;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.core.Authentication;
/**
* The {@link SecurityExpressionRoot} used for {@link Message} expressions.
*
* @since 4.0
* @author Rob Winch
*/
final class MessageSecurityExpressionRoot extends SecurityExpressionRoot {
public MessageSecurityExpressionRoot(Authentication authentication, Message message) {
super(authentication);
}
}
@@ -1,130 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.intercept;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.messaging.access.expression.ExpressionBasedMessageSecurityMetadataSourceFactory;
import org.springframework.util.Assert;
/**
* Performs security handling of Message resources via a ChannelInterceptor implementation.
* <p>
* The <code>SecurityMetadataSource</code> required by this security interceptor is of type {@link
* MessageSecurityMetadataSource}.
* </p>
* <p>
* Refer to {@link AbstractSecurityInterceptor} for details on the workflow.
* </p>
*
* @see 4.0
* @author Rob Winch
*/
public final class ChannelSecurityInterceptor extends AbstractSecurityInterceptor implements ChannelInterceptor {
private final MessageSecurityMetadataSource metadataSource;
/**
* Creates a new instance
*
* @param metadataSource the MessageSecurityMetadataSource to use. Cannot be null.
*
* @see DefaultMessageSecurityMetadataSource
* @see ExpressionBasedMessageSecurityMetadataSourceFactory
*/
public ChannelSecurityInterceptor(MessageSecurityMetadataSource metadataSource) {
Assert.notNull(metadataSource, "metadataSource cannot be null");
this.metadataSource = metadataSource;
}
@Override
public Class<?> getSecureObjectClass() {
return Message.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return metadataSource;
}
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
InterceptorStatusToken token = beforeInvocation(message);
return token == null ? message : new TokenMessage(message,token);
}
@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
if(!(message instanceof TokenMessage)) {
// TODO What if other classes return another instance too?
return;
}
InterceptorStatusToken token = ((TokenMessage)message).getToken();
afterInvocation(token, null);
}
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
if(!(message instanceof TokenMessage)) {
// TODO What if other classes return another instance too?
return;
}
InterceptorStatusToken token = ((TokenMessage)message).getToken();
finallyInvocation(token);
}
public boolean preReceive(MessageChannel channel) {
return true;
}
@Override
public Message<?> postReceive(Message<?> message, MessageChannel channel) {
return message;
}
@Override
public void afterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {
}
static final class TokenMessage implements Message {
private final Message delegate;
private final InterceptorStatusToken token;
TokenMessage(Message delegate, InterceptorStatusToken token) {
this.delegate = delegate;
this.token = token;
}
public InterceptorStatusToken getToken() {
return token;
}
@Override
public MessageHeaders getHeaders() {
return delegate.getHeaders();
}
@Override
public Object getPayload() {
return delegate.getPayload();
}
}
}
@@ -1,73 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.intercept;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.messaging.access.expression.ExpressionBasedMessageSecurityMetadataSourceFactory;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import java.util.*;
/**
* A default implementation of {@link MessageSecurityMetadataSource} that looks up the {@link ConfigAttribute} instances
* using a {@link MessageMatcher}.
*
* <p>
* Each entry is considered in order. The first entry that matches, the corresponding {@code Collection<ConfigAttribute>}
* is returned.
* </p>
*
* @see ChannelSecurityInterceptor
* @see ExpressionBasedMessageSecurityMetadataSourceFactory
*
* @since 4.0
* @author Rob Winch
*/
public final class DefaultMessageSecurityMetadataSource implements MessageSecurityMetadataSource {
private final Map<MessageMatcher<?>,Collection<ConfigAttribute>> messageMap;
public DefaultMessageSecurityMetadataSource(LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>> messageMap) {
this.messageMap = messageMap;
}
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
final Message message = (Message) object;
for (Map.Entry<MessageMatcher<?>, Collection<ConfigAttribute>> entry : messageMap.entrySet()) {
if (entry.getKey().matches(message)) {
return entry.getValue();
}
}
return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
Set<ConfigAttribute> allAttributes = new HashSet<ConfigAttribute>();
for (Collection<ConfigAttribute> entry : messageMap.values()) {
allAttributes.addAll(entry);
}
return allAttributes;
}
@Override
public boolean supports(Class<?> clazz) {
return Message.class.isAssignableFrom(clazz);
}
}
@@ -1,31 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.intercept;
import org.springframework.messaging.Message;
import org.springframework.security.access.SecurityMetadataSource;
/**
* A {@link SecurityMetadataSource} that is used for securing {@link Message}
*
* @see ChannelSecurityInterceptor
* @see DefaultMessageSecurityMetadataSource
*
* @since 4.0
* @author Rob Winch
*/
public interface MessageSecurityMetadataSource extends SecurityMetadataSource {
}
@@ -1,93 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.context;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.messaging.support.ExecutorChannelInterceptor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.Assert;
/**
* <p>
* Creates a {@link ExecutorChannelInterceptor} that will obtain the {@link Authentication} from the specified
* {@link Message#getHeaders()}.
* </p>
*
* @since 4.0
* @author Rob Winch
*/
public final class SecurityContextChannelInterceptor extends ChannelInterceptorAdapter implements ExecutorChannelInterceptor {
private final String authenticationHeaderName;
/**
* Creates a new instance using the header of the name {@link SimpMessageHeaderAccessor#USER_HEADER}.
*/
public SecurityContextChannelInterceptor() {
this(SimpMessageHeaderAccessor.USER_HEADER);
}
/**
* Creates a new instance that uses the specified header to obtain the {@link Authentication}.
*
* @param authenticationHeaderName the header name to obtain the {@link Authentication}. Cannot be null.
*/
public SecurityContextChannelInterceptor(String authenticationHeaderName) {
Assert.notNull(authenticationHeaderName, "authenticationHeaderName cannot be null");
this.authenticationHeaderName = authenticationHeaderName;
}
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
setup(message);
return message;
}
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
cleanup();
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
setup(message);
return message;
}
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
cleanup();
}
private void setup(Message<?> message) {
Object user = message.getHeaders().get(authenticationHeaderName);
if(!(user instanceof Authentication)) {
return;
}
Authentication authentication = (Authentication) user;
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
}
private void cleanup() {
SecurityContextHolder.clearContext();
}
}
@@ -1,43 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.util.matcher;
import org.springframework.messaging.Message;
/**
* API for determining if a {@link Message} should be matched on.
*
* @since 4.0
* @author Rob Winch
*/
public interface MessageMatcher<T> {
/**
* Returns true if the {@link Message} matches, else false
* @param message the {@link Message} to match on
* @return true if the {@link Message} matches, else false
*/
boolean matches(Message<? extends T> message);
/**
* Matches every {@link Message}
*/
MessageMatcher ANY_MESSAGE = new MessageMatcher<Object>() {
public boolean matches(Message<? extends Object> message) {
return true;
}
};
}
@@ -1,86 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.util.matcher;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
/**
* <p>
* MessageMatcher which compares a pre-defined pattern against the destination of a {@link Message}.
* </p>
*
* @since 4.0
* @author Rob Winch
*/
public final class SimpDestinationMessageMatcher implements MessageMatcher<Object> {
private final PathMatcher matcher;
private final String pattern;
/**
* <p>
* Creates a new instance with the specified pattern and a {@link AntPathMatcher} created from the default
* constructor.
* </p>
*
* @param pattern the pattern to use
* @param pathMatcher the {@link PathMatcher} to use.
*/
public SimpDestinationMessageMatcher(String pattern, PathMatcher pathMatcher) {
Assert.notNull(pattern, "pattern cannot be null");
Assert.notNull(pathMatcher, "pathMatcher cannot be null");
this.matcher = pathMatcher;
this.pattern = pattern;
}
/**
* <p>
* Creates a new instance with the specified pattern and a {@link AntPathMatcher} created from the default
* constructor.
* </p>
*
* <p>The mapping matches destinations using the following rules:
*
* <ul>
* <li>? matches one character</li>
* <li>* matches zero or more characters</li>
* <li>** matches zero or more 'directories' in a path</li>
* </ul>
*
* <p>Some examples:
*
* <ul>
* <li>{@code com/t?st.jsp} - matches {@code com/test} but also
* {@code com/tast} or {@code com/txst}</li>
* <li>{@code com/*suffix} - matches all files ending in {@code suffix} in the {@code com} directory</li>
* <li>{@code com/&#42;&#42;/test} - matches all destinations ending with {@code test} underneath the {@code com} path</li>
* </ul>
*
* @param pattern the pattern to use
*/
public SimpDestinationMessageMatcher(String pattern) {
this(pattern, new AntPathMatcher());
}
@Override
public boolean matches(Message<? extends Object> message) {
String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
return destination != null && matcher.match(pattern, destination);
}
}
@@ -1,103 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.expression;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.springframework.security.messaging.access.expression.ExpressionBasedMessageSecurityMetadataSourceFactory.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.messaging.access.intercept.MessageSecurityMetadataSource;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import java.util.Collection;
import java.util.LinkedHashMap;
@RunWith(MockitoJUnitRunner.class)
public class ExpressionBasedMessageSecurityMetadataSourceFactoryTests {
@Mock
MessageMatcher matcher1;
@Mock
MessageMatcher matcher2;
@Mock
Message message;
@Mock
Authentication authentication;
String expression1;
String expression2;
LinkedHashMap<MessageMatcher<?>,String> matcherToExpression;
MessageSecurityMetadataSource source;
MessageSecurityExpressionRoot rootObject;
@Before
public void setup() {
expression1 = "permitAll";
expression2 = "denyAll";
matcherToExpression = new LinkedHashMap<MessageMatcher<?>, String>();
matcherToExpression.put(matcher1, expression1);
matcherToExpression.put(matcher2, expression2);
source = createExpressionMessageMetadataSource(matcherToExpression);
rootObject = new MessageSecurityExpressionRoot(authentication, message);
}
@Test
public void createExpressionMessageMetadataSourceNoMatch() {
Collection<ConfigAttribute> attrs = source.getAttributes(message);
assertThat(attrs).isNull();
}
@Test
public void createExpressionMessageMetadataSourceMatchFirst() {
when(matcher1.matches(message)).thenReturn(true);
Collection<ConfigAttribute> attrs = source.getAttributes(message);
assertThat(attrs.size()).isEqualTo(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute)attr).getAuthorizeExpression().getValue(rootObject)).isEqualTo(true);
}
@Test
public void createExpressionMessageMetadataSourceMatchSecond() {
when(matcher2.matches(message)).thenReturn(true);
Collection<ConfigAttribute> attrs = source.getAttributes(message);
assertThat(attrs.size()).isEqualTo(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute)attr).getAuthorizeExpression().getValue(rootObject)).isEqualTo(false);
}
}
@@ -1,62 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.expression;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.expression.Expression;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MessageExpressionConfigAttributeTests {
@Mock
Expression expression;
MessageExpressionConfigAttribute attribute;
@Before
public void setup() {
attribute = new MessageExpressionConfigAttribute(expression);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullExpression() {
new MessageExpressionConfigAttribute(null);
}
@Test
public void getAuthorizeExpression() {
assertThat(attribute.getAuthorizeExpression()).isSameAs(expression);
}
@Test
public void getAttribute() {
assertThat(attribute.getAttribute()).isNull();
}
@Test
public void toStringUsesExpressionString() {
when(expression.getExpressionString()).thenReturn("toString");
assertThat(attribute.toString()).isEqualTo(expression.getExpressionString());
}
}
@@ -1,114 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.expression;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.core.Authentication;
import java.util.Arrays;
import java.util.Collection;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.springframework.security.access.AccessDecisionVoter.*;
@RunWith(MockitoJUnitRunner.class)
public class MessageExpressionVoterTests {
@Mock
Authentication authentication;
@Mock
Message<Object> message;
Collection<ConfigAttribute> attributes;
@Mock
Expression expression;
@Mock
SecurityExpressionHandler<Message> expressionHandler;
@Mock
EvaluationContext evaluationContext;
MessageExpressionVoter voter;
@Before
public void setup() {
attributes = Arrays.<ConfigAttribute>asList(new MessageExpressionConfigAttribute(expression));
voter = new MessageExpressionVoter();
}
@Test
public void voteGranted() {
when(expression.getValue(any(EvaluationContext.class),eq(Boolean.class))).thenReturn(true);
assertThat(voter.vote(authentication, message, attributes)).isEqualTo(ACCESS_GRANTED);
}
@Test
public void voteDenied() {
when(expression.getValue(any(EvaluationContext.class),eq(Boolean.class))).thenReturn(false);
assertThat(voter.vote(authentication, message, attributes)).isEqualTo(ACCESS_DENIED);
}
@Test
public void voteAbstain() {
attributes = Arrays.<ConfigAttribute>asList(new SecurityConfig("ROLE_USER"));
assertThat(voter.vote(authentication, message, attributes)).isEqualTo(ACCESS_ABSTAIN);
}
@Test
public void supportsObjectClassFalse() {
assertThat(voter.supports(Object.class)).isFalse();
}
@Test
public void supportsMessageClassTrue() {
assertThat(voter.supports(Message.class)).isTrue();
}
@Test
public void supportsSecurityConfigFalse() {
assertThat(voter.supports(new SecurityConfig("ROLE_USER"))).isFalse();
}
@Test
public void supportsMessageExpressionConfigAttributeTrue() {
assertThat(voter.supports(new MessageExpressionConfigAttribute(expression))).isTrue();
}
@Test(expected = IllegalArgumentException.class)
public void setExpressionHandlerNull() {
voter.setExpressionHandler(null);
}
@Test
public void customExpressionHandler() {
voter.setExpressionHandler(expressionHandler);
when(expressionHandler.createEvaluationContext(authentication, message)).thenReturn(evaluationContext);
when(expression.getValue(evaluationContext, Boolean.class)).thenReturn(true);
assertThat(voter.vote(authentication, message, attributes)).isEqualTo(ACCESS_GRANTED);
verify(expressionHandler).createEvaluationContext(authentication, message);
}
}
@@ -1,158 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.intercept;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ChannelSecurityInterceptorTests {
@Mock
Message message;
@Mock
MessageChannel channel;
@Mock
MessageSecurityMetadataSource source;
@Mock
AccessDecisionManager accessDecisionManager;
List<ConfigAttribute> attrs;
ChannelSecurityInterceptor interceptor;
@Before
public void setup() {
attrs = Arrays.<ConfigAttribute>asList(new SecurityConfig("ROLE_USER"));
interceptor = new ChannelSecurityInterceptor(source);
interceptor.setAccessDecisionManager(accessDecisionManager);
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER"));
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test(expected = IllegalArgumentException.class)
public void constructorMessageSecurityMetadataSourceNull() {
new ChannelSecurityInterceptor(null);
}
@Test
public void getSecureObjectClass() throws Exception {
assertThat(interceptor.getSecureObjectClass()).isEqualTo(Message.class);
}
@Test
public void obtainSecurityMetadataSource() throws Exception {
assertThat(interceptor.obtainSecurityMetadataSource()).isEqualTo(source);
}
@Test
public void preSendNullAttributes() throws Exception {
assertThat(interceptor.preSend(message, channel)).isSameAs(message);
}
@Test
public void preSendGrant() throws Exception {
when(source.getAttributes(message)).thenReturn(attrs);
Message<?> result = interceptor.preSend(message, channel);
assertThat(result).isInstanceOf(ChannelSecurityInterceptor.TokenMessage.class);
ChannelSecurityInterceptor.TokenMessage tm = (ChannelSecurityInterceptor.TokenMessage) result;
assertThat(tm.getHeaders()).isSameAs(message.getHeaders());
assertThat(tm.getPayload()).isSameAs(message.getPayload());
assertThat(tm.getToken()).isNotNull();
}
@Test(expected = AccessDeniedException.class)
public void preSendDeny() throws Exception {
when(source.getAttributes(message)).thenReturn(attrs);
doThrow(new AccessDeniedException("")).when(accessDecisionManager).decide(any(Authentication.class), eq(message), eq(attrs));
interceptor.preSend(message, channel);
}
@Test
public void postSendNotTokenMessageNoExceptionThrown() throws Exception {
interceptor.postSend(message, channel, true);
}
@Test
public void postSendTokenMessage() throws Exception {
InterceptorStatusToken token = new InterceptorStatusToken(SecurityContextHolder.createEmptyContext(),true,attrs,message);
ChannelSecurityInterceptor.TokenMessage tokenMessage = new ChannelSecurityInterceptor.TokenMessage(message, token);
interceptor.postSend(tokenMessage, channel, true);
assertThat(SecurityContextHolder.getContext()).isSameAs(token.getSecurityContext());
}
@Test
public void afterSendCompletionNotTokenMessageNoExceptionThrown() throws Exception {
interceptor.afterSendCompletion(message, channel, true, null);
}
@Test
public void afterSendCompletionTokenMessage() throws Exception {
InterceptorStatusToken token = new InterceptorStatusToken(SecurityContextHolder.createEmptyContext(),true,attrs,message);
ChannelSecurityInterceptor.TokenMessage tokenMessage = new ChannelSecurityInterceptor.TokenMessage(message, token);
interceptor.afterSendCompletion(tokenMessage, channel, true, null);
assertThat(SecurityContextHolder.getContext()).isSameAs(token.getSecurityContext());
}
@Test
public void preReceive() throws Exception {
assertThat(interceptor.preReceive(channel)).isTrue();;
}
@Test
public void postReceive() throws Exception {
assertThat(interceptor.postReceive(message, channel)).isSameAs(message);
}
@Test
public void afterReceiveCompletionNullExceptionNoExceptionThrown() throws Exception {
interceptor.afterReceiveCompletion(message, channel, null);
}
}
@@ -1,97 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.access.intercept;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import static org.fest.assertions.Assertions.assertThat;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DefaultMessageSecurityMetadataSourceTests {
@Mock
MessageMatcher matcher1;
@Mock
MessageMatcher matcher2;
@Mock
Message message;
@Mock
Authentication authentication;
SecurityConfig config1;
SecurityConfig config2;
LinkedHashMap<MessageMatcher<?>,Collection<ConfigAttribute>> messageMap;
MessageSecurityMetadataSource source;
@Before
public void setup() {
messageMap = new LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>>();
messageMap.put(matcher1, Arrays.<ConfigAttribute>asList(config1));
messageMap.put(matcher2, Arrays.<ConfigAttribute>asList(config2));
source = new DefaultMessageSecurityMetadataSource(messageMap);
}
@Test
public void getAttributesNull() {
assertThat(source.getAttributes(message)).isNull();
}
@Test
public void getAttributesFirst() {
when(matcher1.matches(message)).thenReturn(true);
assertThat(source.getAttributes(message)).containsOnly(config1);
}
@Test
public void getAttributesSecond() {
when(matcher1.matches(message)).thenReturn(true);
assertThat(source.getAttributes(message)).containsOnly(config2);
}
@Test
public void getAllConfigAttributes() {
assertThat(source.getAllConfigAttributes()).containsOnly(config1,config2);
}
@Test
public void supportsFalse() {
assertThat(source.supports(Object.class)).isFalse();
}
@Test
public void supportsTrue() {
assertThat(source.supports(Message.class)).isTrue();
}
}
@@ -1,149 +0,0 @@
package org.springframework.security.messaging.context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.messaging.context.SecurityContextChannelInterceptor;
import java.security.Principal;
import static org.fest.assertions.Assertions.assertThat;
import static org.springframework.security.core.context.SecurityContextHolder.*;
@RunWith(MockitoJUnitRunner.class)
public class SecurityContextChannelInterceptorTests {
@Mock
MessageChannel channel;
@Mock
MessageHandler handler;
@Mock
Principal principal;
MessageBuilder messageBuilder;
Authentication authentication;
SecurityContextChannelInterceptor interceptor;
@Before
public void setup() {
authentication = new TestingAuthenticationToken("user","pass", "ROLE_USER");
messageBuilder = MessageBuilder.withPayload("payload");
interceptor = new SecurityContextChannelInterceptor();
}
@After
public void cleanup() {
clearContext();
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullHeader() {
new SecurityContextChannelInterceptor(null);
}
@Test
public void preSendCustomHeader() throws Exception {
String headerName = "header";
interceptor = new SecurityContextChannelInterceptor(headerName);
messageBuilder.setHeader(headerName, authentication);
interceptor.preSend(messageBuilder.build(), channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(authentication);
}
@Test
public void preSendUserSet() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, authentication);
interceptor.preSend(messageBuilder.build(), channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(authentication);
}
@Test
public void preSendUserNotAuthentication() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, principal);
interceptor.preSend(messageBuilder.build(), channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void preSendUserNotSet() throws Exception {
interceptor.preSend(messageBuilder.build(), channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterSendCompletion() throws Exception {
SecurityContextHolder.getContext().setAuthentication(authentication);
interceptor.afterSendCompletion(messageBuilder.build(), channel, true, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterSendCompletionNullAuthentication() throws Exception {
interceptor.afterSendCompletion(messageBuilder.build(), channel, true, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void beforeHandleUserSet() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, authentication);
interceptor.beforeHandle(messageBuilder.build(), channel, handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(authentication);
}
@Test
public void beforeHandleUserNotAuthentication() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, principal);
interceptor.beforeHandle(messageBuilder.build(), channel, handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void beforeHandleUserNotSet() throws Exception {
interceptor.beforeHandle(messageBuilder.build(), channel, handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterMessageHandledUserNotSet() throws Exception {
interceptor.afterMessageHandled(messageBuilder.build(), channel, handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterMessageHandled() throws Exception {
SecurityContextHolder.getContext().setAuthentication(authentication);
interceptor.afterMessageHandled(messageBuilder.build(), channel, handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
}
@@ -1,71 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.messaging.util.matcher;
import org.junit.Before;
import org.junit.Test;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import static org.fest.assertions.Assertions.assertThat;
public class SimpDestinationMessageMatcherTests {
MessageBuilder<String> messageBuilder;
SimpDestinationMessageMatcher matcher;
@Before
public void setup() {
messageBuilder = MessageBuilder.withPayload("M");
matcher = new SimpDestinationMessageMatcher("/**");
}
@Test(expected = IllegalArgumentException.class)
public void constructorPatternNull() {
new SimpDestinationMessageMatcher(null);
}
@Test
public void matchesDoesNotMatchNullDestination() throws Exception {
assertThat(matcher.matches(messageBuilder.build())).isFalse();
}
@Test
public void matchesAllWithDestination() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER,"/destination/1");
assertThat(matcher.matches(messageBuilder.build())).isTrue();
}
@Test
public void matchesSpecificWithDestination() throws Exception {
matcher = new SimpDestinationMessageMatcher("/destination/1");
messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER,"/destination/1");
assertThat(matcher.matches(messageBuilder.build())).isTrue();
}
@Test
public void matchesFalseWithDestination() throws Exception {
matcher = new SimpDestinationMessageMatcher("/nomatch");
messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER,"/destination/1");
assertThat(matcher.matches(messageBuilder.build())).isFalse();
}
}
+9 -15
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-openid</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<name>spring-security-openid</name>
<description>spring-security-openid</description>
<url>http://spring.io/spring-security</url>
@@ -42,12 +42,6 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.google.inject</groupId>
@@ -70,37 +64,37 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.0.M2</version>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@@ -112,7 +106,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -173,7 +167,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.0.RC2</version>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
+4 -3
View File
@@ -1,7 +1,7 @@
Implementation-Title: org.springframework.security.test
Implementation-Title: org.springframework.security.openid
Implementation-Version: ${version}
Bundle-SymbolicName: org.springframework.security.test
Bundle-Name: Spring Security Test
Bundle-SymbolicName: org.springframework.security.openid
Bundle-Name: Spring Security OpenID
Bundle-Vendor: SpringSource
Bundle-Version: ${version}
Bundle-ManifestVersion: 2
@@ -15,4 +15,5 @@ Import-Template:
org.springframework.security.web.*;version="${secRange}",
org.springframework.beans.factory;version="${springRange}",
org.springframework.util;version="${springRange}",
org.openid4java.*;version="${openid4javaRange}",
javax.servlet.*;version="0"

Some files were not shown because too many files have changed in this diff Show More