1
0
mirror of synced 2026-07-17 16:45:14 +00:00

Compare commits

..

33 Commits

Author SHA1 Message Date
Spring Operator 4e61de0ef9 URL Cleanup
This commit updates URLs to prefer the https protocol. Redirects are not followed to avoid accidentally expanding intentionally shortened URLs (i.e. if using a URL shortener).

# Fixed URLs

## Fixed Success
These URLs were switched to an https URL with a 2xx status. While the status was successful, your review is still recommended.

* http://www.apache.org/licenses/ with 1 occurrences migrated to:
  https://www.apache.org/licenses/ ([https](https://www.apache.org/licenses/) result 200).
* http://www.apache.org/licenses/LICENSE-2.0 with 1777 occurrences migrated to:
  https://www.apache.org/licenses/LICENSE-2.0 ([https](https://www.apache.org/licenses/LICENSE-2.0) result 200).
* http://www.apache.org/licenses/LICENSE-2.0.html with 1 occurrences migrated to:
  https://www.apache.org/licenses/LICENSE-2.0.html ([https](https://www.apache.org/licenses/LICENSE-2.0.html) result 200).
* http://www.apache.org/licenses/LICENSE-2.0.txt with 1 occurrences migrated to:
  https://www.apache.org/licenses/LICENSE-2.0.txt ([https](https://www.apache.org/licenses/LICENSE-2.0.txt) result 200).
2019-03-14 20:21:48 -05:00
Rob Winch c8e4ffb5b9 Polish URLs
We have performed some polish on your URLs. We do not follow redirects to avoid expanding intentionally shorter URLs (i.e. URL shortened URLs)

# Fixed URLs

## Fixed But Review Recommended
These URLs were fixed, but the https status was not OK. However, the https status was the same as the http request, so we migrated them. Your review is recommended.

| HTTP URL | Result URL | HTTPS Result | HTTP Result | Count |
| --- | --- | --- | --- | --- |
| http://repo.terracotta.org/maven2/ | https://repo.terracotta.org/maven2/ | HttpResponse(httpStatus = 403 FORBIDDEN) | HttpResponse(httpStatus = 403 FORBIDDEN) | 1 |
| http://repository.springsource.com/maven/bundles/external | https://repository.springsource.com/maven/bundles/external | HttpResponse(httpStatus = 404 NOT_FOUND) | HttpResponse(httpStatus = 404 NOT_FOUND) | 1 |
| http://repository.springsource.com/maven/bundles/release | https://repository.springsource.com/maven/bundles/release | HttpResponse(httpStatus = 404 NOT_FOUND) | HttpResponse(httpStatus = 404 NOT_FOUND) | 1 |
## Fixed Success
These URLs were fixed successfully.

| HTTP URL | Result URL | HTTPS Result | HTTP Result | Count |
| --- | --- | --- | --- | --- |
| http://docs.spring.io/spring-ldap/docs/1.3.x/apidocs/ | https://docs.spring.io/spring-ldap/docs/1.3.x/apidocs/ | HttpResponse(httpStatus = 200 OK) | null | 2 |
| http://docs.spring.io/spring/docs/3.2.x/javadoc-api | https://docs.spring.io/spring/docs/3.2.x/javadoc-api | HttpResponse(httpStatus = 301 MOVED_PERMANENTLY redirectUrl = http://docs.spring.io/spring/docs/3.2.x/javadoc-api/) | null | 1 |
| http://docs.spring.io/spring/docs/3.2.x/javadoc-api/ | https://docs.spring.io/spring/docs/3.2.x/javadoc-api/ | HttpResponse(httpStatus = 200 OK) | null | 1 |
| http://download.oracle.com/javase/6/docs/api/ | https://download.oracle.com/javase/6/docs/api/ | HttpResponse(httpStatus = 302 FOUND redirectUrl = https://docs.oracle.com/javase/6/docs/api/) | null | 2 |
| http://spring.io/ | https://spring.io/ | HttpResponse(httpStatus = 200 OK) | null | 54 |
| http://spring.io/spring-security | https://spring.io/spring-security | HttpResponse(httpStatus = 302 FOUND redirectUrl = https://projects.spring.io/spring-security) | null | 54 |
| http://www.apache.org/licenses/LICENSE-2.0.txt | https://www.apache.org/licenses/LICENSE-2.0.txt | HttpResponse(httpStatus = 200 OK) | null | 54 |
| http://forums.gradle.org/gradle/topics/after_upgrade_gradle_to_2_0_version_the_maven_pom_not_support_build_property | https://discuss.gradle.org/gradle/topics/after_upgrade_gradle_to_2_0_version_the_maven_pom_not_support_build_property | HttpResponse(httpStatus = 404 NOT_FOUND) | HttpResponse(httpStatus = 301 MOVED_PERMANENTLY redirectUrl = https://discuss.gradle.org/gradle/topics/after_upgrade_gradle_to_2_0_version_the_maven_pom_not_support_build_property) | 1 |
| http://forums.gradle.org/gradle/topics/eclipse_wtp_deploys_testcode_to_server_example_provided | https://discuss.gradle.org/gradle/topics/eclipse_wtp_deploys_testcode_to_server_example_provided | HttpResponse(httpStatus = 404 NOT_FOUND) | HttpResponse(httpStatus = 301 MOVED_PERMANENTLY redirectUrl = https://discuss.gradle.org/gradle/topics/eclipse_wtp_deploys_testcode_to_server_example_provided) | 1 |

# Ignored
These URLs were intentionally ignored so we didn't migrate them.

| HTTP URL |
| --- |
| http://maven.apache.org/POM/4.0.0 |
| http://maven.apache.org/xsd/maven-4.0.0.xsd |
| http://www.w3.org/2001/XMLSchema-instance |
2019-03-01 17:35:15 -06:00
Spring Buildmaster 2fdef0455b Next development version 2018-01-25 18:32:07 +00:00
Spring Buildmaster 45421d63ac Release version 4.1.5.RELEASE 2018-01-25 18:32:00 +00:00
Rob Winch 976ce05373 DelegatingApplicationListener uses CopyOnWriteArrayList
Fixes: gh-4979
2018-01-25 11:28:01 -06:00
Rob Winch a898415c65 Update .gitignore
- ignore classes/
- ignore s101plugin.state
2018-01-25 11:28:01 -06:00
Joris Portegies Zwart 01910419f0 JavaDoc for Pbkdf2PasswordEncoder refer to constants
Fix Javadoc so that it uses the actual values for default hash width and number of iterations

Fixes gh-4978
2018-01-25 11:27:10 -06:00
Kyle Anderson e7a15e85a1 Fix Typo in Reference Docs
Fixes: gh-4976
2018-01-25 11:26:51 -06:00
Rob Winch 65da28e4bf Add StrictHttpFirewall 2018-01-25 11:26:51 -06:00
Rob Winch 04d14fb6fe Lookup HandlerMappingIntrospector from Bean 2018-01-25 11:26:51 -06:00
Rob Winch 17238707b7 Update to Spring 4.3.14
Fixes: gh-4977
2018-01-25 11:26:40 -06:00
Craig Andrews bf075a2cae Configure permissionEvaluator and roleHierarchy by default
Implementations of AbstractSecurityExpressionHandler (such as the very commonly used DefaultWebSecurityExpressionHandler) get PermissionEvaluator and RoleHierarchy from the application context (if the application context is provided, and exactly one of such a bean exists in it). This approach matches that used in GlobalMethodSecurityConfiguration, making everything in Spring Security work the same way (including WebSecurity).

