1
0
mirror of synced 2026-09-06 01:09:48 +00:00

Compare commits

..

15 Commits

Author SHA1 Message Date
Spring Buildmaster 325b814d49 Release version 4.1.3.RELEASE 2016-08-23 01:05:48 +00:00
Rob Winch 8f1c977c0d Update Dependency Versions (#4035) 2016-08-19 16:09:10 -05:00
Joe Grandja e0d9487e6b Remove unused MvcReqestMatcher.getMvcPattern (#4034) 2016-08-19 14:38:19 -05:00
Rob Winch 9dc3242db3 Remove MvcRequestMatcher.afterPropertiesSet()
The validation does not work due to restrictions within the servlet
container. Specifically we cannot access the servlets that are registered.

This commit reverts the validation logic for MvcRequestMatcher to determine
if servletPath is required.

Fixes gh-4027
2016-08-19 11:12:38 -05:00
Spring Buildmaster a070046f26 Next development version 2016-08-11 19:14:39 +00:00
Spring Buildmaster e412fb7ac0 Release version 4.1.2.RELEASE 2016-08-11 19:14:32 +00:00
Rob Winch 28278eab89 Fix defaultMethodExpressionHandler autowiring
Previously if a Bean for GlobalMethodSecurityConfiguration's
defaultMethodExpressionHandler was found on a Configuration that also
@Autowired a Bean that enabled method security, the Bean that was
@Autowired would not have security enabled.

This fixes the issue by delaying the lookup of Beans populated on
GlobalMethodSecurityConfiguration's defaultMethodExpressionHandler.

Fixes gh-4020
2016-08-10 23:48:49 -05:00
Rob Winch a93fb1e0e7 Fix csrf() when used then not used
Previously if csrf() was used and subsequently not used, the
TestCsrfTokenRepository was still used. This makes it difficult to test
the actual CsrfTokenRepository implementation.

Now the TestCsrfTokenRepository is only used if explicitly enabled.

Fixes gh-4016
2016-08-09 17:28:33 -04:00
Joe Grandja dabcc5416a MvcRequestMatcher servletPath Polish / XML Config
Fixes gh-4014
2016-08-09 15:47:41 -05:00
Rob Winch 8a6d0cd16d MvcRequestMatcher servletPath / JavaConfig
Issue: gh-3987
2016-08-09 15:47:01 -05:00
Rob Winch edb7ef567a Logout is 204 for XMLHttpRequest
Fixes gh-3997
2016-08-02 14:14:44 -07:00
Rob Winch d002681bec Add ObjectPostProcessor support for SmartInitializingSingleton 2016-07-21 10:46:55 -05:00
Rob Winch 6649d46896 DummyRequest supports methods for MvcRequestMatcher
To support MvcRequestMatcher DummyRequest needs to support
getCharacterEncoding() and getAttribute(String)
2016-07-14 16:02:08 -04:00
Rob Winch 1d97ee8dd6 Add HttpSecurity.mvcMatcher
Fixes gh-3970
2016-07-14 11:46:29 -04:00
Rob Winch 7d1344fca8 Fix NPE requestMatchers().mvcMatchers
Fixes gh-3969
2016-07-14 11:45:45 -04:00
181 changed files with 791 additions and 10007 deletions
+5 -1
View File
@@ -6,6 +6,10 @@ jdk:
os:
- linux
branches:
only:
- master
before_cache:
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
cache:
@@ -13,4 +17,4 @@ cache:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
script: ./gradlew build
script: ./gradlew build
+2 -11
View File
@@ -29,7 +29,7 @@ Not sure what a pull request is, or how to submit one? Take a look at GitHub's e
Is there already an issue that addresses your concern? Do a bit of searching in our [GitHub issues ](https://github.com/spring-projects/spring-security/issues) to see if you can find something similar. If not, please create a new issue before submitting a pull request unless the change is not a user facing issue.
# Discuss non-trivial contribution ideas with committers
If you're considering anything more than correcting a typo or fixing a minor bug, please discuss it on the [Spring Security Gitter](https://gitter.im/spring-projects/spring-security) before submitting a pull request. We're happy to provide guidance but please spend an hour or two researching the subject on your own including searching the forums for prior discussions.
If you're considering anything more than correcting a typo or fixing a minor bug , please discuss it on the [Spring Security Gitter](https://gitter.im/spring-projects/spring-security) before submitting a pull request. We're happy to provide guidance but please spend an hour or two researching the subject on your own including searching the forums for prior discussions.
# Sign the Contributor License Agreement
@@ -104,21 +104,12 @@ e.g.
*/
</pre>
# Submit JUnit test cases for all behavior changes
#Submit JUnit test cases for all behavior changes
Search the codebase to find related unit tests and add additional `@Test` methods within.
1. Any new tests should end in the name Tests (note this is plural). For example, a valid name would be `FilterChainProxyTests`. An invalid name would be `FilterChainProxyTest`.
2. New test methods should not start with test. This is an old JUnit3 convention and is not necessary since the method is annotated with @Test.
# Update spring-security-x.y.rnc for schema changes
Update the [RELAX NG](http://www.relaxng.org) schema `spring-security-x.y.rnc` instead of `spring-security-x.y.xsd` if you contribute changes to supported XML configuration. The XML schema file can be generated the following Gradle task:
<pre>
./gradlew spring-security-config:rncToXsd
</pre>
Changes to the XML schema will be overwritten by the Gradle build task.
# Squash commits
Use git rebase --interactive, git add --patch and other tools to "squash" multiple commits into atomic changes. In addition to the man pages for git, there are many resources online to help you understand how these tools work. Here is one: http://book.git-scm.com/4_interactive_rebasing.html.
+2 -8
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-acl</name>
<description>spring-security-acl</description>
<url>http://spring.io/spring-security</url>
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -151,12 +151,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
+2 -8
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-aspects</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-aspects</name>
<description>spring-security-aspects</description>
<url>http://spring.io/spring-security</url>
@@ -45,7 +45,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -130,12 +130,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
+4 -4
View File
@@ -4,17 +4,17 @@ buildscript {
}
dependencies {
classpath("org.springframework.build.gradle:propdeps-plugin:0.0.7")
classpath("io.spring.gradle:spring-io-plugin:0.0.5.RELEASE")
classpath("io.spring.gradle:spring-io-plugin:0.0.4.RELEASE")
classpath("com.bmuschko:gradle-tomcat-plugin:2.2.4")
classpath('me.champeau.gradle:gradle-javadoc-hotfix-plugin:0.1')
classpath('org.asciidoctor:asciidoctor-gradle-plugin:1.5.1')
classpath("io.spring.gradle:docbook-reference-plugin:0.3.1")
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE")
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")
}
}
plugins {
id "org.sonarqube" version "2.1-rc1"
id "org.sonarqube" version "1.2"
}
apply plugin: 'base'
@@ -106,7 +106,7 @@ configure(coreModuleProjects) {
apply plugin: 'emma'
apply plugin: 'spring-io'
ext.springIoVersion = project.hasProperty('platformVersion') ? platformVersion : 'Athens-BUILD-SNAPSHOT'
ext.springIoVersion = project.hasProperty('platformVersion') ? platformVersion : '2.0.1.RELEASE'
configurations {
jacoco //Configuration Group used by Sonar to provide Code Coverage using JaCoCo
+1 -4
View File
@@ -8,10 +8,7 @@ dependencies {
"org.springframework:spring-web:$springVersion",
"org.jasig.cas.client:cas-client-core:$casClientVersion"
optional "net.sf.ehcache:ehcache:$ehcacheVersion",
"com.fasterxml.jackson.core:jackson-databind:$jacksonDatavindVersion"
testCompile "org.skyscreamer:jsonassert:$jsonassertVersion"
optional "net.sf.ehcache:ehcache:$ehcacheVersion"
provided "javax.servlet:javax.servlet-api:$servletApiVersion"
}
+3 -22
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-cas</name>
<description>spring-security-cas</description>
<url>http://spring.io/spring-security</url>
@@ -51,13 +51,13 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -86,13 +86,6 @@
<artifactId>spring-web</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.4</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
@@ -137,12 +130,6 @@
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
@@ -155,12 +142,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
@@ -24,7 +24,6 @@ import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;
/**
* Represents a successful CAS <code>Authentication</code>.
@@ -51,54 +50,29 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
/**
* Constructor.
*
* @param key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param credentials the service/proxy ticket ID from CAS (cannot be
* <code>null</code>)
* <code>null</code>)
* @param authorities the authorities granted to the user (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param userDetails the user details (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
*
* @throws IllegalArgumentException if a <code>null</code> was passed
*/
public CasAuthenticationToken(final String key, final Object principal,
final Object credentials,
final Collection<? extends GrantedAuthority> authorities,
final UserDetails userDetails, final Assertion assertion) {
this(extractKeyHash(key), principal, credentials, authorities, userDetails, assertion);
}
/**
* Private constructor for Jackson Deserialization support
*
* @param keyHash hashCode of provided key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param credentials the service/proxy ticket ID from CAS (cannot be
* <code>null</code>)
* @param authorities the authorities granted to the user (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param userDetails the user details (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
* @throws IllegalArgumentException if a <code>null</code> was passed
* @since 4.2
*/
private CasAuthenticationToken(final Integer keyHash, final Object principal,
final Object credentials,
final Collection<? extends GrantedAuthority> authorities,
final UserDetails userDetails, final Assertion assertion) {
final Object credentials,
final Collection<? extends GrantedAuthority> authorities,
final UserDetails userDetails, final Assertion assertion) {
super(authorities);
if ((principal == null)
if ((key == null) || ("".equals(key)) || (principal == null)
|| "".equals(principal) || (credentials == null)
|| "".equals(credentials) || (authorities == null)
|| (userDetails == null) || (assertion == null)) {
@@ -106,7 +80,7 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
"Cannot pass null or empty values to constructor");
}
this.keyHash = keyHash;
this.keyHash = key.hashCode();
this.principal = principal;
this.credentials = credentials;
this.userDetails = userDetails;
@@ -117,11 +91,6 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
// ~ Methods
// ========================================================================================================
private static Integer extractKeyHash(String key) {
Assert.hasLength(key, "key cannot be null or empty");
return key.hashCode();
}
public boolean equals(final Object obj) {
if (!super.equals(obj)) {
return false;
@@ -1,62 +0,0 @@
/*
* Copyright 2015-2016 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.cas.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.jasig.cas.client.authentication.AttributePrincipal;
import java.util.Date;
import java.util.Map;
/**
* Helps in jackson deserialization of class {@link org.jasig.cas.client.validation.AssertionImpl}, which is
* used with {@link org.springframework.security.cas.authentication.CasAuthenticationToken}.
* To use this class we need to register with {@link com.fasterxml.jackson.databind.ObjectMapper}. Type information
* will be stored in @class property.
* <p>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
*
*
* @author Jitendra Singh
* @see CasJackson2Module
* @see org.springframework.security.jackson2.SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
class AssertionImplMixin {
/**
* Mixin Constructor helps in deserialize {@link org.jasig.cas.client.validation.AssertionImpl}
*
* @param principal the Principal to associate with the Assertion.
* @param validFromDate when the assertion is valid from.
* @param validUntilDate when the assertion is valid to.
* @param authenticationDate when the assertion is authenticated.
* @param attributes the key/value pairs for this attribute.
*/
@JsonCreator
public AssertionImplMixin(@JsonProperty("principal") AttributePrincipal principal,
@JsonProperty("validFromDate") Date validFromDate, @JsonProperty("validUntilDate") Date validUntilDate,
@JsonProperty("authenticationDate") Date authenticationDate, @JsonProperty("attributes") Map<String, Object> attributes){
}
}
@@ -1,58 +0,0 @@
/*
* Copyright 2015-2016 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.cas.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.jasig.cas.client.proxy.ProxyRetriever;
import java.util.Map;
/**
* Helps in deserialize {@link org.jasig.cas.client.authentication.AttributePrincipalImpl} which is used with
* {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. Type information will be stored
* in property named @class.
* <p>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @see CasJackson2Module
* @see org.springframework.security.jackson2.SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
class AttributePrincipalImplMixin {
/**
* Mixin Constructor helps in deserialize {@link org.jasig.cas.client.authentication.AttributePrincipalImpl}
*
* @param name the unique identifier for the principal.
* @param attributes the key/value pairs for this principal.
* @param proxyGrantingTicket the ticket associated with this principal.
* @param proxyRetriever the ProxyRetriever implementation to call back to the CAS server.
*/
@JsonCreator
public AttributePrincipalImplMixin(@JsonProperty("name") String name, @JsonProperty("attributes") Map<String, Object> attributes,
@JsonProperty("proxyGrantingTicket") String proxyGrantingTicket,
@JsonProperty("proxyRetriever") ProxyRetriever proxyRetriever) {
}
}
@@ -1,77 +0,0 @@
/*
* Copyright 2015-2016 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.cas.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
/**
* Mixin class which helps in deserialize {@link org.springframework.security.cas.authentication.CasAuthenticationToken}
* using jackson. Two more dependent classes needs to register along with this mixin class.
* <ol>
* <li>{@link org.springframework.security.cas.jackson2.AssertionImplMixin}</li>
* <li>{@link org.springframework.security.cas.jackson2.AttributePrincipalImplMixin}</li>
* </ol>
*
* <p>
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @see CasJackson2Module
* @see org.springframework.security.jackson2.SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, isGetterVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.ANY)
@JsonIgnoreProperties(ignoreUnknown = true)
class CasAuthenticationTokenMixin {
/**
* Mixin Constructor helps in deserialize {@link CasAuthenticationToken}
*
* @param keyHash hashCode of provided key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param credentials the service/proxy ticket ID from CAS (cannot be
* <code>null</code>)
* @param authorities the authorities granted to the user (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param userDetails the user details (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
*/
@JsonCreator
public CasAuthenticationTokenMixin(@JsonProperty("keyHash") Integer keyHash, @JsonProperty("principal") Object principal,
@JsonProperty("credentials") Object credentials,
@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities,
@JsonProperty("userDetails") UserDetails userDetails, @JsonProperty("assertion") Assertion assertion) {
}
}
@@ -1,56 +0,0 @@
/*
* Copyright 2015-2016 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.cas.jackson2;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.validation.AssertionImpl;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.jackson2.SecurityJacksonModules;
/**
* Jackson module for spring-security-cas. This module register {@link AssertionImplMixin},
* {@link AttributePrincipalImplMixin} and {@link CasAuthenticationTokenMixin}. If no default typing enabled by default then
* it'll enable it because typing info is needed to properly serialize/deserialize objects. In order to use this module just
* add this module into your ObjectMapper configuration.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
* <b>Note: use {@link SecurityJacksonModules#getModules(ClassLoader)} to get list of all security modules on the classpath.</b>
*
* @author Jitendra Singh.
* @see org.springframework.security.jackson2.SecurityJacksonModules
* @since 4.2
*/
public class CasJackson2Module extends SimpleModule {
public CasJackson2Module() {
super(CasJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null));
}
@Override
public void setupModule(SetupContext context) {
SecurityJacksonModules.enableDefaultTyping((ObjectMapper) context.getOwner());
context.setMixInAnnotations(AssertionImpl.class, AssertionImplMixin.class);
context.setMixInAnnotations(AttributePrincipalImpl.class, AttributePrincipalImplMixin.class);
context.setMixInAnnotations(CasAuthenticationToken.class, CasAuthenticationTokenMixin.class);
}
}
@@ -19,7 +19,6 @@ package org.springframework.security.cas.authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.Collections;
import java.util.List;
import org.jasig.cas.client.validation.Assertion;
@@ -103,12 +102,6 @@ public class CasAuthenticationTokenTests {
}
}
@Test(expected = IllegalArgumentException.class)
public void constructorWhenEmptyKeyThenThrowsException() {
new CasAuthenticationToken("", "user", "password", Collections.<GrantedAuthority>emptyList(),
new User("user", "password", Collections.<GrantedAuthority>emptyList()), null);
}
@Test
public void testEqualsWhenEqual() {
final Assertion assertion = new AssertionImpl("test");
@@ -1,155 +0,0 @@
/*
* Copyright 2015-2016 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.cas.jackson2;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.jackson2.SecurityJacksonModules;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
public class CasAuthenticationTokenMixinTests {
private static final String KEY = "casKey";
private static final String PASSWORD = "\"1234\"";
private static final Date START_DATE = new Date();
private static final Date END_DATE = new Date();
public static final String AUTHORITY_JSON = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"authority\": \"ROLE_USER\"}";
public static final String AUTHORITIES_SET_JSON = "[\"java.util.Collections$UnmodifiableSet\", [" + AUTHORITY_JSON + "]]";
public static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.ArrayList\", [" + AUTHORITY_JSON + "]]";
// @formatter:off
public static final String USER_JSON = "{"
+ "\"@class\": \"org.springframework.security.core.userdetails.User\", "
+ "\"username\": \"admin\","
+ " \"password\": " + PASSWORD + ", "
+ "\"accountNonExpired\": true, "
+ "\"accountNonLocked\": true, "
+ "\"credentialsNonExpired\": true, "
+ "\"enabled\": true, "
+ "\"authorities\": " + AUTHORITIES_SET_JSON
+ "}";
// @formatter:on
private static final String CAS_TOKEN_JSON = "{"
+ "\"@class\": \"org.springframework.security.cas.authentication.CasAuthenticationToken\", "
+ "\"keyHash\": " + KEY.hashCode() + ","
+ "\"principal\": " + USER_JSON + ", "
+ "\"credentials\": " + PASSWORD + ", "
+ "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + ","
+ "\"userDetails\": " + USER_JSON +","
+ "\"authenticated\": true, "
+ "\"details\": null,"
+ "\"assertion\": {"
+ "\"@class\": \"org.jasig.cas.client.validation.AssertionImpl\", "
+ "\"principal\": {"
+ "\"@class\": \"org.jasig.cas.client.authentication.AttributePrincipalImpl\", "
+ "\"name\": \"assertName\", "
+ "\"attributes\": {\"@class\": \"java.util.Collections$EmptyMap\"}, "
+ "\"proxyGrantingTicket\": null, "
+ "\"proxyRetriever\": null"
+ "}, "
+ "\"validFromDate\": [\"java.util.Date\", " + START_DATE.getTime() + "], "
+ "\"validUntilDate\": [\"java.util.Date\", " + END_DATE.getTime() + "],"
+ "\"authenticationDate\": [\"java.util.Date\", " + START_DATE.getTime() + "], "
+ "\"attributes\": {\"@class\": \"java.util.Collections$EmptyMap\"}" +
"}"
+ "}";
private static final String CAS_TOKEN_CLEARED_JSON = CAS_TOKEN_JSON.replaceFirst(PASSWORD, "null");
protected ObjectMapper mapper;
@Before
public void setup() {
mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(SecurityJacksonModules.getModules(loader));
}
@Test
public void serializeCasAuthenticationTest() throws JsonProcessingException, JSONException {
CasAuthenticationToken token = createCasAuthenticationToken();
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(CAS_TOKEN_JSON, actualJson, true);
}
@Test
public void serializeCasAuthenticationTestAfterEraseCredentialInvoked() throws JsonProcessingException, JSONException {
CasAuthenticationToken token = createCasAuthenticationToken();
token.eraseCredentials();
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(CAS_TOKEN_CLEARED_JSON, actualJson, true);
}
@Test
public void deserializeCasAuthenticationTestAfterEraseCredentialInvoked() throws Exception {
CasAuthenticationToken token = mapper.readValue(CAS_TOKEN_CLEARED_JSON, CasAuthenticationToken.class);
assertThat(((UserDetails)token.getPrincipal()).getPassword()).isNull();
}
@Test
public void deserializeCasAuthenticationTest() throws IOException, JSONException {
CasAuthenticationToken token = mapper.readValue(CAS_TOKEN_JSON, CasAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin");
assertThat(((User) token.getPrincipal()).getPassword()).isEqualTo("1234");
assertThat(token.getUserDetails()).isNotNull().isInstanceOf(User.class);
assertThat(token.getAssertion()).isNotNull().isInstanceOf(AssertionImpl.class);
assertThat(token.getKeyHash()).isEqualTo(KEY.hashCode());
assertThat(token.getUserDetails().getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
assertThat(token.getAssertion().getAuthenticationDate()).isEqualTo(START_DATE);
assertThat(token.getAssertion().getValidFromDate()).isEqualTo(START_DATE);
assertThat(token.getAssertion().getValidUntilDate()).isEqualTo(END_DATE);
assertThat(token.getAssertion().getPrincipal().getName()).isEqualTo("assertName");
assertThat(token.getAssertion().getAttributes()).hasSize(0);
}
private CasAuthenticationToken createCasAuthenticationToken() {
User principal = new User("admin", "1234", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
Collection<? extends GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
Assertion assertion = new AssertionImpl(new AttributePrincipalImpl("assertName"), START_DATE, END_DATE, START_DATE, Collections.<String, Object>emptyMap());
return new CasAuthenticationToken(KEY, principal, principal.getPassword(), authorities,
new User("admin", "1234", authorities), assertion);
}
}
+8 -14
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-config</name>
<description>spring-security-config</description>
<url>http://spring.io/spring-security</url>
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -97,28 +97,28 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-openid</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@@ -365,13 +365,13 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-aspects</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -390,12 +390,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
@@ -15,12 +15,11 @@
*/
package org.springframework.security.config.ldap;
import java.util.Set;
import org.junit.After;
import org.junit.Test;
import org.w3c.dom.Element;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.*;
import org.junit.*;
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
@@ -33,19 +32,13 @@ import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import org.springframework.security.ldap.userdetails.LdapUserDetailsService;
import org.springframework.security.ldap.userdetails.Person;
import org.springframework.security.ldap.userdetails.PersonContextMapper;
import org.w3c.dom.Element;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.INET_ORG_PERSON_MAPPER_CLASS;
import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.LDAP_AUTHORITIES_POPULATOR_CLASS;
import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.LDAP_SEARCH_CLASS;
import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.LDAP_USER_MAPPER_CLASS;
import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.PERSON_MAPPER_CLASS;
import java.util.*;
/**
* @author Luke Taylor
* @author Rob Winch
* @author Eddú Meléndez
*/
public class LdapUserServiceBeanDefinitionParserTests {
private InMemoryXmlApplicationContext appCtx;
@@ -109,11 +102,13 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben");
assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities())).contains("PREFIX_DEVELOPERS");
assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains(
"PREFIX_DEVELOPERS"));
uds = (UserDetailsService) appCtx.getBean("ldapUDSNoPrefix");
ben = uds.loadUserByUsername("ben");
assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities())).contains("DEVELOPERS");
assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains(
"DEVELOPERS"));
}
@Test
@@ -15,9 +15,6 @@
*/
package org.springframework.security.config.annotation.authentication.configurers.ldap;
import java.io.IOException;
import java.net.ServerSocket;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
@@ -27,7 +24,6 @@ import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.authentication.ProviderManagerBuilder;
import org.springframework.security.config.annotation.web.configurers.ChannelSecurityConfigurer;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
@@ -47,6 +43,9 @@ 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}.
*
@@ -129,7 +128,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
contextSource, groupSearchBase);
defaultAuthoritiesPopulator.setGroupRoleAttribute(groupRoleAttribute);
defaultAuthoritiesPopulator.setGroupSearchFilter(groupSearchFilter);
defaultAuthoritiesPopulator.setRolePrefix(this.rolePrefix);
defaultAuthoritiesPopulator.setRolePrefix(rolePrefix);
this.ldapAuthoritiesPopulator = defaultAuthoritiesPopulator;
return defaultAuthoritiesPopulator;
@@ -162,7 +161,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
}
SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper();
simpleAuthorityMapper.setPrefix(this.rolePrefix);
simpleAuthorityMapper.setPrefix(rolePrefix);
simpleAuthorityMapper.afterPropertiesSet();
this.authoritiesMapper = simpleAuthorityMapper;
return simpleAuthorityMapper;
@@ -616,4 +615,4 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
return new PasswordCompareConfigurer().passwordAttribute("password")
.passwordEncoder(new PlaintextPasswordEncoder());
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2015 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.
@@ -49,7 +49,6 @@ import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.intercept.AfterInvocationManager;
import org.springframework.security.access.intercept.AfterInvocationProviderManager;
import org.springframework.security.access.intercept.RunAsManager;
import org.springframework.security.access.intercept.RunAsManagerImpl;
import org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor;
import org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor;
import org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource;
@@ -67,7 +66,6 @@ import org.springframework.security.authentication.DefaultAuthenticationEventPub
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.util.Assert;
/**
@@ -76,7 +74,6 @@ import org.springframework.util.Assert;
* {@link EnableGlobalMethodSecurity} annotation on the subclass.
*
* @author Rob Winch
* @author Eddú Meléndez
* @since 3.2
* @see EnableGlobalMethodSecurity
*/
@@ -171,13 +168,6 @@ public class GlobalMethodSecurityConfiguration
if (trustResolver != null) {
this.defaultMethodExpressionHandler.setTrustResolver(trustResolver);
}
GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull(
GrantedAuthorityDefaults.class);
if (grantedAuthorityDefaults != null) {
this.defaultMethodExpressionHandler.setDefaultRolePrefix(
grantedAuthorityDefaults.getRolePrefix());
}
}
private <T> T getSingleBeanOrNull(Class<T> type) {
@@ -365,12 +355,6 @@ public class GlobalMethodSecurityConfiguration
sources.add(new SecuredAnnotationSecurityMetadataSource());
}
if (jsr250Enabled()) {
GrantedAuthorityDefaults grantedAuthorityDefaults =
getSingleBeanOrNull(GrantedAuthorityDefaults.class);
if (grantedAuthorityDefaults != null) {
this.jsr250MethodSecurityMetadataSource.setDefaultRolePrefix(
grantedAuthorityDefaults.getRolePrefix());
}
sources.add(jsr250MethodSecurityMetadataSource);
}
return new DelegatingMethodSecurityMetadataSource(sources);
@@ -416,7 +400,7 @@ public class GlobalMethodSecurityConfiguration
public void setMethodSecurityExpressionHandler(
List<MethodSecurityExpressionHandler> handlers) {
if (handlers.size() != 1) {
logger.debug("Not autowiring MethodSecurityExpressionHandler since size != 1. Got "
logger.debug("Not autwiring PermissionEvaluator since size != 1. Got "
+ handlers);
return;
}
@@ -465,4 +449,4 @@ public class GlobalMethodSecurityConfiguration
}
return this.enableMethodSecurity;
}
}
}
@@ -113,7 +113,7 @@ public final class WebSecurity extends
/**
* <p>
* Allows adding {@link RequestMatcher} instances that Spring Security
* Allows adding {@link RequestMatcher} instances that should that Spring Security
* should ignore. Web Security provided by Spring Security (including the
* {@link SecurityContext}) will not be available on {@link HttpServletRequest} that
* match. Typically the requests that are registered should be that of only static
@@ -31,7 +31,6 @@ import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource;
@@ -217,11 +216,6 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
if(roleHiearchyBeanNames.length == 1) {
defaultHandler.setRoleHierarchy(context.getBean(roleHiearchyBeanNames[0], RoleHierarchy.class));
}
String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = context.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
defaultHandler.setDefaultRolePrefix(grantedAuthorityDefaults.getRolePrefix());
}
}
expressionHandler = postProcess(defaultHandler);
@@ -19,12 +19,10 @@ import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
@@ -93,15 +91,7 @@ public final class ServletApiConfigurer<H extends HttpSecurityBuilder<H>> extend
if (trustResolver != null) {
securityContextRequestFilter.setTrustResolver(trustResolver);
}
ApplicationContext context = http.getSharedObject(ApplicationContext.class);
if(context != null) {
String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = context.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
securityContextRequestFilter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix());
}
}
securityContextRequestFilter = postProcess(securityContextRequestFilter);
http.addFilter(securityContextRequestFilter);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* 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.
@@ -33,7 +33,6 @@ import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.context.DelegatingApplicationListener;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy;
import org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy;
@@ -49,10 +48,8 @@ import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.session.ConcurrentSessionFilter;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.security.web.session.SessionManagementFilter;
import org.springframework.security.web.session.SimpleRedirectInvalidSessionStrategy;
import org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy;
import org.springframework.util.Assert;
/**
@@ -92,14 +89,13 @@ import org.springframework.util.Assert;
* @see SessionManagementFilter
* @see ConcurrentSessionFilter
*/
public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
extends AbstractHttpConfigurer<SessionManagementConfigurer<H>, H> {
public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>> extends
AbstractHttpConfigurer<SessionManagementConfigurer<H>, H> {
private final SessionAuthenticationStrategy DEFAULT_SESSION_FIXATION_STRATEGY = createDefaultSessionFixationProtectionStrategy();
private SessionAuthenticationStrategy sessionFixationAuthenticationStrategy = this.DEFAULT_SESSION_FIXATION_STRATEGY;
private SessionAuthenticationStrategy sessionFixationAuthenticationStrategy = DEFAULT_SESSION_FIXATION_STRATEGY;
private SessionAuthenticationStrategy sessionAuthenticationStrategy;
private SessionAuthenticationStrategy providedSessionAuthenticationStrategy;
private InvalidSessionStrategy invalidSessionStrategy;
private SessionInformationExpiredStrategy expiredSessionStrategy;
private List<SessionAuthenticationStrategy> sessionAuthenticationStrategies = new ArrayList<SessionAuthenticationStrategy>();
private SessionRegistry sessionRegistry;
private Integer maximumSessions;
@@ -109,7 +105,6 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
private boolean enableSessionUrlRewriting;
private String invalidSessionUrl;
private String sessionAuthenticationErrorUrl;
private AuthenticationFailureHandler sessionAuthenticationFailureHandler;
/**
* Creates a new instance
@@ -136,12 +131,10 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* Setting this attribute will inject the provided invalidSessionStrategy into the
* {@link SessionManagementFilter}. When an invalid session ID is submitted, the
* strategy will be invoked, redirecting to the configured URL.
* @param invalidSessionStrategy the strategy to use when an invalid session ID is
* submitted.
* @param invalidSessionStrategy the strategy to use when an invalid session ID is submitted.
* @return the {@link SessionManagementConfigurer} for further customization
*/
public SessionManagementConfigurer<H> invalidSessionStrategy(
InvalidSessionStrategy invalidSessionStrategy) {
public SessionManagementConfigurer<H> invalidSessionStrategy(InvalidSessionStrategy invalidSessionStrategy) {
Assert.notNull(invalidSessionStrategy, "invalidSessionStrategy");
this.invalidSessionStrategy = invalidSessionStrategy;
return this;
@@ -163,22 +156,6 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
return this;
}
/**
* Defines the {@code AuthenticationFailureHandler} which will be used when the
* SessionAuthenticationStrategy raises an exception. If not set, an unauthorized
* (402) error code will be returned to the client. Note that this attribute doesn't
* apply if the error occurs during a form-based login, where the URL for
* authentication failure will take precedence.
*
* @param sessionAuthenticationFailureHandler the handler to use
* @return the {@link SessionManagementConfigurer} for further customization
*/
public SessionManagementConfigurer<H> sessionAuthenticationFailureHandler(
AuthenticationFailureHandler sessionAuthenticationFailureHandler) {
this.sessionAuthenticationFailureHandler = sessionAuthenticationFailureHandler;
return this;
}
/**
* If set to true, allows HTTP sessions to be rewritten in the URLs when using
* {@link HttpServletResponse#encodeRedirectURL(String)} or
@@ -221,8 +198,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* {@link SessionAuthenticationStrategy} the supplied sessionAuthenticationStrategy,
* {@link RegisterSessionAuthenticationStrategy}.
*
* NOTE: Supplying a custom {@link SessionAuthenticationStrategy} will override the
* default provided {@link SessionFixationProtectionStrategy}.
* NOTE: Supplying a custom {@link SessionAuthenticationStrategy} will override the default provided {@link SessionFixationProtectionStrategy}.
*
* @param sessionAuthenticationStrategy
* @return the {@link SessionManagementConfigurer} for further customizations
@@ -268,8 +244,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
*/
private void setSessionFixationAuthenticationStrategy(
SessionAuthenticationStrategy sessionFixationAuthenticationStrategy) {
this.sessionFixationAuthenticationStrategy = postProcess(
sessionFixationAuthenticationStrategy);
this.sessionFixationAuthenticationStrategy = postProcess(sessionFixationAuthenticationStrategy);
}
/**
@@ -298,8 +273,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link SessionManagementConfigurer} for further customizations
*/
public SessionManagementConfigurer<H> migrateSession() {
setSessionFixationAuthenticationStrategy(
new SessionFixationProtectionStrategy());
setSessionFixationAuthenticationStrategy(new SessionFixationProtectionStrategy());
return SessionManagementConfigurer.this;
}
@@ -314,8 +288,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @throws IllegalStateException if the container is not Servlet 3.1 or newer.
*/
public SessionManagementConfigurer<H> changeSessionId() {
setSessionFixationAuthenticationStrategy(
new ChangeSessionIdAuthenticationStrategy());
setSessionFixationAuthenticationStrategy(new ChangeSessionIdAuthenticationStrategy());
return SessionManagementConfigurer.this;
}
@@ -328,8 +301,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link SessionManagementConfigurer} for further customizations
*/
public SessionManagementConfigurer<H> none() {
setSessionFixationAuthenticationStrategy(
new NullAuthenticatedSessionStrategy());
setSessionFixationAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
return SessionManagementConfigurer.this;
}
}
@@ -354,12 +326,6 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
return this;
}
public ConcurrencyControlConfigurer expiredSessionStrategy(
SessionInformationExpiredStrategy expiredSessionStrategy) {
SessionManagementConfigurer.this.expiredSessionStrategy = expiredSessionStrategy;
return this;
}
/**
* If true, prevents a user from authenticating when the
* {@link #maximumSessions(int)} has been reached. Otherwise (default), the user
@@ -418,8 +384,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
}
else {
HttpSessionSecurityContextRepository httpSecurityRepository = new HttpSessionSecurityContextRepository();
httpSecurityRepository
.setDisableUrlRewriting(!this.enableSessionUrlRewriting);
httpSecurityRepository.setDisableUrlRewriting(!enableSessionUrlRewriting);
httpSecurityRepository.setAllowSessionCreation(isAllowSessionCreation());
AuthenticationTrustResolver trustResolver = http
.getSharedObject(AuthenticationTrustResolver.class);
@@ -448,18 +413,15 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
.getSharedObject(SecurityContextRepository.class);
SessionManagementFilter sessionManagementFilter = new SessionManagementFilter(
securityContextRepository, getSessionAuthenticationStrategy(http));
if (this.sessionAuthenticationErrorUrl != null) {
sessionManagementFilter.setAuthenticationFailureHandler(
new SimpleUrlAuthenticationFailureHandler(
this.sessionAuthenticationErrorUrl));
if (sessionAuthenticationErrorUrl != null) {
sessionManagementFilter
.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(
sessionAuthenticationErrorUrl));
}
InvalidSessionStrategy strategy = getInvalidSessionStrategy();
if (strategy != null) {
sessionManagementFilter.setInvalidSessionStrategy(strategy);
}
AuthenticationFailureHandler failureHandler = getSessionAuthenticationFailureHandler();
if (failureHandler != null) {
sessionManagementFilter.setAuthenticationFailureHandler(failureHandler);
sessionManagementFilter
.setInvalidSessionStrategy(strategy);
}
AuthenticationTrustResolver trustResolver = http
.getSharedObject(AuthenticationTrustResolver.class);
@@ -470,23 +432,13 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
http.addFilter(sessionManagementFilter);
if (isConcurrentSessionControlEnabled()) {
ConcurrentSessionFilter concurrentSessionFilter = createConccurencyFilter(http);
ConcurrentSessionFilter concurrentSessionFilter = new ConcurrentSessionFilter(
getSessionRegistry(http), expiredUrl);
concurrentSessionFilter = postProcess(concurrentSessionFilter);
http.addFilter(concurrentSessionFilter);
}
}
private ConcurrentSessionFilter createConccurencyFilter(H http) {
SessionInformationExpiredStrategy expireStrategy = getExpiredSessionStrategy();
SessionRegistry sessionRegistry = getSessionRegistry(http);
if(expireStrategy == null) {
return new ConcurrentSessionFilter(sessionRegistry);
}
return new ConcurrentSessionFilter(sessionRegistry, expireStrategy);
}
/**
* Gets the {@link InvalidSessionStrategy} to use. If null and
* {@link #invalidSessionUrl} is not null defaults to
@@ -495,53 +447,14 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link InvalidSessionStrategy} to use
*/
InvalidSessionStrategy getInvalidSessionStrategy() {
if (this.invalidSessionStrategy != null) {
return this.invalidSessionStrategy;
if(invalidSessionStrategy != null) {
return invalidSessionStrategy;
}
if (this.invalidSessionUrl != null) {
this.invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy(
this.invalidSessionUrl);
if (invalidSessionUrl != null) {
invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy(
invalidSessionUrl);
}
if (this.invalidSessionUrl == null) {
return null;
}
if (this.invalidSessionStrategy == null) {
this.invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy(
this.invalidSessionUrl);
}
return this.invalidSessionStrategy;
}
SessionInformationExpiredStrategy getExpiredSessionStrategy() {
if (this.expiredSessionStrategy != null) {
return this.expiredSessionStrategy;
}
if (this.expiredUrl == null) {
return null;
}
if (this.expiredSessionStrategy == null) {
this.expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy(
this.expiredUrl);
}
return this.expiredSessionStrategy;
}
AuthenticationFailureHandler getSessionAuthenticationFailureHandler() {
if (this.sessionAuthenticationFailureHandler != null) {
return this.sessionAuthenticationFailureHandler;
}
if (this.sessionAuthenticationErrorUrl == null) {
return null;
}
if (this.sessionAuthenticationFailureHandler == null) {
this.sessionAuthenticationFailureHandler = new SimpleUrlAuthenticationFailureHandler(
this.sessionAuthenticationErrorUrl);
}
return this.sessionAuthenticationFailureHandler;
return invalidSessionStrategy;
}
/**
@@ -549,7 +462,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link SessionCreationPolicy}
*/
SessionCreationPolicy getSessionCreationPolicy() {
return this.sessionPolicy;
return sessionPolicy;
}
/**
@@ -558,8 +471,8 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return true if the {@link SessionCreationPolicy} allows session creation
*/
private boolean isAllowSessionCreation() {
return SessionCreationPolicy.ALWAYS == this.sessionPolicy
|| SessionCreationPolicy.IF_REQUIRED == this.sessionPolicy;
return SessionCreationPolicy.ALWAYS == sessionPolicy
|| SessionCreationPolicy.IF_REQUIRED == sessionPolicy;
}
/**
@@ -567,7 +480,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return
*/
private boolean isStateless() {
return SessionCreationPolicy.STATELESS == this.sessionPolicy;
return SessionCreationPolicy.STATELESS == sessionPolicy;
}
/**
@@ -578,52 +491,50 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link SessionAuthenticationStrategy} to use
*/
private SessionAuthenticationStrategy getSessionAuthenticationStrategy(H http) {
if (this.sessionAuthenticationStrategy != null) {
return this.sessionAuthenticationStrategy;
if (sessionAuthenticationStrategy != null) {
return sessionAuthenticationStrategy;
}
List<SessionAuthenticationStrategy> delegateStrategies = this.sessionAuthenticationStrategies;
List<SessionAuthenticationStrategy> delegateStrategies = sessionAuthenticationStrategies;
SessionAuthenticationStrategy defaultSessionAuthenticationStrategy;
if (this.providedSessionAuthenticationStrategy == null) {
if (providedSessionAuthenticationStrategy == null) {
// If a user provided SessionAuthenticationStrategy is not supplied
// then default to SessionFixationProtectionStrategy
defaultSessionAuthenticationStrategy = postProcess(
this.sessionFixationAuthenticationStrategy);
}
else {
defaultSessionAuthenticationStrategy = this.providedSessionAuthenticationStrategy;
defaultSessionAuthenticationStrategy = postProcess(sessionFixationAuthenticationStrategy);
} else {
defaultSessionAuthenticationStrategy = providedSessionAuthenticationStrategy;
}
if (isConcurrentSessionControlEnabled()) {
SessionRegistry sessionRegistry = getSessionRegistry(http);
ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlStrategy = new ConcurrentSessionControlAuthenticationStrategy(
sessionRegistry);
concurrentSessionControlStrategy.setMaximumSessions(this.maximumSessions);
concurrentSessionControlStrategy.setMaximumSessions(maximumSessions);
concurrentSessionControlStrategy
.setExceptionIfMaximumExceeded(this.maxSessionsPreventsLogin);
concurrentSessionControlStrategy = postProcess(
concurrentSessionControlStrategy);
.setExceptionIfMaximumExceeded(maxSessionsPreventsLogin);
concurrentSessionControlStrategy = postProcess(concurrentSessionControlStrategy);
RegisterSessionAuthenticationStrategy registerSessionStrategy = new RegisterSessionAuthenticationStrategy(
sessionRegistry);
registerSessionStrategy = postProcess(registerSessionStrategy);
delegateStrategies.addAll(Arrays.asList(concurrentSessionControlStrategy,
defaultSessionAuthenticationStrategy, registerSessionStrategy));
}
else {
delegateStrategies.addAll(Arrays.asList(
concurrentSessionControlStrategy,
defaultSessionAuthenticationStrategy,
registerSessionStrategy));
} else {
delegateStrategies.add(defaultSessionAuthenticationStrategy);
}
this.sessionAuthenticationStrategy = postProcess(
new CompositeSessionAuthenticationStrategy(delegateStrategies));
return this.sessionAuthenticationStrategy;
sessionAuthenticationStrategy = postProcess(new CompositeSessionAuthenticationStrategy(
delegateStrategies));
return sessionAuthenticationStrategy;
}
private SessionRegistry getSessionRegistry(H http) {
if (this.sessionRegistry == null) {
if (sessionRegistry == null) {
SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
registerDelegateApplicationListener(http, sessionRegistry);
this.sessionRegistry = sessionRegistry;
}
return this.sessionRegistry;
return sessionRegistry;
}
private void registerDelegateApplicationListener(H http,
@@ -647,7 +558,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return
*/
private boolean isConcurrentSessionControlEnabled() {
return this.maximumSessions != null;
return maximumSessions != null;
}
/**
@@ -1,42 +0,0 @@
/*
* Copyright 2002-2016 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.core;
import org.springframework.security.core.GrantedAuthority;
/**
* Allows providing defaults for {@link GrantedAuthority}
*
* @author Eddú Meléndez
* @since 4.2.0
*/
public final class GrantedAuthorityDefaults {
private final String rolePrefix;
public GrantedAuthorityDefaults(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
/**
* The default prefix used with role based authorization. Default is "ROLE_".
*
* @return the default role prefix
*/
public String getRolePrefix() {
return this.rolePrefix;
}
}
@@ -15,12 +15,8 @@
*/
package org.springframework.security.config.http;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Element;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
@@ -37,6 +33,9 @@ import org.springframework.security.web.access.intercept.DefaultFilterInvocation
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import java.util.List;
/**
* Allows for convenient creation of a {@link FilterInvocationSecurityMetadataSource} bean
@@ -134,7 +133,8 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
}
static String registerDefaultExpressionHandler(ParserContext pc) {
BeanDefinition expressionHandler = GrantedAuthorityDefaultsParserUtils.registerWithDefaultRolePrefix(pc, DefaultWebSecurityExpressionHandlerBeanFactory.class);
BeanDefinition expressionHandler = BeanDefinitionBuilder.rootBeanDefinition(
DefaultWebSecurityExpressionHandler.class).getBeanDefinition();
String expressionHandlerRef = pc.getReaderContext().generateBeanName(
expressionHandler);
pc.registerBeanComponent(new BeanComponentDefinition(expressionHandler,
@@ -223,12 +223,4 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
return filterInvocationDefinitionMap;
}
static class DefaultWebSecurityExpressionHandlerBeanFactory extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory {
private DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
public DefaultWebSecurityExpressionHandler getBean() {
handler.setDefaultRolePrefix(this.rolePrefix);
return handler;
}
}
}
@@ -1,61 +0,0 @@
/*
* Copyright 2012-2016 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.http;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
/**
* @author Rob Winch
* @since 4.2
*/
class GrantedAuthorityDefaultsParserUtils {
static RootBeanDefinition registerWithDefaultRolePrefix(ParserContext pc, Class<? extends AbstractGrantedAuthorityDefaultsBeanFactory> beanFactoryClass) {
RootBeanDefinition beanFactoryDefinition = new RootBeanDefinition(beanFactoryClass);
String beanFactoryRef = pc.getReaderContext().generateBeanName(beanFactoryDefinition);
pc.getRegistry().registerBeanDefinition(beanFactoryRef, beanFactoryDefinition);
RootBeanDefinition bean = new RootBeanDefinition();
bean.setFactoryBeanName(beanFactoryRef);
bean.setFactoryMethodName("getBean");
return bean;
}
static abstract class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware {
protected String rolePrefix = "ROLE_";
@Override
public final void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
String[] grantedAuthorityDefaultsBeanNames = applicationContext.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = applicationContext.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
this.rolePrefix = grantedAuthorityDefaults.getRolePrefix();
}
}
abstract Object getBean();
}
private GrantedAuthorityDefaultsParserUtils() {}
}
@@ -111,13 +111,13 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
parseHeaderElements(element);
boolean noWriters = headerWriters.isEmpty();
if (disabled && !noWriters) {
parserContext
.getReaderContext()
.error("Cannot specify <headers disabled=\"true\"> with child elements.",
element);
} else if (noWriters) {
if (disabled) {
if (!headerWriters.isEmpty()) {
parserContext
.getReaderContext()
.error("Cannot specify <headers disabled=\"true\"> with child elements.",
element);
}
return null;
}
@@ -15,6 +15,9 @@
*/
package org.springframework.security.config.http;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.*;
import static org.springframework.security.config.http.SecurityFilters.*;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@@ -22,8 +25,6 @@ import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.w3c.dom.Element;
import org.springframework.beans.BeanMetadataElement;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanReference;
@@ -40,7 +41,6 @@ import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.access.vote.AuthenticatedVoter;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.config.Elements;
import org.springframework.security.config.http.GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.channel.ChannelDecisionManagerImpl;
@@ -70,29 +70,12 @@ import org.springframework.security.web.servletapi.SecurityContextHolderAwareReq
import org.springframework.security.web.session.ConcurrentSessionFilter;
import org.springframework.security.web.session.SessionManagementFilter;
import org.springframework.security.web.session.SimpleRedirectInvalidSessionStrategy;
import org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_FILTERS;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_HTTP_METHOD;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL;
import static org.springframework.security.config.http.SecurityFilters.CHANNEL_FILTER;
import static org.springframework.security.config.http.SecurityFilters.CONCURRENT_SESSION_FILTER;
import static org.springframework.security.config.http.SecurityFilters.CORS_FILTER;
import static org.springframework.security.config.http.SecurityFilters.CSRF_FILTER;
import static org.springframework.security.config.http.SecurityFilters.FILTER_SECURITY_INTERCEPTOR;
import static org.springframework.security.config.http.SecurityFilters.HEADERS_FILTER;
import static org.springframework.security.config.http.SecurityFilters.JAAS_API_SUPPORT_FILTER;
import static org.springframework.security.config.http.SecurityFilters.REQUEST_CACHE_FILTER;
import static org.springframework.security.config.http.SecurityFilters.SECURITY_CONTEXT_FILTER;
import static org.springframework.security.config.http.SecurityFilters.SERVLET_API_SUPPORT_FILTER;
import static org.springframework.security.config.http.SecurityFilters.SESSION_MANAGEMENT_FILTER;
import static org.springframework.security.config.http.SecurityFilters.WEB_ASYNC_MANAGER_FILTER;
import org.w3c.dom.Element;
/**
* Stateful class which helps HttpSecurityBDP to create the configuration for the
@@ -114,7 +97,7 @@ class HttpConfigurationBuilder {
private static final String ATT_SESSION_AUTH_STRATEGY_REF = "session-authentication-strategy-ref";
private static final String ATT_SESSION_AUTH_ERROR_URL = "session-authentication-error-url";
private static final String ATT_SECURITY_CONTEXT_REPOSITORY = "security-context-repository-ref";
private static final String ATT_INVALID_SESSION_STRATEGY_REF = "invalid-session-strategy-ref";
private static final String ATT_DISABLE_URL_REWRITING = "disable-url-rewriting";
private static final String ATT_ACCESS_MGR = "access-decision-manager-ref";
@@ -306,7 +289,6 @@ class HttpConfigurationBuilder {
String sessionFixationAttribute = null;
String invalidSessionUrl = null;
String invalidSessionStrategyRef = null;
String sessionAuthStratRef = null;
String errorUrl = null;
@@ -322,8 +304,6 @@ class HttpConfigurationBuilder {
sessionFixationAttribute = sessionMgmtElt
.getAttribute(ATT_SESSION_FIXATION_PROTECTION);
invalidSessionUrl = sessionMgmtElt.getAttribute(ATT_INVALID_SESSION_URL);
invalidSessionStrategyRef = sessionMgmtElt.getAttribute(ATT_INVALID_SESSION_STRATEGY_REF);
sessionAuthStratRef = sessionMgmtElt
.getAttribute(ATT_SESSION_AUTH_STRATEGY_REF);
errorUrl = sessionMgmtElt.getAttribute(ATT_SESSION_AUTH_ERROR_URL);
@@ -331,11 +311,6 @@ class HttpConfigurationBuilder {
Elements.CONCURRENT_SESSIONS);
sessionControlEnabled = sessionCtrlElt != null;
if (StringUtils.hasText(invalidSessionUrl) && StringUtils.hasText(invalidSessionStrategyRef)) {
pc.getReaderContext().error(ATT_INVALID_SESSION_URL + " attribute cannot be used in combination with" +
" the " + ATT_INVALID_SESSION_STRATEGY_REF + " attribute.", sessionMgmtElt);
}
if (sessionControlEnabled) {
if (StringUtils.hasText(sessionAuthStratRef)) {
pc.getReaderContext().error(
@@ -463,16 +438,12 @@ class HttpConfigurationBuilder {
}
if (StringUtils.hasText(invalidSessionUrl)) {
BeanDefinitionBuilder invalidSessionBldr = BeanDefinitionBuilder
.rootBeanDefinition(SimpleRedirectInvalidSessionStrategy.class);
invalidSessionBldr.addConstructorArgValue(invalidSessionUrl);
invalidSession = invalidSessionBldr.getBeanDefinition();
sessionMgmtFilter.addPropertyValue("invalidSessionStrategy", invalidSession);
} else if (StringUtils.hasText(invalidSessionStrategyRef)) {
sessionMgmtFilter.addPropertyReference("invalidSessionStrategy", invalidSessionStrategyRef);
}
sessionMgmtFilter.addConstructorArgReference(sessionAuthStratRef);
@@ -483,7 +454,6 @@ class HttpConfigurationBuilder {
private void createConcurrencyControlFilterAndSessionRegistry(Element element) {
final String ATT_EXPIRY_URL = "expired-url";
final String ATT_EXPIRED_SESSION_STRATEGY_REF = "expired-session-strategy-ref";
final String ATT_SESSION_REGISTRY_ALIAS = "session-registry-alias";
final String ATT_SESSION_REGISTRY_REF = "session-registry-ref";
@@ -519,20 +489,10 @@ class HttpConfigurationBuilder {
filterBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
String expiryUrl = element.getAttribute(ATT_EXPIRY_URL);
String expiredSessionStrategyRef = element.getAttribute(ATT_EXPIRED_SESSION_STRATEGY_REF);
if (StringUtils.hasText(expiryUrl) && StringUtils.hasText(expiredSessionStrategyRef)) {
pc.getReaderContext().error("Cannot use 'expired-url' attribute and 'expired-session-strategy-ref'" +
" attribute together.", source);
}
if (StringUtils.hasText(expiryUrl)) {
BeanDefinitionBuilder expiredSessionBldr = BeanDefinitionBuilder
.rootBeanDefinition(SimpleRedirectSessionInformationExpiredStrategy.class);
expiredSessionBldr.addConstructorArgValue(expiryUrl);
filterBuilder.addConstructorArgValue(expiredSessionBldr.getBeanDefinition());
} else if (StringUtils.hasText(expiredSessionStrategyRef)) {
filterBuilder.addConstructorArgReference(expiredSessionStrategyRef);
WebConfigUtils.validateHttpRedirect(expiryUrl, pc, source);
filterBuilder.addConstructorArgValue(expiryUrl);
}
pc.popAndRegisterContainingComponent();
@@ -560,7 +520,8 @@ class HttpConfigurationBuilder {
}
if ("true".equals(provideServletApi)) {
servApiFilter = GrantedAuthorityDefaultsParserUtils.registerWithDefaultRolePrefix(pc, SecurityContextHolderAwareRequestFilterBeanFactory.class);
servApiFilter = new RootBeanDefinition(
SecurityContextHolderAwareRequestFilter.class);
servApiFilter.getPropertyValues().add("authenticationManager",
authenticationManager);
}
@@ -731,7 +692,7 @@ class HttpConfigurationBuilder {
voters.add(expressionVoter.getBeanDefinition());
}
else {
voters.add(GrantedAuthorityDefaultsParserUtils.registerWithDefaultRolePrefix(pc, RoleVoterBeanFactory.class));
voters.add(new RootBeanDefinition(RoleVoter.class));
voters.add(new RootBeanDefinition(AuthenticatedVoter.class));
}
accessDecisionMgr = new RootBeanDefinition(AffirmativeBased.class);
@@ -868,22 +829,4 @@ class HttpConfigurationBuilder {
return filters;
}
static class RoleVoterBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private RoleVoter voter = new RoleVoter();
public RoleVoter getBean() {
voter.setRolePrefix(this.rolePrefix);
return voter;
}
}
static class SecurityContextHolderAwareRequestFilterBeanFactory extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory {
private SecurityContextHolderAwareRequestFilter filter = new SecurityContextHolderAwareRequestFilter();
public SecurityContextHolderAwareRequestFilter getBean() {
filter.setRolePrefix(this.rolePrefix);
return filter;
}
}
}
@@ -45,8 +45,6 @@ import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.annotation.Jsr250MethodSecurityMetadataSource;
@@ -73,7 +71,6 @@ import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.Elements;
import org.springframework.security.config.authentication.AuthenticationManagerFactoryBean;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.Assert;
@@ -201,8 +198,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
expressionHandlerRef));
}
else {
RootBeanDefinition expressionHandler = registerWithDefaultRolePrefix(pc, DefaultMethodSecurityExpressionHandlerBeanFactory.class);
BeanDefinition expressionHandler = new RootBeanDefinition(
DefaultMethodSecurityExpressionHandler.class);
expressionHandlerRef = pc.getReaderContext().generateBeanName(
expressionHandler);
pc.registerBeanComponent(new BeanComponentDefinition(
@@ -243,8 +240,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
}
if (jsr250Enabled) {
RootBeanDefinition jsrMetadataSource = registerWithDefaultRolePrefix(pc, Jsr250MethodSecurityMetadataSourceBeanFactory.class);
delegates.add(jsrMetadataSource);
delegates.add(BeanDefinitionBuilder.rootBeanDefinition(
Jsr250MethodSecurityMetadataSource.class).getBeanDefinition());
}
// Now create a Map<String, ConfigAttribute> for each <protect-pointcut>
@@ -477,17 +474,6 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
BeanIds.METHOD_SECURITY_METADATA_SOURCE_ADVISOR, advisor);
}
private RootBeanDefinition registerWithDefaultRolePrefix(ParserContext pc, Class<? extends AbstractGrantedAuthorityDefaultsBeanFactory> beanFactoryClass) {
RootBeanDefinition beanFactoryDefinition = new RootBeanDefinition(beanFactoryClass);
String beanFactoryRef = pc.getReaderContext().generateBeanName(beanFactoryDefinition);
pc.getRegistry().registerBeanDefinition(beanFactoryRef, beanFactoryDefinition);
RootBeanDefinition bean = new RootBeanDefinition();
bean.setFactoryBeanName(beanFactoryRef);
bean.setFactoryMethodName("getBean");
return bean;
}
/**
* Delays the lookup of the AuthenticationManager within MethodSecurityInterceptor, to
* prevent issues like SEC-933.
@@ -536,38 +522,6 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
}
}
static class Jsr250MethodSecurityMetadataSourceBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private Jsr250MethodSecurityMetadataSource source = new Jsr250MethodSecurityMetadataSource();
public Jsr250MethodSecurityMetadataSource getBean() {
source.setDefaultRolePrefix(this.rolePrefix);
return source;
}
}
static class DefaultMethodSecurityExpressionHandlerBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
public DefaultMethodSecurityExpressionHandler getBean() {
handler.setDefaultRolePrefix(this.rolePrefix);
return handler;
}
}
static abstract class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware {
protected String rolePrefix = "ROLE_";
@Override
public final void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
String[] grantedAuthorityDefaultsBeanNames = applicationContext.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = applicationContext.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
this.rolePrefix = grantedAuthorityDefaults.getRolePrefix();
}
}
}
/**
* Delays setting a bean of a given name to be lazyily initialized until after all the
* beans are registered.
@@ -1,916 +0,0 @@
namespace a = "http://relaxng.org/ns/compatibility/annotations/1.0"
datatypes xsd = "http://www.w3.org/2001/XMLSchema-datatypes"
default namespace = "http://www.springframework.org/schema/security"
start = http | ldap-server | authentication-provider | ldap-authentication-provider | any-user-service | ldap-server | ldap-authentication-provider
hash =
## Defines the hashing algorithm used on user passwords. Bcrypt is recommended.
attribute hash {"bcrypt" | "plaintext" | "sha" | "sha-256" | "md5" | "md4" | "{sha}" | "{ssha}"}
base64 =
## Whether a string should be base64 encoded
attribute base64 {xsd:boolean}
request-matcher =
## Defines the strategy use for matching incoming requests. Currently the options are 'mvc' (for Spring MVC matcher), 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions.
attribute request-matcher {"mvc" | "ant" | "regex" | "ciRegex"}
port =
## Specifies an IP port number. Used to configure an embedded LDAP server, for example.
attribute port { xsd:positiveInteger }
url =
## Specifies a URL.
attribute url { xsd:token }
id =
## A bean identifier, used for referring to the bean elsewhere in the context.
attribute id {xsd:token}
name =
## A bean identifier, used for referring to the bean elsewhere in the context.
attribute name {xsd:token}
ref =
## Defines a reference to a Spring bean Id.
attribute ref {xsd:token}
cache-ref =
## Defines a reference to a cache for use with a UserDetailsService.
attribute cache-ref {xsd:token}
user-service-ref =
## A reference to a user-service (or UserDetailsService bean) Id
attribute user-service-ref {xsd:token}
authentication-manager-ref =
## A reference to an AuthenticationManager bean
attribute authentication-manager-ref {xsd:token}
data-source-ref =
## A reference to a DataSource bean
attribute data-source-ref {xsd:token}
debug =
## Enables Spring Security debugging infrastructure. This will provide human-readable (multi-line) debugging information to monitor requests coming into the security filters. This may include sensitive information, such as request parameters or headers, and should only be used in a development environment.
element debug {empty}
password-encoder =
## element which defines a password encoding strategy. Used by an authentication provider to convert submitted passwords to hashed versions, for example.
element password-encoder {password-encoder.attlist, salt-source?}
password-encoder.attlist &=
ref | (hash? & base64?)
salt-source =
## Password salting strategy. A system-wide constant or a property from the UserDetails object can be used.
element salt-source {user-property | system-wide | ref}
user-property =
## A property of the UserDetails object which will be used as salt by a password encoder. Typically something like "username" might be used.
attribute user-property {xsd:token}
system-wide =
## A single value that will be used as the salt for a password encoder.
attribute system-wide {xsd:token}
role-prefix =
## A non-empty string prefix that will be added to role strings loaded from persistent storage (e.g. "ROLE_"). Use the value "none" for no prefix in cases where the default is non-empty.
attribute role-prefix {xsd:token}
use-expressions =
## Enables the use of expressions in the 'access' attributes in <intercept-url> elements rather than the traditional list of configuration attributes. Defaults to 'true'. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to 'true', access will be granted.
attribute use-expressions {xsd:boolean}
ldap-server =
## Defines an LDAP server location or starts an embedded server. The url indicates the location of a remote server. If no url is given, an embedded server will be started, listening on the supplied port number. The port is optional and defaults to 33389. A Spring LDAP ContextSource bean will be registered for the server with the id supplied.
element ldap-server {ldap-server.attlist}
ldap-server.attlist &= id?
ldap-server.attlist &= (url | port)?
ldap-server.attlist &=
## Username (DN) of the "manager" user identity which will be used to authenticate to a (non-embedded) LDAP server. If omitted, anonymous access will be used.
attribute manager-dn {xsd:string}?
ldap-server.attlist &=
## The password for the manager DN. This is required if the manager-dn is specified.
attribute manager-password {xsd:string}?
ldap-server.attlist &=
## Explicitly specifies an ldif file resource to load into an embedded LDAP server. The default is classpath*:*.ldiff
attribute ldif { xsd:string }?
ldap-server.attlist &=
## Optional root suffix for the embedded LDAP server. Default is "dc=springframework,dc=org"
attribute root { xsd:string }?
ldap-server-ref-attribute =
## The optional server to use. If omitted, and a default LDAP server is registered (using <ldap-server> with no Id), that server will be used.
attribute server-ref {xsd:token}
group-search-filter-attribute =
## Group search filter. Defaults to (uniqueMember={0}). The substituted parameter is the DN of the user.
attribute group-search-filter {xsd:token}
group-search-base-attribute =
## Search base for group membership searches. Defaults to "" (searching from the root).
attribute group-search-base {xsd:token}
user-search-filter-attribute =
## The LDAP filter used to search for users (optional). For example "(uid={0})". The substituted parameter is the user's login name.
attribute user-search-filter {xsd:token}
user-search-base-attribute =
## Search base for user searches. Defaults to "". Only used with a 'user-search-filter'.
attribute user-search-base {xsd:token}
group-role-attribute-attribute =
## The LDAP attribute name which contains the role name which will be used within Spring Security. Defaults to "cn".
attribute group-role-attribute {xsd:token}
user-details-class-attribute =
## Allows the objectClass of the user entry to be specified. If set, the framework will attempt to load standard attributes for the defined class into the returned UserDetails object
attribute user-details-class {"person" | "inetOrgPerson"}
user-context-mapper-attribute =
## Allows explicit customization of the loaded user object by specifying a UserDetailsContextMapper bean which will be called with the context information from the user's directory entry
attribute user-context-mapper-ref {xsd:token}
ldap-user-service =
## This element configures a LdapUserDetailsService which is a combination of a FilterBasedLdapUserSearch and a DefaultLdapAuthoritiesPopulator.
element ldap-user-service {ldap-us.attlist}
ldap-us.attlist &= id?
ldap-us.attlist &=
ldap-server-ref-attribute?
ldap-us.attlist &=
user-search-filter-attribute?
ldap-us.attlist &=
user-search-base-attribute?
ldap-us.attlist &=
group-search-filter-attribute?
ldap-us.attlist &=
group-search-base-attribute?
ldap-us.attlist &=
group-role-attribute-attribute?
ldap-us.attlist &=
cache-ref?
ldap-us.attlist &=
role-prefix?
ldap-us.attlist &=
(user-details-class-attribute | user-context-mapper-attribute)?
ldap-authentication-provider =
## Sets up an ldap authentication provider
element ldap-authentication-provider {ldap-ap.attlist, password-compare-element?}
ldap-ap.attlist &=
ldap-server-ref-attribute?
ldap-ap.attlist &=
user-search-base-attribute?
ldap-ap.attlist &=
user-search-filter-attribute?
ldap-ap.attlist &=
group-search-base-attribute?
ldap-ap.attlist &=
group-search-filter-attribute?
ldap-ap.attlist &=
group-role-attribute-attribute?
ldap-ap.attlist &=
## A specific pattern used to build the user's DN, for example "uid={0},ou=people". The key "{0}" must be present and will be substituted with the username.
attribute user-dn-pattern {xsd:token}?
ldap-ap.attlist &=
role-prefix?
ldap-ap.attlist &=
(user-details-class-attribute | user-context-mapper-attribute)?
password-compare-element =
## Specifies that an LDAP provider should use an LDAP compare operation of the user's password to authenticate the user
element password-compare {password-compare.attlist, password-encoder?}
password-compare.attlist &=
## The attribute in the directory which contains the user password. Defaults to "userPassword".
attribute password-attribute {xsd:token}?
password-compare.attlist &=
hash?
intercept-methods =
## Can be used inside a bean definition to add a security interceptor to the bean and set up access configuration attributes for the bean's methods
element intercept-methods {intercept-methods.attlist, protect+}
intercept-methods.attlist &=
## Optional AccessDecisionManager bean ID to be used by the created method security interceptor.
attribute access-decision-manager-ref {xsd:token}?
protect =
## Defines a protected method and the access control configuration attributes that apply to it. We strongly advise you NOT to mix "protect" declarations with any services provided "global-method-security".
element protect {protect.attlist, empty}
protect.attlist &=
## A method name
attribute method {xsd:token}
protect.attlist &=
## Access configuration attributes list that applies to the method, e.g. "ROLE_A,ROLE_B".
attribute access {xsd:token}
method-security-metadata-source =
## Creates a MethodSecurityMetadataSource instance
element method-security-metadata-source {msmds.attlist, protect+}
msmds.attlist &= id?
msmds.attlist &= use-expressions?
global-method-security =
## Provides method security for all beans registered in the Spring application context. Specifically, beans will be scanned for matches with the ordered list of "protect-pointcut" sub-elements, Spring Security annotations and/or. Where there is a match, the beans will automatically be proxied and security authorization applied to the methods accordingly. If you use and enable all four sources of method security metadata (ie "protect-pointcut" declarations, expression annotations, @Secured and also JSR250 security annotations), the metadata sources will be queried in that order. In practical terms, this enables you to use XML to override method security metadata expressed in annotations. If using annotations, the order of precedence is EL-based (@PreAuthorize etc.), @Secured and finally JSR-250.
element global-method-security {global-method-security.attlist, (pre-post-annotation-handling | expression-handler)?, protect-pointcut*, after-invocation-provider*}
global-method-security.attlist &=
## Specifies whether the use of Spring Security's pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) should be enabled for this application context. Defaults to "disabled".
attribute pre-post-annotations {"disabled" | "enabled" }?
global-method-security.attlist &=
## Specifies whether the use of Spring Security's @Secured annotations should be enabled for this application context. Defaults to "disabled".
attribute secured-annotations {"disabled" | "enabled" }?
global-method-security.attlist &=
## Specifies whether JSR-250 style attributes are to be used (for example "RolesAllowed"). This will require the javax.annotation.security classes on the classpath. Defaults to "disabled".
attribute jsr250-annotations {"disabled" | "enabled" }?
global-method-security.attlist &=
## Optional AccessDecisionManager bean ID to override the default used for method security.
attribute access-decision-manager-ref {xsd:token}?
global-method-security.attlist &=
## Optional RunAsmanager implementation which will be used by the configured MethodSecurityInterceptor
attribute run-as-manager-ref {xsd:token}?
global-method-security.attlist &=
## Allows the advice "order" to be set for the method security interceptor.
attribute order {xsd:token}?
global-method-security.attlist &=
## If true, class based proxying will be used instead of interface based proxying.
attribute proxy-target-class {xsd:boolean}?
global-method-security.attlist &=
## Can be used to specify that AspectJ should be used instead of the default Spring AOP. If set, secured classes must be woven with the AnnotationSecurityAspect from the spring-security-aspects module.
attribute mode {"aspectj"}?
global-method-security.attlist &=
## An external MethodSecurityMetadataSource instance can be supplied which will take priority over other sources (such as the default annotations).
attribute metadata-source-ref {xsd:token}?
global-method-security.attlist &=
authentication-manager-ref?
after-invocation-provider =
## Allows addition of extra AfterInvocationProvider beans which should be called by the MethodSecurityInterceptor created by global-method-security.
element after-invocation-provider {ref}
pre-post-annotation-handling =
## Allows the default expression-based mechanism for handling Spring Security's pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) to be replace entirely. Only applies if these annotations are enabled.
element pre-post-annotation-handling {invocation-attribute-factory, pre-invocation-advice, post-invocation-advice}
invocation-attribute-factory =
## Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods.
element invocation-attribute-factory {ref}
pre-invocation-advice =
## Customizes the PreInvocationAuthorizationAdviceVoter with the ref as the PreInvocationAuthorizationAdviceVoter for the <pre-post-annotation-handling> element.
element pre-invocation-advice {ref}
post-invocation-advice =
## Customizes the PostInvocationAdviceProvider with the ref as the PostInvocationAuthorizationAdvice for the <pre-post-annotation-handling> element.
element post-invocation-advice {ref}
expression-handler =
## Defines the SecurityExpressionHandler instance which will be used if expression-based access-control is enabled. A default implementation (with no ACL support) will be used if not supplied.
element expression-handler {ref}
protect-pointcut =
## Defines a protected pointcut and the access control configuration attributes that apply to it. Every bean registered in the Spring application context that provides a method that matches the pointcut will receive security authorization.
element protect-pointcut {protect-pointcut.attlist, empty}
protect-pointcut.attlist &=
## An AspectJ expression, including the 'execution' keyword. For example, 'execution(int com.foo.TargetObject.countLength(String))' (without the quotes).
attribute expression {xsd:string}
protect-pointcut.attlist &=
## Access configuration attributes list that applies to all methods matching the pointcut, e.g. "ROLE_A,ROLE_B"
attribute access {xsd:token}
websocket-message-broker =
## Allows securing a Message Broker. There are two modes. If no id is specified: ensures that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver; ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel; and that a ChannelSecurityInterceptor is registered with the clientInboundChannel. If the id is specified, creates a ChannelSecurityInterceptor that can be manually registered with the clientInboundChannel.
element websocket-message-broker { websocket-message-broker.attrlist, (intercept-message* & expression-handler?) }
websocket-message-broker.attrlist &=
## A bean identifier, used for referring to the bean elsewhere in the context. If specified, explicit configuration within clientInboundChannel is required. If not specified, ensures that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver; ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel; and that a ChannelSecurityInterceptor is registered with the clientInboundChannel.
attribute id {xsd:token}?
websocket-message-broker.attrlist &=
## Disables the requirement for CSRF token to be present in the Stomp headers (default false). Changing the default is useful if it is necessary to allow other origins to make SockJS connections.
attribute same-origin-disabled {xsd:boolean}?
intercept-message =
## Creates an authorization rule for a websocket message.
element intercept-message {intercept-message.attrlist}
intercept-message.attrlist &=
## The destination ant pattern which will be mapped to the access attribute. For example, /** matches any message with a destination, /admin/** matches any message that has a destination that starts with admin.
attribute pattern {xsd:token}?
intercept-message.attrlist &=
## The access configuration attributes that apply for the configured message. For example, permitAll grants access to anyone, hasRole('ROLE_ADMIN') requires the user have the role 'ROLE_ADMIN'.
attribute access {xsd:token}?
intercept-message.attrlist &=
## The type of message to match on. Valid values are defined in SimpMessageType (i.e. CONNECT, CONNECT_ACK, HEARTBEAT, MESSAGE, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, DISCONNECT_ACK, OTHER).
attribute type {"CONNECT" | "CONNECT_ACK" | "HEARTBEAT" | "MESSAGE" | "SUBSCRIBE"| "UNSUBSCRIBE" | "DISCONNECT" | "DISCONNECT_ACK" | "OTHER"}?
http-firewall =
## Allows a custom instance of HttpFirewall to be injected into the FilterChainProxy created by the namespace.
element http-firewall {ref}
http =
## Container element for HTTP security configuration. Multiple elements can now be defined, each with a specific pattern to which the enclosed security configuration applies. A pattern can also be configured to bypass Spring Security's filters completely by setting the "security" attribute to "none".
element http {http.attlist, (intercept-url* & access-denied-handler? & form-login? & openid-login? & x509? & jee? & http-basic? & logout? & session-management & remember-me? & anonymous? & port-mappings & custom-filter* & request-cache? & expression-handler? & headers? & csrf? & cors?) }
http.attlist &=
## The request URL pattern which will be mapped to the filter chain created by this <http> element. If omitted, the filter chain will match all requests.
attribute pattern {xsd:token}?
http.attlist &=
## When set to 'none', requests matching the pattern attribute will be ignored by Spring Security. No security filters will be applied and no SecurityContext will be available. If set, the <http> element must be empty, with no children.
attribute security {"none"}?
http.attlist &=
## Allows a RequestMatcher instance to be used, as an alternative to pattern-matching.
attribute request-matcher-ref { xsd:token }?
http.attlist &=
## A legacy attribute which automatically registers a login form, BASIC authentication and a logout URL and logout services. If unspecified, defaults to "false". We'd recommend you avoid using this and instead explicitly configure the services you require.
attribute auto-config {xsd:boolean}?
http.attlist &=
use-expressions?
http.attlist &=
## Controls the eagerness with which an HTTP session is created by Spring Security classes. If not set, defaults to "ifRequired". If "stateless" is used, this implies that the application guarantees that it will not create a session. This differs from the use of "never" which means that Spring Security will not create a session, but will make use of one if the application does.
attribute create-session {"ifRequired" | "always" | "never" | "stateless"}?
http.attlist &=
## A reference to a SecurityContextRepository bean. This can be used to customize how the SecurityContext is stored between requests.
attribute security-context-repository-ref {xsd:token}?
http.attlist &=
request-matcher?
http.attlist &=
## Provides versions of HttpServletRequest security methods such as isUserInRole() and getPrincipal() which are implemented by accessing the Spring SecurityContext. Defaults to "true".
attribute servlet-api-provision {xsd:boolean}?
http.attlist &=
## If available, runs the request as the Subject acquired from the JaasAuthenticationToken. Defaults to "false".
attribute jaas-api-provision {xsd:boolean}?
http.attlist &=
## Optional attribute specifying the ID of the AccessDecisionManager implementation which should be used for authorizing HTTP requests.
attribute access-decision-manager-ref {xsd:token}?
http.attlist &=
## Optional attribute specifying the realm name that will be used for all authentication features that require a realm name (eg BASIC and Digest authentication). If unspecified, defaults to "Spring Security Application".
attribute realm {xsd:token}?
http.attlist &=
## Allows a customized AuthenticationEntryPoint to be set on the ExceptionTranslationFilter.
attribute entry-point-ref {xsd:token}?
http.attlist &=
## Corresponds to the observeOncePerRequest property of FilterSecurityInterceptor. Defaults to "true"
attribute once-per-request {xsd:boolean}?
http.attlist &=
## Prevents the jsessionid parameter from being added to rendered URLs. Defaults to "true" (rewriting is disabled).
attribute disable-url-rewriting {xsd:boolean}?
http.attlist &=
## Exposes the list of filters defined by this configuration under this bean name in the application context.
name?
http.attlist &=
authentication-manager-ref?
access-denied-handler =
## Defines the access-denied strategy that should be used. An access denied page can be defined or a reference to an AccessDeniedHandler instance.
element access-denied-handler {access-denied-handler.attlist, empty}
access-denied-handler.attlist &= (ref | access-denied-handler-page)
access-denied-handler-page =
## The access denied page that an authenticated user will be redirected to if they request a page which they don't have the authority to access.
attribute error-page {xsd:token}
intercept-url =
## Specifies the access attributes and/or filter list for a particular set of URLs.
element intercept-url {intercept-url.attlist, empty}
intercept-url.attlist &=
## The pattern which defines the URL path. The content will depend on the type set in the containing http element, so will default to ant path syntax.
attribute pattern {xsd:token}
intercept-url.attlist &=
## The access configuration attributes that apply for the configured path.
attribute access {xsd:token}?
intercept-url.attlist &=
## The HTTP Method for which the access configuration attributes should apply. If not specified, the attributes will apply to any method.
attribute method {"GET" | "DELETE" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "PATCH" | "TRACE"}?
intercept-url.attlist &=
## The filter list for the path. Currently can be set to "none" to remove a path from having any filters applied. The full filter stack (consisting of all filters created by the namespace configuration, and any added using 'custom-filter'), will be applied to any other paths.
attribute filters {"none"}?
intercept-url.attlist &=
## Used to specify that a URL must be accessed over http or https, or that there is no preference. The value should be "http", "https" or "any", respectively.
attribute requires-channel {xsd:token}?
intercept-url.attlist &=
## The path to the servlet. This attribute is only applicable when 'request-matcher' is 'mvc'. In addition, the value is only required in the following 2 use cases: 1) There are 2 or more HttpServlet's registered in the ServletContext that have mappings starting with '/' and are different; 2) The pattern starts with the same value of a registered HttpServlet path, excluding the default (root) HttpServlet '/'.
attribute servlet-path {xsd:token}?
logout =
## Incorporates a logout processing filter. Most web applications require a logout filter, although you may not require one if you write a controller to provider similar logic.
element logout {logout.attlist, empty}
logout.attlist &=
## Specifies the URL that will cause a logout. Spring Security will initialize a filter that responds to this particular URL. Defaults to /logout if unspecified.
attribute logout-url {xsd:token}?
logout.attlist &=
## Specifies the URL to display once the user has logged out. If not specified, defaults to <form-login-login-page>/?logout (i.e. /login?logout).
attribute logout-success-url {xsd:token}?
logout.attlist &=
## Specifies whether a logout also causes HttpSession invalidation, which is generally desirable. If unspecified, defaults to true.
attribute invalidate-session {xsd:boolean}?
logout.attlist &=
## A reference to a LogoutSuccessHandler implementation which will be used to determine the destination to which the user is taken after logging out.
attribute success-handler-ref {xsd:token}?
logout.attlist &=
## A comma-separated list of the names of cookies which should be deleted when the user logs out
attribute delete-cookies {xsd:token}?
request-cache =
## Allow the RequestCache used for saving requests during the login process to be set
element request-cache {ref}
form-login =
## Sets up a form login configuration for authentication with a username and password
element form-login {form-login.attlist, empty}
form-login.attlist &=
## The URL that the login form is posted to. If unspecified, it defaults to /login.
attribute login-processing-url {xsd:token}?
form-login.attlist &=
## The name of the request parameter which contains the username. Defaults to 'username'.
attribute username-parameter {xsd:token}?
form-login.attlist &=
## The name of the request parameter which contains the password. Defaults to 'password'.
attribute password-parameter {xsd:token}?
form-login.attlist &=
## The URL that will be redirected to after successful authentication, if the user's previous action could not be resumed. This generally happens if the user visits a login page without having first requested a secured operation that triggers authentication. If unspecified, defaults to the root of the application.
attribute default-target-url {xsd:token}?
form-login.attlist &=
## Whether the user should always be redirected to the default-target-url after login.
attribute always-use-default-target {xsd:boolean}?
form-login.attlist &=
## The URL for the login page. If no login URL is specified, Spring Security will automatically create a login URL at GET /login and a corresponding filter to render that login URL when requested.
attribute login-page {xsd:token}?
form-login.attlist &=
## The URL for the login failure page. If no login failure URL is specified, Spring Security will automatically create a failure login URL at /login?error and a corresponding filter to render that login failure URL when requested.
attribute authentication-failure-url {xsd:token}?
form-login.attlist &=
## Reference to an AuthenticationSuccessHandler bean which should be used to handle a successful authentication request. Should not be used in combination with default-target-url (or always-use-default-target-url) as the implementation should always deal with navigation to the subsequent destination
attribute authentication-success-handler-ref {xsd:token}?
form-login.attlist &=
## Reference to an AuthenticationFailureHandler bean which should be used to handle a failed authentication request. Should not be used in combination with authentication-failure-url as the implementation should always deal with navigation to the subsequent destination
attribute authentication-failure-handler-ref {xsd:token}?
form-login.attlist &=
## Reference to an AuthenticationDetailsSource which will be used by the authentication filter
attribute authentication-details-source-ref {xsd:token}?
form-login.attlist &=
## The URL for the ForwardAuthenticationFailureHandler
attribute authentication-failure-forward-url {xsd:token}?
form-login.attlist &=
## The URL for the ForwardAuthenticationSuccessHandler
attribute authentication-success-forward-url {xsd:token}?
openid-login =
## Sets up form login for authentication with an Open ID identity
element openid-login {form-login.attlist, user-service-ref?, attribute-exchange*}
attribute-exchange =
## Sets up an attribute exchange configuration to request specified attributes from the OpenID identity provider. When multiple elements are used, each must have an identifier-attribute attribute. Each configuration will be matched in turn against the supplied login identifier until a match is found.
element attribute-exchange {attribute-exchange.attlist, openid-attribute+}
attribute-exchange.attlist &=
## A regular expression which will be compared against the claimed identity, when deciding which attribute-exchange configuration to use during authentication.
attribute identifier-match {xsd:token}?
openid-attribute =
## Attributes used when making an OpenID AX Fetch Request
element openid-attribute {openid-attribute.attlist}
openid-attribute.attlist &=
## Specifies the name of the attribute that you wish to get back. For example, email.
attribute name {xsd:token}
openid-attribute.attlist &=
## Specifies the attribute type. For example, http://axschema.org/contact/email. See your OP's documentation for valid attribute types.
attribute type {xsd:token}
openid-attribute.attlist &=
## Specifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. Default is false.
attribute required {xsd:boolean}?
openid-attribute.attlist &=
## Specifies the number of attributes that you wish to get back. For example, return 3 emails. The default value is 1.
attribute count {xsd:int}?
filter-chain-map =
## Used to explicitly configure a FilterChainProxy instance with a FilterChainMap
element filter-chain-map {filter-chain-map.attlist, filter-chain+}
filter-chain-map.attlist &=
request-matcher?
filter-chain =
## Used within to define a specific URL pattern and the list of filters which apply to the URLs matching that pattern. When multiple filter-chain elements are assembled in a list in order to configure a FilterChainProxy, the most specific patterns must be placed at the top of the list, with most general ones at the bottom.
element filter-chain {filter-chain.attlist, empty}
filter-chain.attlist &=
(pattern | request-matcher-ref)
filter-chain.attlist &=
## A comma separated list of bean names that implement Filter that should be processed for this FilterChain. If the value is none, then no Filters will be used for this FilterChain.
attribute filters {xsd:token}
pattern =
## The request URL pattern which will be mapped to the FilterChain.
attribute pattern {xsd:token}
request-matcher-ref =
## Allows a RequestMatcher instance to be used, as an alternative to pattern-matching.
attribute request-matcher-ref {xsd:token}
filter-security-metadata-source =
## Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the <http> element. The intercept-url elements used should only contain pattern, method and access attributes. Any others will result in a configuration error.
element filter-security-metadata-source {fsmds.attlist, intercept-url+}
fsmds.attlist &=
use-expressions?
fsmds.attlist &=
id?
fsmds.attlist &=
## Compare after forcing to lowercase
attribute lowercase-comparisons {xsd:boolean}?
fsmds.attlist &=
request-matcher?
http-basic =
## Adds support for basic authentication
element http-basic {http-basic.attlist, empty}
http-basic.attlist &=
## Sets the AuthenticationEntryPoint which is used by the BasicAuthenticationFilter.
attribute entry-point-ref {xsd:token}?
http-basic.attlist &=
## Reference to an AuthenticationDetailsSource which will be used by the authentication filter
attribute authentication-details-source-ref {xsd:token}?
session-management =
## Session-management related functionality is implemented by the addition of a SessionManagementFilter to the filter stack.
element session-management {session-management.attlist, concurrency-control?}
session-management.attlist &=
## Indicates how session fixation protection will be applied when a user authenticates. If set to "none", no protection will be applied. "newSession" will create a new empty session, with only Spring Security-related attributes migrated. "migrateSession" will create a new session and copy all session attributes to the new session. In Servlet 3.1 (Java EE 7) and newer containers, specifying "changeSessionId" will keep the existing session and use the container-supplied session fixation protection (HttpServletRequest#changeSessionId()). Defaults to "changeSessionId" in Servlet 3.1 and newer containers, "migrateSession" in older containers. Throws an exception if "changeSessionId" is used in older containers.
attribute session-fixation-protection {"none" | "newSession" | "migrateSession" | "changeSessionId" }?
session-management.attlist &=
## The URL to which a user will be redirected if they submit an invalid session indentifier. Typically used to detect session timeouts.
attribute invalid-session-url {xsd:token}?
session-management.attlist &=
## Allows injection of the InvalidSessionStrategy instance used by the SessionManagementFilter
attribute invalid-session-strategy-ref {xsd:token}?
session-management.attlist &=
## Allows injection of the SessionAuthenticationStrategy instance used by the SessionManagementFilter
attribute session-authentication-strategy-ref {xsd:token}?
session-management.attlist &=
## Defines the URL of the error page which should be shown when the SessionAuthenticationStrategy raises an exception. If not set, an unauthorized (401) error code will be returned to the client. Note that this attribute doesn't apply if the error occurs during a form-based login, where the URL for authentication failure will take precedence.
attribute session-authentication-error-url {xsd:token}?
concurrency-control =
## Enables concurrent session control, limiting the number of authenticated sessions a user may have at the same time.
element concurrency-control {concurrency-control.attlist, empty}
concurrency-control.attlist &=
## The maximum number of sessions a single authenticated user can have open at the same time. Defaults to "1". A negative value denotes unlimitted sessions.
attribute max-sessions {xsd:integer}?
concurrency-control.attlist &=
## The URL a user will be redirected to if they attempt to use a session which has been "expired" because they have logged in again.
attribute expired-url {xsd:token}?
concurrency-control.attlist &=
## Allows injection of the SessionInformationExpiredStrategy instance used by the ConcurrentSessionFilter
attribute expired-session-strategy-ref {xsd:token}?
concurrency-control.attlist &=
## Specifies that an unauthorized error should be reported when a user attempts to login when they already have the maximum configured sessions open. The default behaviour is to expire the original session. If the session-authentication-error-url attribute is set on the session-management URL, the user will be redirected to this URL.
attribute error-if-maximum-exceeded {xsd:boolean}?
concurrency-control.attlist &=
## Allows you to define an alias for the SessionRegistry bean in order to access it in your own configuration.
attribute session-registry-alias {xsd:token}?
concurrency-control.attlist &=
## Allows you to define an external SessionRegistry bean to be used by the concurrency control setup.
attribute session-registry-ref {xsd:token}?
remember-me =
## Sets up remember-me authentication. If used with the "key" attribute (or no attributes) the cookie-only implementation will be used. Specifying "token-repository-ref" or "remember-me-data-source-ref" will use the more secure, persisten token approach.
element remember-me {remember-me.attlist}
remember-me.attlist &=
## The "key" used to identify cookies from a specific token-based remember-me application. You should set this to a unique value for your application. If unset, it will default to a random value generated by SecureRandom.
attribute key {xsd:token}?
remember-me.attlist &=
(token-repository-ref | remember-me-data-source-ref | remember-me-services-ref)
remember-me.attlist &=
user-service-ref?
remember-me.attlist &=
## Exports the internally defined RememberMeServices as a bean alias, allowing it to be used by other beans in the application context.
attribute services-alias {xsd:token}?
remember-me.attlist &=
## Determines whether the "secure" flag will be set on the remember-me cookie. If set to true, the cookie will only be submitted over HTTPS (recommended). By default, secure cookies will be used if the request is made on a secure connection.
attribute use-secure-cookie {xsd:boolean}?
remember-me.attlist &=
## The period (in seconds) for which the remember-me cookie should be valid.
attribute token-validity-seconds {xsd:string}?
remember-me.attlist &=
## Reference to an AuthenticationSuccessHandler bean which should be used to handle a successful remember-me authentication.
attribute authentication-success-handler-ref {xsd:token}?
remember-me.attlist &=
## The name of the request parameter which toggles remember-me authentication. Defaults to 'remember-me'.
attribute remember-me-parameter {xsd:token}?
remember-me.attlist &=
## The name of cookie which store the token for remember-me authentication. Defaults to 'remember-me'.
attribute remember-me-cookie {xsd:token}?
token-repository-ref =
## Reference to a PersistentTokenRepository bean for use with the persistent token remember-me implementation.
attribute token-repository-ref {xsd:token}
remember-me-services-ref =
## Allows a custom implementation of RememberMeServices to be used. Note that this implementation should return RememberMeAuthenticationToken instances with the same "key" value as specified in the remember-me element. Alternatively it should register its own AuthenticationProvider. It should also implement the LogoutHandler interface, which will be invoked when a user logs out. Typically the remember-me cookie would be removed on logout.
attribute services-ref {xsd:token}?
remember-me-data-source-ref =
## DataSource bean for the database that contains the token repository schema.
data-source-ref
anonymous =
## Adds support for automatically granting all anonymous web requests a particular principal identity and a corresponding granted authority.
element anonymous {anonymous.attlist}
anonymous.attlist &=
## The key shared between the provider and filter. This generally does not need to be set. If unset, it will default to a random value generated by SecureRandom.
attribute key {xsd:token}?
anonymous.attlist &=
## The username that should be assigned to the anonymous request. This allows the principal to be identified, which may be important for logging and auditing. if unset, defaults to "anonymousUser".
attribute username {xsd:token}?
anonymous.attlist &=
## The granted authority that should be assigned to the anonymous request. Commonly this is used to assign the anonymous request particular roles, which can subsequently be used in authorization decisions. If unset, defaults to "ROLE_ANONYMOUS".
attribute granted-authority {xsd:token}?
anonymous.attlist &=
## With the default namespace setup, the anonymous "authentication" facility is automatically enabled. You can disable it using this property.
attribute enabled {xsd:boolean}?
port-mappings =
## Defines the list of mappings between http and https ports for use in redirects
element port-mappings {port-mappings.attlist, port-mapping+}
port-mappings.attlist &= empty
port-mapping =
## Provides a method to map http ports to https ports when forcing a redirect.
element port-mapping {http-port, https-port}
http-port =
## The http port to use.
attribute http {xsd:token}
https-port =
## The https port to use.
attribute https {xsd:token}
x509 =
## Adds support for X.509 client authentication.
element x509 {x509.attlist}
x509.attlist &=
## The regular expression used to obtain the username from the certificate's subject. Defaults to matching on the common name using the pattern "CN=(.*?),".
attribute subject-principal-regex {xsd:token}?
x509.attlist &=
## Explicitly specifies which user-service should be used to load user data for X.509 authenticated clients. If ommitted, the default user-service will be used.
user-service-ref?
x509.attlist &=
## Reference to an AuthenticationDetailsSource which will be used by the authentication filter
attribute authentication-details-source-ref {xsd:token}?
jee =
## Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication.
element jee {jee.attlist}
jee.attlist &=
## A comma-separate list of roles to look for in the incoming HttpServletRequest.
attribute mappable-roles {xsd:token}
jee.attlist &=
## Explicitly specifies which user-service should be used to load user data for container authenticated clients. If ommitted, the set of mappable-roles will be used to construct the authorities for the user.
user-service-ref?
authentication-manager =
## Registers the AuthenticationManager instance and allows its list of AuthenticationProviders to be defined. Also allows you to define an alias to allow you to reference the AuthenticationManager in your own beans.
element authentication-manager {authman.attlist & authentication-provider* & ldap-authentication-provider*}
authman.attlist &=
id?
authman.attlist &=
## An alias you wish to use for the AuthenticationManager bean (not required it you are using a specific id)
attribute alias {xsd:token}?
authman.attlist &=
## If set to true, the AuthenticationManger will attempt to clear any credentials data in the returned Authentication object, once the user has been authenticated.
attribute erase-credentials {xsd:boolean}?
authentication-provider =
## Indicates that the contained user-service should be used as an authentication source.
element authentication-provider {ap.attlist & any-user-service & password-encoder?}
ap.attlist &=
## Specifies a reference to a separately configured AuthenticationProvider instance which should be registered within the AuthenticationManager.
ref?
ap.attlist &=
## Specifies a reference to a separately configured UserDetailsService from which to obtain authentication data.
user-service-ref?
user-service =
## Creates an in-memory UserDetailsService from a properties file or a list of "user" child elements. Usernames are converted to lower-case internally to allow for case-insensitive lookups, so this should not be used if case-sensitivity is required.
element user-service {id? & (properties-file | (user*))}
properties-file =
## The location of a Properties file where each line is in the format of username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]
attribute properties {xsd:token}?
user =
## Represents a user in the application.
element user {user.attlist, empty}
user.attlist &=
## The username assigned to the user.
attribute name {xsd:token}
user.attlist &=
## The password assigned to the user. This may be hashed if the corresponding authentication provider supports hashing (remember to set the "hash" attribute of the "user-service" element). This attribute be omitted in the case where the data will not be used for authentication, but only for accessing authorities. If omitted, the namespace will generate a random value, preventing its accidental use for authentication. Cannot be empty.
attribute password {xsd:string}?
user.attlist &=
## One of more authorities granted to the user. Separate authorities with a comma (but no space). For example, "ROLE_USER,ROLE_ADMINISTRATOR"
attribute authorities {xsd:token}
user.attlist &=
## Can be set to "true" to mark an account as locked and unusable.
attribute locked {xsd:boolean}?
user.attlist &=
## Can be set to "true" to mark an account as disabled and unusable.
attribute disabled {xsd:boolean}?
jdbc-user-service =
## Causes creation of a JDBC-based UserDetailsService.
element jdbc-user-service {id? & jdbc-user-service.attlist}
jdbc-user-service.attlist &=
## The bean ID of the DataSource which provides the required tables.
attribute data-source-ref {xsd:token}
jdbc-user-service.attlist &=
cache-ref?
jdbc-user-service.attlist &=
## An SQL statement to query a username, password, and enabled status given a username. Default is "select username,password,enabled from users where username = ?"
attribute users-by-username-query {xsd:token}?
jdbc-user-service.attlist &=
## An SQL statement to query for a user's granted authorities given a username. The default is "select username, authority from authorities where username = ?"
attribute authorities-by-username-query {xsd:token}?
jdbc-user-service.attlist &=
## An SQL statement to query user's group authorities given a username. The default is "select g.id, g.group_name, ga.authority from groups g, group_members gm, group_authorities ga where gm.username = ? and g.id = ga.group_id and g.id = gm.group_id"
attribute group-authorities-by-username-query {xsd:token}?
jdbc-user-service.attlist &=
role-prefix?
csrf =
## Element for configuration of the CsrfFilter for protection against CSRF. It also updates the default RequestCache to only replay "GET" requests.
element csrf {csrf-options.attlist}
csrf-options.attlist &=
## Specifies if csrf protection should be disabled. Default false (i.e. CSRF protection is enabled).
attribute disabled {xsd:boolean}?
csrf-options.attlist &=
## The RequestMatcher instance to be used to determine if CSRF should be applied. Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS"
attribute request-matcher-ref { xsd:token }?
csrf-options.attlist &=
## The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository
attribute token-repository-ref { xsd:token }?
headers =
## Element for configuration of the HeaderWritersFilter. Enables easy setting for the X-Frame-Options, X-XSS-Protection and X-Content-Type-Options headers.
element headers { headers-options.attlist, (cache-control? & xss-protection? & hsts? & frame-options? & content-type-options? & hpkp? & content-security-policy? & header*)}
headers-options.attlist &=
## Specifies if the default headers should be disabled. Default false.
attribute defaults-disabled {xsd:boolean}?
headers-options.attlist &=
## Specifies if headers should be disabled. Default false.
attribute disabled {xsd:boolean}?
hsts =
## Adds support for HTTP Strict Transport Security (HSTS)
element hsts {hsts-options.attlist}
hsts-options.attlist &=
## Specifies if HTTP Strict Transport Security (HSTS) should be disabled. Default false.
attribute disabled {xsd:boolean}?
hsts-options.attlist &=
## Specifies if subdomains should be included. Default true.
attribute include-subdomains {xsd:boolean}?
hsts-options.attlist &=
## Specifies the maximum ammount of time the host should be considered a Known HSTS Host. Default one year.
attribute max-age-seconds {xsd:integer}?
hsts-options.attlist &=
## The RequestMatcher instance to be used to determine if the header should be set. Default is if HttpServletRequest.isSecure() is true.
attribute request-matcher-ref { xsd:token }?
cors =
## Element for configuration of CorsFilter. If no CorsFilter or CorsConfigurationSource is specified a HandlerMappingIntrospector is used as the CorsConfigurationSource
element cors { cors-options.attlist }
cors-options.attlist &=
ref?
cors-options.attlist &=
## Specifies a bean id that is a CorsConfigurationSource used to construct the CorsFilter to use
attribute configuration-source-ref {xsd:token}?
hpkp =
## Adds support for HTTP Public Key Pinning (HPKP).
element hpkp {hpkp.pins,hpkp.attlist}
hpkp.pins =
## The list with pins
element pins {hpkp.pin+}
hpkp.pin =
## A pin is specified using the base64-encoded SPKI fingerprint as value and the cryptographic hash algorithm as attribute
element pin {
## The cryptographic hash algorithm
attribute algorithm { xsd:string }?,
text
}
hpkp.attlist &=
## Specifies if HTTP Public Key Pinning (HPKP) should be disabled. Default false.
attribute disabled {xsd:boolean}?
hpkp.attlist &=
## Specifies if subdomains should be included. Default false.
attribute include-subdomains {xsd:boolean}?
hpkp.attlist &=
## Sets the value for the max-age directive of the Public-Key-Pins header. Default 60 days.
attribute max-age-seconds {xsd:integer}?
hpkp.attlist &=
## Specifies if the browser should only report pin validation failures. Default true.
attribute report-only {xsd:boolean}?
hpkp.attlist &=
## Specifies the URI to which the browser should report pin validation failures.
attribute report-uri {xsd:string}?
content-security-policy =
## Adds support for Content Security Policy (CSP)
element content-security-policy {csp-options.attlist}
csp-options.attlist &=
## The security policy directive(s) for the Content-Security-Policy header or if report-only is set to true, then the Content-Security-Policy-Report-Only header is used.
attribute policy-directives {xsd:token}?
csp-options.attlist &=
## Set to true, to enable the Content-Security-Policy-Report-Only header for reporting policy violations only. Defaults to false.
attribute report-only {xsd:boolean}?
cache-control =
## Adds Cache-Control no-cache, no-store, must-revalidate, Pragma no-cache, and Expires 0 for every request
element cache-control {cache-control.attlist}
cache-control.attlist &=
## Specifies if Cache Control should be disabled. Default false.
attribute disabled {xsd:boolean}?
frame-options =
## Enable basic clickjacking support for newer browsers (IE8+), will set the X-Frame-Options header.
element frame-options {frame-options.attlist,empty}
frame-options.attlist &=
## If disabled, the X-Frame-Options header will not be included. Default false.
attribute disabled {xsd:boolean}?
frame-options.attlist &=
## Specify the policy to use for the X-Frame-Options-Header.
attribute policy {"DENY","SAMEORIGIN","ALLOW-FROM"}?
frame-options.attlist &=
## Specify the strategy to use when ALLOW-FROM is chosen.
attribute strategy {"static","whitelist","regexp"}?
frame-options.attlist &=
## Specify a reference to the custom AllowFromStrategy to use when ALLOW-FROM is chosen.
ref?
frame-options.attlist &=
## Specify a value to use for the chosen strategy.
attribute value {xsd:string}?
frame-options.attlist &=
## Specify the request parameter to use for the origin when using a 'whitelist' or 'regexp' based strategy. Default is 'from'.
attribute from-parameter {xsd:string}?
xss-protection =
## Enable basic XSS browser protection, supported by newer browsers (IE8+), will set the X-XSS-Protection header.
element xss-protection {xss-protection.attlist,empty}
xss-protection.attlist &=
## disable the X-XSS-Protection header. Default is 'false' meaning it is enabled.
attribute disabled {xsd:boolean}?
xss-protection.attlist &=
## specify that XSS Protection should be explicitly enabled or disabled. Default is 'true' meaning it is enabled.
attribute enabled {xsd:boolean}?
xss-protection.attlist &=
## Add mode=block to the header or not, default is on.
attribute block {xsd:boolean}?
content-type-options =
## Add a X-Content-Type-Options header to the resopnse. Value is always 'nosniff'.
element content-type-options {content-type-options.attlist, empty}
content-type-options.attlist &=
## If disabled, the X-Content-Type-Options header will not be included. Default false.
attribute disabled {xsd:boolean}?
header=
## Add additional headers to the response.
element header {header.attlist}
header.attlist &=
## The name of the header to add.
attribute name {xsd:token}?
header.attlist &=
## The value for the header.
attribute value {xsd:token}?
header.attlist &=
## Reference to a custom HeaderWriter implementation.
ref?
any-user-service = user-service | jdbc-user-service | ldap-user-service
custom-filter =
## Used to indicate that a filter bean declaration should be incorporated into the security filter chain.
element custom-filter {custom-filter.attlist}
custom-filter.attlist &=
ref
custom-filter.attlist &=
(after | before | position)
after =
## The filter immediately after which the custom-filter should be placed in the chain. This feature will only be needed by advanced users who wish to mix their own filters into the security filter chain and have some knowledge of the standard Spring Security filters. The filter names map to specific Spring Security implementation filters.
attribute after {named-security-filter}
before =
## The filter immediately before which the custom-filter should be placed in the chain
attribute before {named-security-filter}
position =
## The explicit position at which the custom-filter should be placed in the chain. Use if you are replacing a standard filter.
attribute position {named-security-filter}
named-security-filter = "FIRST" | "CHANNEL_FILTER" | "SECURITY_CONTEXT_FILTER" | "CONCURRENT_SESSION_FILTER" | "WEB_ASYNC_MANAGER_FILTER" | "HEADERS_FILTER" | "CORS_FILTER" | "CSRF_FILTER" | "LOGOUT_FILTER" | "X509_FILTER" | "PRE_AUTH_FILTER" | "CAS_FILTER" | "FORM_LOGIN_FILTER" | "OPENID_FILTER" | "LOGIN_PAGE_FILTER" | "DIGEST_AUTH_FILTER" | "BASIC_AUTH_FILTER" | "REQUEST_CACHE_FILTER" | "SERVLET_API_SUPPORT_FILTER" | "JAAS_API_SUPPORT_FILTER" | "REMEMBER_ME_FILTER" | "ANONYMOUS_FILTER" | "SESSION_MANAGEMENT_FILTER" | "EXCEPTION_TRANSLATION_FILTER" | "FILTER_SECURITY_INTERCEPTOR" | "SWITCH_USER_FILTER" | "LAST"
@@ -17,7 +17,7 @@ package org.springframework.security.config.annotation.method.configuration
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import java.lang.reflect.Proxy;
@@ -27,7 +27,6 @@ import org.springframework.beans.factory.config.BeanPostProcessor
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter
import org.springframework.security.config.annotation.method.configuration.NamespaceGlobalMethodSecurityTests.BaseMethodConfig;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import javax.sql.DataSource
@@ -497,27 +496,4 @@ public class GlobalMethodSecurityConfigurationTests extends BaseSpringSpec {
return new RoleHierarchyImpl(hierarchy:"ROLE_USER > ROLE_ADMIN")
}
}
def "GrantedAuthorityDefaults autowires"() {
when:
loadConfig(CustomGrantedAuthorityConfig)
def preAdviceVoter = context.getBean(MethodInterceptor).accessDecisionManager.decisionVoters.find { it instanceof PreInvocationAuthorizationAdviceVoter}
then:
preAdviceVoter.preAdvice.expressionHandler.defaultRolePrefix == "ROLE:"
}
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class CustomGrantedAuthorityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
}
@Bean
public GrantedAuthorityDefaults ga() {
return new GrantedAuthorityDefaults("ROLE:")
}
}
}
@@ -15,7 +15,6 @@
*/
package org.springframework.security.config.annotation.method.configuration
import org.springframework.security.access.annotation.Jsr250MethodSecurityMetadataSource
import org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor
import static org.assertj.core.api.Assertions.assertThat
@@ -49,7 +48,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.authentication.BaseAuthenticationConfig;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* 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.
@@ -13,9 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
package org.springframework.security.config.annotation.web.configurers;
import static org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurerConfigs.*
@@ -295,7 +293,7 @@ public class ExpressionUrlAuthorizationConfigurerTests extends BaseSpringSpec {
response.status == HttpServletResponse.SC_UNAUTHORIZED
when:
super.setup()
login(new UsernamePasswordAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_FORBIDDEN
@@ -341,12 +339,16 @@ public class ExpressionUrlAuthorizationConfigurerTests extends BaseSpringSpec {
def "authorizeRequests() fullyAuthenticated"() {
setup:
loadConfig(FullyAuthenticatedConfig)
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
when:
super.setup()
login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
response.status == HttpServletResponse.SC_FORBIDDEN
when:
super.setup()
login()
@@ -67,7 +67,7 @@ class NamespaceSessionManagementTests extends BaseSpringSpec {
concurrentStrategy.maximumSessions == 1
concurrentStrategy.exceptionIfMaximumExceeded
concurrentStrategy.sessionRegistry == CustomSessionManagementConfig.SR
findFilter(ConcurrentSessionFilter).sessionInformationExpiredStrategy.destinationUrl == "/expired-session"
findFilter(ConcurrentSessionFilter).expiredUrl == "/expired-session"
}
@EnableWebSecurity
@@ -15,11 +15,12 @@
*/
package org.springframework.security.config.doc
import groovy.util.slurpersupport.GPathResult
import spock.lang.*
import groovy.util.slurpersupport.GPathResult;
import org.springframework.security.config.http.SecurityFilters
import spock.lang.*
/**
* Tests to ensure that the xsd is properly documented.
*
@@ -27,19 +28,11 @@ import org.springframework.security.config.http.SecurityFilters
*/
class XsdDocumentedTests extends Specification {
def ignoredIds = [
'nsa-any-user-service',
'nsa-any-user-service-parents',
'nsa-authentication',
'nsa-websocket-security',
'nsa-ldap',
'nsa-method-security',
'nsa-web'
]
def ignoredIds = ['nsa-any-user-service','nsa-any-user-service-parents','nsa-authentication','nsa-websocket-security','nsa-ldap','nsa-method-security','nsa-web']
@Shared def reference = new File('../docs/manual/src/docs/asciidoc/index.adoc')
@Shared File schema31xDocument = new File('src/main/resources/org/springframework/security/config/spring-security-3.1.xsd')
@Shared File schemaDocument = new File('src/main/resources/org/springframework/security/config/spring-security-4.2.xsd')
@Shared File schemaDocument = new File('src/main/resources/org/springframework/security/config/spring-security-4.1.xsd')
@Shared Map<String,Element> elementNameToElement
@Shared GPathResult schemaRootElement
@@ -58,53 +51,32 @@ class XsdDocumentedTests extends Specification {
def 'SEC-2139: named-security-filter are all defined and ordered properly'() {
setup:
def expectedFilters = (EnumSet.allOf(SecurityFilters) as List).sort { it.order }
def expectedFilters = (EnumSet.allOf(SecurityFilters) as List).sort { it.order }
when:
def nsf = schemaRootElement.simpleType.find { it.@name == 'named-security-filter' }
def nsfValues = nsf.children().children().collect { c ->
Enum.valueOf(SecurityFilters, c.@value.toString())
}
def nsf = schemaRootElement.simpleType.find { it.@name == 'named-security-filter' }
def nsfValues = nsf.children().children().collect { c ->
Enum.valueOf(SecurityFilters, c.@value.toString())
}
then:
expectedFilters == nsfValues
expectedFilters == nsfValues
}
def 'SEC-2139: 3.1.x named-security-filter are all defined and ordered properly'() {
setup:
def expectedFilters = [
"FIRST",
"CHANNEL_FILTER",
"SECURITY_CONTEXT_FILTER",
"CONCURRENT_SESSION_FILTER",
"LOGOUT_FILTER",
"X509_FILTER",
"PRE_AUTH_FILTER",
"CAS_FILTER",
"FORM_LOGIN_FILTER",
"OPENID_FILTER",
"LOGIN_PAGE_FILTER",
"DIGEST_AUTH_FILTER",
"BASIC_AUTH_FILTER",
"REQUEST_CACHE_FILTER",
"SERVLET_API_SUPPORT_FILTER",
"JAAS_API_SUPPORT_FILTER",
"REMEMBER_ME_FILTER",
"ANONYMOUS_FILTER",
"SESSION_MANAGEMENT_FILTER",
"EXCEPTION_TRANSLATION_FILTER",
"FILTER_SECURITY_INTERCEPTOR",
"SWITCH_USER_FILTER",
"LAST"
].collect {
Enum.valueOf(SecurityFilters, it)
}
def schema31xRootElement = new XmlSlurper().parse(schema31xDocument)
def expectedFilters = ["FIRST", "CHANNEL_FILTER", "SECURITY_CONTEXT_FILTER", "CONCURRENT_SESSION_FILTER", "LOGOUT_FILTER", "X509_FILTER",
"PRE_AUTH_FILTER", "CAS_FILTER", "FORM_LOGIN_FILTER", "OPENID_FILTER", "LOGIN_PAGE_FILTER", "DIGEST_AUTH_FILTER","BASIC_AUTH_FILTER",
"REQUEST_CACHE_FILTER", "SERVLET_API_SUPPORT_FILTER", "JAAS_API_SUPPORT_FILTER", "REMEMBER_ME_FILTER", "ANONYMOUS_FILTER",
"SESSION_MANAGEMENT_FILTER", "EXCEPTION_TRANSLATION_FILTER", "FILTER_SECURITY_INTERCEPTOR", "SWITCH_USER_FILTER", "LAST"].collect {
Enum.valueOf(SecurityFilters, it)
}
def schema31xRootElement = new XmlSlurper().parse(schema31xDocument)
when:
def nsf = schema31xRootElement.simpleType.find { it.@name == 'named-security-filter' }
def nsfValues = nsf.children().children().collect { c ->
Enum.valueOf(SecurityFilters, c.@value.toString())
}
def nsf = schema31xRootElement.simpleType.find { it.@name == 'named-security-filter' }
def nsfValues = nsf.children().children().collect { c ->
Enum.valueOf(SecurityFilters, c.@value.toString())
}
then:
expectedFilters == nsfValues
expectedFilters == nsfValues
}
/**
@@ -116,8 +88,8 @@ class XsdDocumentedTests extends Specification {
def 'the latest schema is being validated'() {
when: 'all the schemas are found'
def schemas = schemaDocument.getParentFile().list().findAll { it.endsWith('.xsd') }
then: 'the count is equal to 11, if not then schemaDocument needs updated'
schemas.size() == 11
then: 'the count is equal to 10, if not then schemaDocument needs updated'
schemas.size() == 10
}
/**
@@ -127,22 +99,22 @@ class XsdDocumentedTests extends Specification {
*/
def 'the entire schema is included in the appendix documentation'() {
setup: 'get all the documented ids and the expected ids'
def documentedIds = []
reference.eachLine { line ->
if(line.matches("\\[\\[(nsa-.*)\\]\\]")) {
documentedIds.add(line.substring(2,line.length() - 2))
def documentedIds = []
reference.eachLine { line ->
if(line.matches("\\[\\[(nsa-.*)\\]\\]")) {
documentedIds.add(line.substring(2,line.length() - 2))
}
}
}
when: 'the schema is compared to the appendix documentation'
def expectedIds = [] as Set
elementNameToElement*.value*.ids*.each { expectedIds.addAll it }
documentedIds.removeAll ignoredIds
expectedIds.removeAll ignoredIds
def undocumentedIds = (expectedIds - documentedIds)
def shouldNotBeDocumented = (documentedIds - expectedIds)
def expectedIds = [] as Set
elementNameToElement*.value*.ids*.each { expectedIds.addAll it }
documentedIds.removeAll ignoredIds
expectedIds.removeAll ignoredIds
def undocumentedIds = (expectedIds - documentedIds)
def shouldNotBeDocumented = (documentedIds - expectedIds)
then: 'all the elements and attributes are documented'
shouldNotBeDocumented.empty
undocumentedIds.empty
shouldNotBeDocumented.empty
undocumentedIds.empty
}
/**
@@ -152,55 +124,55 @@ class XsdDocumentedTests extends Specification {
*/
def 'validate parents and children are linked in the appendix documentation'() {
when: "get all the links for each element's children and parents"
def docAttrNameToChildren = [:]
def docAttrNameToParents = [:]
def docAttrNameToChildren = [:]
def docAttrNameToParents = [:]
def currentDocAttrNameToElmt
def docAttrName
def currentDocAttrNameToElmt
def docAttrName
reference.eachLine { line ->
if(line.matches('^\\[\\[.*\\]\\]$')) {
def id = line.substring(2,line.length() - 2)
if(id.endsWith("-children")) {
docAttrName = id.substring(0,id.length() - 9)
currentDocAttrNameToElmt = docAttrNameToChildren
} else if(id.endsWith("-parents")) {
docAttrName = id.substring(0,id.length() - 8)
currentDocAttrNameToElmt = docAttrNameToParents
} else if(docAttrName && !id.startsWith(docAttrName)) {
currentDocAttrNameToElmt = null
docAttrName = null
reference.eachLine { line ->
if(line.matches('^\\[\\[.*\\]\\]$')) {
def id = line.substring(2,line.length() - 2)
if(id.endsWith("-children")) {
docAttrName = id.substring(0,id.length() - 9)
currentDocAttrNameToElmt = docAttrNameToChildren
} else if(id.endsWith("-parents")) {
docAttrName = id.substring(0,id.length() - 8)
currentDocAttrNameToElmt = docAttrNameToParents
} else if(docAttrName && !id.startsWith(docAttrName)) {
currentDocAttrNameToElmt = null
docAttrName = null
}
}
if(docAttrName) {
def expression = '^\\* <<(nsa-.*),.*>>$'
if(line.matches(expression)) {
String elmtId = line.replaceAll(expression, '$1')
currentDocAttrNameToElmt.get(docAttrName, []).add(elmtId)
}
}
}
if(docAttrName) {
def expression = '^\\* <<(nsa-.*),.*>>$'
if(line.matches(expression)) {
String elmtId = line.replaceAll(expression, '$1')
currentDocAttrNameToElmt.get(docAttrName, []).add(elmtId)
def schemaAttrNameToParents = [:]
def schemaAttrNameToChildren = [:]
elementNameToElement.each { entry ->
def key = 'nsa-'+entry.key
if(ignoredIds.contains(key)) {
return
}
def parentIds = entry.value.allParentElmts.values()*.id.findAll { !ignoredIds.contains(it) }.sort()
if(parentIds) {
schemaAttrNameToParents.put(key,parentIds)
}
def childIds = entry.value.allChildElmts.values()*.id.findAll { !ignoredIds.contains(it) }.sort()
if(childIds) {
schemaAttrNameToChildren.put(key,childIds)
}
}
}
def schemaAttrNameToParents = [:]
def schemaAttrNameToChildren = [:]
elementNameToElement.each { entry ->
def key = 'nsa-'+entry.key
if(ignoredIds.contains(key)) {
return
}
def parentIds = entry.value.allParentElmts.values()*.id.findAll { !ignoredIds.contains(it) }.sort()
if(parentIds) {
schemaAttrNameToParents.put(key,parentIds)
}
def childIds = entry.value.allChildElmts.values()*.id.findAll { !ignoredIds.contains(it) }.sort()
if(childIds) {
schemaAttrNameToChildren.put(key,childIds)
}
}
then: "the expected parents and children are all documented"
schemaAttrNameToChildren.sort() == docAttrNameToChildren.sort()
schemaAttrNameToParents.sort() == docAttrNameToParents.sort()
schemaAttrNameToChildren.sort() == docAttrNameToChildren.sort()
schemaAttrNameToParents.sort() == docAttrNameToParents.sort()
}
/**
@@ -109,18 +109,6 @@ class HttpHeadersConfigTests extends AbstractHttpConfigTests {
// --- defaults disabled
// gh-3986
def 'http headers defaults-disabled with no override'() {
httpAutoConfig {
'headers'('defaults-disabled':true) {
}
}
createAppContext()
expect:
getFilter(HeaderWriterFilter) == null
}
def 'http headers content-type-options'() {
httpAutoConfig {
'headers'('defaults-disabled':true) {
@@ -419,7 +419,7 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
'form-login'()
}
createAppContext()
def handlers = getFilter(LogoutFilter).handler.logoutHandlers
def handlers = getFilter(LogoutFilter).handlers
expect:
handlers[2] instanceof CookieClearingLogoutHandler
@@ -101,7 +101,7 @@ class RememberMeConfigTests extends AbstractHttpConfigTests {
createAppContext(AUTH_PROVIDER_XML)
List logoutHandlers = FieldUtils.getFieldValue(getFilter(LogoutFilter.class), "handler").logoutHandlers;
List logoutHandlers = FieldUtils.getFieldValue(getFilter(LogoutFilter.class), "handlers");
Map ams = appContext.getBeansOfType(ProviderManager.class);
ProviderManager am = (ams.values() as List).find { it instanceof ProviderManager && it.providers.size() == 2}
RememberMeAuthenticationProvider rmp = am.providers.find { it instanceof RememberMeAuthenticationProvider}
@@ -124,7 +124,7 @@ class RememberMeConfigTests extends AbstractHttpConfigTests {
createAppContext(AUTH_PROVIDER_XML)
def rememberMeServices = rememberMeServices()
List logoutHandlers = getFilter(LogoutFilter.class).handler.logoutHandlers
List logoutHandlers = getFilter(LogoutFilter.class).handlers
expect:
rememberMeServices
@@ -15,6 +15,13 @@
*/
package org.springframework.security.config.http
import static org.junit.Assert.assertSame
import static org.mockito.Mockito.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.mockito.Mockito
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
@@ -34,6 +41,7 @@ import org.springframework.security.web.authentication.logout.CookieClearingLogo
import org.springframework.security.web.authentication.logout.LogoutFilter
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter
import org.springframework.security.web.authentication.session.SessionAuthenticationException
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy
import org.springframework.security.web.context.NullSecurityContextRepository
import org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper
@@ -42,13 +50,6 @@ import org.springframework.security.web.savedrequest.RequestCacheAwareFilter
import org.springframework.security.web.session.ConcurrentSessionFilter
import org.springframework.security.web.session.SessionManagementFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import static org.junit.Assert.assertSame
import static org.mockito.Matchers.any
import static org.mockito.Mockito.verify
/**
* Tests session-related functionality for the &lt;http&gt; namespace element and &lt;session-management&gt;
*
@@ -163,13 +164,13 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
then:
concurrentSessionFilter instanceof ConcurrentSessionFilter
concurrentSessionFilter.sessionInformationExpiredStrategy.destinationUrl == '/expired'
concurrentSessionFilter.expiredUrl == '/expired'
appContext.getBean("sr") != null
getFilter(SessionManagementFilter.class) != null
sessionRegistryIsValid();
concurrentSessionFilter.handlers.logoutHandlers.size() == 1
def logoutHandler = concurrentSessionFilter.handlers.logoutHandlers[0]
concurrentSessionFilter.handlers.size() == 1
def logoutHandler = concurrentSessionFilter.handlers[0]
logoutHandler instanceof SecurityContextLogoutHandler
logoutHandler.invalidateHttpSession
@@ -189,7 +190,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
List filters = getFilters("/someurl")
ConcurrentSessionFilter concurrentSessionFilter = filters.get(1)
def logoutHandlers = concurrentSessionFilter.handlers.logoutHandlers
def logoutHandlers = concurrentSessionFilter.handlers
then: 'ConcurrentSessionFilter contains the customized LogoutHandlers'
logoutHandlers.size() == 3
@@ -215,7 +216,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
List filters = getFilters("/someurl")
ConcurrentSessionFilter concurrentSessionFilter = filters.get(1)
def logoutHandlers = concurrentSessionFilter.handlers.logoutHandlers
def logoutHandlers = concurrentSessionFilter.handlers
then: 'SecurityContextLogoutHandler and RememberMeServices are in ConcurrentSessionFilter logoutHandlers'
!filters.find { it instanceof LogoutFilter }
@@ -237,7 +238,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
List filters = getFilters("/someurl")
ConcurrentSessionFilter concurrentSessionFilter = filters.get(1)
def logoutHandlers = concurrentSessionFilter.handlers.logoutHandlers
def logoutHandlers = concurrentSessionFilter.handlers
then: 'Only SecurityContextLogoutHandler is found in ConcurrentSessionFilter logoutHandlers'
!filters.find { it instanceof LogoutFilter }
@@ -270,7 +271,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
List filters = getFilters("/someurl");
expect:
filters.get(1).sessionInformationExpiredStrategy.class.name == 'org.springframework.security.web.session.ConcurrentSessionFilter$ResponseBodySessionInformationExpiredStrategy'
filters.get(1).expiredUrl == null
}
def externalSessionStrategyIsSupported() {
@@ -15,29 +15,29 @@
*/
package org.springframework.security.config.authentication;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.After;
import org.junit.Test;
import org.w3c.dom.Element;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication
.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.authentication.AbstractUserDetailsServiceBeanDefinitionParser;
import org.springframework.security.config.authentication.CachingUserDetailsService;
import org.springframework.security.config.authentication.JdbcUserServiceBeanDefinitionParser;
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.util.FieldUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.w3c.dom.Element;
/**
* @author Ben Alex
* @author Luke Taylor
* @author Eddú Meléndez
*/
public class JdbcUserServiceBeanDefinitionParserTests {
private static String USER_CACHE_XML = "<b:bean id='userCache' class='org.springframework.security.authentication.dao.MockUserCache'/>";
@@ -154,8 +154,8 @@ public class JdbcUserServiceBeanDefinitionParserTests {
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext
.getBean("myUserService");
UserDetails rod = mgr.loadUserByUsername("rod");
assertThat(AuthorityUtils.authorityListToSet(rod.getAuthorities()))
.contains("PREFIX_ROLE_SUPERVISOR");
assertThat(AuthorityUtils.authorityListToSet(rod.getAuthorities()).contains(
"PREFIX_ROLE_SUPERVISOR"));
}
private void setContext(String context) {
@@ -1,183 +0,0 @@
/*
* Copyright 2002-2016 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.core;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class GrantedAuthorityDefaultsJcTests {
@Autowired
FilterChainProxy springSecurityFilterChain;
@Autowired
MessageService messageService;
MockHttpServletRequest request;
MockHttpServletResponse response;
MockFilterChain chain;
@Before
public void setup() {
setup("USER");
request = new MockHttpServletRequest();
request.setMethod("GET");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void doFilter() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void doFilterDenied() throws Exception {
setup("DENIED");
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@Test
public void message() {
messageService.getMessage();
}
@Test
public void jsrMessage() {
messageService.getJsrMessage();
}
@Test(expected = AccessDeniedException.class)
public void messageDenied() {
setup("DENIED");
messageService.getMessage();
}
@Test(expected = AccessDeniedException.class)
public void jsrMessageDenied() {
setup("DENIED");
messageService.getJsrMessage();
}
// SEC-2926
@Test
public void doFilterIsUserInRole() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
chain = new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
assertThat(httpRequest.isUserInRole("USER")).isTrue();
assertThat(httpRequest.isUserInRole("INVALID")).isFalse();
super.doFilter(request, response);
}
};
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
private void setup(String role) {
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password", role);
SecurityContextHolder.getContext().setAuthentication(user);
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true, jsr250Enabled=true)
static class Config extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().access("hasRole('USER')");
}
@Bean
public MessageService messageService() {
return new HelloWorldMessageService();
}
@Bean
public static GrantedAuthorityDefaults grantedAuthorityDefaults() {
return new GrantedAuthorityDefaults("");
}
}
}
@@ -1,146 +0,0 @@
/*
* Copyright 2002-2016 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.core;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class GrantedAuthorityDefaultsXmlTests {
@Autowired
FilterChainProxy springSecurityFilterChain;
@Autowired
MessageService messageService;
MockHttpServletRequest request;
MockHttpServletResponse response;
MockFilterChain chain;
@Before
public void setup() {
setup("USER");
request = new MockHttpServletRequest();
request.setMethod("GET");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void doFilter() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void doFilterDenied() throws Exception {
setup("DENIED");
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@Test
public void message() {
messageService.getMessage();
}
@Test
public void jsrMessage() {
messageService.getJsrMessage();
}
@Test(expected = AccessDeniedException.class)
public void messageDenied() {
setup("DENIED");
messageService.getMessage();
}
@Test(expected = AccessDeniedException.class)
public void jsrMessageDenied() {
setup("DENIED");
messageService.getJsrMessage();
}
// SEC-2926
@Test
public void doFilterIsUserInRole() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
chain = new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
assertThat(httpRequest.isUserInRole("USER")).isTrue();
assertThat(httpRequest.isUserInRole("INVALID")).isFalse();
super.doFilter(request, response);
}
};
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
private void setup(String role) {
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password", role);
SecurityContextHolder.getContext().setAuthentication(user);
}
}
@@ -1,36 +0,0 @@
/*
* Copyright 2002-2016 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.core;
import javax.annotation.security.RolesAllowed;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* @author Rob Winch
*/
public class HelloWorldMessageService implements MessageService {
@PreAuthorize("hasRole('USER')")
public String getMessage() {
return "Hello World";
}
@RolesAllowed("USER")
public String getJsrMessage() {
return "Hello JSR";
}
}
@@ -1,24 +0,0 @@
/*
* Copyright 2002-2016 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.core;
/**
* @author Rob Winch
*/
public interface MessageService {
String getMessage();
String getJsrMessage();
}
@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns:b="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/security"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<http use-expressions="true">
<intercept-url access="hasRole('USER')" pattern="/**" />
<form-login/>
<logout/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="password" authorities="USER"/>
<user name="admin" password="password" authorities="USER,ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
<global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled"/>
<b:bean class="org.springframework.security.config.core.HelloWorldMessageService"/>
<b:bean class="org.springframework.security.config.core.GrantedAuthorityDefaults"
c:rolePrefix=""/>
</b:beans>
+2 -4
View File
@@ -24,16 +24,14 @@ dependencies {
'javax.annotation:jsr250-api:1.0',
"org.aspectj:aspectjrt:$aspectjVersion",
"org.springframework:spring-jdbc:$springVersion",
"org.springframework:spring-tx:$springVersion",
"com.fasterxml.jackson.core:jackson-databind:$jacksonDatavindVersion"
"org.springframework:spring-tx:$springVersion"
included cryptoProject
testCompile "commons-collections:commons-collections:$commonsCollectionsVersion",
"org.springframework:spring-test:$springVersion",
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
powerMockDependencies,
"org.skyscreamer:jsonassert:$jsonassertVersion"
powerMockDependencies
testRuntime "org.hsqldb:hsqldb:$hsqlVersion"
}
+1 -26
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-core</name>
<description>spring-security-core</description>
<url>http://spring.io/spring-security</url>
@@ -79,13 +79,6 @@
<artifactId>spring-expression</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.4</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
@@ -258,18 +251,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.3.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>mockito-all</artifactId>
<groupId>org.mockito</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
@@ -294,12 +275,6 @@
</exclusions>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
@@ -66,7 +66,7 @@ public class DefaultMethodSecurityExpressionHandler extends
*/
public StandardEvaluationContext createEvaluationContextInternal(Authentication auth,
MethodInvocation mi) {
return new MethodSecurityEvaluationContext(auth, mi, getParameterNameDiscoverer());
return new MethodSecurityEvaluationContext(auth, mi, parameterNameDiscoverer);
}
/**
@@ -78,9 +78,9 @@ public class DefaultMethodSecurityExpressionHandler extends
authentication);
root.setThis(invocation.getThis());
root.setPermissionEvaluator(getPermissionEvaluator());
root.setTrustResolver(getTrustResolver());
root.setTrustResolver(trustResolver);
root.setRoleHierarchy(getRoleHierarchy());
root.setDefaultRolePrefix(getDefaultRolePrefix());
root.setDefaultRolePrefix(defaultRolePrefix);
return root;
}
@@ -189,13 +189,6 @@ public class DefaultMethodSecurityExpressionHandler extends
this.trustResolver = trustResolver;
}
/**
* @return The current {@link AuthenticationTrustResolver}
*/
protected AuthenticationTrustResolver getTrustResolver() {
return trustResolver;
}
/**
* Sets the {@link ParameterNameDiscoverer} to use. The default is
* {@link DefaultSecurityParameterNameDiscoverer}.
@@ -205,13 +198,6 @@ public class DefaultMethodSecurityExpressionHandler extends
this.parameterNameDiscoverer = parameterNameDiscoverer;
}
/**
* @return The current {@link ParameterNameDiscoverer}
*/
protected ParameterNameDiscoverer getParameterNameDiscoverer() {
return parameterNameDiscoverer;
}
public void setPermissionCacheOptimizer(
PermissionCacheOptimizer permissionCacheOptimizer) {
this.permissionCacheOptimizer = permissionCacheOptimizer;
@@ -239,11 +225,4 @@ public class DefaultMethodSecurityExpressionHandler extends
public void setDefaultRolePrefix(String defaultRolePrefix) {
this.defaultRolePrefix = defaultRolePrefix;
}
/**
* @return The default role prefix
*/
protected String getDefaultRolePrefix() {
return defaultRolePrefix;
}
}
@@ -1,69 +0,0 @@
/*
* Copyright 2012-2016 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.access.hierarchicalroles;
import org.springframework.util.Assert;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
/**
* Utility methods for {@link RoleHierarchy}.
*
* @author Thomas Darimont
* @since 4.2.0
*/
public final class RoleHierarchyUtils {
private RoleHierarchyUtils() {
}
/**
* Converts the supplied {@link Map} of role name to implied role name(s) to a string
* representation understood by {@link RoleHierarchyImpl#setHierarchy(String)}.
* The map key is the role name and the map value is a {@link List} of implied role name(s).
*
* @param roleHierarchyMap the mapping(s) of role name to implied role name(s)
* @return a string representation of a role hierarchy
* @throws IllegalArgumentException if roleHierarchyMap is null or empty or if a role name is null or
* empty or if an implied role name(s) is null or empty
*
*/
public static String roleHierarchyFromMap(Map<String, List<String>> roleHierarchyMap) {
Assert.notEmpty(roleHierarchyMap, "roleHierarchyMap cannot be empty");
StringWriter roleHierarchyBuffer = new StringWriter();
PrintWriter roleHierarchyWriter = new PrintWriter(roleHierarchyBuffer);
for (Map.Entry<String, List<String>> roleHierarchyEntry : roleHierarchyMap.entrySet()) {
String role = roleHierarchyEntry.getKey();
List<String> impliedRoles = roleHierarchyEntry.getValue();
Assert.hasLength(role, "role name must be supplied");
Assert.notEmpty(impliedRoles, "implied role name(s) cannot be empty");
for (String impliedRole : impliedRoles) {
String roleMapping = role + " > " + impliedRole;
roleHierarchyWriter.println(roleMapping);
}
}
return roleHierarchyBuffer.toString();
}
}
@@ -40,8 +40,8 @@ public abstract class AbstractAuthenticationToken implements Authentication,
// ~ Instance fields
// ================================================================================================
private final Collection<GrantedAuthority> authorities;
private Object details;
private final Collection<GrantedAuthority> authorities;
private boolean authenticated = false;
// ~ Constructors
@@ -51,7 +51,7 @@ public abstract class AbstractAuthenticationToken implements Authentication,
* Creates a token with the supplied array of authorities.
*
* @param authorities the collection of <tt>GrantedAuthority</tt>s for the principal
* represented by this authentication object.
* represented by this authentication object.
*/
public AbstractAuthenticationToken(Collection<? extends GrantedAuthority> authorities) {
if (authorities == null) {
@@ -215,7 +215,8 @@ public abstract class AbstractAuthenticationToken implements Authentication,
sb.append(authority);
}
} else {
}
else {
sb.append("Not granted any authorities");
}
@@ -20,7 +20,6 @@ import java.io.Serializable;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;
/**
* Represents an anonymous <code>Authentication</code>.
@@ -42,34 +41,24 @@ public class AnonymousAuthenticationToken extends AbstractAuthenticationToken im
/**
* Constructor.
*
* @param key to identify if this object made by an authorised client
* @param principal the principal (typically a <code>UserDetails</code>)
* @param key to identify if this object made by an authorised client
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
*
* @throws IllegalArgumentException if a <code>null</code> was passed
*/
public AnonymousAuthenticationToken(String key, Object principal,
Collection<? extends GrantedAuthority> authorities) {
this(extractKeyHash(key), principal, authorities);
}
/**
* Constructor helps in Jackson Deserialization
*
* @param keyHash hashCode of provided Key, constructed by above constructor
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
* @since 4.2
*/
private AnonymousAuthenticationToken(Integer keyHash, Object principal,
Collection<? extends GrantedAuthority> authorities) {
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
if (principal == null || "".equals(principal)) {
throw new IllegalArgumentException("principal cannot be null or empty");
if ((key == null) || ("".equals(key)) || (principal == null)
|| "".equals(principal) || (authorities == null)
|| (authorities.isEmpty())) {
throw new IllegalArgumentException(
"Cannot pass null or empty values to constructor");
}
Assert.notEmpty(authorities, "authorities cannot be null or empty");
this.keyHash = keyHash;
this.keyHash = key.hashCode();
this.principal = principal;
setAuthenticated(true);
}
@@ -77,11 +66,6 @@ public class AnonymousAuthenticationToken extends AbstractAuthenticationToken im
// ~ Methods
// ========================================================================================================
private static Integer extractKeyHash(String key) {
Assert.hasLength(key, "key cannot be empty or null");
return key.hashCode();
}
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
@@ -46,13 +46,14 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken {
/**
* Constructor.
*
* @param key to identify if this object made by an authorised client
* @param principal the principal (typically a <code>UserDetails</code>)
* @param key to identify if this object made by an authorised client
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
*
* @throws IllegalArgumentException if a <code>null</code> was passed
*/
public RememberMeAuthenticationToken(String key, Object principal,
Collection<? extends GrantedAuthority> authorities) {
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
if ((key == null) || ("".equals(key)) || (principal == null)
@@ -66,22 +67,6 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken {
setAuthenticated(true);
}
/**
* Private Constructor to help in Jackson deserialization.
*
* @param keyHash hashCode of above given key.
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
* @since 4.2
*/
private RememberMeAuthenticationToken(Integer keyHash, Object principal, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.keyHash = keyHash;
this.principal = principal;
setAuthenticated(true);
}
// ~ Methods
// ========================================================================================================
@@ -38,7 +38,7 @@ 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 = 420L;
public static final long SERIAL_VERSION_UID = 410L;
static final String MIN_SPRING_VERSION = "4.3.2.RELEASE";
@@ -24,8 +24,6 @@ import java.util.List;
import java.util.Set;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
@@ -110,8 +108,7 @@ import org.springframework.util.Assert;
* @author colin sampaleanu
* @author Luke Taylor
*/
public class JdbcDaoImpl extends JdbcDaoSupport
implements UserDetailsService, MessageSourceAware {
public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
// ~ Static fields/initializers
// =====================================================================================
@@ -127,7 +124,8 @@ public class JdbcDaoImpl extends JdbcDaoSupport
// ~ Instance fields
// ================================================================================================
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
protected final MessageSourceAccessor messages = SpringSecurityMessageSource
.getAccessor();
private String authoritiesByUsernameQuery;
private String groupAuthoritiesByUsernameQuery;
@@ -149,13 +147,6 @@ public class JdbcDaoImpl extends JdbcDaoSupport
// ~ Methods
// ========================================================================================================
/**
* @return the messages
*/
protected MessageSourceAccessor getMessages() {
return this.messages;
}
/**
* Allows subclasses to add their own granted authorities to the list to be returned
* in the <tt>UserDetails</tt>.
@@ -178,7 +169,6 @@ public class JdbcDaoImpl extends JdbcDaoSupport
"Use of either authorities or groups must be enabled");
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
List<UserDetails> users = loadUsersByUsername(username);
@@ -226,7 +216,6 @@ public class JdbcDaoImpl extends JdbcDaoSupport
protected List<UserDetails> loadUsersByUsername(String username) {
return getJdbcTemplate().query(this.usersByUsernameQuery,
new String[] { username }, new RowMapper<UserDetails>() {
@Override
public UserDetails mapRow(ResultSet rs, int rowNum)
throws SQLException {
String username = rs.getString(1);
@@ -247,7 +236,6 @@ public class JdbcDaoImpl extends JdbcDaoSupport
protected List<GrantedAuthority> loadUserAuthorities(String username) {
return getJdbcTemplate().query(this.authoritiesByUsernameQuery,
new String[] { username }, new RowMapper<GrantedAuthority>() {
@Override
public GrantedAuthority mapRow(ResultSet rs, int rowNum)
throws SQLException {
String roleName = JdbcDaoImpl.this.rolePrefix + rs.getString(2);
@@ -266,7 +254,6 @@ public class JdbcDaoImpl extends JdbcDaoSupport
protected List<GrantedAuthority> loadGroupAuthorities(String username) {
return getJdbcTemplate().query(this.groupAuthoritiesByUsernameQuery,
new String[] { username }, new RowMapper<GrantedAuthority>() {
@Override
public GrantedAuthority mapRow(ResultSet rs, int rowNum)
throws SQLException {
String roleName = getRolePrefix() + rs.getString(3);
@@ -406,10 +393,4 @@ public class JdbcDaoImpl extends JdbcDaoSupport
public void setEnableGroups(boolean enableGroups) {
this.enableGroups = enableGroups;
}
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
}
@@ -1,59 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
/**
* This is a Jackson mixin class helps in serialize/deserialize
* {@link org.springframework.security.authentication.AnonymousAuthenticationToken} class. To use this class you need to register it
* with {@link com.fasterxml.jackson.databind.ObjectMapper} and {@link SimpleGrantedAuthorityMixin} because
* AnonymousAuthenticationToken contains SimpleGrantedAuthority.
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
*
* <i>Note: This class will save full class name into a property called @class</i>
*
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, isGetterVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.ANY)
@JsonIgnoreProperties(ignoreUnknown = true)
class AnonymousAuthenticationTokenMixin {
/**
* Constructor used by Jackson to create object of {@link org.springframework.security.authentication.AnonymousAuthenticationToken}.
*
* @param keyHash hashCode of key provided at the time of token creation by using
* {@link org.springframework.security.authentication.AnonymousAuthenticationToken#AnonymousAuthenticationToken(String, Object, Collection)}
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
*/
@JsonCreator
public AnonymousAuthenticationTokenMixin(@JsonProperty("keyHash") Integer keyHash, @JsonProperty("principal") Object principal,
@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities) {
}
}
@@ -1,63 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collections;
/**
* Jackson module for spring-security-core. This module register {@link AnonymousAuthenticationTokenMixin},
* {@link RememberMeAuthenticationTokenMixin}, {@link SimpleGrantedAuthorityMixin}, {@link UnmodifiableSetMixin},
* {@link UserMixin} and {@link UsernamePasswordAuthenticationTokenMixin}. If no default typing enabled by default then
* it'll enable it because typing info is needed to properly serialize/deserialize objects. In order to use this module just
* add this module into your ObjectMapper configuration.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
* <b>Note: use {@link SecurityJacksonModules#getModules(ClassLoader)} to get list of all security modules.</b>
*
* @author Jitendra Singh.
* @see SecurityJacksonModules
* @since 4.2
*/
public class CoreJackson2Module extends SimpleModule {
public CoreJackson2Module() {
super(CoreJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null));
}
@Override
public void setupModule(SetupContext context) {
SecurityJacksonModules.enableDefaultTyping((ObjectMapper) context.getOwner());
context.setMixInAnnotations(AnonymousAuthenticationToken.class, AnonymousAuthenticationTokenMixin.class);
context.setMixInAnnotations(RememberMeAuthenticationToken.class, RememberMeAuthenticationTokenMixin.class);
context.setMixInAnnotations(SimpleGrantedAuthority.class, SimpleGrantedAuthorityMixin.class);
context.setMixInAnnotations(Collections.<Object>unmodifiableSet(Collections.emptySet()).getClass(), UnmodifiableSetMixin.class);
context.setMixInAnnotations(User.class, UserMixin.class);
context.setMixInAnnotations(UsernamePasswordAuthenticationToken.class, UsernamePasswordAuthenticationTokenMixin.class);
}
}
@@ -1,66 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
/**
* This mixin class helps in serialize/deserialize
* {@link org.springframework.security.authentication.RememberMeAuthenticationToken} class. To use this class you need to register it
* with {@link com.fasterxml.jackson.databind.ObjectMapper} and 2 more mixin classes.
*
* <ol>
* <li>{@link SimpleGrantedAuthorityMixin}</li>
* <li>{@link UserMixin}</li>
* <li>{@link UnmodifiableSetMixin}</li>
* </ol>
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
*
* <i>Note: This class will save TypeInfo (full class name) into a property called @class</i>
*
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.ANY)
@JsonIgnoreProperties(ignoreUnknown = true)
class RememberMeAuthenticationTokenMixin {
/**
* Constructor used by Jackson to create
* {@link org.springframework.security.authentication.RememberMeAuthenticationToken} object.
*
* @param keyHash hashCode of above given key.
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
*/
@JsonCreator
public RememberMeAuthenticationTokenMixin(@JsonProperty("keyHash") Integer keyHash,
@JsonProperty("principal") Object principal,
@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities) {
}
}
@@ -1,106 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ClassUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* This utility class will find all the SecurityModules in classpath.
*
* <p>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModules(SecurityJacksonModules.getModules());
* </pre>
* Above code is equivalent to
* <p>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
* mapper.registerModule(new CoreJackson2Module());
* mapper.registerModule(new CasJackson2Module());
* mapper.registerModule(new WebJackson2Module());
* </pre>
*
* @author Jitendra Singh.
* @since 4.2
*/
public final class SecurityJacksonModules {
private static final Log logger = LogFactory.getLog(SecurityJacksonModules.class);
private static final List<String> securityJackson2ModuleClasses = Arrays.asList(
"org.springframework.security.jackson2.CoreJackson2Module",
"org.springframework.security.cas.jackson2.CasJackson2Module",
"org.springframework.security.web.jackson2.WebJackson2Module"
);
private SecurityJacksonModules() {
}
public static void enableDefaultTyping(ObjectMapper mapper) {
if(mapper != null) {
TypeResolverBuilder<?> typeBuilder = mapper.getDeserializationConfig().getDefaultTyper(null);
if (typeBuilder == null) {
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
}
}
}
@SuppressWarnings("unchecked")
private static Module loadAndGetInstance(String className, ClassLoader loader) {
Module instance = null;
try {
Class<? extends Module> securityModule = (Class<? extends Module>) ClassUtils.forName(className, loader);
if (securityModule != null) {
if(logger.isDebugEnabled()) {
logger.debug("Loaded module " + className + ", now registering");
}
instance = securityModule.newInstance();
}
} catch (Exception e) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot load module " + className, e);
}
}
return instance;
}
/**
* @param loader the ClassLoader to use
* @return List of available security modules in classpath.
*/
public static List<Module> getModules(ClassLoader loader) {
List<Module> modules = new ArrayList<Module>();
for (String className : securityJackson2ModuleClasses) {
Module module = loadAndGetInstance(className, loader);
if (module != null) {
modules.add(module);
}
}
return modules;
}
}
@@ -1,47 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.annotation.*;
/**
* Jackson Mixin class helps in serialize/deserialize
* {@link org.springframework.security.core.authority.SimpleGrantedAuthority}.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class SimpleGrantedAuthorityMixin {
/**
* Mixin Constructor.
* @param role the role
*/
@JsonCreator
public SimpleGrantedAuthorityMixin(@JsonProperty("authority") String role) {
}
}
@@ -1,47 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.Set;
/**
* This mixin class used to deserialize java.util.Collections$UnmodifiableSet and used with various AuthenticationToken
* implementation's mixin classes.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
class UnmodifiableSetMixin {
/**
* Mixin Constructor
* @param s the Set
*/
@JsonCreator
UnmodifiableSetMixin(Set<?> s) {}
}
@@ -1,78 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.io.IOException;
import java.util.Set;
/**
* Custom Deserializer for {@link User} class. This is already registered with {@link UserMixin}.
* You can also use it directly with your mixin class.
*
* @author Jitendra Singh
* @see UserMixin
* @since 4.2
*/
class UserDeserializer extends JsonDeserializer<User> {
/**
* This method will create {@link User} object. It will ensure successful object creation even if password key is null in
* serialized json, because credentials may be removed from the {@link User} by invoking {@link User#eraseCredentials()}.
* In that case there won't be any password key in serialized json.
*
* @param jp the JsonParser
* @param ctxt the DeserializationContext
* @return the user
* @throws IOException if a exception during IO occurs
* @throws JsonProcessingException if an error during JSON processing occurs
*/
@Override
public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
JsonNode jsonNode = mapper.readTree(jp);
Set<GrantedAuthority> authorities = mapper.convertValue(jsonNode.get("authorities"), new TypeReference<Set<SimpleGrantedAuthority>>() {
});
JsonNode password = readJsonNode(jsonNode, "password");
User result = new User(
readJsonNode(jsonNode, "username").asText(), password.asText(""),
readJsonNode(jsonNode, "enabled").asBoolean(), readJsonNode(jsonNode, "accountNonExpired").asBoolean(),
readJsonNode(jsonNode, "credentialsNonExpired").asBoolean(),
readJsonNode(jsonNode, "accountNonLocked").asBoolean(), authorities
);
if(password.asText(null) == null) {
result.eraseCredentials();
}
return result;
}
private JsonNode readJsonNode(JsonNode jsonNode, String field) {
return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance();
}
}
@@ -1,49 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* This mixin class helps in serialize/deserialize {@link org.springframework.security.core.userdetails.User}.
* This class also register a custom deserializer {@link UserDeserializer} to deserialize User object successfully.
* In order to use this mixin you need to register two more mixin classes in your ObjectMapper configuration.
* <ol>
* <li>{@link SimpleGrantedAuthorityMixin}</li>
* <li>{@link UnmodifiableSetMixin}</li>
* </ol>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @see UserDeserializer
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonDeserialize(using = UserDeserializer.class)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class UserMixin {
}
@@ -1,85 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.io.IOException;
import java.util.List;
/**
* Custom deserializer for {@link UsernamePasswordAuthenticationToken}. At the time of deserialization
* it will invoke suitable constructor depending on the value of <b>authenticated</b> property.
* It will ensure that the token's state must not change.
* <p>
* This deserializer is already registered with {@link UsernamePasswordAuthenticationTokenMixin} but
* you can also registered it with your own mixin class.
*
* @author Jitendra Singh
* @see UsernamePasswordAuthenticationTokenMixin
* @since 4.2
*/
class UsernamePasswordAuthenticationTokenDeserializer extends JsonDeserializer<UsernamePasswordAuthenticationToken> {
/**
* This method construct {@link UsernamePasswordAuthenticationToken} object from serialized json.
* @param jp the JsonParser
* @param ctxt the DeserializationContext
* @return the user
* @throws IOException if a exception during IO occurs
* @throws JsonProcessingException if an error during JSON processing occurs
*/
@Override
public UsernamePasswordAuthenticationToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
UsernamePasswordAuthenticationToken token = null;
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
JsonNode jsonNode = mapper.readTree(jp);
Boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean();
JsonNode principalNode = readJsonNode(jsonNode, "principal");
Object principal = null;
if(principalNode.isObject()) {
principal = mapper.readValue(principalNode.toString(), new TypeReference<User>() {});
} else {
principal = principalNode.asText();
}
Object credentials = readJsonNode(jsonNode, "credentials").asText();
List<GrantedAuthority> authorities = mapper.readValue(
readJsonNode(jsonNode, "authorities").toString(), new TypeReference<List<GrantedAuthority>>() {
});
if (authenticated) {
token = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
} else {
token = new UsernamePasswordAuthenticationToken(principal, credentials);
}
token.setDetails(readJsonNode(jsonNode, "details"));
return token;
}
private JsonNode readJsonNode(JsonNode jsonNode, String field) {
return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance();
}
}
@@ -1,48 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* This mixin class is used to serialize / deserialize
* {@link org.springframework.security.authentication.UsernamePasswordAuthenticationToken}. This class register
* a custom deserializer {@link UsernamePasswordAuthenticationTokenDeserializer}.
*
* In order to use this mixin you'll need to add 3 more mixin classes.
* <ol>
* <li>{@link UnmodifiableSetMixin}</li>
* <li>{@link SimpleGrantedAuthorityMixin}</li>
* <li>{@link UserMixin}</li>
* </ol>
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonDeserialize(using = UsernamePasswordAuthenticationTokenDeserializer.class)
abstract class UsernamePasswordAuthenticationTokenMixin {
}
@@ -1,26 +0,0 @@
/*
* Copyright 2002-2016 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.
*/
/**
* Mix-in classes to add Jackson serialization support.
*
* @author Jitendra Singh
* @since 4.2
*/
package org.springframework.security.jackson2;
/**
* Package contains Jackson mixin classes.
*/
@@ -1,87 +0,0 @@
/*
* Copyright 2012-2016 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.access.hierarchicalroles;
import org.junit.Test;
import java.util.*;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link RoleHierarchyUtils}.
*
* @author Joe Grandja
*/
public class RoleHierarchyUtilsTests {
@Test
public void roleHierarchyFromMapWhenMapValidThenConvertsCorrectly() throws Exception {
String expectedRoleHierarchy = "ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_B > ROLE_D\nROLE_C > ROLE_D\n";
Map<String, List<String>> roleHierarchyMap = new TreeMap<String, List<String>>();
roleHierarchyMap.put("ROLE_A", asList("ROLE_B", "ROLE_C"));
roleHierarchyMap.put("ROLE_B", asList("ROLE_D"));
roleHierarchyMap.put("ROLE_C", asList("ROLE_D"));
String roleHierarchy = RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
assertThat(roleHierarchy).isEqualTo(expectedRoleHierarchy);
}
@Test(expected = IllegalArgumentException.class)
public void roleHierarchyFromMapWhenMapNullThenThrowsIllegalArgumentException() throws Exception {
RoleHierarchyUtils.roleHierarchyFromMap(null);
}
@Test(expected = IllegalArgumentException.class)
public void roleHierarchyFromMapWhenMapEmptyThenThrowsIllegalArgumentException() throws Exception {
RoleHierarchyUtils.roleHierarchyFromMap(Collections.<String, List<String>>emptyMap());
}
@Test(expected = IllegalArgumentException.class)
public void roleHierarchyFromMapWhenRoleNullThenThrowsIllegalArgumentException() throws Exception {
Map<String, List<String>> roleHierarchyMap = new HashMap<String, List<String>>();
roleHierarchyMap.put(null, asList("ROLE_B", "ROLE_C"));
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
}
@Test(expected = IllegalArgumentException.class)
public void roleHierarchyFromMapWhenRoleEmptyThenThrowsIllegalArgumentException() throws Exception {
Map<String, List<String>> roleHierarchyMap = new HashMap<String, List<String>>();
roleHierarchyMap.put("", asList("ROLE_B", "ROLE_C"));
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
}
@Test(expected = IllegalArgumentException.class)
public void roleHierarchyFromMapWhenImpliedRolesNullThenThrowsIllegalArgumentException() throws Exception {
Map<String, List<String>> roleHierarchyMap = new HashMap<String, List<String>>();
roleHierarchyMap.put("ROLE_A", null);
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
}
@Test(expected = IllegalArgumentException.class)
public void roleHierarchyFromMapWhenImpliedRolesEmptyThenThrowsIllegalArgumentException() throws Exception {
Map<String, List<String>> roleHierarchyMap = new HashMap<String, List<String>>();
roleHierarchyMap.put("ROLE_A", Collections.<String>emptyList());
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
}
}
@@ -72,8 +72,10 @@ public class UsernamePasswordAuthenticationTokenTests {
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("Password");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_ONE");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_TWO");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_ONE"));
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_TWO"));
}
@Test(expected = NoSuchMethodException.class)
@@ -19,7 +19,6 @@ package org.springframework.security.authentication.anonymous;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
@@ -147,19 +146,4 @@ public class AnonymousAuthenticationTokenTests {
token.setAuthenticated(false);
assertThat(!token.isAuthenticated()).isTrue();
}
@Test(expected = IllegalArgumentException.class)
public void constructorWhenNullAuthoritiesThenThrowIllegalArgumentException() throws Exception {
new AnonymousAuthenticationToken("key", "principal", null);
}
@Test(expected = IllegalArgumentException.class)
public void constructorWhenEmptyAuthoritiesThenThrowIllegalArgumentException() throws Exception {
new AnonymousAuthenticationToken("key", "principal", Collections.<GrantedAuthority>emptyList());
}
@Test(expected = IllegalArgumentException.class)
public void constructorWhenPrincipalIsEmptyStringThenThrowIllegalArgumentException() throws Exception {
new AnonymousAuthenticationToken("key", "", ROLES_12);
}
}
@@ -89,7 +89,8 @@ public class RemoteAuthenticationProviderTests {
.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
assertThat(result.getPrincipal()).isEqualTo("rod");
assertThat(result.getCredentials()).isEqualTo("password");
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains("foo");
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())
.contains("foo"));
}
@Test
@@ -86,8 +86,10 @@ public class RememberMeAuthenticationTokenTests {
assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_ONE");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_TWO");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_ONE"));
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_TWO"));
assertThat(token.isAuthenticated()).isTrue();
}
@@ -16,28 +16,19 @@
package org.springframework.security.core.userdetails.jdbc;
import java.util.Locale;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.context.MessageSource;
import org.springframework.security.PopulatedDatabase;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests {@link JdbcDaoImpl}.
*
* @author Ben Alex
* @author Eddú Meléndez
*/
public class JdbcDaoImplTests {
@@ -69,20 +60,19 @@ public class JdbcDaoImplTests {
assertThat(user.getPassword()).isEqualTo("koala");
assertThat(user.isEnabled()).isTrue();
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()))
.contains("ROLE_TELLER");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()))
.contains("ROLE_SUPERVISOR");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_TELLER"));
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_SUPERVISOR"));
}
@Test
public void testCheckDaoOnlyReturnsGrantedAuthoritiesGrantedToUser()
throws Exception {
public void testCheckDaoOnlyReturnsGrantedAuthoritiesGrantedToUser() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
UserDetails user = dao.loadUserByUsername("scott");
assertThat(user.getAuthorities()).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()))
.contains("ROLE_TELLER");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_TELLER"));
}
@Test
@@ -143,10 +133,10 @@ public class JdbcDaoImplTests {
assertThat(user.getUsername()).isEqualTo("rod");
assertThat(user.getAuthorities()).hasSize(2);
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()))
.contains("ARBITRARY_PREFIX_ROLE_TELLER");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()))
.contains("ARBITRARY_PREFIX_ROLE_SUPERVISOR");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ARBITRARY_PREFIX_ROLE_TELLER"));
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ARBITRARY_PREFIX_ROLE_SUPERVISOR"));
}
@Test
@@ -195,23 +185,4 @@ public class JdbcDaoImplTests {
}
}
@Test(expected = IllegalArgumentException.class)
public void setMessageSourceWhenNullThenThrowsException() throws Exception {
JdbcDaoImpl dao = new JdbcDaoImpl();
dao.setMessageSource(null);
}
@Test
public void setMessageSourceWhenNotNullThenCanGet() throws Exception {
MessageSource source = mock(MessageSource.class);
JdbcDaoImpl dao = new JdbcDaoImpl();
dao.setMessageSource(source);
String code = "code";
dao.getMessages().getMessage(code);
verify(source).getMessage(eq(code), any(Object[].class), any(Locale.class));
}
}
@@ -1,46 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
/**
* @author Jitenra Singh
* @since 4.2
*/
public abstract class AbstractMixinTests {
protected ObjectMapper mapper;
@Before
public void setup() {
mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(SecurityJacksonModules.getModules(loader));
}
User createDefaultUser() {
return createUser("admin", "1234", "ROLE_USER");
}
User createUser(String username, String password, String authority) {
return new User(username, password, AuthorityUtils.createAuthorityList(authority));
}
}
@@ -1,89 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
private static final String HASH_KEY = "key";
// @formatter:off
private static final String ANONYMOUS_JSON = "{"
+ "\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", "
+ "\"details\": null,"
+ "\"principal\": " + UserDeserializerTests.USER_JSON + ","
+ "\"authenticated\": true, "
+ "\"keyHash\": " + HASH_KEY.hashCode() + ","
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}";
// @formatter:on
@Test
public void serializeAnonymousAuthenticationTokenTest() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(
HASH_KEY, user, user.getAuthorities()
);
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(ANONYMOUS_JSON, actualJson, true);
}
@Test
public void deserializeAnonymousAuthenticationTokenTest() throws IOException {
AnonymousAuthenticationToken token = mapper
.readValue(ANONYMOUS_JSON, AnonymousAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getKeyHash()).isEqualTo(HASH_KEY.hashCode());
assertThat(token.getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}
@Test(expected = JsonMappingException.class)
public void deserializeAnonymousAuthenticationTokenWithoutAuthoritiesTest() throws IOException {
String jsonString = "{\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", \"details\": null," +
"\"principal\": \"user\", \"authenticated\": true, \"keyHash\": " + HASH_KEY.hashCode() + "," +
"\"authorities\": [\"java.util.ArrayList\", []]}";
mapper.readValue(jsonString, AnonymousAuthenticationToken.class);
}
@Test
public void serializeAnonymousAuthenticationTokenMixinAfterEraseCredentialTest() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(
HASH_KEY, user, user.getAuthorities()
);
token.eraseCredentials();
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(ANONYMOUS_JSON.replace(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true);
}
}
@@ -1,116 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.io.IOException;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests {
private static final String REMEMBERME_KEY = "rememberMe";
// @formatter:off
private static final String REMEMBERME_AUTH_JSON = "{"
+ "\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\", "
+ "\"keyHash\": " + REMEMBERME_KEY.hashCode() + ", "
+ "\"authenticated\": true, \"details\": null" + ", "
+ "\"principal\": " + UserDeserializerTests.USER_JSON + ", "
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}";
// @formatter:on
// @formatter:off
private static final String REMEMBERME_AUTH_STRINGPRINCIPAL_JSON = "{"
+ "\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\","
+ "\"keyHash\": " + REMEMBERME_KEY.hashCode() + ", "
+ "\"authenticated\": true, "
+ "\"details\": null,"
+ "\"principal\": \"admin\", "
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}";
// @formatter:on
@Test(expected = IllegalArgumentException.class)
public void testWithNullPrincipal() throws JsonProcessingException, JSONException {
new RememberMeAuthenticationToken("key", null, Collections.<GrantedAuthority>emptyList());
}
@Test(expected = IllegalArgumentException.class)
public void testWithNullKey() throws JsonProcessingException, JSONException {
new RememberMeAuthenticationToken(null, "principal", Collections.<GrantedAuthority>emptyList());
}
@Test
public void serializeRememberMeAuthenticationToken() throws JsonProcessingException, JSONException {
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, "admin", Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")));
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON, actualJson, true);
}
@Test
public void serializeRememberMeAuthenticationWithUserToken() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user, user.getAuthorities());
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(String.format(REMEMBERME_AUTH_JSON, "\"password\""), actualJson, true);
}
@Test
public void serializeRememberMeAuthenticationWithUserTokenAfterEraseCredential() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user, user.getAuthorities());
token.eraseCredentials();
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(REMEMBERME_AUTH_JSON.replace(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true);
}
@Test
public void deserializeRememberMeAuthenticationToken() throws IOException {
RememberMeAuthenticationToken token = mapper.readValue(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON, RememberMeAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isEqualTo("admin").isEqualTo(token.getName());
assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}
@Test
public void deserializeRememberMeAuthenticationTokenWithUserTest() throws IOException {
RememberMeAuthenticationToken token = mapper
.readValue(String.format(REMEMBERME_AUTH_JSON, "\"password\""), RememberMeAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
assertThat(((User)token.getPrincipal()).getUsername()).isEqualTo("admin");
assertThat(((User)token.getPrincipal()).getPassword()).isEqualTo("1234");
assertThat(((User) token.getPrincipal()).getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
assertThat(((User) token.getPrincipal()).isEnabled()).isEqualTo(true);
}
}
@@ -1,64 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import java.io.IOException;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
public class SecurityContextMixinTests extends AbstractMixinTests {
// @formatter:off
public static final String SECURITY_CONTEXT_JSON = "{"
+ "\"@class\": \"org.springframework.security.core.context.SecurityContextImpl\", "
+ "\"authentication\": " + UsernamePasswordAuthenticationTokenMixinTests.AUTHENTICATED_STRINGPRINCIPAL_JSON
+ "}";
// @formatter:on
@Test
public void securityContextSerializeTest() throws JsonProcessingException, JSONException {
SecurityContext context = new SecurityContextImpl();
context.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "1234", Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"))));
String actualJson = mapper.writeValueAsString(context);
JSONAssert.assertEquals(SECURITY_CONTEXT_JSON, actualJson, true);
}
@Test
public void securityContextDeserializeTest() throws IOException {
SecurityContext context = mapper.readValue(SECURITY_CONTEXT_JSON, SecurityContextImpl.class);
assertThat(context).isNotNull();
assertThat(context.getAuthentication()).isNotNull().isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isEqualTo("admin");
assertThat(context.getAuthentication().getCredentials()).isEqualTo("1234");
assertThat(context.getAuthentication().isAuthenticated()).isTrue();
assertThat(context.getAuthentication().getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}
}
@@ -1,67 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.io.IOException;
import static org.assertj.core.api.Assertions.*;
/**
* @author Jitendra Singh
* @since 4.2
*/
public class SimpleGrantedAuthorityMixinTests extends AbstractMixinTests {
// @formatter:off
public static final String AUTHORITY_JSON = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"authority\": \"ROLE_USER\"}";
public static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.ArrayList\", [" + AUTHORITY_JSON + "]]";
public static final String AUTHORITIES_SET_JSON = "[\"java.util.Collections$UnmodifiableSet\", [" + AUTHORITY_JSON + "]]";
public static final String NO_AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.ArrayList\", []]";
public static final String NO_AUTHORITIES_SET_JSON = "[\"java.util.Collections$UnmodifiableSet\", []]";
// @formatter:on
@Test
public void serializeSimpleGrantedAuthorityTest() throws JsonProcessingException, JSONException {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
String serializeJson = mapper.writeValueAsString(authority);
JSONAssert.assertEquals(AUTHORITY_JSON, serializeJson, true);
}
@Test
public void deserializeGrantedAuthorityTest() throws IOException {
SimpleGrantedAuthority authority = mapper.readValue(AUTHORITY_JSON, SimpleGrantedAuthority.class);
assertThat(authority).isNotNull();
assertThat(authority.getAuthority()).isNotNull().isEqualTo("ROLE_USER");
}
@Test(expected = JsonMappingException.class)
public void deserializeGrantedAuthorityWithoutRoleTest() throws IOException {
String json = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"}";
mapper.readValue(json, SimpleGrantedAuthority.class);
}
}
@@ -1,124 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import java.io.IOException;
import java.util.Collections;
import java.util.regex.Pattern;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
public class UserDeserializerTests extends AbstractMixinTests {
public static final String USER_PASSWORD = "\"1234\"";
// @formatter:off
public static final String USER_JSON = "{"
+ "\"@class\": \"org.springframework.security.core.userdetails.User\", "
+ "\"username\": \"admin\","
+ " \"password\": "+ USER_PASSWORD +", "
+ "\"accountNonExpired\": true, "
+ "\"accountNonLocked\": true, "
+ "\"credentialsNonExpired\": true, "
+ "\"enabled\": true, "
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON
+ "}";
// @formatter:on
@Test
public void serializeUserTest() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
String userJson = mapper.writeValueAsString(user);
JSONAssert.assertEquals(userWithPasswordJson(user.getPassword()), userJson, true);
}
@Test
public void serializeUserWithoutAuthority() throws JsonProcessingException, JSONException {
User user = new User("admin", "1234", Collections.<GrantedAuthority>emptyList());
String userJson = mapper.writeValueAsString(user);
JSONAssert.assertEquals(userWithNoAuthoritiesJson(), userJson, true);
}
@Test(expected = IllegalArgumentException.class)
public void deserializeUserWithNullPasswordEmptyAuthorityTest() throws IOException {
String userJsonWithoutPasswordString = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON, "[]");
mapper.readValue(userJsonWithoutPasswordString, User.class);
}
@Test
public void deserializeUserWithNullPasswordNoAuthorityTest() throws Exception {
String userJsonWithoutPasswordString = removeNode(userWithNoAuthoritiesJson(), mapper, "password");
User user = mapper.readValue(userJsonWithoutPasswordString, User.class);
assertThat(user).isNotNull();
assertThat(user.getUsername()).isEqualTo("admin");
assertThat(user.getPassword()).isNull();
assertThat(user.getAuthorities()).isEmpty();
assertThat(user.isEnabled()).isEqualTo(true);
}
@Test(expected = IllegalArgumentException.class)
public void deserializeUserWithNoClassIdInAuthoritiesTest() throws Exception {
String userJson = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON, "[{\"authority\": \"ROLE_USER\"}]");
mapper.readValue(userJson, User.class);
}
@Test
public void deserializeUserWithClassIdInAuthoritiesTest() throws IOException {
User user = mapper.readValue(userJson(), User.class);
assertThat(user).isNotNull();
assertThat(user.getUsername()).isEqualTo("admin");
assertThat(user.getPassword()).isEqualTo("1234");
assertThat(user.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}
private String removeNode(String json, ObjectMapper mapper, String toRemove) throws Exception {
ObjectNode node = mapper.getFactory().createParser(json).readValueAsTree();
node.remove(toRemove);
String result = mapper.writeValueAsString(node);
JSONAssert.assertNotEquals(json, result, false);
return result;
}
public static String userJson() {
return USER_JSON;
}
public static String userWithPasswordJson(String password) {
return userJson().replaceAll(Pattern.quote(USER_PASSWORD), "\""+ password +"\"");
}
public static String userWithNoAuthoritiesJson() {
return userJson().replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON, SimpleGrantedAuthorityMixinTests.NO_AUTHORITIES_SET_JSON);
}
}
@@ -1,123 +0,0 @@
/*
* Copyright 2015-2016 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.jackson2;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixinTests {
// @formatter:off
private static final String AUTHENTICATED_JSON = "{"
+ "\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
+ "\"principal\": "+ UserDeserializerTests.USER_JSON + ", "
+ "\"credentials\": \"1234\", "
+ "\"authenticated\": true, "
+ "\"details\": null, "
+ "\"authorities\": "+ SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}";
// @formatter:on
// @formatter:off
public static final String AUTHENTICATED_STRINGPRINCIPAL_JSON = AUTHENTICATED_JSON.replace( UserDeserializerTests.USER_JSON, "\"admin\"");
// @formatter:on
// @formatter:off
private static final String UNAUTHENTICATED_STRINGPRINCIPAL_JSON = AUTHENTICATED_STRINGPRINCIPAL_JSON
.replace("\"authenticated\": true, ", "\"authenticated\": false, ")
.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON, SimpleGrantedAuthorityMixinTests.NO_AUTHORITIES_ARRAYLIST_JSON);
// @formatter:on
@Test
public void serializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin", "1234");
String serializedJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
}
@Test
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
String serializedJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
}
@Test
public void deserializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException, JSONException {
UsernamePasswordAuthenticationToken token = mapper
.readValue(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.isAuthenticated()).isEqualTo(false);
assertThat(token.getAuthorities()).isNotNull().hasSize(0);
}
@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException {
UsernamePasswordAuthenticationToken expectedToken = createToken();
UsernamePasswordAuthenticationToken token = mapper
.readValue(AUTHENTICATED_STRINGPRINCIPAL_JSON, UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.isAuthenticated()).isTrue();
assertThat(token.getAuthorities()).isEqualTo(expectedToken.getAuthorities());
}
@Test
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinWithUserTest() throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = createToken();
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_JSON, actualJson, true);
}
@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithUserTest() throws IOException {
UsernamePasswordAuthenticationToken token = mapper
.readValue(AUTHENTICATED_JSON, UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
assertThat(((User)token.getPrincipal()).getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
assertThat(token.isAuthenticated()).isEqualTo(true);
assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}
@Test
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinAfterEraseCredentialInvoked() throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = createToken();
token.eraseCredentials();
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_JSON.replaceAll(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true);
}
private UsernamePasswordAuthenticationToken createToken() {
User user = createDefaultUser();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
return token;
}
}
+1 -7
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-crypto</name>
<description>spring-security-crypto</description>
<url>http://spring.io/spring-security</url>
@@ -92,12 +92,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
@@ -59,8 +59,7 @@ public final class Hex {
int lsb = Character.digit(s.charAt(i + 1), 16);
if (msb < 0 || lsb < 0) {
throw new IllegalArgumentException(
"Detected a Non-hex character at " + (i + 1) + " or " + (i + 2) + " position");
throw new IllegalArgumentException("Non-hex character in input: " + s);
}
result[i / 2] = (byte) ((msb << 4) | lsb);
}
@@ -1,84 +0,0 @@
/*
* Copyright 2002-2016 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.crypto.codec;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test cases for {@link Hex}.
*
* @author Kazuki Shimizu
*/
public class HexTests {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void encode() {
assertThat(Hex.encode(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C',
(byte) 'D' })).isEqualTo(new char[] {'4','1','4','2','4','3','4','4'});
}
@Test
public void encodeEmptyByteArray() {
assertThat(Hex.encode(new byte[] {})).isEmpty();
}
@Test
public void decode() {
assertThat(Hex.decode("41424344")).isEqualTo(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C',
(byte) 'D' });
}
@Test
public void decodeEmptyString() {
assertThat(Hex.decode("")).isEmpty();
}
@Test
public void decodeNotEven() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Hex-encoded string must have an even number of characters");
Hex.decode("414243444");
}
@Test
public void decodeExistNonHexCharAtFirst() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Detected a Non-hex character at 1 or 2 position");
Hex.decode("G0");
}
@Test
public void decodeExistNonHexCharAtSecond() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Detected a Non-hex character at 3 or 4 position");
Hex.decode("410G");
}
@Test
public void decodeExistNonHexCharAtBoth() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Detected a Non-hex character at 5 or 6 position");
Hex.decode("4142GG");
}
}
+2 -8
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-data</name>
<description>spring-security-data</description>
<url>http://spring.io/spring-security</url>
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -108,12 +108,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
@@ -77,7 +77,7 @@ From a Spring Security perspective, the first thing you should do is follow the
.. <<appendix-faq-session-listener-missing>>
.. <<appendix-faq-unwanted-session-creation>>
. Miscellaneous
.. <<appendix-faq-forbidden-csrf>>
.. <<forbidden-csrf>>
.. <<appendix-faq-no-security-on-forward>>
.. <<appendix-faq-method-security-in-web-context>>
.. <<appendix-faq-no-filters-no-context>>
@@ -474,4 +474,4 @@ public class BeanPostProcessor implements BeanPostProcessor {
----
You would then register this bean in your application context. Spring will automatically invoke it on the beans defined in the application context.
You would then register this bean in your application context. Spring will automatically invoke it on the beans defined in the application context.
@@ -1,20 +0,0 @@
[[jackson]]
=== Jackson Support
Spring Security has added Jackson Support for persisting Spring Security related classes.
This can improve the performance of serializing Spring Security related classes when working with distributed sessions (i.e. session replication, Spring Session, etc).
To use it, register the `JacksonJacksonModules.getModules(ClassLoader)` as http://wiki.fasterxml.com/JacksonFeatureModules[Jackson Modules].
[source,java]
----
ObjectMapper mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
List<Module> modules = SecurityJacksonModules.getModules(loader);
mapper.registerModules(modules);
// ... use ObjectMapper as normally ...
SecurityContext context = new SecurityContextImpl();
// ...
String json = mapper.writeValueAsString(context);
----
+43 -40
View File
@@ -375,33 +375,46 @@ git clone https://github.com/spring-projects/spring-security.git
This will give you access to the entire project history (including all releases and branches) on your local machine.
[[new]]
== What's New in Spring Security 4.2
== What's New in Spring Security 4.1
There were https://github.com/spring-projects/spring-security/milestone/86?closed=1[50+ M1 issues] closed.
The overwhelming majority of these features were contributed by the community.
Below you can find the highlights of this release.
There were https://github.com/spring-projects/spring-security/issues?utf8=%E2%9C%93&q=milestone%3A%224.1.0+RC1%22[100+ RC1 issues] and https://github.com/spring-projects/spring-security/issues?utf8=%E2%9C%93&q=milestone%3A%224.1.0+RC2%22[60+ RC2 issues] fixed in Spring Security 4.1.
=== Web Improvements
Here is the list of improvements:
* https://github.com/spring-projects/spring-security/pull/3812[#3812] - <<jackson,Jackson Support>>
* https://github.com/spring-projects/spring-security/pull/3938[#3938] - Add <<request-matching,HTTP response splitting prevention>>
* https://github.com/spring-projects/spring-security/pull/3978[#3978] - Support for Standford WebAuth and Shibboleth using the newly added http://docs.spring.io/spring-security/site/docs/4.2.x-SNAPSHOT/apidocs/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilter.html[RequestAttributeAuthenticationFilter].
* https://github.com/spring-projects/spring-security/issues/3795[#3795] - `ConcurrentSessionFilter` supports `InvalidSessionStrategy`
* https://github.com/spring-projects/spring-security/pull/3904[#3904] - Add `CompositeLogoutHandler`
=== Java Configuration Improvements
* <<jc-authentication-userdetailsservice,Simplified UserDetailsService Java Configuration>>
* <<jc-authentication-authenticationprovider,Simplified AuthenticationProvider Java Configuration>>
* Configurable Content Negotiating `LogoutSuccessHandler`(s) via `LogoutConfigurer`
* Configurable `InvalidSessionStrategy` via `SessionManagementConfigurer`
* Ability to add a `Filter` at a specific location in the chain using `HttpSecurity.addFilterAt`
=== Configuration Improvements
=== Web Application Security Improvements
* <<mvc-requestmatcher,MvcRequestMatcher>>
* <<headers-csp,Content Security Policy (CSP)>>
* <<headers-hpkp,HTTP Public Key Pinning (HPKP)>>
* <<cors,CORS>>
* <<csrf-cookie,CookieCsrfTokenRepository>> provides simple AngularJS & CSRF integration
* Added `ForwardAuthenticationFailureHandler` & `ForwardAuthenticationSuccessHandler`
* <<mvc-authentication-principal,AuthenticationPrincipal>> supports expression attribute to support transforming the `Authentication.getPrincipal()` object (i.e. handling immutable custom `User` domain objects)
* https://github.com/spring-projects/spring-security/pull/3956[#3956] - Central configuration of the http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-jc.html#m3to4-role-prefixing[default role prefix]. See the issue for details.
* https://github.com/spring-projects/spring-security/issues/3899[#3899] - <<nsa-concurrency-control-max-sessions,concurrency-control@max-sessions>> supports unlimited sessions.
* https://github.com/spring-projects/spring-security/issues/3990[#3990] - Support for constructing `RoleHierarchy` from `Map` (i.e. `yml`)
* https://github.com/spring-projects/spring-security/pull/4062[#4062] - Custom cookiePath to `CookieCsrfTokenRepository`
* https://github.com/spring-projects/spring-security/issues/3794[#3794] - Allow configuration of `InvalidSessionStrategy` on `SessionManagementConfigurer`
* https://github.com/spring-projects/spring-security/issues/4020[#4020] - Fix Exposing Beans for defaultMethodExpressionHandler can prevent Method Security
=== Authorization Improvements
* <<el-access-web-path-variables,Path Variables in Web Security Expressions>>
* <<method-security-meta-annotations,Method Security Meta Annotations>>
=== Miscellaneous
=== Crypto Module Improvements
* SCrypt support with `SCryptPasswordEncoder`
* PBKDF2 support with <<spring-security-crypto-passwordencoders,Pbkdf2PasswordEncoder>>
* New `BytesEncryptor` implementation for BouncyCastle using _AES/CBC/PKCS5Padding_ and _AES/GCM/NoPadding_ algorithms
* https://github.com/spring-projects/spring-security/issues/4018[#4018] - Fix after `csrf()` is invoked, future `MockMvc` infocations use original `CsrfTokenRepository`
* Version Updates
=== Testing Improvements
* <<test-method-withanonymoususer,@WithAnonymousUser>>
* <<test-method-withuserdetails,@WithUserDetails>> allows specifying the `UserDetailsService` bean name
* <<test-method-meta-annotations,Test Meta Annotations>>
* Ability to mock a list of `GrantedAuthority` using `SecurityMockMvcResultMatchers.withAuthorities`
=== General Improvements
* Re-organization of sample projects
* Moved to GitHub issues
[[samples]]
== Samples and Guides (Start Here)
@@ -712,10 +725,10 @@ protected void configure(HttpSecurity http) throws Exception {
----
<1> Provides logout support. This is automatically applied when using `WebSecurityConfigurerAdapter`.
<2> The URL that triggers log out to occur (default is `/logout`). If CSRF protection is enabled (default), then the request must also be a POST. For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutUrl-java.lang.String-[JavaDoc].
<3> The URL to redirect to after logout has occurred. The default is `/login?logout`. For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessUrl-java.lang.String-[JavaDoc].
<4> Let's you specify a custom `LogoutSuccessHandler`. If this is specified, `logoutSuccessUrl()` is ignored. For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessHandler-org.springframework.security.web.authentication.logout.LogoutSuccessHandler-[JavaDoc].
<5> Specify whether to invalidate the `HttpSession` at the time of logout. This is *true* by default. Configures the `SecurityContextLogoutHandler` under the covers. For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#invalidateHttpSession-boolean-[JavaDoc].
<2> The URL that triggers log out to occur (default is `/logout`). If CSRF protection is enabled (default), then the request must also be a POST. For for information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutUrl(java.lang.String)[JavaDoc].
<3> The URL to redirect to after logout has occurred. The default is `/login?logout`. For for information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessUrl(java.lang.String)[JavaDoc].
<4> Let's you specify a custom `LogoutSuccessHandler`. If this is specified, `logoutSuccessUrl()` is ignored. For for information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessHandler(org.springframework.security.web.authentication.logout.LogoutSuccessHandler)[JavaDoc].
<5> Specify whether to invalidate the `HttpSession` at the time of logout. This is *true* by default. Configures the `SecurityContextLogoutHandler` under the covers. For for information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#invalidateHttpSession(boolean)[JavaDoc].
<6> Adds a `LogoutHandler`. `SecurityContextLogoutHandler` is added as the last `LogoutHandler` by default.
<7> Allows specifying the names of cookies to be removed on logout success. This is a shortcut for adding a `CookieClearingLogoutHandler` explicitly.
@@ -2212,7 +2225,7 @@ The `AuthenticationEntryPoint` is responsible for step three in the above list.
==== Authentication Mechanism
Once your browser submits your authentication credentials (either as an HTTP form post or HTTP header) there needs to be something on the server that "collects" these authentication details. By now we're at step six in the above list. In Spring Security we have a special name for the function of collecting authentication details from a user agent (usually a web browser), referring to it as the "authentication mechanism". Examples are form-base login and Basic authentication. Once the authentication details have been collected from the user agent, an `Authentication` "request" object is built and then presented to the `AuthenticationManager`.
Once your browser submits your authentication credentials (either as an HTTP form post or HTTP header) there needs to be something on the server that"collects" these authentication details. By now we're at step six in the above list. In Spring Security we have a special name for the function of collecting authentication details from a user agent (usually a web browser), referring to it as the "authentication mechanism". Examples are form-base login and Basic authentication. Once the authentication details have been collected from the user agent, an `Authentication` "request" object is built and then presented to the `AuthenticationManager`.
After the authentication mechanism receives back the fully-populated `Authentication` object, it will deem the request valid, put the `Authentication` into the `SecurityContextHolder`, and cause the original request to be retried (step seven above). If, on the other hand, the `AuthenticationManager` rejected the request, the authentication mechanism will ask the user agent to retry (step two above).
@@ -2463,8 +2476,6 @@ When an authentication provider (such as Spring Security's `DaoAuthenticationPro
If you want to generate encoded passwords directly in Java for storage in your user database, then you can use the `encode` method on the `PasswordEncoder`.
include::{include-dir}/jackson.adoc[]
include::{include-dir}/test.adoc[]
[[web-app-security]]
@@ -2565,7 +2576,6 @@ In practice we recommend that you use method security at your service layer, to
Security defined at the service layer is much more robust and harder to bypass, so you should always take advantage of Spring Security's method security options.
The `HttpFirewall` also prevents https://www.owasp.org/index.php/HTTP_Response_Splitting[HTTP Response Splitting] by rejecting new line characters in the HTTP Response headers.
=== Use with other Filter-Based Frameworks
If you're using some other framework that is also filter-based, then you need to make sure that the Spring Security filters come first. This enables the `SecurityContextHolder` to be populated in time for use by the other filters. Examples are the use of SiteMesh to decorate your web pages or a web framework like Wicket which uses a filter to handle its requests.
@@ -2762,7 +2772,7 @@ The login form simply contains `username` and `password` input fields, and posts
[[form-login-flow-handling]]
==== Application Flow on Authentication Success and Failure
The filter calls the configured `AuthenticationManager` to process each authentication request. The destination following a successful authentication or an authentication failure is controlled by the `AuthenticationSuccessHandler` and `AuthenticationFailureHandler` strategy interfaces, respectively. The filter has properties which allow you to set these so you can customize the behaviour completely footnote:[In versions prior to 3.0, the application flow at this point had evolved to a stage was controlled by a mix of properties on this class and strategy plugins. The decision was made for 3.0 to refactor the code to make these two strategies entirely responsible.]. Some standard implementations are supplied such as `SimpleUrlAuthenticationSuccessHandler`, `SavedRequestAwareAuthenticationSuccessHandler`, `SimpleUrlAuthenticationFailureHandler`, `ExceptionMappingAuthenticationFailureHandler` and `DelegatingAuthenticationFailureHandler`. Have a look at the Javadoc for these classes and also for `AbstractAuthenticationProcessingFilter` to get an overview of how they work and the supported features.
The filter calls the configured `AuthenticationManager` to process each authentication request. The destination following a successful authentication or an authentication failure is controlled by the `AuthenticationSuccessHandler` and `AuthenticationFailureHandler` strategy interfaces, respectively. The filter has properties which allow you to set these so you can customize the behaviour completely footnote:[In versions prior to 3.0, the application flow at this point had evolved to a stage was controlled by a mix of properties on this class and strategy plugins. The decision was made for 3.0 to refactor the code to make these two strategies entirely responsible.]. Some standard implementations are supplied such as `SimpleUrlAuthenticationSuccessHandler`, `SavedRequestAwareAuthenticationSuccessHandler`, `SimpleUrlAuthenticationFailureHandler` and `ExceptionMappingAuthenticationFailureHandler`. Have a look at the Javadoc for these classes and also for `AbstractAuthenticationProcessingFilter` to get an overview of how they work and the supported features.
If authentication is successful, the resulting `Authentication` object will be placed into the `SecurityContextHolder`. The configured `AuthenticationSuccessHandler` will then be called to either redirect or forward the user to the appropriate destination. By default a `SavedRequestAwareAuthenticationSuccessHandler` is used, which means that the user will be redirected to the original destination they requested before they were asked to login.
@@ -3459,7 +3469,7 @@ As previously mentioned, this is not as secure as using a session, but in many c
==== Logging In
In order to protect against http://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests[forging log in requests] the log in form should be protected against CSRF attacks too. Since the `CsrfToken` is stored in HttpSession, this means an HttpSession will be created as soon as `CsrfToken` token attribute is accessed. While this sounds bad in a RESTful / stateless architecture the reality is that state is necessary to implement practical security. Without state, we have nothing we can do if a token is compromised. Practically speaking, the CSRF token is quite small in size and should have a negligible impact on our architecture.
A common technique to protect the log in form is by using a javascript function to obtain a valid CSRF token before the form submission. By doing this, there is no need to think about session timeouts (discussed in the previous section) because the session is created right before the form submission (assuming that <<csrf-cookie,CookieCsrfTokenRepository>> isn't configured instead), so the user can stay on the login page and submit the username/password when he wants. In order to achieve this, you can take advantage of the `CsrfTokenArgumentResolver` provided by Spring Security and expose an endpoint like it's described on <<mvc-csrf-resolver,here>>.
A common technique to protect the log in form is by using a javascript function to obtain a valid CSRF token before the form submission. By doing this, there is no need to think about session timeouts (discussed in the previous section) because the session is created right before the form submission (assuming that <<csrf-cookie,CookieCsrfTokenRepository>> isn't configured instead), so the user can stay on the login page and submit the username/password when he wants. In order to achieve this, you can take advantadge of the `CsrfTokenArgumentResolver` provided by Spring Security and expose an endpoint like it's described on <<mvc-csrf-resolver,here>>.
[[csrf-logout]]
@@ -4028,7 +4038,7 @@ Allowing your website to be added to a frame can be a security issue. For exampl
[NOTE]
====
Another modern approach to dealing with clickjacking is to use <<headers-csp>>.
Another modern approach to dealing with clickjacking is to use <<headers-content-security-policy>>.
====
There are a number ways to mitigate clickjacking attacks. For example, to protect legacy browsers from clickjacking attacks you can use https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Best-for-now_Legacy_Browser_Frame_Breaking_Script[frame breaking code]. While not perfect, the frame breaking code is the best you can do for the legacy browsers.
@@ -4079,7 +4089,7 @@ protected void configure(HttpSecurity http) throws Exception {
[[headers-xss-protection]]
==== X-XSS-Protection
Some browsers have built in support for filtering out https://www.owasp.org/index.php/Testing_for_Reflected_Cross_site_scripting_(OWASP-DV-001)[reflected XSS attacks]. This is by no means foolproof, but does assist in XSS protection.
Some browsers have built in support for filtering out https://www.owasp.org/index.php/Testing_for_Reflected_Cross_site_scripting_(OWASP-DV-001)[reflected XSS attacks]. This is by no means full proof, but does assist in XSS protection.
The filtering is typically enabled by default, so adding the header typically just ensures it is enabled and instructs the browser what to do when a XSS attack is detected. For example, the filter might try to change the content in the least invasive way to still render everything. At times, this type of replacement can become a http://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/[XSS vulnerability in itself]. Instead, it is best to block the content rather than attempt to fix it. To do this we can add the following header:
@@ -8582,9 +8592,6 @@ Session-management related functionality is implemented by the addition of a `Se
* **invalid-session-url**
Setting this attribute will inject the `SessionManagementFilter` with a `SimpleRedirectInvalidSessionStrategy` configured with the attribute value. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.
[[nsa-session-management-invalid-session-strategy-ref]]
* **invalid-session-url**
Allows injection of the InvalidSessionStrategy instance used by the SessionManagementFilter. Use either this or the `invalid-session-url` attribute but not both.
[[nsa-session-management-session-authentication-error-url]]
* **session-authentication-error-url**
@@ -8639,14 +8646,10 @@ If set to "true" a `SessionAuthenticationException` will be raised when a user a
* **expired-url**
The URL a user will be redirected to if they attempt to use a session which has been "expired" by the concurrent session controller because the user has exceeded the number of allowed sessions and has logged in again elsewhere. Should be set unless `exception-if-maximum-exceeded` is set. If no value is supplied, an expiry message will just be written directly back to the response.
[[nsa-concurrency-control-expired-session-strategy-ref]]
* **expired-url**
Allows injection of the ExpiredSessionStrategy instance used by the ConcurrentSessionFilter
[[nsa-concurrency-control-max-sessions]]
* **max-sessions**
Maps to the `maximumSessions` property of `ConcurrentSessionControlAuthenticationStrategy`.
Specify `-1` as the value to support unlimitted sessions.
[[nsa-concurrency-control-session-registry-alias]]
@@ -9944,4 +9947,4 @@ Provides Spring Security's JSP tag implementations.
include::{include-dir}/faq.adoc[]
include::{include-dir}/migrating.adoc[]
include::{include-dir}/migrating.adoc[]
+1 -1
View File
@@ -1 +1 @@
version=4.2.0.M1
version=4.1.3.RELEASE
+1 -2
View File
@@ -35,7 +35,6 @@ ext.springDataRedisVersion = '1.7.2.RELEASE'
ext.springSessionVersion = '1.2.1.RELEASE'
ext.springBootVersion = '1.4.0.RELEASE'
ext.thymeleafVersion = '2.1.5.RELEASE'
ext.jsonassertVersion = '1.3.0'
ext.spockDependencies = [
dependencies.create("org.spockframework:spock-spring:$spockVersion") {
@@ -164,7 +163,7 @@ configurations.all {
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
project.tasks.matching { it instanceof Test && it.name != 'integrationTest' }.all {
jvmArgs = ['-ea', '-Xmx500m', '-XX:MaxPermSize=512m']
jvmArgs = ['-ea', '-Xmx500m']
maxParallelForks = guessMaxForks()
logging.captureStandardOutput(LogLevel.INFO)
}
+1 -1
View File
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14-bin.zip
+4 -10
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>itest-context</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>itest-context</name>
<description>itest-context</description>
<url>http://spring.io/spring-security</url>
@@ -57,7 +57,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -132,13 +132,13 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -152,12 +152,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
+6 -12
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>itest-web</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>itest-web</name>
<description>itest-web</description>
<url>http://spring.io/spring-security</url>
@@ -150,31 +150,31 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -199,12 +199,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
+2 -8
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-ldap</name>
<description>spring-security-ldap</description>
<url>http://spring.io/spring-security</url>
@@ -73,7 +73,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -200,12 +200,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
@@ -16,25 +16,25 @@
package org.springframework.security.ldap.userdetails;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.util.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.naming.directory.SearchControls;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.naming.directory.SearchControls;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import org.springframework.util.Assert;
/**
* The default strategy for obtaining user role information from the directory.
* <p>
@@ -160,7 +160,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
public DefaultLdapAuthoritiesPopulator(ContextSource contextSource,
String groupSearchBase) {
Assert.notNull(contextSource, "contextSource must not be null");
this.ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
getLdapTemplate().setSearchControls(getSearchControls());
this.groupSearchBase = groupSearchBase;
@@ -168,8 +168,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
logger.info("groupSearchBase is null. No group search will be performed.");
}
else if (groupSearchBase.length() == 0) {
logger.info(
"groupSearchBase is empty. Searches will be performed from the context source base");
logger.info("groupSearchBase is empty. Searches will be performed from the context source base");
}
}
@@ -198,7 +197,6 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @param user the user who's authorities are required
* @return the set of roles granted to the user.
*/
@Override
public final Collection<GrantedAuthority> getGrantedAuthorities(
DirContextOperations user, String username) {
String userDn = user.getNameInNamespace();
@@ -215,8 +213,8 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
roles.addAll(extraRoles);
}
if (this.defaultRole != null) {
roles.add(this.defaultRole);
if (defaultRole != null) {
roles.add(defaultRole);
}
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(roles.size());
@@ -234,13 +232,13 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
if (logger.isDebugEnabled()) {
logger.debug("Searching for roles for user '" + username + "', DN = " + "'"
+ userDn + "', with filter " + this.groupSearchFilter
+ userDn + "', with filter " + groupSearchFilter
+ " in search base '" + getGroupSearchBase() + "'");
}
Set<String> userRoles = getLdapTemplate().searchForSingleAttributeValues(
getGroupSearchBase(), this.groupSearchFilter,
new String[] { userDn, username }, this.groupRoleAttribute);
getGroupSearchBase(), groupSearchFilter,
new String[] { userDn, username }, groupRoleAttribute);
if (logger.isDebugEnabled()) {
logger.debug("Roles from search: " + userRoles);
@@ -248,11 +246,11 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
for (String role : userRoles) {
if (this.convertToUpperCase) {
if (convertToUpperCase) {
role = role.toUpperCase();
}
authorities.add(new SimpleGrantedAuthority(this.rolePrefix + role));
authorities.add(new SimpleGrantedAuthority(rolePrefix + role));
}
return authorities;
@@ -263,7 +261,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
}
protected String getGroupSearchBase() {
return this.groupSearchBase;
return groupSearchBase;
}
/**
@@ -312,7 +310,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
public void setSearchSubtree(boolean searchSubtree) {
int searchScope = searchSubtree ? SearchControls.SUBTREE_SCOPE
: SearchControls.ONELEVEL_SCOPE;
this.searchControls.setSearchScope(searchScope);
searchControls.setSearchScope(searchScope);
}
/**
@@ -332,7 +330,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @see org.springframework.security.ldap.SpringSecurityLdapTemplate
*/
protected SpringSecurityLdapTemplate getLdapTemplate() {
return this.ldapTemplate;
return ldapTemplate;
}
/**
@@ -342,7 +340,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @see #setGroupRoleAttribute(String)
*/
protected final String getGroupRoleAttribute() {
return this.groupRoleAttribute;
return groupRoleAttribute;
}
/**
@@ -352,7 +350,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @see #setGroupSearchFilter(String)
*/
protected final String getGroupSearchFilter() {
return this.groupSearchFilter;
return groupSearchFilter;
}
/**
@@ -362,7 +360,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @see #setRolePrefix(String)
*/
protected final String getRolePrefix() {
return this.rolePrefix;
return rolePrefix;
}
/**
@@ -372,7 +370,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @see #setConvertToUpperCase(boolean)
*/
protected final boolean isConvertToUpperCase() {
return this.convertToUpperCase;
return convertToUpperCase;
}
/**
@@ -382,7 +380,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @see #setDefaultRole(String)
*/
private GrantedAuthority getDefaultRole() {
return this.defaultRole;
return defaultRole;
}
/**
@@ -391,6 +389,6 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @return the search controls
*/
private SearchControls getSearchControls() {
return this.searchControls;
return searchControls;
}
}
@@ -16,7 +16,6 @@
package org.springframework.security.ldap.userdetails;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.userdetails.UserDetails;
/**
@@ -24,7 +23,7 @@ import org.springframework.security.core.userdetails.UserDetails;
*
* @author Luke Taylor
*/
public interface LdapUserDetails extends UserDetails, CredentialsContainer {
public interface LdapUserDetails extends UserDetails {
// ~ Methods
// ========================================================================================================
@@ -107,11 +107,6 @@ public class LdapUserDetailsImpl implements LdapUserDetails, PasswordPolicyData
return enabled;
}
@Override
public void eraseCredentials() {
password = null;
}
public int getTimeBeforeExpiration() {
return timeBeforeExpiration;
}
@@ -20,7 +20,6 @@ import java.util.Collection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
@@ -35,7 +34,6 @@ import org.springframework.util.Assert;
* object.
*
* @author Luke Taylor
* @author Eddú Meléndez
*/
public class LdapUserDetailsMapper implements UserDetailsContextMapper {
// ~ Instance fields
@@ -50,17 +48,16 @@ public class LdapUserDetailsMapper implements UserDetailsContextMapper {
// ~ Methods
// ========================================================================================================
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection<? extends GrantedAuthority> authorities) {
String dn = ctx.getNameInNamespace();
this.logger.debug("Mapping user details from context with DN: " + dn);
logger.debug("Mapping user details from context with DN: " + dn);
LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence();
essence.setDn(dn);
Object passwordValue = ctx.getObjectAttribute(this.passwordAttributeName);
Object passwordValue = ctx.getObjectAttribute(passwordAttributeName);
if (passwordValue != null) {
essence.setPassword(mapPassword(passwordValue));
@@ -69,13 +66,12 @@ public class LdapUserDetailsMapper implements UserDetailsContextMapper {
essence.setUsername(username);
// Map the roles
for (int i = 0; (this.roleAttributes != null)
&& (i < this.roleAttributes.length); i++) {
String[] rolesForAttribute = ctx.getStringAttributes(this.roleAttributes[i]);
for (int i = 0; (roleAttributes != null) && (i < roleAttributes.length); i++) {
String[] rolesForAttribute = ctx.getStringAttributes(roleAttributes[i]);
if (rolesForAttribute == null) {
this.logger.debug("Couldn't read role attribute '"
+ this.roleAttributes[i] + "' for user " + dn);
logger.debug("Couldn't read role attribute '" + roleAttributes[i]
+ "' for user " + dn);
continue;
}
@@ -108,7 +104,6 @@ public class LdapUserDetailsMapper implements UserDetailsContextMapper {
}
@Override
public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
throw new UnsupportedOperationException(
"LdapUserDetailsMapper only supports reading from a context. Please"
@@ -148,10 +143,10 @@ public class LdapUserDetailsMapper implements UserDetailsContextMapper {
*/
protected GrantedAuthority createAuthority(Object role) {
if (role instanceof String) {
if (this.convertToUpperCase) {
if (convertToUpperCase) {
role = ((String) role).toUpperCase();
}
return new SimpleGrantedAuthority(this.rolePrefix + role);
return new SimpleGrantedAuthority(rolePrefix + role);
}
return null;
}
@@ -42,7 +42,6 @@ import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
*
* @author Luke Taylor
* @author Rob Winch
* @author Eddú Meléndez
*/
public class LdapAuthenticationProviderTests {
@@ -138,10 +137,10 @@ public class LdapAuthenticationProviderTests {
assertThat(user.getUsername()).isEqualTo("ben");
assertThat(populator.getRequestedUsername()).isEqualTo("ben");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()))
.contains("ROLE_FROM_ENTRY");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()))
.contains("ROLE_FROM_POPULATOR");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_FROM_ENTRY"));
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_FROM_POPULATOR"));
}
@Test
@@ -169,8 +168,8 @@ public class LdapAuthenticationProviderTests {
UserDetails user = (UserDetails) ldapProvider.authenticate(authRequest)
.getPrincipal();
assertThat(user.getAuthorities()).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()))
.contains("ROLE_FROM_ENTRY");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_FROM_ENTRY"));
}
@Test
@@ -1,43 +0,0 @@
/*
* Copyright 2012-2016 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.junit.Test;
import org.springframework.security.core.CredentialsContainer;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests {@link LdapUserDetailsImpl}
*
* @author Joe Grandja
*/
public class LdapUserDetailsImplTests {
@Test
public void credentialsAreCleared() {
LdapUserDetailsImpl.Essence mutableLdapUserDetails = new LdapUserDetailsImpl.Essence();
mutableLdapUserDetails.setDn("uid=username1,ou=people,dc=example,dc=com");
mutableLdapUserDetails.setUsername("username1");
mutableLdapUserDetails.setPassword("password");
LdapUserDetails ldapUserDetails = mutableLdapUserDetails.createUserDetails();
assertThat(ldapUserDetails).isInstanceOf(CredentialsContainer.class);
ldapUserDetails.eraseCredentials();
assertThat(ldapUserDetails.getPassword()).isNull();
}
}
@@ -16,22 +16,20 @@
package org.springframework.security.ldap.userdetails;
import static org.assertj.core.api.Assertions.assertThat;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import org.junit.Test;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests {@link LdapUserDetailsMapper}.
*
* @author Luke Taylor
* @author Eddú Meléndez
*/
public class LdapUserDetailsMapperTests {
@@ -74,7 +72,8 @@ public class LdapUserDetailsMapperTests {
"ani", AuthorityUtils.NO_AUTHORITIES);
assertThat(user.getAuthorities()).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains("ROLE_X");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_X"));
}
@Test
@@ -94,5 +93,4 @@ public class LdapUserDetailsMapperTests {
assertThat(user.getPassword()).isEqualTo("mypassword");
}
}
+3 -9
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-messaging</name>
<description>spring-security-messaging</description>
<url>http://spring.io/spring-security</url>
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -102,7 +102,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@@ -232,12 +232,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
+3 -9
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-openid</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<name>spring-security-openid</name>
<description>spring-security-openid</description>
<url>http://spring.io/spring-security</url>
@@ -63,13 +63,13 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.0.M1</version>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -164,12 +164,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>

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