Issue gh-4077
2017-10-30 00:57:37 -05:00
Spring Buildmaster d0ede98db5 Next development version 2016-12-21 16:50:22 +00:00
Spring Buildmaster 57ed7ddf3c Release version 4.1.4.RELEASE 2016-12-21 16:50:16 +00:00
Rob Winch 5574fd2029 Update to Spring 4.3.5.RELEASE
Fixes gh-4168
2016-12-21 10:14:33 -06:00
Rob Winch ed2ae21074 Block URL Encoded "/" in DefaultHttpFirewall
Fixes gh-4170
2016-12-21 09:32:35 -06:00
Rob Winch d25c4a23ba Remove only master from .travis.yml 2016-08-30 09:14:04 -05:00
Spring Buildmaster 548a542417 Next development version 2016-08-23 01:05:57 +00:00
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
711 changed files with 30169 additions and 18815 deletions
+16
View File
@@ -0,0 +1,16 @@
language: java
jdk:
- oraclejdk8
os:
- linux
before_cache:
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
cache:
directories:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
script: ./gradlew build
+2 -2
View File
@@ -40,5 +40,5 @@ appropriate to the circumstances. Maintainers are obligated to maintain confiden
with regard to the reporter of an incident.
This Code of Conduct is adapted from the
https://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at
https://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/]
http://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at
http://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/]
+6 -15
View File
@@ -12,7 +12,7 @@ Each Spring module is slightly different than another in terms of team size, num
# Importing into IDE
The following provides information on setting up a development environment that can run the sample in [Spring Tool Suite 3.6.0+](https://www.springsource.org/sts). Other IDE's should work using Gradle's IDE support, but have not been tested.
The following provides information on setting up a development environment that can run the sample in [Spring Tool Suite 3.6.0+](http://www.springsource.org/sts). Other IDE's should work using Gradle's IDE support, but have not been tested.
* IDE Setup
* Install Spring Tool Suite 3.6.0+
@@ -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
@@ -59,8 +59,8 @@ Please carefully follow the whitespace and formatting conventions already presen
Whitespace management tips
1. You can use the [AnyEdit Eclipse plugin](https://marketplace.eclipse.org/content/anyedit-tools) to ensure spaces are used and to clean up trailing whitespaces.
1. Use git's pre-commit.sample hook to prevent invalid whitespace from being pushed out. You can enable it by moving ~/spring-security/.git/hooks/pre-commit.sample to ~/spring-security/.git/hooks/pre-commit and ensuring it is executable. For more information on hooks refer to [Pro Git's Pre-Commit Hook's section](https://git-scm.com/book/cs/ch7-3.html)
1. You can use the [AnyEdit Eclipse plugin](http://marketplace.eclipse.org/content/anyedit-tools) to ensure spaces are used and to clean up trailing whitespaces.
1. Use git's pre-commit.sample hook to prevent invalid whitespace from being pushed out. You can enable it by moving ~/spring-security/.git/hooks/pre-commit.sample to ~/spring-security/.git/hooks/pre-commit and ensuring it is executable. For more information on hooks refer to [Pro Git's Pre-Commit Hook's section](http://git-scm.com/book/cs/ch7-3.html)
# Add Apache license header to all new classes
@@ -104,23 +104,14 @@ 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](https://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: https://book.git-scm.com/4_interactive_rebasing.html.
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.
# Use real name in git commits
Please configure git to use your real first and last name for any commits you intend to submit as pull requests. For example, this is not acceptable:
+13 -17
View File
@@ -1,17 +1,13 @@
image::https://badges.gitter.im/Join%20Chat.svg[Gitter,link=https://gitter.im/spring-projects/spring-security?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge]
[NOTE]
======
This branch of Spring Security has reached its https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-Versions#supported-versions[End of Life], meaning that there are no further maintenance releases or security patches planned.
Please migrate to a supported branch as soon as possible.
======
image:https://travis-ci.org/spring-projects/spring-security.svg?branch=master["Build Status", link="https://travis-ci.org/spring-security/spring-security"]
= Spring Security
Spring Security provides security services for the https://docs.spring.io[Spring IO Platform]. Spring Security 3.1 requires Spring 3.0.3 as
Spring Security provides security services for the http://docs.spring.io[Spring IO Platform]. Spring Security 3.1 requires Spring 3.0.3 as
a minimum and also requires Java 5.
For a detailed list of features and access to the latest release, please visit https://spring.io/projects[Spring projects].
For a detailed list of features and access to the latest release, please visit http://spring.io/projects[Spring projects].
== Code of Conduct
This project adheres to the Contributor Covenant link:CODE_OF_CONDUCT.adoc[code of conduct].
@@ -21,21 +17,21 @@ By participating, you are expected to uphold this code. Please report unaccepta
See https://github.com/spring-projects/spring-framework/wiki/Downloading-Spring-artifacts[downloading Spring artifacts] for Maven repository information.
== Documentation
Be sure to read the https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/[Spring Security Reference].
Extensive JavaDoc for the Spring Security code is also available in the https://docs.spring.io/spring-security/site/docs/current/apidocs/[Spring Security API Documentation].
Be sure to read the http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/[Spring Security Reference].
Extensive JavaDoc for the Spring Security code is also available in the http://docs.spring.io/spring-security/site/docs/current/apidocs/[Spring Security API Documentation].
== Quick Start
We recommend you visit https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/[Spring Security Reference] and read the "Getting Started" page.
We recommend you visit http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/[Spring Security Reference] and read the "Getting Started" page.
== Building from Source
Spring Security uses a https://gradle.org[Gradle]-based build system.
In the instructions below, https://vimeo.com/34436402[`./gradlew`] is invoked from the root of the source tree and serves as
Spring Security uses a http://gradle.org[Gradle]-based build system.
In the instructions below, http://vimeo.com/34436402[`./gradlew`] is invoked from the root of the source tree and serves as
a cross-platform, self-contained bootstrap mechanism for the build.
=== Prerequisites
https://help.github.com/set-up-git-redirect[Git] and the https://www.oracle.com/technetwork/java/javase/downloads[JDK8 build].
http://help.github.com/set-up-git-redirect[Git] and the http://www.oracle.com/technetwork/java/javase/downloads[JDK7 build].
Be sure that your `JAVA_HOME` environment variable points to the `jdk1.8.0` folder extracted from the JDK download.
Be sure that your `JAVA_HOME` environment variable points to the `jdk1.7.0` folder extracted from the JDK download.
=== Check out sources
[indent=0]
@@ -59,11 +55,11 @@ Discover more commands with `./gradlew tasks`.
See also the https://github.com/spring-projects/spring-framework/wiki/Gradle-build-and-release-FAQ[Gradle build and release FAQ].
== Getting Support
Check out the https://stackoverflow.com/questions/tagged/spring-security[Spring Security tags on Stack Overflow].
https://spring.io/services[Commercial support] is available too.
Check out the http://stackoverflow.com/questions/tagged/spring-security[Spring Security tags on Stack Overflow].
http://spring.io/services[Commercial support] is available too.
== Contributing
https://help.github.com/send-pull-requests[Pull requests] are welcome; see the https://github.com/spring-projects/spring-security/blob/master/CONTRIBUTING.md[contributor guidelines] for details.
http://help.github.com/send-pull-requests[Pull requests] are welcome; see the https://github.com/spring-projects/spring-security/blob/master/CONTRIBUTING.md[contributor guidelines] for details.
== License
Spring Security is Open Source software released under the
+7 -7
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<name>spring-security-acl</name>
<description>spring-security-acl</description>
<url>https://spring.io/spring-security</url>
@@ -35,7 +35,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.23.RELEASE</version>
<version>4.3.14.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -95,14 +95,14 @@
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
<version>2.9.0</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
<version>1.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -120,7 +120,7 @@
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.6</version>
<version>2.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -132,7 +132,7 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
<version>1.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -16,20 +16,18 @@
package org.springframework.security.acls.domain;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.Sid;
import org.springframework.security.acls.model.SidRetrievalStrategy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.Assert;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* Default implementation of {@link AclAuthorizationStrategy}.
* <p>
@@ -120,8 +118,7 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
}
// Iterate this principal's authorities to determine right
Set<String> authorities = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (authorities.contains(requiredAuthority.getAuthority())) {
if (authentication.getAuthorities().contains(requiredAuthority)) {
return;
}
@@ -26,8 +26,6 @@ import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.AclService;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.acls.model.Sid;
import org.springframework.security.acls.model.SidRetrievalStrategy;
import org.springframework.security.core.Authentication;
@@ -39,6 +37,7 @@ import org.springframework.security.core.Authentication;
public class AclPermissionEvaluatorTests {
@Test
@SuppressWarnings("unchecked")
public void hasPermissionReturnsTrueIfAclGrantsPermission() throws Exception {
AclService service = mock(AclService.class);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
@@ -49,8 +48,8 @@ public class AclPermissionEvaluatorTests {
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
when(service.readAclById(any(ObjectIdentity.class), anyListOf(Sid.class))).thenReturn(acl);
when(acl.isGranted(anyListOf(Permission.class), anyListOf(Sid.class), eq(false))).thenReturn(true);
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
}
@@ -69,8 +68,8 @@ public class AclPermissionEvaluatorTests {
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
when(service.readAclById(any(ObjectIdentity.class), anyListOf(Sid.class))).thenReturn(acl);
when(acl.isGranted(anyListOf(Permission.class), anyListOf(Sid.class), eq(false))).thenReturn(true);
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();
@@ -1,72 +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
*
* https://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.acls.domain;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.security.acls.model.Acl;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
/**
*
* @author Rob Winch
*
*/
@RunWith(MockitoJUnitRunner.class)
public class AclAuthorizationStrategyImplTests {
@Mock
Acl acl;
GrantedAuthority authority;
AclAuthorizationStrategyImpl strategy;
@Before
public void setup() {
authority = new SimpleGrantedAuthority("ROLE_AUTH");
TestingAuthenticationToken authentication = new TestingAuthenticationToken("foo", "bar", Arrays.asList(authority));
authentication.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
// gh-4085
@Test
public void securityCheckWhenCustomAuthorityThenNameIsUsed() {
strategy = new AclAuthorizationStrategyImpl(new CustomAuthority());
strategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL);
}
@SuppressWarnings("serial")
class CustomAuthority implements GrantedAuthority {
@Override
public String getAuthority() {
return authority.getAuthority();
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* 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.
@@ -61,14 +61,14 @@ public class AuditLoggerTests {
public void nonAuditableAceIsIgnored() {
AccessControlEntry ace = mock(AccessControlEntry.class);
logger.logIfNeeded(true, ace);
assertThat(bytes.size()).isZero();
assertThat(bytes.size()).isEqualTo(0);
}
@Test
public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() throws Exception {
when(ace.isAuditSuccess()).thenReturn(false);
logger.logIfNeeded(true, ace);
assertThat(bytes.size()).isZero();
assertThat(bytes.size()).isEqualTo(0);
}
@Test
@@ -76,20 +76,20 @@ public class AuditLoggerTests {
when(ace.isAuditSuccess()).thenReturn(true);
logger.logIfNeeded(true, ace);
assertThat(bytes.toString()).startsWith("GRANTED due to ACE");
assertThat(bytes.toString().startsWith("GRANTED due to ACE")).isTrue();
}
@Test
public void failureIsntLoggedIfAceDoesntRequireFailureAudit() throws Exception {
when(ace.isAuditFailure()).thenReturn(false);
logger.logIfNeeded(false, ace);
assertThat(bytes.size()).isZero();
assertThat(bytes.size()).isEqualTo(0);
}
@Test
public void failureIsLoggedIfAceRequiresFailureAudit() throws Exception {
when(ace.isAuditFailure()).thenReturn(true);
logger.logIfNeeded(false, ace);
assertThat(bytes.toString()).startsWith("DENIED due to ACE");
assertThat(bytes.toString().startsWith("DENIED due to ACE")).isTrue();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* 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.
@@ -137,9 +137,9 @@ public class ObjectIdentityImplTests {
String string = "SOME_STRING";
assertThat(string).isNotSameAs(obj);
assertThat(obj).isNotNull();
assertThat(obj).isNotEqualTo("DIFFERENT_OBJECT_TYPE");
assertThat(obj).isNotEqualTo(new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(2)));
assertThat(obj.equals(null)).isFalse();
assertThat(obj.equals("DIFFERENT_OBJECT_TYPE")).isFalse();
assertThat(obj.equals(new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(2)))).isFalse();
assertThat(obj).isNotEqualTo(new ObjectIdentityImpl(
"org.springframework.security.acls.domain.ObjectIdentityImplTests$MockOtherIdDomainObject",
Long.valueOf(1)));
@@ -151,7 +151,7 @@ public class ObjectIdentityImplTests {
public void hashcodeIsDifferentForDifferentJavaTypes() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, Long.valueOf(1));
ObjectIdentity obj2 = new ObjectIdentityImpl(String.class, Long.valueOf(1));
assertThat(obj.hashCode()).isNotEqualTo(obj2.hashCode());
assertThat(obj.hashCode() == obj2.hashCode()).isFalse();
}
@Test
@@ -175,7 +175,7 @@ public class ObjectIdentityImplTests {
public void stringAndNumericIdsAreNotEqual() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, "1000");
ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, Long.valueOf(1000));
assertThat(obj).isNotEqualTo(obj2);
assertThat(obj.equals(obj2)).isFalse();
}
// ~ Inner Classes
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* 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.
@@ -104,17 +104,17 @@ public class SpringCacheBasedAclCacheTests {
// Try to evict an entry that doesn't exist
myCache.evictFromCache(Long.valueOf(3));
myCache.evictFromCache(new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(102)));
assertThat(realCache).hasSize(4);
assertThat(4).isEqualTo(realCache.size());
myCache.evictFromCache(Long.valueOf(1));
assertThat(realCache).hasSize(2);
assertThat(2).isEqualTo(realCache.size());
// Check the second object inserted
assertThat(acl2).isEqualTo(myCache.getFromCache(Long.valueOf(2)));
assertThat(acl2).isEqualTo(myCache.getFromCache(identity2));
myCache.evictFromCache(identity2);
assertThat(realCache).isEmpty();
assertThat(0).isEqualTo(realCache.size());
}
@SuppressWarnings("rawtypes")
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "https://www.springframework.org/dtd/spring-beans.dtd">
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!--
- Application context containing business beans.
+6 -6
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-aspects</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<name>spring-security-aspects</name>
<description>spring-security-aspects</description>
<url>https://spring.io/spring-security</url>
@@ -35,7 +35,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.23.RELEASE</version>
<version>4.3.14.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -45,7 +45,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -79,7 +79,7 @@
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.14</version>
<version>1.8.4</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@@ -92,7 +92,7 @@
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
<version>1.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -116,7 +116,7 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
<version>1.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
-3
View File
@@ -1,8 +1,5 @@
apply plugin: 'maven-bom'
apply from: "$rootDir/gradle/maven-deployment.gradle"
apply from: "$rootDir/gradle/artifactory.gradle"
apply from: "$rootDir/gradle/ossrh.gradle"
apply from: "$rootDir/gradle/deploy-artifacts.gradle"
generatePom.enabled = false
sonarqube.skipProject = true
+13 -54
View File
@@ -1,48 +1,34 @@
buildscript {
repositories {
maven {
url = 'https://repo.spring.io/plugins-snapshot'
if (project.hasProperty('artifactoryUsername')) {
credentials {
username "$artifactoryUsername"
password "$artifactoryPassword"
}
}
}
maven { url "https://repo.spring.io/plugins-release" }
}
dependencies {
classpath "com.github.ben-manes:gradle-versions-plugin:0.17.0"
classpath("org.springframework.build.gradle:propdeps-plugin:0.0.7")
classpath("io.spring.gradle:spring-io-plugin:0.0.8.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.7')
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.5.22.RELEASE")
classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.12.0"
classpath 'org.hidetake:gradle-ssh-plugin:2.10.1'
classpath 'io.codearte.gradle.nexus:gradle-nexus-staging-plugin:0.10.0'
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'
apply from: "$rootDir/gradle/finalize-deploy.gradle"
description = 'Spring Security'
allprojects {
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: "com.github.ben-manes.versions"
ext.releaseBuild = version.endsWith('RELEASE')
ext.snapshotBuild = version.endsWith('SNAPSHOT')
ext.springVersion = '4.3.30.RELEASE'
ext.springLdapVersion = '2.3.3.RELEASE'
ext.springVersion = '4.3.14.RELEASE'
ext.springLdapVersion = '2.2.0.RELEASE'
group = 'org.springframework.security'
@@ -53,6 +39,7 @@ allprojects {
maven { url "https://repo.terracotta.org/maven2/" }
}
eclipse.project.name = "${project.name}-4.1.x"
}
sonarqube {
@@ -72,7 +59,6 @@ sonarqube {
// Set up different subproject lists for individual configuration
ext.javaProjects = subprojects.findAll { project -> project.name != 'docs' && project.name != 'manual' && project.name != 'guides' && project.name != 'spring-security-bom' }
ext.sampleProjects = subprojects.findAll { project -> project.name.startsWith('spring-security-samples') }
ext.sampleBootProjects = subprojects.findAll { project -> project.name.startsWith('spring-security-samples-boot') }
ext.itestProjects = subprojects.findAll { project -> project.name.startsWith('itest') }
ext.coreModuleProjects = javaProjects - sampleProjects - itestProjects
ext.aspectjProjects = [project(':spring-security-aspects'), project(':spring-security-samples-xml-aspectj'), project(':spring-security-samples-javaconfig-aspectj')]
@@ -97,6 +83,7 @@ configure(allprojects - javaProjects) {
}
configure(subprojects - coreModuleProjects - project(':spring-security-samples-javaconfig-messages') - project(':spring-security-bom')) {
tasks.findByPath("artifactoryPublish")?.enabled = false
sonarqube {
skipProject = true
}
@@ -112,39 +99,28 @@ configure(javaProjects) {
}
apply from: "$rootDir/gradle/ide.gradle"
apply from: "$rootDir/gradle/release-checks.gradle"
apply from: "$rootDir/gradle/maven-deployment.gradle"
}
configure(coreModuleProjects) {
apply from: "$rootDir/gradle/maven-deployment.gradle"
apply from: "$rootDir/gradle/artifactory.gradle"
apply from: "$rootDir/gradle/ossrh.gradle"
apply from: "$rootDir/gradle/deploy-artifacts.gradle"
apply plugin: 'emma'
apply plugin: 'spring-io'
ext.springIoVersion = project.hasProperty('platformVersion') ? platformVersion : 'Brussels-SR9'
ext.springIoVersion = project.hasProperty('platformVersion') ? platformVersion : '2.0.1.RELEASE'
configurations {
jacoco //Configuration Group used by Sonar to provide Code Coverage using JaCoCo
}
dependencyManagement {
imports {
mavenBom("org.springframework:spring-framework-bom:${springVersion}")
}
springIoTestRuntime {
imports {
mavenBom("io.spring.platform:platform-bom:${springIoVersion}") {
bomProperties([
'assertj.version': '2.6.0',
'mockito.version': '1.10.19'
])
}
mavenBom "io.spring.platform:platform-bom:${springIoVersion}"
}
}
}
dependencies {
jacoco "org.jacoco:org.jacoco.agent:0.7.9:runtime"
jacoco "org.jacoco:org.jacoco.agent:0.7.5.201505241946:runtime"
}
test {
jvmArgs "-javaagent:${configurations.jacoco.asPath}=destfile=${buildDir}/jacoco.exec,includes=${project.group}.*"
@@ -210,20 +186,3 @@ artifacts {
archives project(':docs').docsZip
archives project(':docs').schemaZip
}
if (project.hasProperty('artifactoryUsername')) {
allprojects { project ->
project.repositories { repos ->
all { repo ->
if (!repo.url.toString().startsWith("https://repo.spring.io/")) {
return;
}
repo.credentials {
username = artifactoryUsername
password = artifactoryPassword
}
}
}
}
}
+8
View File
@@ -2,6 +2,14 @@ apply plugin: 'groovy'
repositories {
mavenCentral()
maven {
name = 'SpringSource Enterprise Release'
url = 'https://repository.springsource.com/maven/bundles/release'
}
maven {
name = 'SpringSource Enterprise External'
url = 'https://repository.springsource.com/maven/bundles/external'
}
}
dependencies {
@@ -15,6 +15,5 @@ public class MavenBomPlugin implements Plugin<Project> {
project.plugins.apply(MavenPlugin)
project.task(MAVEN_BOM_TASK_NAME, type: MavenBomTask, group: 'Generate', description: 'Configures the pom as a Maven Build of Materials (BOM)')
project.install.dependsOn project.mavenBom
project.uploadArchives.dependsOn project.mavenBom
}
}
+17 -27
View File
@@ -13,47 +13,37 @@ public class MavenBomTask extends DefaultTask {
public MavenBomTask() {
this.group = "Generate"
this.description = "Generates a Maven Build of Materials (BOM). See https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Importing_Dependencies"
this.description = "Generates a Maven Build of Materials (BOM). See http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Importing_Dependencies"
this.projects = project.subprojects
this.bomFile = project.file("${->project.buildDir}/maven-bom/${->project.name}-${->project.version}.txt")
}
@TaskAction
public void configureBom() {
// project.configurations.archives.artifacts.clear()
project.configurations.archives.artifacts.clear()
bomFile.parentFile.mkdirs()
bomFile.write("Maven Build of Materials (BOM). See https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Importing_Dependencies")
bomFile.write("Maven Build of Materials (BOM). See http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Importing_Dependencies")
project.artifacts {
// work around GRADLE-2406 by attaching text artifact
archives(bomFile)
}
project.install {
repositories.mavenInstaller {
customizePom(pom)
}
}
pom.whenConfigured {
packaging = "pom"
withXml {
asNode().children().last() + {
delegate.dependencyManagement {
delegate.dependencies {
projects.sort { dep -> "$dep.group:$dep.name" }.each { p ->
project.uploadArchives {
repositories.mavenDeployer {
customizePom(pom)
}
}
}
public void customizePom(pom) {
pom.whenConfigured {
packaging = "pom"
withXml {
asNode().children().last() + {
delegate.dependencyManagement {
delegate.dependencies {
projects.sort { dep -> "$dep.group:$dep.name" }.each { p ->
delegate.dependency {
delegate.groupId(p.group)
delegate.artifactId(p.name)
delegate.version(p.version)
delegate.dependency {
delegate.groupId(p.group)
delegate.artifactId(p.name)
delegate.version(p.version)
}
}
}
}
}
@@ -62,4 +52,4 @@ public class MavenBomTask extends DefaultTask {
}
}
}
}
}
@@ -4,13 +4,12 @@ import org.gradle.api.Project
import org.gradle.api.Plugin
import org.gradle.api.tasks.TaskAction
import org.gradle.api.logging.LogLevel
import org.gradle.api.file.*
import org.gradle.api.file.FileCollection
import org.gradle.api.tasks.SourceSet
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.plugins.ide.eclipse.GenerateEclipseProject
import org.gradle.plugins.ide.eclipse.GenerateEclipseClasspath
import org.gradle.plugins.ide.eclipse.EclipsePlugin
@@ -42,25 +41,28 @@ class AspectJPlugin implements Plugin<Project> {
project.configurations.create('aspectpath')
}
project.tasks.withType(JavaCompile) { javaCompileTask ->
def javaCompileTaskName = javaCompileTask.name
def ajCompileTask = project.tasks.create(name: javaCompileTaskName + 'Aspect', overwrite: true, description: 'Compiles AspectJ Source', type: Ajc) {
inputs.files(javaCompileTask.inputs.files)
inputs.properties(javaCompileTask.inputs.properties)
sourceRoots.addAll(project.sourceSets.main.java.srcDirs)
if(javaCompileTaskName.contains("Test")) {
sourceRoots.addAll(project.sourceSets.test.java.srcDirs)
}
compileClasspath = javaCompileTask.classpath
destinationDir = javaCompileTask.destinationDir
aspectPath = project.configurations.aspectpath
}
javaCompileTask.deleteAllActions()
javaCompileTask.dependsOn ajCompileTask
project.tasks.create(name: 'compileAspect', overwrite: true, description: 'Compiles AspectJ Source', type: Ajc) {
dependsOn project.configurations*.getTaskDependencyFromProjectDependency(true, "compileJava")
dependsOn project.processResources
sourceSet = project.sourceSets.main
inputs.files(sourceSet.allSource)
outputs.dir(sourceSet.output.classesDir)
aspectPath = project.configurations.aspectpath
}
project.tasks.compileJava.deleteAllActions()
project.tasks.compileJava.dependsOn project.tasks.compileAspect
project.tasks.create(name: 'compileTestAspect', overwrite: true, description: 'Compiles AspectJ Test Source', type: Ajc) {
dependsOn project.processTestResources, project.compileJava, project.jar
sourceSet = project.sourceSets.test
inputs.files(sourceSet.allSource)
outputs.dir(sourceSet.output.classesDir)
aspectPath = project.files(project.configurations.aspectpath, project.jar.archivePath)
}
project.tasks.compileTestJava.deleteAllActions()
project.tasks.compileTestJava.dependsOn project.tasks.compileTestAspect
project.tasks.withType(GenerateEclipseProject) {
project.eclipse.project.file.whenMerged { p ->
@@ -89,9 +91,7 @@ class AspectJPlugin implements Plugin<Project> {
}
class Ajc extends DefaultTask {
Set<File> sourceRoots = []
FileCollection compileClasspath
File destinationDir
SourceSet sourceSet
FileCollection aspectPath
Ajc() {
@@ -103,18 +103,15 @@ class Ajc extends DefaultTask {
logger.info("="*30)
logger.info("="*30)
logger.info("Running ajc ...")
logger.info("classpath: ${compileClasspath?.files}")
logger.info("srcDirs ${sourceRoots}")
logger.info("classpath: ${sourceSet.compileClasspath.asPath}")
logger.info("srcDirs $sourceSet.java.srcDirs")
ant.taskdef(resource: "org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: project.configurations.ajtools.asPath)
if(sourceRoots.empty) {
return
}
ant.iajc(classpath: compileClasspath.asPath, fork: 'true', destDir: destinationDir.absolutePath,
ant.iajc(classpath: sourceSet.compileClasspath.asPath, fork: 'true', destDir: sourceSet.output.classesDir.absolutePath,
source: project.convention.plugins.java.sourceCompatibility,
target: project.convention.plugins.java.targetCompatibility,
aspectPath: aspectPath.asPath, sourceRootCopyFilter: '**/*.java', showWeaveInfo: 'true') {
sourceroots {
sourceRoots.each {
sourceSet.java.srcDirs.each {
logger.info(" sourceRoot $it")
pathelement(location: it.absolutePath)
}
+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:$jacksonDatabindVersion"
testCompile "org.skyscreamer:jsonassert:$jsonassertVersion"
optional "net.sf.ehcache:ehcache:$ehcacheVersion"
provided "javax.servlet:javax.servlet-api:$servletApiVersion"
}
+8 -21
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<name>spring-security-cas</name>
<description>spring-security-cas</description>
<url>https://spring.io/spring-security</url>
@@ -35,7 +35,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.23.RELEASE</version>
<version>4.3.14.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -51,13 +51,13 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.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.8.11.3</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
@@ -103,20 +96,20 @@
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
<version>2.9.0</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
<version>1.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -137,16 +130,10 @@
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
<version>1.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -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;
@@ -26,7 +26,7 @@ import org.springframework.util.Assert;
/**
* Caches tickets using a Spring IoC defined <a
* href="https://www.ehcache.org/">EHCACHE</a>.
* href="http://ehcache.sourceforge.net">EHCACHE</a>.
*
* @author Ben Alex
*/
@@ -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
*
* https://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.SecurityJackson2Modules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@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
*
* https://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.SecurityJackson2Modules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@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
*
* https://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.SecurityJackson2Modules
* @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
*
* https://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.SecurityJackson2Modules;
/**
* Jackson module for spring-security-cas. This module register {@link AssertionImplMixin},
* {@link AttributePrincipalImplMixin} and {@link CasAuthenticationTokenMixin}. If no default typing enabled by default then
* it'll enable it because typing info is needed to properly serialize/deserialize objects. In order to use this module just
* add this module into your ObjectMapper configuration.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
* <b>Note: use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get list of all security modules on the classpath.</b>
*
* @author Jitendra Singh.
* @see org.springframework.security.jackson2.SecurityJackson2Modules
* @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) {
SecurityJackson2Modules.enableDefaultTyping((ObjectMapper) context.getOwner());
context.setMixInAnnotations(AssertionImpl.class, AssertionImplMixin.class);
context.setMixInAnnotations(AttributePrincipalImpl.class, AttributePrincipalImplMixin.class);
context.setMixInAnnotations(CasAuthenticationToken.class, CasAuthenticationTokenMixin.class);
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
/**
* Spring Security support for Jasig's Central Authentication Service (<a href="https://www.jasig.org/cas">CAS</a>).
* Spring Security support for Jasig's Central Authentication Service (<a href="http://www.jasig.org/cas">CAS</a>).
*/
package org.springframework.security.cas;
@@ -132,7 +132,7 @@ final class DefaultServiceAuthenticationDetails extends WebAuthenticationDetails
* @return
*/
static Pattern createArtifactPattern(String artifactParameterName) {
Assert.hasLength(artifactParameterName, "artifactParameterName is expected to have a length");
Assert.hasLength(artifactParameterName);
return Pattern.compile("&?" + Pattern.quote(artifactParameterName) + "=[^&]*");
}
@@ -47,7 +47,7 @@ public class ServiceAuthenticationDetailsSource implements
// ===================================================================================================
/**
* Creates an implementation that uses the specified ServiceProperties and the default
* Creates an implementation that uses the specified ServiceProperites and the default
* CAS artifactParameterName.
*
* @param serviceProperties The ServiceProperties to use to construct the serviceUrl.
@@ -66,7 +66,7 @@ public class CasAuthenticationProviderTests {
private ServiceProperties makeServiceProperties() {
final ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setSendRenew(false);
serviceProperties.setService("https://localhost");
serviceProperties.setService("http://test.com");
return serviceProperties;
}
@@ -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
*
* https://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.SecurityJackson2Modules;
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.Collections$UnmodifiableRandomAccessList\", [" + 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.HashMap\"}, "
+ "\"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.HashMap\"}" +
"}"
+ "}";
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(SecurityJackson2Modules.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);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* 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.
@@ -57,7 +57,10 @@ public class GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests {
assertion, "ticket");
UserDetails user = uds.loadUserDetails(token);
Set<String> roles = AuthorityUtils.authorityListToSet(user.getAuthorities());
assertThat(roles).containsOnly(
"role_a1", "role_a2", "role_b", "role_c");
assertThat(roles.size()).isEqualTo(4);
assertThat(roles).contains("role_a1");
assertThat(roles).contains("role_a2");
assertThat(roles).contains("role_b");
assertThat(roles).contains("role_c");
}
}
@@ -16,6 +16,11 @@
package org.springframework.security.cas.web;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import javax.servlet.FilterChain;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.junit.After;
import org.junit.Test;
@@ -30,13 +35,9 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.FilterChain;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
/**
* Tests {@link CasAuthenticationFilter}.
*
@@ -145,7 +146,8 @@ public class CasAuthenticationFilterTests {
.createAuthorityList("ROLE_ANONYMOUS")));
assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("un", "principal"));
new TestingAuthenticationToken("un", "principal", AuthorityUtils
.createAuthorityList("ROLE_ANONYMOUS")));
assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("un", "principal", "ROLE_ANONYMOUS"));
@@ -2,7 +2,7 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="serviceProperties"
class="org.springframework.security.cas.ServiceProperties">
@@ -2,7 +2,7 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="serviceProperties"
class="org.springframework.security.cas.ServiceProperties">
+3 -2
View File
@@ -39,8 +39,8 @@ dependencies {
"org.springframework:spring-orm:$springVersion",
"org.springframework:spring-tx:$springVersion",
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
"org.eclipse.persistence:javax.persistence:$javaPersistenceVersion",
"org.hibernate:hibernate-entitymanager:$hibernateVersion",
"org.eclipse.persistence:javax.persistence:2.0.5",
"org.hibernate:hibernate-entitymanager:4.1.0.Final",
"org.codehaus.groovy:groovy-all:$groovyVersion",
"org.apache.directory.server:apacheds-core:$apacheDsVersion",
"org.apache.directory.server:apacheds-core-entry:$apacheDsVersion",
@@ -50,6 +50,7 @@ dependencies {
'org.apache.directory.shared:shared-ldap:0.9.15',
'ldapsdk:ldapsdk:4.1',
powerMockDependencies,
"org.hibernate:hibernate-entitymanager:3.6.10.Final",
"org.hsqldb:hsqldb:$hsqlVersion",
spockDependencies
+25 -25
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<name>spring-security-config</name>
<description>spring-security-config</description>
<url>https://spring.io/spring-security</url>
@@ -35,7 +35,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.23.RELEASE</version>
<version>4.3.14.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -51,7 +51,7 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -90,35 +90,35 @@
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.14</version>
<version>1.8.4</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-openid</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@@ -155,19 +155,19 @@
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.10</version>
<version>3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
<version>1.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -239,19 +239,19 @@
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.1</version>
<version>2.0.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.12.Final</version>
<version>4.1.0.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.6</version>
<version>2.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -275,7 +275,7 @@
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.5</version>
<version>1.6.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
@@ -287,37 +287,37 @@
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-support</artifactId>
<version>1.6.5</version>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.6.5</version>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.5</version>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-common</artifactId>
<version>1.6.5</version>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-reflect</artifactId>
<version>1.6.5</version>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
<version>1.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -347,7 +347,7 @@
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.20.RELEASE</version>
<version>1.10.2.RELEASE</version>
<scope>test</scope>
<exclusions>
<exclusion>
@@ -359,19 +359,19 @@
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.3.2.RELEASE</version>
<version>2.2.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-aspects</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>4.2.13.RELEASE</version>
<version>4.1.5.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -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
@@ -86,7 +86,7 @@ public final class SecurityNamespaceHandler implements NamespaceHandler {
if (!namespaceMatchesVersion(element)) {
pc.getReaderContext()
.fatal("You cannot use a spring-security-2.0.xsd or spring-security-3.0.xsd or spring-security-3.1.xsd schema or spring-security-3.2.xsd schema or spring-security-4.0.xsd schema "
+ "with Spring Security 4.2. Please update your schema declarations to the 4.2 schema.",
+ "with Spring Security 4.1. Please update your schema declarations to the 4.1 schema.",
element);
}
String name = pc.getDelegate().getLocalName(element);
@@ -221,7 +221,7 @@ public final class SecurityNamespaceHandler implements NamespaceHandler {
private boolean matchesVersionInternal(Element element) {
String schemaLocation = element.getAttributeNS(
"http://www.w3.org/2001/XMLSchema-instance", "schemaLocation");
return schemaLocation.matches("(?m).*spring-security-4\\.2.*.xsd.*")
return schemaLocation.matches("(?m).*spring-security-4\\.1.*.xsd.*")
|| schemaLocation.matches("(?m).*spring-security.xsd.*")
|| !schemaLocation.matches("(?m).*spring-security.*");
}
@@ -141,8 +141,8 @@ public class AuthenticationManagerBuilder
*
* <p>
* When using with a persistent data store, it is best to add users external of
* configuration using something like <a href="https://flywaydb.org/">Flyway</a> or <a
* href="https://www.liquibase.org/">Liquibase</a> to create the schema and adding
* configuration using something like <a href="http://flywaydb.org/">Flyway</a> or <a
* href="http://www.liquibase.org/">Liquibase</a> to create the schema and adding
* users to ensure these steps are only done once and that the optimal SQL is used.
* </p>
*
@@ -151,7 +151,7 @@ public class AuthenticationManagerBuilder
* {@link #getDefaultUserDetailsService()} method. Note that additional
* {@link UserDetailsService}'s may override this {@link UserDetailsService} as the
* default. See the <a href=
* "https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#user-schema"
* "http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#user-schema"
* >User Schema</a> section of the reference for the default schema.
* </p>
*
@@ -31,13 +31,11 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.Assert;
@@ -50,7 +48,6 @@ import org.springframework.util.Assert;
*
*/
@Configuration
@Import(ObjectPostProcessorConfiguration.class)
public class AuthenticationConfiguration {
private AtomicBoolean buildingAuthenticationManager = new AtomicBoolean();
@@ -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());
}
}
}
@@ -16,16 +16,19 @@
package org.springframework.security.config.annotation.authentication.configurers.provisioning;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.authentication.ProviderManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.userdetails.UserDetailsServiceConfigurer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.util.Assert;
/**
* Base class for populating an
@@ -79,7 +82,13 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* should provided. The remaining attributes have reasonable defaults.
*/
public class UserDetailsBuilder {
private UserBuilder user;
private String username;
private String password;
private List<GrantedAuthority> authorities;
private boolean accountExpired;
private boolean accountLocked;
private boolean credentialsExpired;
private boolean disabled;
private final C builder;
/**
@@ -108,7 +117,8 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* additional attributes for this user)
*/
private UserDetailsBuilder username(String username) {
this.user = User.withUsername(username);
Assert.notNull(username, "username cannot be null");
this.username = username;
return this;
}
@@ -120,7 +130,8 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* additional attributes for this user)
*/
public UserDetailsBuilder password(String password) {
this.user.password(password);
Assert.notNull(password, "password cannot be null");
this.password = password;
return this;
}
@@ -150,8 +161,14 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* additional attributes for this user)
*/
public UserDetailsBuilder roles(String... roles) {
this.user.roles(roles);
return this;
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(
roles.length);
for (String role : roles) {
Assert.isTrue(!role.startsWith("ROLE_"), role
+ " cannot start with ROLE_ (it is automatically added)");
authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
return authorities(authorities);
}
/**
@@ -164,8 +181,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* @see #roles(String...)
*/
public UserDetailsBuilder authorities(GrantedAuthority... authorities) {
this.user.authorities(authorities);
return this;
return authorities(Arrays.asList(authorities));
}
/**
@@ -178,7 +194,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* @see #roles(String...)
*/
public UserDetailsBuilder authorities(List<? extends GrantedAuthority> authorities) {
this.user.authorities(authorities);
this.authorities = new ArrayList<GrantedAuthority>(authorities);
return this;
}
@@ -192,8 +208,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* @see #roles(String...)
*/
public UserDetailsBuilder authorities(String... authorities) {
this.user.authorities(authorities);
return this;
return authorities(AuthorityUtils.createAuthorityList(authorities));
}
/**
@@ -204,7 +219,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* additional attributes for this user)
*/
public UserDetailsBuilder accountExpired(boolean accountExpired) {
this.user.accountExpired(accountExpired);
this.accountExpired = accountExpired;
return this;
}
@@ -216,7 +231,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* additional attributes for this user)
*/
public UserDetailsBuilder accountLocked(boolean accountLocked) {
this.user.accountLocked(accountLocked);
this.accountLocked = accountLocked;
return this;
}
@@ -228,7 +243,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* additional attributes for this user)
*/
public UserDetailsBuilder credentialsExpired(boolean credentialsExpired) {
this.user.credentialsExpired(credentialsExpired);
this.credentialsExpired = credentialsExpired;
return this;
}
@@ -240,12 +255,13 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* additional attributes for this user)
*/
public UserDetailsBuilder disabled(boolean disabled) {
this.user.disabled(disabled);
this.disabled = disabled;
return this;
}
private UserDetails build() {
return this.user.build();
return new User(username, password, !disabled, !accountExpired,
!credentialsExpired, !accountLocked, authorities);
}
}
}
@@ -16,10 +16,8 @@
package org.springframework.security.config.annotation.configuration;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@@ -36,11 +34,9 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
* @since 3.2
*/
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class ObjectPostProcessorConfiguration {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public ObjectPostProcessor<Object> objectPostProcessor(
AutowireCapableBeanFactory beanFactory) {
return new AutowireBeanFactoryObjectPostProcessor(beanFactory);
@@ -25,6 +25,7 @@ import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration;
/**
* <p>
@@ -44,7 +45,7 @@ import org.springframework.security.config.annotation.authentication.configurati
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ GlobalMethodSecuritySelector.class })
@Import({ GlobalMethodSecuritySelector.class, ObjectPostProcessorConfiguration.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableGlobalMethodSecurity {
@@ -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.
@@ -28,10 +28,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.context.annotation.Role;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.AnnotationMetadata;
@@ -68,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;
/**
@@ -77,12 +74,10 @@ import org.springframework.util.Assert;
* {@link EnableGlobalMethodSecurity} annotation on the subclass.
*
* @author Rob Winch
* @author Eddú Meléndez
* @since 3.2
* @see EnableGlobalMethodSecurity
*/
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class GlobalMethodSecurityConfiguration
implements ImportAware, SmartInitializingSingleton {
private static final Log logger = LogFactory
@@ -173,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) {
@@ -367,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);
@@ -418,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;
}
@@ -467,4 +449,4 @@ public class GlobalMethodSecurityConfiguration
}
return this.enableMethodSecurity;
}
}
}
@@ -15,18 +15,14 @@
*/
package org.springframework.security.config.annotation.method.configuration;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.security.access.annotation.Jsr250MethodSecurityMetadataSource;
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
class Jsr250MetadataSourceConfiguration {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource() {
return new Jsr250MethodSecurityMetadataSource();
}
@@ -201,17 +201,17 @@ public final class HttpSecurity extends
* .authenticationUserDetailsService(
* new AutoProvisioningUserDetailsService())
* .attributeExchange(&quot;https://www.google.com/.*&quot;).attribute(&quot;email&quot;)
* .type(&quot;https://axschema.org/contact/email&quot;).required(true).and()
* .attribute(&quot;firstname&quot;).type(&quot;https://axschema.org/namePerson/first&quot;)
* .type(&quot;http://axschema.org/contact/email&quot;).required(true).and()
* .attribute(&quot;firstname&quot;).type(&quot;http://axschema.org/namePerson/first&quot;)
* .required(true).and().attribute(&quot;lastname&quot;)
* .type(&quot;https://axschema.org/namePerson/last&quot;).required(true).and().and()
* .type(&quot;http://axschema.org/namePerson/last&quot;).required(true).and().and()
* .attributeExchange(&quot;.*yahoo.com.*&quot;).attribute(&quot;email&quot;)
* .type(&quot;https://schema.openid.net/contact/email&quot;).required(true).and()
* .attribute(&quot;fullname&quot;).type(&quot;https://axschema.org/namePerson&quot;)
* .type(&quot;http://schema.openid.net/contact/email&quot;).required(true).and()
* .attribute(&quot;fullname&quot;).type(&quot;http://axschema.org/namePerson&quot;)
* .required(true).and().and().attributeExchange(&quot;.*myopenid.com.*&quot;)
* .attribute(&quot;email&quot;).type(&quot;https://schema.openid.net/contact/email&quot;)
* .attribute(&quot;email&quot;).type(&quot;http://schema.openid.net/contact/email&quot;)
* .required(true).and().attribute(&quot;fullname&quot;)
* .type(&quot;https://schema.openid.net/namePerson&quot;).required(true);
* .type(&quot;http://schema.openid.net/namePerson&quot;).required(true);
* }
* }
*
@@ -906,7 +906,7 @@ public final class HttpSecurity extends
* requiring HTTPS for some requests is supported, but not recommended since an
* application that allows for HTTP introduces many security vulnerabilities. For one
* such example, read about <a
* href="https://en.wikipedia.org/wiki/Firesheep">Firesheep</a>.
* href="http://en.wikipedia.org/wiki/Firesheep">Firesheep</a>.
*
* <pre>
* &#064;Configuration
@@ -25,7 +25,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpMethod;
@@ -114,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
@@ -383,8 +382,5 @@ public final class WebSecurity extends
this.defaultWebSecurityExpressionHandler
.setApplicationContext(applicationContext);
this.ignoredRequestRegistry = new IgnoredRequestConfigurer(applicationContext);
try {
this.httpFirewall = applicationContext.getBean(HttpFirewall.class);
} catch(NoSuchBeanDefinitionException e) {}
}
}
@@ -22,6 +22,7 @@ import java.lang.annotation.Target;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
/**
@@ -72,7 +73,7 @@ import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ WebSecurityConfiguration.class,
@Import({ WebSecurityConfiguration.class, ObjectPostProcessorConfiguration.class,
SpringWebMvcImportSelector.class })
@EnableGlobalAuthentication
@Configuration
@@ -15,14 +15,7 @@
*/
package org.springframework.security.config.annotation.web.configuration;
import java.util.List;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.BeanResolver;
import org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver;
import org.springframework.security.web.method.annotation.CsrfTokenArgumentResolver;
import org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor;
@@ -31,6 +24,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import java.util.List;
/**
* Used to add a {@link RequestDataValueProcessor} for Spring MVC and Spring Security CSRF
* integration. This configuration is added whenever {@link EnableWebMvc} is added by
@@ -41,15 +36,12 @@ import org.springframework.web.servlet.support.RequestDataValueProcessor;
* @author Rob Winch
* @since 3.2
*/
class WebMvcSecurityConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware {
private BeanResolver beanResolver;
class WebMvcSecurityConfiguration extends WebMvcConfigurerAdapter {
@Override
@SuppressWarnings("deprecation")
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
AuthenticationPrincipalArgumentResolver authenticationPrincipalResolver = new AuthenticationPrincipalArgumentResolver();
authenticationPrincipalResolver.setBeanResolver(beanResolver);
argumentResolvers.add(authenticationPrincipalResolver);
argumentResolvers.add(new AuthenticationPrincipalArgumentResolver());
argumentResolvers
.add(new org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver());
argumentResolvers.add(new CsrfTokenArgumentResolver());
@@ -59,9 +51,4 @@ class WebMvcSecurityConfiguration extends WebMvcConfigurerAdapter implements App
public RequestDataValueProcessor requestDataValueProcessor() {
return new CsrfRequestDataValueProcessor();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.beanResolver = new BeanFactoryResolver(applicationContext.getAutowireCapableBeanFactory());
}
}
@@ -34,7 +34,6 @@ import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
@@ -45,7 +44,6 @@ import org.springframework.security.config.annotation.authentication.configurati
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.DefaultLoginPageConfigurer;
import org.springframework.security.config.annotation.web.configurers.SecurityContextConfigurer;
import org.springframework.security.core.Authentication;
@@ -61,23 +59,8 @@ import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
/**
* Provides a convenient base class for creating a {@link WebSecurityConfigurer}
* instance. The implementation allows customization by overriding methods.
*
* <p>
* Will automatically apply the result of looking up
* {@link AbstractHttpConfigurer} from {@link SpringFactoriesLoader} to allow
* developers to extend the defaults.
* To do this, you must create a class that extends AbstractHttpConfigurer and then create a file in the classpath at "META-INF/spring.factories" that looks something like:
* </p>
* <pre>
* org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyClassThatExtendsAbstractHttpConfigurer
* </pre>
* If you have multiple classes that should be added you can use "," to separate the values. For example:
*
* <pre>
* org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyClassThatExtendsAbstractHttpConfigurer, sample.OtherThatExtendsAbstractHttpConfigurer
* </pre>
* Provides a convenient base class for creating a {@link WebSecurityConfigurer} instance.
* The implementation allows customization by overriding methods.
*
* @see EnableWebSecurity
*
@@ -182,7 +165,6 @@ public abstract class WebSecurityConfigurerAdapter implements
* ] * @return the {@link HttpSecurity}
* @throws Exception
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected final HttpSecurity getHttp() throws Exception {
if (http != null) {
return http;
@@ -213,13 +195,6 @@ public abstract class WebSecurityConfigurerAdapter implements
.apply(new DefaultLoginPageConfigurer<HttpSecurity>()).and()
.logout();
// @formatter:on
ClassLoader classLoader = this.context.getClassLoader();
List<AbstractHttpConfigurer> defaultHttpConfigurers =
SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader);
for(AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
http.apply(configurer);
}
}
configure(http);
return http;
@@ -325,13 +300,6 @@ public abstract class WebSecurityConfigurerAdapter implements
/**
* Override this method to configure {@link WebSecurity}. For example, if you wish to
* ignore certain requests.
*
* Endpoints specified in this method will be ignored by Spring Security, meaning it
* will not protect them from CSRF, XSS, Clickjacking, and so on.
*
* Instead, if you want to protect endpoints against common vulnerabilities, then see
* {@link #configure(HttpSecurity)} and the {@link HttpSecurity#authorizeRequests}
* configuration method.
*/
public void configure(WebSecurity web) throws Exception {
}
@@ -345,10 +313,6 @@ public abstract class WebSecurityConfigurerAdapter implements
* http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
* </pre>
*
* Any endpoint that requires defense against common vulnerabilities can be specified here, including public ones.
* See {@link HttpSecurity#authorizeRequests} and the `permitAll()` authorization rule
* for more details on public endpoints.
*
* @param http the {@link HttpSecurity} to modify
* @throws Exception if an error occurs
*/
@@ -162,7 +162,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
/**
* Specifies the {@link AuthenticationSuccessHandler} to be used. The default is
* {@link SavedRequestAwareAuthenticationSuccessHandler} with no additional properties
* {@link SavedRequestAwareAuthenticationSuccessHandler} with no additional properites
* set.
*
* @param successHandler the {@link AuthenticationSuccessHandler}.
@@ -29,7 +29,7 @@ import org.springframework.security.web.DefaultSecurityFilterChain;
* @author Rob Winch
*
*/
public abstract class AbstractHttpConfigurer<T extends AbstractHttpConfigurer<T, B>, B extends HttpSecurityBuilder<B>>
abstract class AbstractHttpConfigurer<T extends AbstractHttpConfigurer<T, B>, B extends HttpSecurityBuilder<B>>
extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, B> {
/**
@@ -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);
@@ -365,7 +359,7 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
/**
* Specify that URLs requires a specific IP Address or <a href=
* "https://forum.spring.io/showthread.php?102783-How-to-use-hasIpAddress&p=343971#post343971"
* "http://forum.springsource.org/showthread.php?102783-How-to-use-hasIpAddress&p=343971#post343971"
* >subnet</a>.
*
* @param ipaddressExpression the ipaddress (i.e. 192.168.1.79) or local subnet
@@ -28,7 +28,6 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import org.springframework.security.web.header.HeaderWriter;
import org.springframework.security.web.header.HeaderWriterFilter;
import org.springframework.security.web.header.writers.*;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter.XFrameOptionsMode;
import org.springframework.security.web.util.matcher.RequestMatcher;
@@ -57,7 +56,6 @@ import org.springframework.util.Assert;
* @author Rob Winch
* @author Tim Ysewyn
* @author Joe Grandja
* @author Eddú Meléndez
* @since 3.2
*/
public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
@@ -80,8 +78,6 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
private final ContentSecurityPolicyConfig contentSecurityPolicy = new ContentSecurityPolicyConfig();
private final ReferrerPolicyConfig referrerPolicy = new ReferrerPolicyConfig();
/**
* Creates a new instance
*
@@ -104,7 +100,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
/**
* Configures the {@link XContentTypeOptionsHeaderWriter} which inserts the <a href=
* "https://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx"
* "http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx"
* >X-Content-Type-Options</a>:
*
* <pre>
@@ -160,7 +156,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
*
* <p>
* Allows customizing the {@link XXssProtectionHeaderWriter} which adds the <a href=
* "https://web.archive.org/web/20160201174302/https://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx"
* "http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx"
* >X-XSS-Protection header</a>
* </p>
*
@@ -306,7 +302,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
/**
* Allows customizing the {@link HstsHeaderWriter} which provides support for <a
* href="https://tools.ietf.org/html/rfc6797">HTTP Strict Transport Security
* href="http://tools.ietf.org/html/rfc6797">HTTP Strict Transport Security
* (HSTS)</a>.
*
* @return the {@link HeadersConfigurer} for additional customizations
@@ -331,7 +327,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
* <p>
* This instructs browsers how long to remember to keep this domain as a known
* HSTS Host. See <a
* href="https://tools.ietf.org/html/rfc6797#section-6.1.1">Section 6.1.1</a> for
* href="http://tools.ietf.org/html/rfc6797#section-6.1.1">Section 6.1.1</a> for
* additional details.
* </p>
*
@@ -364,7 +360,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.2">Section
* See <a href="http://tools.ietf.org/html/rfc6797#section-6.1.2">Section
* 6.1.2</a> for additional details.
* </p>
*
@@ -483,7 +479,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
/**
* Allows customizing the {@link HpkpHeaderWriter} which provides support for <a
* href="https://tools.ietf.org/html/rfc7469">HTTP Public Key Pinning (HPKP)</a>.
* href="http://tools.ietf.org/html/rfc7469">HTTP Public Key Pinning (HPKP)</a>.
*
* @return the {@link HeadersConfigurer} for additional customizations
*
@@ -506,7 +502,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
* <p>
* The pin directive specifies a way for web host operators to indicate
* a cryptographic identity that should be bound to a given web host.
* See <a href="https://tools.ietf.org/html/rfc7469#section-2.1.1">Section 2.1.1</a> for additional details.
* See <a href="http://tools.ietf.org/html/rfc7469#section-2.1.1">Section 2.1.1</a> for additional details.
* </p>
*
* @param pins the map of base64-encoded SPKI fingerprint &amp; cryptographic hash algorithm pairs.
@@ -525,7 +521,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
* <p>
* The pin directive specifies a way for web host operators to indicate
* a cryptographic identity that should be bound to a given web host.
* See <a href="https://tools.ietf.org/html/rfc7469#section-2.1.1">Section 2.1.1</a> for additional details.
* See <a href="http://tools.ietf.org/html/rfc7469#section-2.1.1">Section 2.1.1</a> for additional details.
* </p>
*
* @param pins a list of base64-encoded SPKI fingerprints.
@@ -544,7 +540,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
*
* <p>
* This instructs browsers how long they should regard the host (from whom the message was received)
* as a known pinned host. See <a href="https://tools.ietf.org/html/rfc7469#section-2.1.2">Section
* as a known pinned host. See <a href="http://tools.ietf.org/html/rfc7469#section-2.1.2">Section
* 2.1.2</a> for additional details.
* </p>
*
@@ -564,7 +560,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc7469#section-2.1.3">Section 2.1.3</a>
* See <a href="http://tools.ietf.org/html/rfc7469#section-2.1.3">Section 2.1.3</a>
* for additional details.
* </p>
*
@@ -581,7 +577,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc7469#section-2.1">Section 2.1</a>
* See <a href="http://tools.ietf.org/html/rfc7469#section-2.1">Section 2.1</a>
* for additional details.
* </p>
*
@@ -598,7 +594,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc7469#section-2.1.4">Section 2.1.4</a>
* See <a href="http://tools.ietf.org/html/rfc7469#section-2.1.4">Section 2.1.4</a>
* for additional details.
* </p>
*
@@ -615,7 +611,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc7469#section-2.1.4">Section 2.1.4</a>
* See <a href="http://tools.ietf.org/html/rfc7469#section-2.1.4">Section 2.1.4</a>
* for additional details.
* </p>
*
@@ -774,7 +770,6 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
addIfNotNull(writers, frameOptions.writer);
addIfNotNull(writers, hpkp.writer);
addIfNotNull(writers, contentSecurityPolicy.writer);
addIfNotNull(writers, referrerPolicy.writer);
writers.addAll(headerWriters);
return writers;
}
@@ -784,68 +779,4 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
values.add(value);
}
}
/**
* <p>
* Allows configuration for <a href="https://www.w3.org/TR/referrer-policy/">Referrer Policy</a>.
* </p>
*
* <p>
* Configuration is provided to the {@link ReferrerPolicyHeaderWriter} which support the writing
* of the header as detailed in the W3C Technical Report:
* </p>
* <ul>
* <li>Referrer-Policy</li>
* </ul>
*
* <p>Default value is:</p>
*
* <pre>
* Referrer-Policy: no-referrer
* </pre>
*
* @see ReferrerPolicyHeaderWriter
* @since 4.2
* @return the ReferrerPolicyConfig for additional configuration
*/
public ReferrerPolicyConfig referrerPolicy() {
this.referrerPolicy.writer = new ReferrerPolicyHeaderWriter();
return this.referrerPolicy;
}
/**
* <p>
* Allows configuration for <a href="https://www.w3.org/TR/referrer-policy/">Referrer Policy</a>.
* </p>
*
* <p>
* Configuration is provided to the {@link ReferrerPolicyHeaderWriter} which support the writing
* of the header as detailed in the W3C Technical Report:
* </p>
* <ul>
* <li>Referrer-Policy</li>
* </ul>
*
* @see ReferrerPolicyHeaderWriter
* @since 4.2
* @return the ReferrerPolicyConfig for additional configuration
* @throws IllegalArgumentException if policy is null or empty
*/
public ReferrerPolicyConfig referrerPolicy(ReferrerPolicy policy) {
this.referrerPolicy.writer = new ReferrerPolicyHeaderWriter(policy);
return this.referrerPolicy;
}
public final class ReferrerPolicyConfig {
private ReferrerPolicyHeaderWriter writer;
private ReferrerPolicyConfig() {
}
public HeadersConfigurer<H> and() {
return HeadersConfigurer.this;
}
}
}
@@ -129,7 +129,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>> extends
* <p>
* It is considered best practice to use an HTTP POST on any action that changes state
* (i.e. log out) to protect against <a
* href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">CSRF attacks</a>. If
* href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">CSRF attacks</a>. If
* you really want to use an HTTP GET, you can use
* <code>logoutRequestMatcher(new AntPathRequestMatcher(logoutUrl, "GET"));</code>
* </p>
@@ -23,7 +23,6 @@ import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
@@ -86,12 +85,6 @@ public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>> exte
return this;
}
@Override
public H disable() {
getBuilder().setSharedObject(RequestCache.class, new NullRequestCache());
return super.disable();
}
@Override
public void init(H http) throws Exception {
http.setSharedObject(RequestCache.class, getRequestCache(http));
@@ -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;
}
/**
@@ -481,7 +481,7 @@ final class AuthenticationConfigBuilder {
SimpleAttributes2GrantedAuthoritiesMapper.class));
String roles = jeeElt.getAttribute(ATT_MAPPABLE_ROLES);
Assert.hasLength(roles, "roles is expected to have length");
Assert.state(StringUtils.hasText(roles));
BeanDefinitionBuilder rolesBuilder = BeanDefinitionBuilder
.rootBeanDefinition(StringUtils.class);
rolesBuilder.addConstructorArgValue(roles);
@@ -45,7 +45,6 @@ import org.springframework.util.StringUtils;
* Parser for the {@code CsrfFilter}.
*
* @author Rob Winch
* @author Ankur Pathak
* @since 3.2
*/
public class CsrfBeanDefinitionParser implements BeanDefinitionParser {
@@ -68,13 +67,11 @@ public class CsrfBeanDefinitionParser implements BeanDefinitionParser {
boolean webmvcPresent = ClassUtils.isPresent(DISPATCHER_SERVLET_CLASS_NAME,
getClass().getClassLoader());
if (webmvcPresent) {
if (!pc.getRegistry().containsBeanDefinition(REQUEST_DATA_VALUE_PROCESSOR)) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(
CsrfRequestDataValueProcessor.class);
BeanComponentDefinition componentDefinition = new BeanComponentDefinition(
beanDefinition, REQUEST_DATA_VALUE_PROCESSOR);
pc.registerBeanComponent(componentDefinition);
}
RootBeanDefinition beanDefinition = new RootBeanDefinition(
CsrfRequestDataValueProcessor.class);
BeanComponentDefinition componentDefinition = new BeanComponentDefinition(
beanDefinition, REQUEST_DATA_VALUE_PROCESSOR);
pc.registerBeanComponent(componentDefinition);
}
String matcherRef = null;
@@ -15,16 +15,9 @@
*/
package org.springframework.security.config.http;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_REQUEST_MATCHER_REF;
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.BeanMetadataElement;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedMap;
@@ -40,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
@@ -102,7 +98,7 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
MatcherType matcherType = MatcherType.fromElement(httpElt);
boolean useExpressions = isUseExpressions(httpElt);
ManagedMap<BeanMetadataElement, BeanDefinition> requestToAttributesMap = parseInterceptUrlsForFilterInvocationRequestMap(
ManagedMap<BeanDefinition, BeanDefinition> requestToAttributesMap = parseInterceptUrlsForFilterInvocationRequestMap(
matcherType, interceptUrls, useExpressions, addAllAuth, pc);
BeanDefinitionBuilder fidsBuilder;
@@ -137,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,
@@ -151,11 +148,11 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
return !StringUtils.hasText(useExpressions) || "true".equals(useExpressions);
}
private static ManagedMap<BeanMetadataElement, BeanDefinition> parseInterceptUrlsForFilterInvocationRequestMap(
private static ManagedMap<BeanDefinition, BeanDefinition> parseInterceptUrlsForFilterInvocationRequestMap(
MatcherType matcherType, List<Element> urlElts, boolean useExpressions,
boolean addAuthenticatedAll, ParserContext parserContext) {
ManagedMap<BeanMetadataElement, BeanDefinition> filterInvocationDefinitionMap = new ManagedMap<BeanMetadataElement, BeanDefinition>();
ManagedMap<BeanDefinition, BeanDefinition> filterInvocationDefinitionMap = new ManagedMap<BeanDefinition, BeanDefinition>();
for (Element urlElt : urlElts) {
String access = urlElt.getAttribute(ATT_ACCESS);
@@ -164,10 +161,8 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
}
String path = urlElt.getAttribute(ATT_PATTERN);
String matcherRef = urlElt.getAttribute(ATT_REQUEST_MATCHER_REF);
boolean hasMatcherRef = StringUtils.hasText(matcherRef);
if (!hasMatcherRef && !StringUtils.hasText(path)) {
if (!StringUtils.hasText(path)) {
parserContext.getReaderContext().error(
"path attribute cannot be empty or null", urlElt);
}
@@ -185,7 +180,7 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'", urlElt);
}
BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference(matcherRef) : matcherType.createMatcher(parserContext, path,
BeanDefinition matcher = matcherType.createMatcher(parserContext, path,
method, servletPath);
BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder
.rootBeanDefinition(SecurityConfig.class);
@@ -194,7 +189,7 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
logger.info("Creating access control expression attribute '" + access
+ "' for " + path);
// The single expression will be parsed later by the
// ExpressionBasedFilterInvocationSecurityMetadataSource
// ExpressionFilterInvocationSecurityMetadataSource
attributeBuilder.addConstructorArgValue(new String[] { access });
attributeBuilder.setFactoryMethod("createList");
@@ -228,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
*
* https://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() {}
}
@@ -31,7 +31,6 @@ import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.security.web.header.HeaderWriterFilter;
import org.springframework.security.web.header.writers.*;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy;
import org.springframework.security.web.header.writers.frameoptions.RegExpAllowFromStrategy;
import org.springframework.security.web.header.writers.frameoptions.StaticAllowFromStrategy;
import org.springframework.security.web.header.writers.frameoptions.WhiteListedAllowFromStrategy;
@@ -46,7 +45,6 @@ import org.w3c.dom.Node;
*
* @author Marten Deinum
* @author Tim Ysewyn
* @author Eddú Meléndez
* @since 3.2
*/
public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
@@ -84,7 +82,6 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
private static final String GENERIC_HEADER_ELEMENT = "header";
private static final String CONTENT_SECURITY_POLICY_ELEMENT = "content-security-policy";
private static final String REFERRER_POLICY_ELEMENT = "referrer-policy";
private static final String ALLOW_FROM = "ALLOW-FROM";
@@ -112,17 +109,15 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
parseContentSecurityPolicyElement(disabled, element, parserContext);
parseReferrerPolicyElement(element, parserContext);
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;
}
@@ -296,23 +291,6 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
headerWriters.add(headersWriter.getBeanDefinition());
}
private void parseReferrerPolicyElement(Element element, ParserContext context) {
Element referrerPolicyElement = (element == null) ? null : DomUtils.getChildElementByTagName(element, REFERRER_POLICY_ELEMENT);
if (referrerPolicyElement != null) {
addReferrerPolicy(referrerPolicyElement, context);
}
}
private void addReferrerPolicy(Element referrerPolicyElement, ParserContext context) {
BeanDefinitionBuilder headersWriter = BeanDefinitionBuilder.genericBeanDefinition(ReferrerPolicyHeaderWriter.class);
String policy = referrerPolicyElement.getAttribute(ATT_POLICY);
if (StringUtils.hasLength(policy)) {
headersWriter.addConstructorArgValue(ReferrerPolicy.get(policy));
}
headerWriters.add(headersWriter.getBeanDefinition());
}
private void attrNotAllowed(ParserContext context, String attrName,
String otherAttrName, Element element) {
context.getReaderContext().error(
@@ -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,30 +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_REQUEST_MATCHER_REF;
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
@@ -115,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";
@@ -307,7 +289,6 @@ class HttpConfigurationBuilder {
String sessionFixationAttribute = null;
String invalidSessionUrl = null;
String invalidSessionStrategyRef = null;
String sessionAuthStratRef = null;
String errorUrl = null;
@@ -323,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);
@@ -332,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(
@@ -464,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);
@@ -484,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";
@@ -520,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();
@@ -561,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);
}
@@ -583,7 +543,7 @@ class HttpConfigurationBuilder {
}
private void createChannelProcessingFilter() {
ManagedMap<BeanMetadataElement, BeanDefinition> channelRequestMap = parseInterceptUrlsForChannelSecurity();
ManagedMap<BeanDefinition, BeanDefinition> channelRequestMap = parseInterceptUrlsForChannelSecurity();
if (channelRequestMap.isEmpty()) {
return;
@@ -637,17 +597,15 @@ class HttpConfigurationBuilder {
* will be empty unless the <tt>requires-channel</tt> attribute has been used on a URL
* path.
*/
private ManagedMap<BeanMetadataElement, BeanDefinition> parseInterceptUrlsForChannelSecurity() {
private ManagedMap<BeanDefinition, BeanDefinition> parseInterceptUrlsForChannelSecurity() {
ManagedMap<BeanMetadataElement, BeanDefinition> channelRequestMap = new ManagedMap<BeanMetadataElement, BeanDefinition>();
ManagedMap<BeanDefinition, BeanDefinition> channelRequestMap = new ManagedMap<BeanDefinition, BeanDefinition>();
for (Element urlElt : interceptUrls) {
String path = urlElt.getAttribute(ATT_PATH_PATTERN);
String method = urlElt.getAttribute(ATT_HTTP_METHOD);
String matcherRef = urlElt.getAttribute(ATT_REQUEST_MATCHER_REF);
boolean hasMatcherRef = StringUtils.hasText(matcherRef);
if (!hasMatcherRef && !StringUtils.hasText(path)) {
if (!StringUtils.hasText(path)) {
pc.getReaderContext().error("pattern attribute cannot be empty or null",
urlElt);
}
@@ -655,7 +613,7 @@ class HttpConfigurationBuilder {
String requiredChannel = urlElt.getAttribute(ATT_REQUIRES_CHANNEL);
if (StringUtils.hasText(requiredChannel)) {
BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference(matcherRef) : matcherType.createMatcher(pc, path, method);
BeanDefinition matcher = matcherType.createMatcher(pc, path, method);
RootBeanDefinition channelAttributes = new RootBeanDefinition(
ChannelAttributeFactory.class);
@@ -734,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);
@@ -871,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;
}
}
}
@@ -60,7 +60,7 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
.getLog(HttpSecurityBeanDefinitionParser.class);
private static final String ATT_AUTHENTICATION_MANAGER_REF = "authentication-manager-ref";
static final String ATT_REQUEST_MATCHER_REF = "request-matcher-ref";
private static final String ATT_REQUEST_MATCHER_REF = "request-matcher-ref";
static final String ATT_PATH_PATTERN = "pattern";
static final String ATT_HTTP_METHOD = "method";
@@ -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.
@@ -163,7 +163,7 @@ final class ProtectPointcutPostProcessor implements BeanPostProcessor {
}
public void setPointcutMap(Map<String, List<ConfigAttribute>> map) {
Assert.notEmpty(map, "configAttributes cannot be empty");
Assert.notEmpty(map);
for (String expression : map.keySet()) {
List<ConfigAttribute> value = map.get(expression);
addPointcut(expression, value);
@@ -255,8 +255,8 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
for (String beanName : beanNames) {
BeanDefinition bd = registry.getBeanDefinition(beanName);
String beanClassName = bd.getBeanClassName();
if (SimpAnnotationMethodMessageHandler.class.getName().equals(beanClassName) ||
WEB_SOCKET_AMMH_CLASS_NAME.equals(beanClassName)) {
if (beanClassName.equals(SimpAnnotationMethodMessageHandler.class
.getName()) || beanClassName.equals(WEB_SOCKET_AMMH_CLASS_NAME)) {
PropertyValue current = bd.getPropertyValues().getPropertyValue(
CUSTOM_ARG_RESOLVERS_PROP);
ManagedList<Object> argResolvers = new ManagedList<Object>();
@@ -275,16 +275,16 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
}
}
}
else if ("org.springframework.web.socket.server.support.WebSocketHttpRequestHandler"
.equals(beanClassName)) {
else if (beanClassName
.equals("org.springframework.web.socket.server.support.WebSocketHttpRequestHandler")) {
addCsrfTokenHandshakeInterceptor(bd);
}
else if ("org.springframework.web.socket.sockjs.transport.TransportHandlingSockJsService"
.equals(beanClassName)) {
else if (beanClassName
.equals("org.springframework.web.socket.sockjs.transport.TransportHandlingSockJsService")) {
addCsrfTokenHandshakeInterceptor(bd);
}
else if ("org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService"
.equals(beanClassName)) {
else if (beanClassName
.equals("org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService")) {
addCsrfTokenHandshakeInterceptor(bd);
}
}
@@ -1,5 +1,4 @@
http\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-4.2.xsd
http\://www.springframework.org/schema/security/spring-security-4.2.xsd=org/springframework/security/config/spring-security-4.2.xsd
http\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-4.1.xsd
http\://www.springframework.org/schema/security/spring-security-4.1.xsd=org/springframework/security/config/spring-security-4.1.xsd
http\://www.springframework.org/schema/security/spring-security-4.0.xsd=org/springframework/security/config/spring-security-4.0.xsd
http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd
@@ -1,5 +1,5 @@
<?xml version="1.0"?>
<!DOCTYPE catalog PUBLIC "-//OASIS//DTD Entity Resolution XML Catalog V1.0//EN" "https://www.oasis-open.org/committees/entity/release/1.0/catalog.dtd">
<!DOCTYPE catalog PUBLIC "-//OASIS//DTD Entity Resolution XML Catalog V1.0//EN" "http://www.oasis-open.org/committees/entity/release/1.0/catalog.dtd">
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<system systemId="https://www.springframework.org/schema/security/spring-security-2.0.xsd" uri="spring-security-2.0.xsd"/>
<system systemId="http://www.springframework.org/schema/security/spring-security-2.0.xsd" uri="spring-security-2.0.xsd"/>
</catalog>
@@ -1,4 +1,4 @@
namespace a = "https://relaxng.org/ns/compatibility/annotations/1.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"
@@ -444,7 +444,7 @@ 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, https://axschema.org/contact/email. See your OP's documentation for valid attribute types.
## 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.
@@ -1439,7 +1439,7 @@
</xs:attribute>
<xs:attribute name="type" use="required" type="xs:token">
<xs:annotation>
<xs:documentation>Specifies the attribute type. For example, https://axschema.org/contact/email. See your
<xs:documentation>Specifies the attribute type. For example, http://axschema.org/contact/email. See your
OP's documentation for valid attribute types.
</xs:documentation>
</xs:annotation>
@@ -1,4 +1,4 @@
namespace a = "https://relaxng.org/ns/compatibility/annotations/1.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"
@@ -444,7 +444,7 @@ 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, https://axschema.org/contact/email. See your OP's documentation for valid attribute types.
## 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.
@@ -739,7 +739,7 @@ hsts-options.attlist &=
## Specifies if subdomains should be included. Default true.
attribute include-subdomains {xsd:boolean}?
hsts-options.attlist &=
## Specifies the maximum amount of time the host should be considered a Known HSTS Host. Default one year.
## 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.
@@ -1441,7 +1441,7 @@
</xs:attribute>
<xs:attribute name="type" use="required" type="xs:token">
<xs:annotation>
<xs:documentation>Specifies the attribute type. For example, https://axschema.org/contact/email. See your
<xs:documentation>Specifies the attribute type. For example, http://axschema.org/contact/email. See your
OP's documentation for valid attribute types.
</xs:documentation>
</xs:annotation>
@@ -2299,7 +2299,7 @@
</xs:attribute>
<xs:attribute name="max-age-seconds" type="xs:integer">
<xs:annotation>
<xs:documentation>Specifies the maximum amount of time the host should be considered a Known HSTS Host.
<xs:documentation>Specifies the maximum ammount of time the host should be considered a Known HSTS Host.
Default one year.
</xs:documentation>
</xs:annotation>
@@ -1,4 +1,4 @@
namespace a = "https://relaxng.org/ns/compatibility/annotations/1.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"
@@ -460,7 +460,7 @@ 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, https://axschema.org/contact/email. See your OP's documentation for valid attribute types.
## 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.
@@ -759,7 +759,7 @@ hsts-options.attlist &=
## Specifies if subdomains should be included. Default true.
attribute include-subdomains {xsd:boolean}?
hsts-options.attlist &=
## Specifies the maximum amount of time the host should be considered a Known HSTS Host. Default one year.
## 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.
@@ -1509,7 +1509,7 @@
</xs:attribute>
<xs:attribute name="type" use="required" type="xs:token">
<xs:annotation>
<xs:documentation>Specifies the attribute type. For example, https://axschema.org/contact/email. See your
<xs:documentation>Specifies the attribute type. For example, http://axschema.org/contact/email. See your
OP's documentation for valid attribute types.
</xs:documentation>
</xs:annotation>
@@ -2358,7 +2358,7 @@
</xs:attribute>
<xs:attribute name="max-age-seconds" type="xs:integer">
<xs:annotation>
<xs:documentation>Specifies the maximum amount of time the host should be considered a Known HSTS Host.
<xs:documentation>Specifies the maximum ammount of time the host should be considered a Known HSTS Host.
Default one year.
</xs:documentation>
</xs:annotation>
@@ -1,4 +1,4 @@
namespace a = "https://relaxng.org/ns/compatibility/annotations/1.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"
@@ -469,7 +469,7 @@ 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, https://axschema.org/contact/email. See your OP's documentation for valid attribute types.
## 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.
@@ -768,7 +768,7 @@ hsts-options.attlist &=
## Specifies if subdomains should be included. Default true.
attribute include-subdomains {xsd:boolean}?
hsts-options.attlist &=
## Specifies the maximum amount of time the host should be considered a Known HSTS Host. Default one year.
## 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.
@@ -1534,7 +1534,7 @@
</xs:attribute>
<xs:attribute name="type" use="required" type="xs:token">
<xs:annotation>
<xs:documentation>Specifies the attribute type. For example, https://axschema.org/contact/email. See your
<xs:documentation>Specifies the attribute type. For example, http://axschema.org/contact/email. See your
OP's documentation for valid attribute types.
</xs:documentation>
</xs:annotation>
@@ -2387,7 +2387,7 @@
</xs:attribute>
<xs:attribute name="max-age-seconds" type="xs:integer">
<xs:annotation>
<xs:documentation>Specifies the maximum amount of time the host should be considered a Known HSTS Host.
<xs:documentation>Specifies the maximum ammount of time the host should be considered a Known HSTS Host.
Default one year.
</xs:documentation>
</xs:annotation>
@@ -1,919 +0,0 @@
namespace a = "https://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 &=
(pattern | request-matcher-ref)
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, https://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 &=
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 unlimited 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 wrapped by LazyCsrfTokenRepository.
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? & referrer-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 amount 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}?
referrer-policy =
## Adds support for Referrer Policy
element referrer-policy {referrer-options.attlist}
referrer-options.attlist &=
## The policies for the Referrer-Policy header.
attribute policy {"no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"}?
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.*
@@ -27,6 +25,9 @@ import org.springframework.beans.factory.config.BeanPostProcessor
import org.springframework.context.ApplicationListener
import org.springframework.context.annotation.Bean
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.PermissionEvaluator
import org.springframework.security.access.hierarchicalroles.RoleHierarchy
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl
import org.springframework.security.access.event.AuthorizedEvent
import org.springframework.security.access.vote.AffirmativeBased
import org.springframework.security.authentication.RememberMeAuthenticationToken
@@ -37,6 +38,7 @@ 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.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurerConfigs.CustomExpressionRootConfig
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor
@@ -295,7 +297,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 +343,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()
@@ -572,4 +578,119 @@ public class ExpressionUrlAuthorizationConfigurerTests extends BaseSpringSpec {
}
}
def "permissionEvaluator autowired"() {
setup:
loadConfig(PermissionEvaluatorConfig)
when: "invoke hasPermission expression that allows access"
super.setup()
login()
request.servletPath = "/allow/1"
springSecurityFilterChain.doFilter(request, response, chain)
then: "permissionEvaluator with id and type works - allows access"
response.status == HttpServletResponse.SC_OK
when: "invoke hasPermission expression that denies access"
super.setup()
login()
request.servletPath = "/deny/1"
springSecurityFilterChain.doFilter(request, response, chain)
then: "permissionEvaluator with id and type works - denies access"
response.status == HttpServletResponse.SC_FORBIDDEN
when: "invoke hasPermission expression that allows access"
super.setup()
login()
request.servletPath = "/allowObject/1"
springSecurityFilterChain.doFilter(request, response, chain)
then: "permissionEvaluator with object works - allows access"
response.status == HttpServletResponse.SC_OK
when: "invoke hasPermission expression that denies access"
super.setup()
login()
request.servletPath = "/denyObject/1"
springSecurityFilterChain.doFilter(request, response, chain)
then: "permissionEvaluator with object works - denies access"
response.status == HttpServletResponse.SC_FORBIDDEN
}
@EnableWebSecurity
static class PermissionEvaluatorConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/allow/**").access("hasPermission('ID', 'TYPE', 'PERMISSION')")
.antMatchers("/allowObject/**").access("hasPermission('TESTOBJ', 'PERMISSION')")
.antMatchers("/deny/**").access("hasPermission('ID', 'TYPE', 'NO PERMISSION')")
.antMatchers("/denyObject/**").access("hasPermission('TESTOBJ', 'NO PERMISSION')")
.anyRequest().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER")
}
@Bean
public PermissionEvaluator permissionEvaluator(){
return new PermissionEvaluator(){
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
return "TESTOBJ".equals(targetDomainObject) && "PERMISSION".equals(permission);
}
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
Object permission) {
return "ID".equals(targetId) && "TYPE".equals(targetType) && "PERMISSION".equals(permission);
}
};
}
}
@EnableWebSecurity
static class RoleHierarchyConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/allow/**").access("hasRole('XXX')")
.antMatchers("/deny/**").access("hasRole('NOPE')")
.anyRequest().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER")
}
@Bean
public RoleHierarchy roleHierarchy(){
return new RoleHierarchyImpl("USER > XXX");
}
}
def "roleHierarchy autowired"() {
setup:
loadConfig(PermissionEvaluatorConfig)
when: "invoke roleHierarchy expression that allows access"
super.setup()
login()
request.servletPath = "/allow/1"
springSecurityFilterChain.doFilter(request, response, chain)
then: "permissionEvaluator with id and type works - allows access"
response.status == HttpServletResponse.SC_OK
when: "invoke roleHierarchy expression that denies access"
super.setup()
login()
request.servletPath = "/deny/1"
springSecurityFilterChain.doFilter(request, response, chain)
then: "permissionEvaluator with id and type works - denies access"
response.status == HttpServletResponse.SC_FORBIDDEN
}
}
@@ -20,14 +20,12 @@ import org.springframework.security.config.annotation.BaseSpringSpec
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 static org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy
/**
*
* @author Rob Winch
* @author Tim Ysewyn
* @author Joe Grandja
* @author Eddú Meléndez
*/
class HeadersConfigurerTests extends BaseSpringSpec {
@@ -351,7 +349,7 @@ class HeadersConfigurerTests extends BaseSpringSpec {
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
responseHeaders == ['Public-Key-Pins-Report-Only' : 'max-age=5184000 ; pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=" ; report-uri="https://example.net/pkp-report"']
responseHeaders == ['Public-Key-Pins-Report-Only' : 'max-age=5184000 ; pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=" ; report-uri="http://example.net/pkp-report"']
}
@EnableWebSecurity
@@ -364,7 +362,7 @@ class HeadersConfigurerTests extends BaseSpringSpec {
.defaultsDisabled()
.httpPublicKeyPinning()
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
.reportUri(new URI("https://example.net/pkp-report"))
.reportUri(new URI("http://example.net/pkp-report"))
}
}
@@ -375,7 +373,7 @@ class HeadersConfigurerTests extends BaseSpringSpec {
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
responseHeaders == ['Public-Key-Pins-Report-Only' : 'max-age=5184000 ; pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=" ; report-uri="https://example.net/pkp-report"']
responseHeaders == ['Public-Key-Pins-Report-Only' : 'max-age=5184000 ; pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=" ; report-uri="http://example.net/pkp-report"']
}
@EnableWebSecurity
@@ -388,7 +386,7 @@ class HeadersConfigurerTests extends BaseSpringSpec {
.defaultsDisabled()
.httpPublicKeyPinning()
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
.reportUri("https://example.net/pkp-report")
.reportUri("http://example.net/pkp-report")
}
}
@@ -455,46 +453,4 @@ class HeadersConfigurerTests extends BaseSpringSpec {
}
}
def "headers.referrerPolicy default"() {
setup:
loadConfig(ReferrerPolicyDefaultConfig)
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
responseHeaders == ['Referrer-Policy': 'no-referrer']
}
@EnableWebSecurity
static class ReferrerPolicyDefaultConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.defaultsDisabled()
.referrerPolicy();
}
}
def "headers.referrerPolicy custom"() {
setup:
loadConfig(ReferrerPolicyCustomConfig)
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
responseHeaders == ['Referrer-Policy': 'same-origin']
}
@EnableWebSecurity
static class ReferrerPolicyCustomConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.defaultsDisabled()
.referrerPolicy(ReferrerPolicy.SAME_ORIGIN);
}
}
}
@@ -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.context.annotation.Bean;
package org.springframework.security.config.annotation.web.configurers;
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@@ -91,28 +89,6 @@ public class NamespaceHttpFirewallTests extends BaseSpringSpec {
}
}
def "http-firewall bean"() {
setup:
loadConfig(CustomHttpFirewallBeanConfig)
springSecurityFilterChain = context.getBean(FilterChainProxy)
request.setParameter("deny", "true")
when:
springSecurityFilterChain.doFilter(request,response,chain)
then: "the custom firewall is used"
thrown(RequestRejectedException)
}
@Configuration
static class CustomHttpFirewallBeanConfig extends BaseWebConfig {
@Override
protected void configure(HttpSecurity http) { }
@Bean
CustomHttpFirewall firewall() {
return new CustomHttpFirewall();
}
}
static class CustomHttpFirewall extends DefaultHttpFirewall {
@Override
@@ -83,21 +83,21 @@ public class NamespaceHttpOpenIDLoginTests extends BaseSpringSpec {
def googleAttrs = consumer.attributesToFetchFactory.createAttributeList("https://www.google.com/1")
googleAttrs[0].name == "email"
googleAttrs[0].type == "https://axschema.org/contact/email"
googleAttrs[0].type == "http://axschema.org/contact/email"
googleAttrs[0].required
googleAttrs[1].name == "firstname"
googleAttrs[1].type == "https://axschema.org/namePerson/first"
googleAttrs[1].type == "http://axschema.org/namePerson/first"
googleAttrs[1].required
googleAttrs[2].name == "lastname"
googleAttrs[2].type == "https://axschema.org/namePerson/last"
googleAttrs[2].type == "http://axschema.org/namePerson/last"
googleAttrs[2].required
def yahooAttrs = consumer.attributesToFetchFactory.createAttributeList("https://rwinch.yahoo.com/rwinch/id")
yahooAttrs[0].name == "email"
yahooAttrs[0].type == "https://schema.openid.net/contact/email"
yahooAttrs[0].type == "http://schema.openid.net/contact/email"
yahooAttrs[0].required
yahooAttrs[1].name == "fullname"
yahooAttrs[1].type == "https://axschema.org/namePerson"
yahooAttrs[1].type == "http://axschema.org/namePerson"
yahooAttrs[1].required
when:
springSecurityFilterChain.doFilter(request,response,chain)
@@ -122,26 +122,26 @@ public class NamespaceHttpOpenIDLoginTests extends BaseSpringSpec {
.openidLogin()
.attributeExchange("https://www.google.com/.*") // attribute-exchange@identifier-match
.attribute("email") // openid-attribute@name
.type("https://axschema.org/contact/email") // openid-attribute@type
.type("http://axschema.org/contact/email") // openid-attribute@type
.required(true) // openid-attribute@required
.count(1) // openid-attribute@count
.and()
.attribute("firstname")
.type("https://axschema.org/namePerson/first")
.type("http://axschema.org/namePerson/first")
.required(true)
.and()
.attribute("lastname")
.type("https://axschema.org/namePerson/last")
.type("http://axschema.org/namePerson/last")
.required(true)
.and()
.and()
.attributeExchange(".*yahoo.com.*")
.attribute("email")
.type("https://schema.openid.net/contact/email")
.type("http://schema.openid.net/contact/email")
.required(true)
.and()
.attribute("fullname")
.type("https://axschema.org/namePerson")
.type("http://axschema.org/namePerson")
.required(true)
.and()
.and()
@@ -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) {
@@ -624,7 +612,7 @@ class HttpHeadersConfigTests extends AbstractHttpConfigTests {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'('report-uri':'https://example.net/pkp-report') {
'hpkp'('report-uri':'http://example.net/pkp-report') {
'pins'() {
'pin'('algorithm':'sha256', 'E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=')
}
@@ -637,7 +625,7 @@ class HttpHeadersConfigTests extends AbstractHttpConfigTests {
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure: true), response, new MockFilterChain())
then:
assertHeaders(response, ['Public-Key-Pins-Report-Only': 'max-age=5184000 ; pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" ; report-uri="https://example.net/pkp-report"'])
assertHeaders(response, ['Public-Key-Pins-Report-Only': 'max-age=5184000 ; pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" ; report-uri="http://example.net/pkp-report"'])
}
// --- disable single default header ---
@@ -920,38 +908,6 @@ class HttpHeadersConfigTests extends AbstractHttpConfigTests {
assertHeaders(response, expectedHeaders)
}
def 'http headers defaults : referrer-policy'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'referrer-policy'()
}
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['Referrer-Policy': 'no-referrer'])
}
def 'http headers defaults : referrer-policy same-origin'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'referrer-policy'('policy': 'same-origin')
}
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['Referrer-Policy': 'same-origin'])
}
def assertHeaders(MockHttpServletResponse response, Map<String,String> expected) {
assert response.headerNames == expected.keySet()
expected.each { headerName, value ->
@@ -88,7 +88,7 @@ class OpenIDConfigTests extends AbstractHttpConfigTests {
openIDFilter.setConsumer(new OpenIDConsumer() {
public String beginConsumption(HttpServletRequest req, String claimedIdentity, String returnToUrl, String realm)
throws OpenIDConsumerException {
return "https://testopenid.com?openid.return_to=" + returnToUrl;
return "http://testopenid.com?openid.return_to=" + returnToUrl;
}
public OpenIDAuthenticationToken endConsumption(HttpServletRequest req) throws OpenIDConsumerException {
@@ -118,7 +118,7 @@ class OpenIDConfigTests extends AbstractHttpConfigTests {
response.getContentAsString().contains(AbstractRememberMeServices.DEFAULT_PARAMETER)
when: "Login is submitted with remember-me selected"
request.servletPath = "/login/openid"
request.setParameter(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, "https://ww1.openid.com")
request.setParameter(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, "http://hey.openid.com/")
request.setParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "on")
response = new MockHttpServletResponse();
fc.doFilter(request, response, new MockFilterChain());
@@ -126,27 +126,27 @@ class OpenIDConfigTests extends AbstractHttpConfigTests {
.append(AbstractRememberMeServices.DEFAULT_PARAMETER)
.append("=").append("on").toString();
then: "return_to URL contains remember-me choice"
response.getRedirectedUrl() == "https://testopenid.com?openid.return_to=" + expectedReturnTo
response.getRedirectedUrl() == "http://testopenid.com?openid.return_to=" + expectedReturnTo
}
def openIDWithAttributeExchangeConfigurationIsParsedCorrectly() {
xml.http() {
'openid-login'() {
'attribute-exchange'() {
'openid-attribute'(name: 'nickname', type: 'https://schema.openid.net/namePerson/friendly')
'openid-attribute'(name: 'email', type: 'https://schema.openid.net/contact/email', required: 'true',
'openid-attribute'(name: 'nickname', type: 'http://schema.openid.net/namePerson/friendly')
'openid-attribute'(name: 'email', type: 'http://schema.openid.net/contact/email', required: 'true',
'count': '2')
}
}
}
createAppContext()
List attributes = getFilter(OpenIDAuthenticationFilter).consumer.attributesToFetchFactory.createAttributeList('https://someid')
List attributes = getFilter(OpenIDAuthenticationFilter).consumer.attributesToFetchFactory.createAttributeList('http://someid')
expect:
attributes.size() == 2
attributes[0].name == 'nickname'
attributes[0].type == 'https://schema.openid.net/namePerson/friendly'
attributes[0].type == 'http://schema.openid.net/namePerson/friendly'
!attributes[0].required
attributes[1].required
attributes[1].getCount() == 2
@@ -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() {
@@ -1,53 +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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.authentication.configuration;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*
* @author Rob Winch
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
public class EnableGlobalAuthenticationTests {
@Autowired
AuthenticationConfiguration auth;
// gh-4086
@Test
public void authenticationConfigurationWhenGetAuthenticationManagerThenNotNull() throws Exception {
assertThat(auth.getAuthenticationManager()).isNotNull();
}
@Configuration
@EnableGlobalAuthentication
static class Config {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
}
@@ -1,101 +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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.Filter;
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.Configuration;
import org.springframework.http.HttpHeaders;
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.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
*
* @author Rob Winch
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class HttpSecurityHeadersTests {
@Autowired
WebApplicationContext wac;
@Autowired
Filter springSecurityFilterChain;
MockMvc mockMvc;
@Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.addFilters(springSecurityFilterChain)
.build();
}
// gh-2953
// gh-3975
@Test
public void headerWhenSpringMvcResourceThenCacheRelatedHeadersReset() throws Exception {
mockMvc.perform(get("/resources/file.js"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.CACHE_CONTROL,"max-age=12345"))
.andExpect(header().doesNotExist(HttpHeaders.PRAGMA))
.andExpect(header().doesNotExist(HttpHeaders.EXPIRES));
}
@Test
public void headerWhenNotSpringResourceThenCacheRelatedHeadersSet() throws Exception {
mockMvc.perform(get("/notresource"))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL,"no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0"));
}
@EnableWebSecurity
static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
}
}
@EnableWebMvc
@Configuration
static class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/").setCachePeriod(12345);
}
}
}
@@ -1,96 +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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web;
import static org.assertj.core.api.Assertions.assertThat;
import static org.powermock.api.mockito.PowerMockito.*;
import java.util.Arrays;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.core.io.support.SpringFactoriesLoader;
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.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
/**
*
* @author Rob Winch
*
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ SpringFactoriesLoader.class })
public class WebSecurityConfigurerAdapterPowermockTests {
ConfigurableWebApplicationContext context;
@After
public void close() {
if(context != null) {
context.close();
}
}
@Test
public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() {
spy(SpringFactoriesLoader.class);
DefaultConfigurer configurer = new DefaultConfigurer();
when(SpringFactoriesLoader
.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
.thenReturn(Arrays.<AbstractHttpConfigurer>asList(configurer));
loadConfig(Config.class);
assertThat(configurer.init).isTrue();
assertThat(configurer.configure).isTrue();
}
private void loadConfig(Class<?>... classes) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setClassLoader(getClass().getClassLoader());
context.register(classes);
context.refresh();
this.context = context;
}
@EnableWebSecurity
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
}
}
static class DefaultConfigurer extends AbstractHttpConfigurer<DefaultConfigurer,HttpSecurity> {
boolean init;
boolean configure;
@Override
public void init(HttpSecurity builder) throws Exception {
this.init = true;
}
@Override
public void configure(HttpSecurity builder) throws Exception {
this.configure = true;
}
}
}

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