1
0
mirror of synced 2026-07-13 14:45:10 +00:00

Compare commits

..

15 Commits

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

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

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

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

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

Now the TestCsrfTokenRepository is only used if explicitly enabled.

Fixes gh-4016
2016-08-09 17:28:33 -04:00
Joe Grandja dabcc5416a MvcRequestMatcher servletPath Polish / XML Config
Fixes gh-4014
2016-08-09 15:47:41 -05:00
Rob Winch 8a6d0cd16d MvcRequestMatcher servletPath / JavaConfig
Issue: gh-3987
2016-08-09 15:47:01 -05:00
Rob Winch edb7ef567a Logout is 204 for XMLHttpRequest
Fixes gh-3997
2016-08-02 14:14:44 -07:00
Rob Winch d002681bec Add ObjectPostProcessor support for SmartInitializingSingleton 2016-07-21 10:46:55 -05:00
Rob Winch 6649d46896 DummyRequest supports methods for MvcRequestMatcher
To support MvcRequestMatcher DummyRequest needs to support
getCharacterEncoding() and getAttribute(String)
2016-07-14 16:02:08 -04:00
Rob Winch 1d97ee8dd6 Add HttpSecurity.mvcMatcher
Fixes gh-3970
2016-07-14 11:46:29 -04:00
Rob Winch 7d1344fca8 Fix NPE requestMatchers().mvcMatchers
Fixes gh-3969
2016-07-14 11:45:45 -04:00
899 changed files with 42682 additions and 38466 deletions
+5 -1
View File
@@ -6,6 +6,10 @@ jdk:
os:
- linux
branches:
only:
- master
before_cache:
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
cache:
@@ -13,4 +17,4 @@ cache:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
script: ./gradlew build --refresh-dependencies --no-daemon
script: ./gradlew build
+2 -11
View File
@@ -29,7 +29,7 @@ Not sure what a pull request is, or how to submit one? Take a look at GitHub's e
Is there already an issue that addresses your concern? Do a bit of searching in our [GitHub issues ](https://github.com/spring-projects/spring-security/issues) to see if you can find something similar. If not, please create a new issue before submitting a pull request unless the change is not a user facing issue.
# Discuss non-trivial contribution ideas with committers
If you're considering anything more than correcting a typo or fixing a minor bug, please discuss it on the [Spring Security Gitter](https://gitter.im/spring-projects/spring-security) before submitting a pull request. We're happy to provide guidance but please spend an hour or two researching the subject on your own including searching the forums for prior discussions.
If you're considering anything more than correcting a typo or fixing a minor bug , please discuss it on the [Spring Security Gitter](https://gitter.im/spring-projects/spring-security) before submitting a pull request. We're happy to provide guidance but please spend an hour or two researching the subject on your own including searching the forums for prior discussions.
# Sign the Contributor License Agreement
@@ -104,21 +104,12 @@ e.g.
*/
</pre>
# Submit JUnit test cases for all behavior changes
#Submit JUnit test cases for all behavior changes
Search the codebase to find related unit tests and add additional `@Test` methods within.
1. Any new tests should end in the name Tests (note this is plural). For example, a valid name would be `FilterChainProxyTests`. An invalid name would be `FilterChainProxyTest`.
2. New test methods should not start with test. This is an old JUnit3 convention and is not necessary since the method is annotated with @Test.
# Update spring-security-x.y.rnc for schema changes
Update the [RELAX NG](http://www.relaxng.org) schema `spring-security-x.y.rnc` instead of `spring-security-x.y.xsd` if you contribute changes to supported XML configuration. The XML schema file can be generated the following Gradle task:
<pre>
./gradlew spring-security-config:rncToXsd
</pre>
Changes to the XML schema will be overwritten by the Gradle build task.
# Squash commits
Use git rebase --interactive, git add --patch and other tools to "squash" multiple commits into atomic changes. In addition to the man pages for git, there are many resources online to help you understand how these tools work. Here is one: http://book.git-scm.com/4_interactive_rebasing.html.
Vendored
-113
View File
@@ -1,113 +0,0 @@
def projectProperties = [
[$class: 'BuildDiscarderProperty',
strategy: [$class: 'LogRotator', numToKeepStr: '5']],
pipelineTriggers([cron('@daily')])
]
properties(projectProperties)
def SUCCESS = hudson.model.Result.SUCCESS.toString()
currentBuild.result = SUCCESS
try {
parallel check: {
stage('Check') {
node {
checkout scm
try {
sh "./gradlew clean check --refresh-dependencies --no-daemon"
} catch(Exception e) {
currentBuild.result = 'FAILED: check'
throw e
} finally {
junit '**/build/*-results/*.xml'
}
}
}
},
sonar: {
stage('Sonar') {
node {
checkout scm
withCredentials([string(credentialsId: 'spring-sonar.login', variable: 'SONAR_LOGIN')]) {
try {
sh "./gradlew clean sonarqube -PexcludeProjects='**/samples/**' -Dsonar.host.url=$SPRING_SONAR_HOST_URL -Dsonar.login=$SONAR_LOGIN --refresh-dependencies --no-daemon"
} catch(Exception e) {
currentBuild.result = 'FAILED: sonar'
throw e
}
}
}
}
},
springio: {
stage('Spring IO') {
node {
checkout scm
try {
sh "./gradlew clean springIoCheck -PplatformVersion=Cairo-BUILD-SNAPSHOT -PexcludeProjects='**/samples/**' --refresh-dependencies --no-daemon --stacktrace"
} catch(Exception e) {
currentBuild.result = 'FAILED: springio'
throw e
} finally {
junit '**/build/spring-io*-results/*.xml'
}
}
}
}
if(currentBuild.result == 'SUCCESS') {
parallel artifactory: {
stage('Artifactory Deploy') {
node {
checkout scm
withCredentials([usernamePassword(credentialsId: '02bd1690-b54f-4c9f-819d-a77cb7a9822c', usernameVariable: 'ARTIFACTORY_USERNAME', passwordVariable: 'ARTIFACTORY_PASSWORD')]) {
sh "./gradlew check artifactoryPublish -x check -PartifactoryUsername=$ARTIFACTORY_USERNAME -PartifactoryPassword=$ARTIFACTORY_PASSWORD --no-daemon --stacktrace"
}
}
}
},
docs: {
stage('Deploy Docs') {
node {
checkout scm
withCredentials([file(credentialsId: 'docs.spring.io-jenkins_private_ssh_key', variable: 'DEPLOY_SSH_KEY')]) {
sh "./gradlew deployDocs -PdeployDocsSshKeyPath=$DEPLOY_SSH_KEY -PdeployDocsSshUsername=$SPRING_DOCS_USERNAME --refresh-dependencies --no-daemon --stacktrace"
}
}
}
},
schema: {
stage('Deploy Schema') {
node {
checkout scm
withCredentials([file(credentialsId: 'docs.spring.io-jenkins_private_ssh_key', variable: 'DEPLOY_SSH_KEY')]) {
sh "./gradlew deploySchema -PdeployDocsSshKeyPath=$DEPLOY_SSH_KEY -PdeployDocsSshUsername=$SPRING_DOCS_USERNAME --refresh-dependencies --no-daemon --stacktrace"
}
}
}
}
}
} finally {
def buildStatus = currentBuild.result
def buildNotSuccess = !SUCCESS.equals(buildStatus)
def lastBuildNotSuccess = !SUCCESS.equals(currentBuild.previousBuild?.result)
if(buildNotSuccess || lastBuildNotSuccess) {
stage('Notifiy') {
node {
final def RECIPIENTS = [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']]
def subject = "${buildStatus}: Build ${env.JOB_NAME} ${env.BUILD_NUMBER} status is now ${buildStatus}"
def details = """The build status changed to ${buildStatus}. For details see ${env.BUILD_URL}"""
emailext (
subject: subject,
body: details,
recipientProviders: RECIPIENTS,
to: "$SPRING_SECURITY_TEAM_EMAILS"
)
}
}
}
}
+4 -4
View File
@@ -4,8 +4,8 @@ image:https://travis-ci.org/spring-projects/spring-security.svg?branch=master["B
= Spring Security
Spring Security provides security services for the http://docs.spring.io[Spring IO Platform]. Spring Security 5.0 requires Spring 5.0 as
a minimum and also requires Java 8.
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 http://spring.io/projects[Spring projects].
@@ -29,9 +29,9 @@ In the instructions below, http://vimeo.com/34436402[`./gradlew`] is invoked fro
a cross-platform, self-contained bootstrap mechanism for the build.
=== Prerequisites
http://help.github.com/set-up-git-redirect[Git] and the http://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]
+19
View File
@@ -0,0 +1,19 @@
// Acl Module build file
dependencies {
compile project(':spring-security-core'),
springCoreDependency,
'aopalliance:aopalliance:1.0',
"org.springframework:spring-aop:$springVersion",
"org.springframework:spring-context:$springVersion",
"org.springframework:spring-tx:$springVersion",
"org.springframework:spring-jdbc:$springVersion"
optional "net.sf.ehcache:ehcache:$ehcacheVersion"
testCompile "org.springframework:spring-beans:$springVersion",
"org.springframework:spring-context-support:$springVersion",
"org.springframework:spring-test:$springVersion"
testRuntime "org.hsqldb:hsqldb:$hsqlVersion"
}
+165
View File
@@ -0,0 +1,165 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
<version>4.1.3.RELEASE</version>
<name>spring-security-acl</name>
<description>spring-security-acl</description>
<url>http://spring.io/spring-security</url>
<organization>
<name>spring.io</name>
<url>http://spring.io/</url>
</organization>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rwinch</id>
<name>Rob Winch</name>
<email>rwinch@gopivotal.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/spring-projects/spring-security</connection>
<developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>
<url>https://github.com/spring-projects/spring-security</url>
</scm>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<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.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
-19
View File
@@ -1,19 +0,0 @@
apply plugin: 'io.spring.convention.spring-module'
dependencies {
compile project(':spring-security-core')
compile 'aopalliance:aopalliance'
compile 'org.springframework:spring-aop'
compile 'org.springframework:spring-context'
compile 'org.springframework:spring-core'
compile 'org.springframework:spring-jdbc'
compile 'org.springframework:spring-tx'
optional 'net.sf.ehcache:ehcache'
testCompile 'org.springframework:spring-beans'
testCompile 'org.springframework:spring-context-support'
testCompile 'org.springframework:spring-test'
testRuntime 'org.hsqldb:hsqldb'
}
@@ -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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.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();
}
}
}
+6 -7
View File
@@ -1,15 +1,14 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
</appender>
<logger name="org.springframework.security" level="${sec.log.level:-WARN}"/>
<logger name="org.springframework.security" level="${sec.log.level}:-WARN"/>
<root level="${root.level:-WARN}">
<root level="${root.level}:-WARN">
<appender-ref ref="STDOUT" />
</root>
</root>
</configuration>
+10
View File
@@ -0,0 +1,10 @@
dependencies {
compile project(':spring-security-core'),
springCoreDependency,
"org.springframework:spring-beans:$springVersion",
"org.springframework:spring-context:$springVersion"
testCompile 'aopalliance:aopalliance:1.0',
"org.springframework:spring-aop:$springVersion"
}
+144
View File
@@ -0,0 +1,144 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-aspects</artifactId>
<version>4.1.3.RELEASE</version>
<name>spring-security-aspects</name>
<description>spring-security-aspects</description>
<url>http://spring.io/spring-security</url>
<organization>
<name>spring.io</name>
<url>http://spring.io/</url>
</organization>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rwinch</id>
<name>Rob Winch</name>
<email>rwinch@gopivotal.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/spring-projects/spring-security</connection>
<developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>
<url>https://github.com/spring-projects/spring-security</url>
</scm>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.4</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
-12
View File
@@ -1,12 +0,0 @@
apply plugin: 'io.spring.convention.spring-module'
apply plugin: 'aspectj'
dependencies {
compile project(':spring-security-core')
compile 'org.springframework:spring-beans'
compile 'org.springframework:spring-context'
compile 'org.springframework:spring-core'
testCompile 'aopalliance:aopalliance'
testCompile 'org.springframework:spring-aop'
}
@@ -1,15 +0,0 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.springframework.security" level="${sec.log.level:-WARN}"/>
<root level="${root.level:-WARN}">
<appender-ref ref="STDOUT" />
</root>
</configuration>
+9
View File
@@ -0,0 +1,9 @@
apply plugin: 'maven-bom'
apply from: "$rootDir/gradle/maven-deployment.gradle"
generatePom.enabled = false
sonarqube.skipProject = true
mavenBom {
projects = coreModuleProjects
}
-10
View File
@@ -1,10 +0,0 @@
apply plugin: 'maven-bom'
apply plugin: 'io.spring.convention.artifactory'
sonarqube.skipProject = true
project.rootProject.allprojects.each { p ->
p.plugins.withType(io.spring.gradle.convention.SpringMavenPlugin) {
project.mavenBom.projects.add(p)
}
}
+180 -11
View File
@@ -1,19 +1,188 @@
buildscript {
dependencies {
classpath 'io.spring.gradle:spring-build-conventions:0.0.2.RELEASE'
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
}
repositories {
maven { url 'https://repo.spring.io/plugins-snapshot' }
maven { url "https://repo.spring.io/plugins-release" }
}
dependencies {
classpath("org.springframework.build.gradle:propdeps-plugin:0.0.7")
classpath("io.spring.gradle:spring-io-plugin:0.0.4.RELEASE")
classpath("com.bmuschko:gradle-tomcat-plugin:2.2.4")
classpath('me.champeau.gradle:gradle-javadoc-hotfix-plugin:0.1')
classpath('org.asciidoctor:asciidoctor-gradle-plugin:1.5.1')
classpath("io.spring.gradle:docbook-reference-plugin:0.3.1")
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")
}
}
apply plugin: 'io.spring.convention.root'
group = 'org.springframework.security'
plugins {
id "org.sonarqube" version "1.2"
}
apply plugin: 'base'
description = 'Spring Security'
ext.snapshotBuild = version.contains("SNAPSHOT")
ext.releaseBuild = version.contains("SNAPSHOT")
ext.milestoneBuild = !(snapshotBuild || releaseBuild)
allprojects {
apply plugin: 'idea'
apply plugin: 'eclipse'
dependencyManagementExport.projects = subprojects.findAll { !it.name.contains('-boot') }
ext.releaseBuild = version.endsWith('RELEASE')
ext.snapshotBuild = version.endsWith('SNAPSHOT')
ext.springVersion = '4.3.2.RELEASE'
ext.springLdapVersion = '2.0.2.RELEASE'
group = 'org.springframework.security'
repositories {
mavenCentral()
maven { url "https://repo.spring.io/libs-snapshot" }
maven { url "https://repo.spring.io/plugins-release" }
maven { url "http://repo.terracotta.org/maven2/" }
}
eclipse.project.name = "${project.name}-4.1.x"
}
sonarqube {
properties {
property "sonar.java.coveragePlugin", "jacoco"
property "sonar.projectName", "Spring Security"
property "sonar.jacoco.reportPath", "${buildDir.name}/jacoco.exec"
property "sonar.links.homepage", 'https://www.springsource.org/spring-security'
property "sonar.links.ci", 'https://build.springsource.org/browse/SEC-B32X'
property "sonar.links.issue", 'https://jira.springsource.org/browse/SEC'
property "sonar.links.scm", 'https://github.com/SpringSource/spring-security'
property "sonar.links.scm_dev", 'https://github.com/SpringSource/spring-security.git'
property "sonar.java.coveragePlugin", "jacoco"
}
}
// 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.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')]
configure(allprojects - javaProjects) {
task afterEclipseImport {
ext.srcFile = file('.classpath')
inputs.file srcFile
outputs.dir srcFile
onlyIf { !srcFile.exists() }
doLast {
srcFile << """<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>
"""
}
}
}
configure(subprojects - coreModuleProjects - project(':spring-security-samples-javaconfig-messages') - project(':spring-security-bom')) {
tasks.findByPath("artifactoryPublish")?.enabled = false
sonarqube {
skipProject = true
}
}
configure(javaProjects) {
ext.TOMCAT_GRADLE = "$rootDir/gradle/tomcat.gradle"
ext.WAR_SAMPLE_GRADLE = "$rootDir/gradle/war-sample.gradle"
ext.BOOT_SAMPLE_GRADLE = "$rootDir/gradle/boot-sample.gradle"
apply from: "$rootDir/gradle/javaprojects.gradle"
if(!project.name.contains('gae')) {
apply from: "$rootDir/gradle/checkstyle.gradle"
}
apply from: "$rootDir/gradle/ide.gradle"
apply from: "$rootDir/gradle/release-checks.gradle"
apply from: "$rootDir/gradle/maven-deployment.gradle"
}
configure(coreModuleProjects) {
apply plugin: 'emma'
apply plugin: 'spring-io'
ext.springIoVersion = project.hasProperty('platformVersion') ? platformVersion : '2.0.1.RELEASE'
configurations {
jacoco //Configuration Group used by Sonar to provide Code Coverage using JaCoCo
}
dependencyManagement {
springIoTestRuntime {
imports {
mavenBom "io.spring.platform:platform-bom:${springIoVersion}"
}
}
}
dependencies {
jacoco "org.jacoco:org.jacoco.agent:0.7.5.201505241946:runtime"
}
test {
jvmArgs "-javaagent:${configurations.jacoco.asPath}=destfile=${buildDir}/jacoco.exec,includes=${project.group}.*"
}
integrationTest {
jvmArgs "-javaagent:${configurations.jacoco.asPath}=destfile=${buildDir}/jacoco.exec,includes=${project.group}.*"
}
}
configure (aspectjProjects) {
apply plugin: 'java'
apply plugin: 'aspectj'
}
task coreBuild {
dependsOn coreModuleProjects*.tasks*.matching { task -> task.name == 'build' }
}
task coreInstall {
dependsOn coreModuleProjects*.tasks*.matching { task -> task.name == 'install' }
}
// Task for creating the distro zip
task dist(type: Zip) {
dependsOn { subprojects*.tasks*.matching { task -> task.name.endsWith('generatePom') } }
classifier = 'dist'
evaluationDependsOn(':docs')
evaluationDependsOn(':docs:manual')
def zipRootDir = "${project.name}-$version"
into(zipRootDir) {
from(rootDir) {
include '*.adoc'
include '*.txt'
}
into('docs') {
with(project(':docs').apiSpec)
with(project(':docs:manual').spec)
with(project(':docs:guides').spec)
}
project.coreModuleProjects*.tasks*.withType(AbstractArchiveTask).flatten().each{ archiveTask ->
if(archiveTask!=dist){
into("$zipRootDir/dist") {
from archiveTask.outputs.files
}
}
}
sampleProjects.each { project->
into("$zipRootDir/samples/$project.name") {
from(project.projectDir) {
include "src/main/**"
include "pom.xml"
}
}
}
}
}
artifacts {
archives dist
archives project(':docs').docsZip
archives project(':docs').schemaZip
}
@@ -13,9 +13,7 @@ public class MavenBomPlugin implements Plugin<Project> {
public void apply(Project project) {
project.plugins.apply(JavaPlugin)
project.plugins.apply(MavenPlugin)
project.group = project.rootProject.group
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
}
}
}
+2 -2
View File
@@ -6,7 +6,7 @@ import org.gradle.api.tasks.*
public class MavenBomTask extends DefaultTask {
Set<Project> projects = []
Set<Project> projects
File bomFile
@@ -52,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
@@ -26,11 +25,15 @@ class AspectJPlugin implements Plugin<Project> {
void apply(Project project) {
project.plugins.apply(JavaPlugin)
if (!project.hasProperty('aspectjVersion')) {
throw new GradleException("You must set the property 'aspectjVersion' before applying the aspectj plugin")
}
if (project.configurations.findByName('ajtools') == null) {
project.configurations.create('ajtools')
project.dependencies {
ajtools "org.aspectj:aspectjtools"
optional "org.aspectj:aspectjrt"
ajtools "org.aspectj:aspectjtools:${project.aspectjVersion}"
optional "org.aspectj:aspectjrt:${project.aspectjVersion}"
}
}
@@ -38,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 ->
@@ -85,9 +91,7 @@ class AspectJPlugin implements Plugin<Project> {
}
class Ajc extends DefaultTask {
Set<File> sourceRoots = []
FileCollection compileClasspath
File destinationDir
SourceSet sourceSet
FileCollection aspectPath
Ajc() {
@@ -99,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)
}
+14
View File
@@ -0,0 +1,14 @@
dependencies {
compile project(':spring-security-core'),
project(':spring-security-web'),
springCoreDependency,
"org.springframework:spring-context:$springVersion",
"org.springframework:spring-beans:$springVersion",
"org.springframework:spring-web:$springVersion",
"org.jasig.cas.client:cas-client-core:$casClientVersion"
optional "net.sf.ehcache:ehcache:$ehcacheVersion"
provided "javax.servlet:javax.servlet-api:$servletApiVersion"
}
+156
View File
@@ -0,0 +1,156 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>4.1.3.RELEASE</version>
<name>spring-security-cas</name>
<description>spring-security-cas</description>
<url>http://spring.io/spring-security</url>
<organization>
<name>spring.io</name>
<url>http://spring.io/</url>
</organization>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rwinch</id>
<name>Rob Winch</name>
<email>rwinch@gopivotal.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/spring-projects/spring-security</connection>
<developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>
<url>https://github.com/spring-projects/spring-security</url>
</scm>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.4.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.9.0</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
-18
View File
@@ -1,18 +0,0 @@
apply plugin: 'io.spring.convention.spring-module'
dependencies {
compile project(':spring-security-core')
compile project(':spring-security-web')
compile 'org.jasig.cas.client:cas-client-core'
compile 'org.springframework:spring-beans'
compile 'org.springframework:spring-context'
compile 'org.springframework:spring-core'
compile 'org.springframework:spring-web'
optional 'com.fasterxml.jackson.core:jackson-databind'
optional 'net.sf.ehcache:ehcache'
provided 'javax.servlet:javax.servlet-api'
testCompile 'org.skyscreamer:jsonassert'
}
@@ -24,7 +24,6 @@ import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;
/**
* Represents a successful CAS <code>Authentication</code>.
@@ -51,54 +50,29 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
/**
* Constructor.
*
* @param key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param credentials the service/proxy ticket ID from CAS (cannot be
* <code>null</code>)
* <code>null</code>)
* @param authorities the authorities granted to the user (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param userDetails the user details (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
*
* @throws IllegalArgumentException if a <code>null</code> was passed
*/
public CasAuthenticationToken(final String key, final Object principal,
final Object credentials,
final Collection<? extends GrantedAuthority> authorities,
final UserDetails userDetails, final Assertion assertion) {
this(extractKeyHash(key), principal, credentials, authorities, userDetails, assertion);
}
/**
* Private constructor for Jackson Deserialization support
*
* @param keyHash hashCode of provided key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param credentials the service/proxy ticket ID from CAS (cannot be
* <code>null</code>)
* @param authorities the authorities granted to the user (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param userDetails the user details (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
* @throws IllegalArgumentException if a <code>null</code> was passed
* @since 4.2
*/
private CasAuthenticationToken(final Integer keyHash, final Object principal,
final Object credentials,
final Collection<? extends GrantedAuthority> authorities,
final UserDetails userDetails, final Assertion assertion) {
final Object credentials,
final Collection<? extends GrantedAuthority> authorities,
final UserDetails userDetails, final Assertion assertion) {
super(authorities);
if ((principal == null)
if ((key == null) || ("".equals(key)) || (principal == null)
|| "".equals(principal) || (credentials == null)
|| "".equals(credentials) || (authorities == null)
|| (userDetails == null) || (assertion == null)) {
@@ -106,7 +80,7 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
"Cannot pass null or empty values to constructor");
}
this.keyHash = keyHash;
this.keyHash = key.hashCode();
this.principal = principal;
this.credentials = credentials;
this.userDetails = userDetails;
@@ -117,11 +91,6 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
// ~ Methods
// ========================================================================================================
private static Integer extractKeyHash(String key) {
Assert.hasLength(key, "key cannot be null or empty");
return key.hashCode();
}
public boolean equals(final Object obj) {
if (!super.equals(obj)) {
return false;
@@ -1,62 +0,0 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.cas.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.jasig.cas.client.authentication.AttributePrincipal;
import java.util.Date;
import java.util.Map;
/**
* Helps in jackson deserialization of class {@link org.jasig.cas.client.validation.AssertionImpl}, which is
* used with {@link org.springframework.security.cas.authentication.CasAuthenticationToken}.
* To use this class we need to register with {@link com.fasterxml.jackson.databind.ObjectMapper}. Type information
* will be stored in @class property.
* <p>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
*
*
* @author Jitendra Singh
* @see CasJackson2Module
* @see org.springframework.security.jackson2.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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.cas.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.jasig.cas.client.proxy.ProxyRetriever;
import java.util.Map;
/**
* Helps in deserialize {@link org.jasig.cas.client.authentication.AttributePrincipalImpl} which is used with
* {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. Type information will be stored
* in property named @class.
* <p>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @see CasJackson2Module
* @see org.springframework.security.jackson2.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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.cas.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
/**
* Mixin class which helps in deserialize {@link org.springframework.security.cas.authentication.CasAuthenticationToken}
* using jackson. Two more dependent classes needs to register along with this mixin class.
* <ol>
* <li>{@link org.springframework.security.cas.jackson2.AssertionImplMixin}</li>
* <li>{@link org.springframework.security.cas.jackson2.AttributePrincipalImplMixin}</li>
* </ol>
*
* <p>
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @see CasJackson2Module
* @see org.springframework.security.jackson2.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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.cas.jackson2;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.validation.AssertionImpl;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.jackson2.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);
}
}
@@ -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) + "=[^&]*");
}
@@ -19,7 +19,6 @@ package org.springframework.security.cas.authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.Collections;
import java.util.List;
import org.jasig.cas.client.validation.Assertion;
@@ -103,12 +102,6 @@ public class CasAuthenticationTokenTests {
}
}
@Test(expected = IllegalArgumentException.class)
public void constructorWhenEmptyKeyThenThrowsException() {
new CasAuthenticationToken("", "user", "password", Collections.<GrantedAuthority>emptyList(),
new User("user", "password", Collections.<GrantedAuthority>emptyList()), null);
}
@Test
public void testEqualsWhenEqual() {
final Assertion assertion = new AssertionImpl("test");
@@ -1,155 +0,0 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.cas.jackson2;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.jackson2.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.ArrayList\", [" + AUTHORITY_JSON + "]]";
// @formatter:off
public static final String USER_JSON = "{"
+ "\"@class\": \"org.springframework.security.core.userdetails.User\", "
+ "\"username\": \"admin\","
+ " \"password\": " + PASSWORD + ", "
+ "\"accountNonExpired\": true, "
+ "\"accountNonLocked\": true, "
+ "\"credentialsNonExpired\": true, "
+ "\"enabled\": true, "
+ "\"authorities\": " + AUTHORITIES_SET_JSON
+ "}";
// @formatter:on
private static final String CAS_TOKEN_JSON = "{"
+ "\"@class\": \"org.springframework.security.cas.authentication.CasAuthenticationToken\", "
+ "\"keyHash\": " + KEY.hashCode() + ","
+ "\"principal\": " + USER_JSON + ", "
+ "\"credentials\": " + PASSWORD + ", "
+ "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + ","
+ "\"userDetails\": " + USER_JSON +","
+ "\"authenticated\": true, "
+ "\"details\": null,"
+ "\"assertion\": {"
+ "\"@class\": \"org.jasig.cas.client.validation.AssertionImpl\", "
+ "\"principal\": {"
+ "\"@class\": \"org.jasig.cas.client.authentication.AttributePrincipalImpl\", "
+ "\"name\": \"assertName\", "
+ "\"attributes\": {\"@class\": \"java.util.Collections$EmptyMap\"}, "
+ "\"proxyGrantingTicket\": null, "
+ "\"proxyRetriever\": null"
+ "}, "
+ "\"validFromDate\": [\"java.util.Date\", " + START_DATE.getTime() + "], "
+ "\"validUntilDate\": [\"java.util.Date\", " + END_DATE.getTime() + "],"
+ "\"authenticationDate\": [\"java.util.Date\", " + START_DATE.getTime() + "], "
+ "\"attributes\": {\"@class\": \"java.util.Collections$EmptyMap\"}" +
"}"
+ "}";
private static final String CAS_TOKEN_CLEARED_JSON = CAS_TOKEN_JSON.replaceFirst(PASSWORD, "null");
protected ObjectMapper mapper;
@Before
public void setup() {
mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(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);
}
}
-15
View File
@@ -1,15 +0,0 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.springframework.security" level="${sec.log.level:-WARN}"/>
<root level="${root.level:-WARN}">
<appender-ref ref="STDOUT" />
</root>
</configuration>
+78
View File
@@ -0,0 +1,78 @@
import javax.security.auth.login.ConfigurationSpi;
// Config Module build file
apply plugin: 'groovy'
apply plugin: 'trang'
compileTestJava.dependsOn(':spring-security-core:compileTestJava')
dependencies {
// NB: Don't add other compile time dependencies to the config module as this breaks tooling
compile project(':spring-security-core'),
springCoreDependency,
'aopalliance:aopalliance:1.0',
"org.springframework:spring-aop:$springVersion",
"org.springframework:spring-context:$springVersion",
"org.springframework:spring-beans:$springVersion"
optional project(':spring-security-web'),
project(':spring-security-ldap'),
project(':spring-security-openid'),
project(':spring-security-messaging'),
"org.springframework:spring-web:$springVersion",
"org.springframework:spring-websocket:$springVersion",
"org.springframework:spring-webmvc:$springVersion",
"org.aspectj:aspectjweaver:$aspectjVersion",
"org.springframework:spring-jdbc:$springVersion",
"org.springframework:spring-tx:$springVersion"
provided "javax.servlet:javax.servlet-api:$servletApiVersion"
testCompile project(':spring-security-cas'),
project(':spring-security-core').sourceSets.test.output,
project(':spring-security-aspects'),
'javax.annotation:jsr250-api:1.0',
"org.springframework.ldap:spring-ldap-core:$springLdapVersion",
"org.springframework:spring-expression:$springVersion",
"org.springframework:spring-jdbc:$springVersion",
"org.springframework:spring-orm:$springVersion",
"org.springframework:spring-tx:$springVersion",
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
"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",
"org.apache.directory.server:apacheds-protocol-shared:$apacheDsVersion",
"org.apache.directory.server:apacheds-protocol-ldap:$apacheDsVersion",
"org.apache.directory.server:apacheds-server-jndi:$apacheDsVersion",
'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
testCompile('org.openid4java:openid4java-nodeps:0.9.6') {
exclude group: 'com.google.code.guice', module: 'guice'
}
testCompile("org.springframework.data:spring-data-jpa:$springDataJpaVersion") {
exclude group: 'org.aspectj', module: 'aspectjrt'
}
testRuntime "org.hsqldb:hsqldb:$hsqlVersion",
"cglib:cglib-nodep:$cglibVersion"
}
test {
inputs.file file("$rootDir/docs/manual/src/docbook/appendix-namespace.xml")
}
rncToXsd {
rncDir = file('src/main/resources/org/springframework/security/config/')
xsdDir = rncDir
xslFile = new File(rncDir, 'spring-security.xsl')
}
build.dependsOn rncToXsd
+404
View File
@@ -0,0 +1,404 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.3.RELEASE</version>
<name>spring-security-config</name>
<description>spring-security-config</description>
<url>http://spring.io/spring-security</url>
<organization>
<name>spring.io</name>
<url>http://spring.io/</url>
</organization>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rwinch</id>
<name>Rob Winch</name>
<email>rwinch@gopivotal.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/spring-projects/spring-security</connection>
<developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>
<url>https://github.com/spring-projects/spring-security</url>
</scm>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<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.1.3.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-openid</artifactId>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.3.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ldapsdk</groupId>
<artifactId>ldapsdk</artifactId>
<version>4.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-core</artifactId>
<version>1.5.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-core-entry</artifactId>
<version>1.5.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-protocol-ldap</artifactId>
<version>1.5.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-protocol-shared</artifactId>
<version>1.5.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-server-jndi</artifactId>
<version>1.5.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.shared</groupId>
<artifactId>shared-ldap</artifactId>
<version>0.9.15</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.0.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openid4java</groupId>
<artifactId>openid4java-nodeps</artifactId>
<version>0.9.6</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>guice</artifactId>
<groupId>com.google.code.guice</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>mockito-all</artifactId>
<groupId>org.mockito</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-support</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-common</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-reflect</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>0.7-groovy-2.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>junit-dep</artifactId>
<groupId>junit</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-spring</artifactId>
<version>0.7-groovy-2.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>junit-dep</artifactId>
<groupId>junit</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.2.RELEASE</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>aspectjrt</artifactId>
<groupId>org.aspectj</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.0.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-aspects</artifactId>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
-80
View File
@@ -1,80 +0,0 @@
apply plugin: 'io.spring.convention.spring-module'
apply plugin: 'trang'
dependencies {
// NB: Don't add other compile time dependencies to the config module as this breaks tooling
compile project(':spring-security-core')
compile 'aopalliance:aopalliance:1.0'
compile 'org.springframework:spring-aop'
compile 'org.springframework:spring-beans'
compile 'org.springframework:spring-context'
compile 'org.springframework:spring-core'
optional project(':spring-security-ldap')
optional project(':spring-security-messaging')
optional project(':spring-security-oauth2-client')
optional project(':spring-security-jwt-jose')
optional project(':spring-security-openid')
optional project(':spring-security-web')
optional project(':spring-security-webflux')
optional 'org.aspectj:aspectjweaver'
optional 'org.springframework:spring-jdbc'
optional 'org.springframework:spring-tx'
optional 'org.springframework:spring-webmvc'
optional'org.springframework:spring-web'
optional'org.springframework:spring-websocket'
provided 'javax.servlet:javax.servlet-api'
testCompile project(':spring-security-aspects')
testCompile project(':spring-security-cas')
testCompile project(path : ':spring-security-core', configuration : 'tests')
testCompile project(path : ':spring-security-webflux', configuration : 'tests')
testCompile apachedsDependencies
testCompile powerMockDependencies
testCompile spockDependencies
testCompile 'ch.qos.logback:logback-classic'
testCompile 'javax.annotation:jsr250-api:1.0'
testCompile 'ldapsdk:ldapsdk:4.1'
testCompile('net.sourceforge.htmlunit:htmlunit') {
exclude group: 'commons-logging', module: 'commons-logging'
}
testCompile 'org.codehaus.groovy:groovy-all'
testCompile 'org.eclipse.persistence:javax.persistence'
testCompile 'org.hibernate:hibernate-entitymanager'
testCompile 'org.hsqldb:hsqldb'
testCompile ('org.openid4java:openid4java-nodeps') {
exclude group: 'com.google.code.guice', module: 'guice'
}
testCompile('org.seleniumhq.selenium:htmlunit-driver') {
exclude group: 'commons-logging', module: 'commons-logging'
}
testCompile('org.seleniumhq.selenium:selenium-java') {
exclude group: 'commons-logging', module: 'commons-logging'
exclude group: 'io.netty', module: 'netty'
}
testCompile 'org.slf4j:jcl-over-slf4j'
testCompile 'org.springframework.ldap:spring-ldap-core'
testCompile 'org.springframework:spring-expression'
testCompile 'org.springframework:spring-jdbc'
testCompile 'org.springframework:spring-orm'
testCompile 'org.springframework:spring-tx'
testCompile ('org.springframework.data:spring-data-jpa') {
exclude group: 'org.aspectj', module: 'aspectjrt'
}
testRuntime 'cglib:cglib-nodep'
testRuntime 'org.hsqldb:hsqldb'
}
test {
inputs.file file("$rootDir/docs/manual/src/docbook/appendix-namespace.xml")
}
rncToXsd {
rncDir = file('src/main/resources/org/springframework/security/config/')
xsdDir = rncDir
xslFile = new File(rncDir, 'spring-security.xsl')
}
build.dependsOn rncToXsd
@@ -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
@@ -1,19 +1,19 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
</appender>
<logger name="org.springframework.security" level="${sec.log.level:-WARN}"/>
<logger name="org.springframework.security" level="${sec.log.level}:-WARN"/>
<logger name="org.apache.directory" level="ERROR"/>
<logger name="JdbmTable" level="INFO"/>
<logger name="JdbmIndex" level="INFO"/>
<logger name="org.apache.mina" level="WARN"/>
<logger name="org.apache.directory" level="ERROR"/>
<logger name="JdbmTable" level="INFO"/>
<logger name="JdbmIndex" level="INFO"/>
<logger name="org.apache.mina" level="WARN"/>
<root level="${root.level:-WARN}">
<root level="${root.level}:-WARN">
<appender-ref ref="STDOUT" />
</root>
</root>
</configuration>
@@ -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.*");
}
@@ -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);
}
}
}
@@ -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,71 +0,0 @@
/*
*
* * Copyright 2002-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.config.annotation.method.configuration;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
*
* @author Rob Winch
* @since 5.0
*/
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ ReactiveMethodSecuritySelector.class })
@Configuration
public @interface EnableReactiveMethodSecurity {
/**
* Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
* to standard Java interface-based proxies. The default is {@code false}. <strong>
* Applicable only if {@link #mode()} is set to {@link AdviceMode#PROXY}</strong>.
* <p>Note that setting this attribute to {@code true} will affect <em>all</em>
* Spring-managed beans requiring proxying, not just those marked with {@code @Cacheable}.
* For example, other beans marked with Spring's {@code @Transactional} annotation will
* be upgraded to subclass proxying at the same time. This approach has no negative
* impact in practice unless one is explicitly expecting one type of proxy vs another,
* e.g. in tests.
*/
boolean proxyTargetClass() default false;
/**
* Indicate how security advice should be applied. The default is
* {@link AdviceMode#PROXY}.
* @see AdviceMode
*
* @return the {@link AdviceMode} to use
*/
AdviceMode mode() default AdviceMode.PROXY;
/**
* Indicate the ordering of the execution of the security advisor when multiple
* advices are applied at a specific joinpoint. The default is
* {@link Ordered#LOWEST_PRECEDENCE}.
*
* @return the order the security advisor should be applied
*/
int order() default Ordered.LOWEST_PRECEDENCE;
}
@@ -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.
@@ -66,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;
/**
@@ -75,7 +74,6 @@ import org.springframework.util.Assert;
* {@link EnableGlobalMethodSecurity} annotation on the subclass.
*
* @author Rob Winch
* @author Eddú Meléndez
* @since 3.2
* @see EnableGlobalMethodSecurity
*/
@@ -170,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) {
@@ -364,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);
@@ -415,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;
}
@@ -464,4 +449,4 @@ public class GlobalMethodSecurityConfiguration
}
return this.enableMethodSecurity;
}
}
}
@@ -1,85 +0,0 @@
/*
*
* * Copyright 2002-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.config.annotation.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.ImportAware;
import org.springframework.context.annotation.Role;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.security.access.expression.method.*;
import org.springframework.security.access.intercept.aopalliance.MethodSecurityMetadataSourceAdvisor;
import org.springframework.security.access.method.AbstractMethodSecurityMetadataSource;
import org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource;
import org.springframework.security.access.method.PrePostAdviceMethodInterceptor;
import org.springframework.security.access.prepost.PrePostAnnotationSecurityMetadataSource;
import java.util.Arrays;
/**
* @author Rob Winch
* @since 5.0
*/
@Configuration
class ReactiveMethodSecurityConfiguration implements ImportAware {
private int advisorOrder;
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public MethodSecurityMetadataSourceAdvisor methodSecurityInterceptor(AbstractMethodSecurityMetadataSource source) throws Exception {
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"securityMethodInterceptor", source, "methodMetadataSource");
advisor.setOrder(advisorOrder);
return advisor;
}
@Bean
public DelegatingMethodSecurityMetadataSource methodMetadataSource() {
ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory(
new DefaultMethodSecurityExpressionHandler());
PrePostAnnotationSecurityMetadataSource prePostSource = new PrePostAnnotationSecurityMetadataSource(
attributeFactory);
return new DelegatingMethodSecurityMetadataSource(Arrays.asList(prePostSource));
}
@Bean
public PrePostAdviceMethodInterceptor securityMethodInterceptor(AbstractMethodSecurityMetadataSource source, MethodSecurityExpressionHandler handler) {
ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice(
handler);
ExpressionBasedPreInvocationAdvice preAdvice = new ExpressionBasedPreInvocationAdvice();
preAdvice.setExpressionHandler(handler);
PrePostAdviceMethodInterceptor result = new PrePostAdviceMethodInterceptor(source);
result.setPostAdvice(postAdvice);
result.setPreAdvice(preAdvice);
return result;
}
@Bean
public DefaultMethodSecurityExpressionHandler methodSecurityExpressionHandler() {
return new DefaultMethodSecurityExpressionHandler();
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
this.advisorOrder = (int) importMetadata.getAnnotationAttributes(EnableReactiveMethodSecurity.class.getName()).get("order");
}
}
@@ -1,57 +0,0 @@
/*
*
* * Copyright 2002-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.config.annotation.method.configuration;
import org.springframework.cache.annotation.ProxyCachingConfiguration;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.AdviceModeImportSelector;
import org.springframework.context.annotation.AutoProxyRegistrar;
import org.springframework.lang.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* @author Rob Winch
* @since 5.0
*/
class ReactiveMethodSecuritySelector extends
AdviceModeImportSelector<EnableReactiveMethodSecurity> {
@Override
protected String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
case PROXY:
return getProxyImports();
default:
throw new IllegalStateException("AdviceMode " + adviceMode + " is not supported");
}
}
/**
* Return the imports to use if the {@link AdviceMode} is set to {@link AdviceMode#PROXY}.
* <p>Take care of adding the necessary JSR-107 import if it is available.
*/
private String[] getProxyImports() {
List<String> result = new ArrayList<>();
result.add(AutoProxyRegistrar.class.getName());
result.add(ReactiveMethodSecurityConfiguration.class.getName());
return result.toArray(new String[result.size()]);
}
}
@@ -77,10 +77,6 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
order += STEP;
put(LogoutFilter.class, order);
order += STEP;
filterToOrder.put(
"org.springframework.security.oauth2.client.web.AuthorizationCodeRequestRedirectFilter",
order);
order += STEP;
put(X509AuthenticationFilter.class, order);
order += STEP;
put(AbstractPreAuthenticatedProcessingFilter.class, order);
@@ -88,10 +84,6 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
filterToOrder.put("org.springframework.security.cas.web.CasAuthenticationFilter",
order);
order += STEP;
filterToOrder.put(
"org.springframework.security.oauth2.client.web.AuthorizationCodeAuthenticationProcessingFilter",
order);
order += STEP;
put(UsernamePasswordAuthenticationFilter.class, order);
order += STEP;
put(ConcurrentSessionFilter.class, order);
@@ -61,9 +61,6 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer;
import org.springframework.security.oauth2.client.web.AuthorizationGrantTokenExchanger;
import org.springframework.security.oauth2.client.web.AuthorizationRequestUriBuilder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.PortMapper;
import org.springframework.security.web.PortMapperImpl;
@@ -899,158 +896,6 @@ public final class HttpSecurity extends
return getOrApply(new FormLoginConfigurer<HttpSecurity>());
}
/**
* Configures authentication against an external <i>OAuth 2.0</i> or <i>OpenID Connect 1.0</i> Provider.
* <br>
* <br>
*
* The <i>&quot;authentication flow&quot;</i> is realized using the <b>Authorization Code Grant</b>,
* as specified in the <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">OAuth 2.0 Authorization Framework</a>.
* <br>
* <br>
*
* As a prerequisite to using this feature, the developer must register a <i>Client</i> with an <i>Authorization Server</i>.
* The output of the <i>Client Registration</i> process results in a number of properties that are then used for configuring
* an instance of a {@link org.springframework.security.oauth2.client.registration.ClientRegistration}.
* Properties specific to a <i>Client</i> include: <i>client_id</i>, <i>client_secret</i>, <i>scope</i>, <i>redirect_uri</i>, etc.
* There are also properties specific to the <i>Provider</i>, for example,
* <i>Authorization Endpoint URI</i>, <i>Token Endpoint URI</i>, <i>UserInfo Endpoint URI</i>, etc.
* <br>
* <br>
*
* Multiple client support is provided for use cases where the application provides the user the option
* for <i>&quot;Logging in&quot;</i> against one or more Providers, for example, <i>Google</i>, <i>GitHub</i>, <i>Facebook</i>, etc.
* <br>
* <br>
*
* {@link org.springframework.security.oauth2.client.registration.ClientRegistration}(s) are composed within a
* {@link org.springframework.security.oauth2.client.registration.ClientRegistrationRepository}.
* An instance of {@link org.springframework.security.oauth2.client.registration.ClientRegistrationRepository} is <b>required</b>
* and may be supplied via the {@link ApplicationContext} or configured using
* {@link OAuth2LoginConfigurer#clients(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository)}.
* <br>
* <br>
*
* The default configuration provides an auto-generated login page at <code>&quot;/login&quot;</code> and
* redirects to <code>&quot;/login?error&quot;</code> when an authentication error occurs.
* The login page will display each of the clients (composed within the
* {@link org.springframework.security.oauth2.client.registration.ClientRegistrationRepository})
* with an anchor link to <code>&quot;/oauth2/authorization/code/{clientAlias}&quot;</code>.
* Clicking through the link will initiate the <i>&quot;Authorization Request&quot;</i> flow
* redirecting the end-user's user-agent to the <i>Authorization Endpoint</i> of the <i>Provider</i>.
* Assuming the <i>Resource Owner</i> (end-user) grants the <i>Client</i> access, the <i>Authorization Server</i>
* will redirect the end-user's user-agent to the <i>Redirection Endpoint</i> containing the <i>Authorization Code</i>
* - the <i>Redirection Endpoint</i> is automatically configured for the application and
* defaults to <code>&quot;/oauth2/authorize/code/{clientAlias}&quot;</code>.
*
* <p>
* At this point in the <i>&quot;authentication flow&quot;</i>, the configured
* {@link AuthorizationGrantTokenExchanger}
* will exchange the <i>Authorization Code</i> for an <i>Access Token</i> and then use it to access the protected resource
* at the <i>UserInfo Endpoint</i> (via {@link org.springframework.security.oauth2.client.user.OAuth2UserService})
* in order to retrieve the details of the <i>Resource Owner</i> (end-user) and establish the <i>&quot;authenticated&quot;</i> session.
*
* <h2>Example Configurations</h2>
*
* The minimal configuration defaults to automatically generating a login page at <code>&quot;/login&quot;</code>
* and redirecting to <code>&quot;/login?error&quot;</code> when an authentication error occurs or redirecting to
* <code>&quot;/&quot;</code> when an authenticated session is established.
*
* <pre>
* &#064;EnableWebSecurity
* public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
*
* &#064;Override
* protected void configure(HttpSecurity http) throws Exception {
* http
* .authorizeRequests()
* .anyRequest().authenticated()
* .and()
* .oauth2Login();
* }
*
* &#064;Bean
* public ClientRegistrationRepository clientRegistrationRepository() {
* // ClientRegistrationRepositoryImpl must be composed of at least one ClientRegistration instance
* return new ClientRegistrationRepositoryImpl();
* }
* }
* </pre>
*
* The following shows the configuration options available for customizing the defaults.
*
* <pre>
* &#064;EnableWebSecurity
* public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
*
* &#064;Override
* protected void configure(HttpSecurity http) throws Exception {
* http
* .authorizeRequests()
* .anyRequest().authenticated()
* .and()
* .oauth2Login()
* .clients(this.clientRegistrationRepository())
* .authorizationRequestBuilder(this.authorizationRequestBuilder())
* .authorizationCodeTokenExchanger(this.authorizationCodeTokenExchanger())
* .userInfoEndpoint()
* .userInfoService(this.userInfoService())
* .userInfoEndpoint()
* // Provide a mapping between a Converter implementation and a UserInfo Endpoint URI
* .userInfoTypeConverter(this.userInfoConverter(),
* new URI("https://www.googleapis.com/oauth2/v3/userinfo"));
* }
*
* &#064;Bean
* public ClientRegistrationRepository clientRegistrationRepository() {
* // ClientRegistrationRepositoryImpl must be composed of at least one ClientRegistration instance
* return new ClientRegistrationRepositoryImpl();
* }
*
* &#064;Bean
* public AuthorizationRequestUriBuilder authorizationRequestBuilder() {
* // Custom URI builder for the &quot;Authorization Request&quot;
* return new AuthorizationRequestUriBuilderImpl();
* }
*
* &#064;Bean
* public AuthorizationGrantTokenExchanger&lt;AuthorizationCodeAuthenticationToken&gt; authorizationCodeTokenExchanger() {
* // Custom implementation that exchanges an &quot;Authorization Code Grant&quot; for an &quot;Access Token&quot;
* return new AuthorizationCodeTokenExchangerImpl();
* }
*
* &#064;Bean
* public OAuth2UserService userInfoService() {
* // Custom implementation that retrieves the details of the authenticated user at the &quot;UserInfo Endpoint&quot;
* return new OAuth2UserServiceImpl();
* }
*
* &#064;Bean
* public Converter&lt;ClientHttpResponse, UserInfo&gt; userInfoConverter() {
* // Default converter implementation for UserInfo
* return new org.springframework.security.oauth2.client.user.converter.UserInfoConverter();
* }
* }
* </pre>
*
* @author Joe Grandja
* @since 5.0
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section 4.1 Authorization Code Grant Flow</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1.1">Section 4.1.1 Authorization Request</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1.2">Section 4.1.2 Authorization Response</a>
* @see org.springframework.security.oauth2.client.registration.ClientRegistration
* @see org.springframework.security.oauth2.client.registration.ClientRegistrationRepository
* @see AuthorizationRequestUriBuilder
* @see AuthorizationGrantTokenExchanger
* @see org.springframework.security.oauth2.client.user.OAuth2UserService
*
* @return the {@link OAuth2LoginConfigurer} for further customizations
* @throws Exception
*/
public OAuth2LoginConfigurer<HttpSecurity> oauth2Login() throws Exception {
return getOrApply(new OAuth2LoginConfigurer<HttpSecurity>());
}
/**
* Configures channel security. In order for this configuration to be useful at least
* one mapping to a required channel must be provided.
@@ -113,7 +113,7 @@ public final class WebSecurity extends
/**
* <p>
* Allows adding {@link RequestMatcher} instances that Spring Security
* Allows adding {@link RequestMatcher} instances that should that Spring Security
* should ignore. Web Security provided by Spring Security (including the
* {@link SecurityContext}) will not be available on {@link HttpServletRequest} that
* match. Typically the requests that are registered should be that of only static
@@ -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());
}
}
@@ -160,7 +160,7 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
}
@Bean
public static AutowiredWebSecurityConfigurersIgnoreParents autowiredWebSecurityConfigurersIgnoreParents(
public AutowiredWebSecurityConfigurersIgnoreParents autowiredWebSecurityConfigurersIgnoreParents(
ConfigurableListableBeanFactory beanFactory) {
return new AutowiredWebSecurityConfigurersIgnoreParents(beanFactory);
}
@@ -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;
@@ -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);
@@ -213,7 +213,7 @@ public final class FormLoginConfigurer<H extends HttpSecurityBuilder<H>> extends
* Forward Authentication Failure Handler
*
* @param forwardUrl the target URL in case of failure
* @return the {@link FormLoginConfigurer} for additional customization
* @return he {@link FormLoginConfigurer} for additional customization
*/
public FormLoginConfigurer<H> failureForwardUrl(String forwardUrl) {
failureHandler(new ForwardAuthenticationFailureHandler(forwardUrl));
@@ -224,7 +224,7 @@ public final class FormLoginConfigurer<H extends HttpSecurityBuilder<H>> extends
* Forward Authentication Success Handler
*
* @param forwardUrl the target URL in case of success
* @return the {@link FormLoginConfigurer} for additional customization
* @return he {@link FormLoginConfigurer} for additional customization
*/
public FormLoginConfigurer<H> successForwardUrl(String forwardUrl) {
successHandler(new ForwardAuthenticationSuccessHandler(forwardUrl));
@@ -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
*
@@ -227,7 +223,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
}
/**
* Allows completing configuration of X-XSS-Protection and continuing
* Allows completing configuration of Strict Transport Security and continuing
* configuration of headers.
*
* @return the {@link HeadersConfigurer} for additional configuration
@@ -282,7 +278,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
}
/**
* Allows completing configuration of Cache Control and continuing
* Allows completing configuration of Strict Transport Security and continuing
* configuration of headers.
*
* @return the {@link HeadersConfigurer} for additional configuration
@@ -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;
}
}
}
@@ -19,12 +19,10 @@ import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
@@ -93,15 +91,7 @@ public final class ServletApiConfigurer<H extends HttpSecurityBuilder<H>> extend
if (trustResolver != null) {
securityContextRequestFilter.setTrustResolver(trustResolver);
}
ApplicationContext context = http.getSharedObject(ApplicationContext.class);
if(context != null) {
String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = context.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
securityContextRequestFilter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix());
}
}
securityContextRequestFilter = postProcess(securityContextRequestFilter);
http.addFilter(securityContextRequestFilter);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,6 @@ import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.context.DelegatingApplicationListener;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy;
import org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy;
@@ -49,10 +48,8 @@ import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.session.ConcurrentSessionFilter;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.security.web.session.SessionManagementFilter;
import org.springframework.security.web.session.SimpleRedirectInvalidSessionStrategy;
import org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy;
import org.springframework.util.Assert;
/**
@@ -92,14 +89,13 @@ import org.springframework.util.Assert;
* @see SessionManagementFilter
* @see ConcurrentSessionFilter
*/
public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
extends AbstractHttpConfigurer<SessionManagementConfigurer<H>, H> {
public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>> extends
AbstractHttpConfigurer<SessionManagementConfigurer<H>, H> {
private final SessionAuthenticationStrategy DEFAULT_SESSION_FIXATION_STRATEGY = createDefaultSessionFixationProtectionStrategy();
private SessionAuthenticationStrategy sessionFixationAuthenticationStrategy = this.DEFAULT_SESSION_FIXATION_STRATEGY;
private SessionAuthenticationStrategy sessionFixationAuthenticationStrategy = DEFAULT_SESSION_FIXATION_STRATEGY;
private SessionAuthenticationStrategy sessionAuthenticationStrategy;
private SessionAuthenticationStrategy providedSessionAuthenticationStrategy;
private InvalidSessionStrategy invalidSessionStrategy;
private SessionInformationExpiredStrategy expiredSessionStrategy;
private List<SessionAuthenticationStrategy> sessionAuthenticationStrategies = new ArrayList<SessionAuthenticationStrategy>();
private SessionRegistry sessionRegistry;
private Integer maximumSessions;
@@ -109,7 +105,6 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
private boolean enableSessionUrlRewriting;
private String invalidSessionUrl;
private String sessionAuthenticationErrorUrl;
private AuthenticationFailureHandler sessionAuthenticationFailureHandler;
/**
* Creates a new instance
@@ -136,12 +131,10 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* Setting this attribute will inject the provided invalidSessionStrategy into the
* {@link SessionManagementFilter}. When an invalid session ID is submitted, the
* strategy will be invoked, redirecting to the configured URL.
* @param invalidSessionStrategy the strategy to use when an invalid session ID is
* submitted.
* @param invalidSessionStrategy the strategy to use when an invalid session ID is submitted.
* @return the {@link SessionManagementConfigurer} for further customization
*/
public SessionManagementConfigurer<H> invalidSessionStrategy(
InvalidSessionStrategy invalidSessionStrategy) {
public SessionManagementConfigurer<H> invalidSessionStrategy(InvalidSessionStrategy invalidSessionStrategy) {
Assert.notNull(invalidSessionStrategy, "invalidSessionStrategy");
this.invalidSessionStrategy = invalidSessionStrategy;
return this;
@@ -163,22 +156,6 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
return this;
}
/**
* Defines the {@code AuthenticationFailureHandler} which will be used when the
* SessionAuthenticationStrategy raises an exception. If not set, an unauthorized
* (402) error code will be returned to the client. Note that this attribute doesn't
* apply if the error occurs during a form-based login, where the URL for
* authentication failure will take precedence.
*
* @param sessionAuthenticationFailureHandler the handler to use
* @return the {@link SessionManagementConfigurer} for further customization
*/
public SessionManagementConfigurer<H> sessionAuthenticationFailureHandler(
AuthenticationFailureHandler sessionAuthenticationFailureHandler) {
this.sessionAuthenticationFailureHandler = sessionAuthenticationFailureHandler;
return this;
}
/**
* If set to true, allows HTTP sessions to be rewritten in the URLs when using
* {@link HttpServletResponse#encodeRedirectURL(String)} or
@@ -221,8 +198,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* {@link SessionAuthenticationStrategy} the supplied sessionAuthenticationStrategy,
* {@link RegisterSessionAuthenticationStrategy}.
*
* NOTE: Supplying a custom {@link SessionAuthenticationStrategy} will override the
* default provided {@link SessionFixationProtectionStrategy}.
* NOTE: Supplying a custom {@link SessionAuthenticationStrategy} will override the default provided {@link SessionFixationProtectionStrategy}.
*
* @param sessionAuthenticationStrategy
* @return the {@link SessionManagementConfigurer} for further customizations
@@ -268,8 +244,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
*/
private void setSessionFixationAuthenticationStrategy(
SessionAuthenticationStrategy sessionFixationAuthenticationStrategy) {
this.sessionFixationAuthenticationStrategy = postProcess(
sessionFixationAuthenticationStrategy);
this.sessionFixationAuthenticationStrategy = postProcess(sessionFixationAuthenticationStrategy);
}
/**
@@ -298,8 +273,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link SessionManagementConfigurer} for further customizations
*/
public SessionManagementConfigurer<H> migrateSession() {
setSessionFixationAuthenticationStrategy(
new SessionFixationProtectionStrategy());
setSessionFixationAuthenticationStrategy(new SessionFixationProtectionStrategy());
return SessionManagementConfigurer.this;
}
@@ -314,8 +288,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @throws IllegalStateException if the container is not Servlet 3.1 or newer.
*/
public SessionManagementConfigurer<H> changeSessionId() {
setSessionFixationAuthenticationStrategy(
new ChangeSessionIdAuthenticationStrategy());
setSessionFixationAuthenticationStrategy(new ChangeSessionIdAuthenticationStrategy());
return SessionManagementConfigurer.this;
}
@@ -328,8 +301,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link SessionManagementConfigurer} for further customizations
*/
public SessionManagementConfigurer<H> none() {
setSessionFixationAuthenticationStrategy(
new NullAuthenticatedSessionStrategy());
setSessionFixationAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
return SessionManagementConfigurer.this;
}
}
@@ -354,12 +326,6 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
return this;
}
public ConcurrencyControlConfigurer expiredSessionStrategy(
SessionInformationExpiredStrategy expiredSessionStrategy) {
SessionManagementConfigurer.this.expiredSessionStrategy = expiredSessionStrategy;
return this;
}
/**
* If true, prevents a user from authenticating when the
* {@link #maximumSessions(int)} has been reached. Otherwise (default), the user
@@ -418,8 +384,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
}
else {
HttpSessionSecurityContextRepository httpSecurityRepository = new HttpSessionSecurityContextRepository();
httpSecurityRepository
.setDisableUrlRewriting(!this.enableSessionUrlRewriting);
httpSecurityRepository.setDisableUrlRewriting(!enableSessionUrlRewriting);
httpSecurityRepository.setAllowSessionCreation(isAllowSessionCreation());
AuthenticationTrustResolver trustResolver = http
.getSharedObject(AuthenticationTrustResolver.class);
@@ -448,18 +413,15 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
.getSharedObject(SecurityContextRepository.class);
SessionManagementFilter sessionManagementFilter = new SessionManagementFilter(
securityContextRepository, getSessionAuthenticationStrategy(http));
if (this.sessionAuthenticationErrorUrl != null) {
sessionManagementFilter.setAuthenticationFailureHandler(
new SimpleUrlAuthenticationFailureHandler(
this.sessionAuthenticationErrorUrl));
if (sessionAuthenticationErrorUrl != null) {
sessionManagementFilter
.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(
sessionAuthenticationErrorUrl));
}
InvalidSessionStrategy strategy = getInvalidSessionStrategy();
if (strategy != null) {
sessionManagementFilter.setInvalidSessionStrategy(strategy);
}
AuthenticationFailureHandler failureHandler = getSessionAuthenticationFailureHandler();
if (failureHandler != null) {
sessionManagementFilter.setAuthenticationFailureHandler(failureHandler);
sessionManagementFilter
.setInvalidSessionStrategy(strategy);
}
AuthenticationTrustResolver trustResolver = http
.getSharedObject(AuthenticationTrustResolver.class);
@@ -470,23 +432,13 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
http.addFilter(sessionManagementFilter);
if (isConcurrentSessionControlEnabled()) {
ConcurrentSessionFilter concurrentSessionFilter = createConccurencyFilter(http);
ConcurrentSessionFilter concurrentSessionFilter = new ConcurrentSessionFilter(
getSessionRegistry(http), expiredUrl);
concurrentSessionFilter = postProcess(concurrentSessionFilter);
http.addFilter(concurrentSessionFilter);
}
}
private ConcurrentSessionFilter createConccurencyFilter(H http) {
SessionInformationExpiredStrategy expireStrategy = getExpiredSessionStrategy();
SessionRegistry sessionRegistry = getSessionRegistry(http);
if(expireStrategy == null) {
return new ConcurrentSessionFilter(sessionRegistry);
}
return new ConcurrentSessionFilter(sessionRegistry, expireStrategy);
}
/**
* Gets the {@link InvalidSessionStrategy} to use. If null and
* {@link #invalidSessionUrl} is not null defaults to
@@ -495,53 +447,14 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link InvalidSessionStrategy} to use
*/
InvalidSessionStrategy getInvalidSessionStrategy() {
if (this.invalidSessionStrategy != null) {
return this.invalidSessionStrategy;
if(invalidSessionStrategy != null) {
return invalidSessionStrategy;
}
if (this.invalidSessionUrl != null) {
this.invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy(
this.invalidSessionUrl);
if (invalidSessionUrl != null) {
invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy(
invalidSessionUrl);
}
if (this.invalidSessionUrl == null) {
return null;
}
if (this.invalidSessionStrategy == null) {
this.invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy(
this.invalidSessionUrl);
}
return this.invalidSessionStrategy;
}
SessionInformationExpiredStrategy getExpiredSessionStrategy() {
if (this.expiredSessionStrategy != null) {
return this.expiredSessionStrategy;
}
if (this.expiredUrl == null) {
return null;
}
if (this.expiredSessionStrategy == null) {
this.expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy(
this.expiredUrl);
}
return this.expiredSessionStrategy;
}
AuthenticationFailureHandler getSessionAuthenticationFailureHandler() {
if (this.sessionAuthenticationFailureHandler != null) {
return this.sessionAuthenticationFailureHandler;
}
if (this.sessionAuthenticationErrorUrl == null) {
return null;
}
if (this.sessionAuthenticationFailureHandler == null) {
this.sessionAuthenticationFailureHandler = new SimpleUrlAuthenticationFailureHandler(
this.sessionAuthenticationErrorUrl);
}
return this.sessionAuthenticationFailureHandler;
return invalidSessionStrategy;
}
/**
@@ -549,7 +462,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link SessionCreationPolicy}
*/
SessionCreationPolicy getSessionCreationPolicy() {
return this.sessionPolicy;
return sessionPolicy;
}
/**
@@ -558,8 +471,8 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return true if the {@link SessionCreationPolicy} allows session creation
*/
private boolean isAllowSessionCreation() {
return SessionCreationPolicy.ALWAYS == this.sessionPolicy
|| SessionCreationPolicy.IF_REQUIRED == this.sessionPolicy;
return SessionCreationPolicy.ALWAYS == sessionPolicy
|| SessionCreationPolicy.IF_REQUIRED == sessionPolicy;
}
/**
@@ -567,7 +480,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return
*/
private boolean isStateless() {
return SessionCreationPolicy.STATELESS == this.sessionPolicy;
return SessionCreationPolicy.STATELESS == sessionPolicy;
}
/**
@@ -578,52 +491,50 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link SessionAuthenticationStrategy} to use
*/
private SessionAuthenticationStrategy getSessionAuthenticationStrategy(H http) {
if (this.sessionAuthenticationStrategy != null) {
return this.sessionAuthenticationStrategy;
if (sessionAuthenticationStrategy != null) {
return sessionAuthenticationStrategy;
}
List<SessionAuthenticationStrategy> delegateStrategies = this.sessionAuthenticationStrategies;
List<SessionAuthenticationStrategy> delegateStrategies = sessionAuthenticationStrategies;
SessionAuthenticationStrategy defaultSessionAuthenticationStrategy;
if (this.providedSessionAuthenticationStrategy == null) {
if (providedSessionAuthenticationStrategy == null) {
// If a user provided SessionAuthenticationStrategy is not supplied
// then default to SessionFixationProtectionStrategy
defaultSessionAuthenticationStrategy = postProcess(
this.sessionFixationAuthenticationStrategy);
}
else {
defaultSessionAuthenticationStrategy = this.providedSessionAuthenticationStrategy;
defaultSessionAuthenticationStrategy = postProcess(sessionFixationAuthenticationStrategy);
} else {
defaultSessionAuthenticationStrategy = providedSessionAuthenticationStrategy;
}
if (isConcurrentSessionControlEnabled()) {
SessionRegistry sessionRegistry = getSessionRegistry(http);
ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlStrategy = new ConcurrentSessionControlAuthenticationStrategy(
sessionRegistry);
concurrentSessionControlStrategy.setMaximumSessions(this.maximumSessions);
concurrentSessionControlStrategy.setMaximumSessions(maximumSessions);
concurrentSessionControlStrategy
.setExceptionIfMaximumExceeded(this.maxSessionsPreventsLogin);
concurrentSessionControlStrategy = postProcess(
concurrentSessionControlStrategy);
.setExceptionIfMaximumExceeded(maxSessionsPreventsLogin);
concurrentSessionControlStrategy = postProcess(concurrentSessionControlStrategy);
RegisterSessionAuthenticationStrategy registerSessionStrategy = new RegisterSessionAuthenticationStrategy(
sessionRegistry);
registerSessionStrategy = postProcess(registerSessionStrategy);
delegateStrategies.addAll(Arrays.asList(concurrentSessionControlStrategy,
defaultSessionAuthenticationStrategy, registerSessionStrategy));
}
else {
delegateStrategies.addAll(Arrays.asList(
concurrentSessionControlStrategy,
defaultSessionAuthenticationStrategy,
registerSessionStrategy));
} else {
delegateStrategies.add(defaultSessionAuthenticationStrategy);
}
this.sessionAuthenticationStrategy = postProcess(
new CompositeSessionAuthenticationStrategy(delegateStrategies));
return this.sessionAuthenticationStrategy;
sessionAuthenticationStrategy = postProcess(new CompositeSessionAuthenticationStrategy(
delegateStrategies));
return sessionAuthenticationStrategy;
}
private SessionRegistry getSessionRegistry(H http) {
if (this.sessionRegistry == null) {
if (sessionRegistry == null) {
SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
registerDelegateApplicationListener(http, sessionRegistry);
this.sessionRegistry = sessionRegistry;
}
return this.sessionRegistry;
return sessionRegistry;
}
private void registerDelegateApplicationListener(H http,
@@ -647,7 +558,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return
*/
private boolean isConcurrentSessionControlEnabled() {
return this.maximumSessions != null;
return maximumSessions != null;
}
/**
@@ -1,224 +0,0 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.jwt.JwtDecoder;
import org.springframework.security.jwt.nimbus.NimbusJwtDecoderJwkSupport;
import org.springframework.security.oauth2.client.web.AuthorizationCodeAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.authentication.AuthorizationCodeAuthenticationProvider;
import org.springframework.security.oauth2.client.authentication.AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.client.web.AuthorizationGrantTokenExchanger;
import org.springframework.security.oauth2.client.authentication.jwt.DefaultProviderJwtDecoderRegistry;
import org.springframework.security.oauth2.client.authentication.jwt.ProviderJwtDecoderRegistry;
import org.springframework.security.oauth2.client.web.nimbus.NimbusAuthorizationCodeTokenExchanger;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.token.InMemoryAccessTokenRepository;
import org.springframework.security.oauth2.client.token.SecurityTokenRepository;
import org.springframework.security.oauth2.client.user.OAuth2UserService;
import org.springframework.security.oauth2.client.user.web.nimbus.NimbusOAuth2UserService;
import org.springframework.security.oauth2.core.AccessToken;
import org.springframework.security.oauth2.core.provider.DefaultProviderMetadata;
import org.springframework.security.oauth2.core.provider.ProviderMetadata;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.matcher.RequestVariablesExtractor;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* @author Joe Grandja
*/
final class AuthorizationCodeAuthenticationFilterConfigurer<H extends HttpSecurityBuilder<H>, R extends RequestMatcher & RequestVariablesExtractor> extends
AbstractAuthenticationFilterConfigurer<H, AuthorizationCodeAuthenticationFilterConfigurer<H, R>, AuthorizationCodeAuthenticationProcessingFilter> {
private R authorizationResponseMatcher;
private AuthorizationGrantTokenExchanger<AuthorizationCodeAuthenticationToken> authorizationCodeTokenExchanger;
private SecurityTokenRepository<AccessToken> accessTokenRepository;
private OAuth2UserService userInfoService;
private Map<URI, Class<? extends OAuth2User>> customUserTypes = new HashMap<>();
private Map<URI, String> userNameAttributeNames = new HashMap<>();
private GrantedAuthoritiesMapper userAuthoritiesMapper;
AuthorizationCodeAuthenticationFilterConfigurer() {
super(new AuthorizationCodeAuthenticationProcessingFilter(), null);
}
AuthorizationCodeAuthenticationFilterConfigurer<H, R> authorizationResponseMatcher(R authorizationResponseMatcher) {
Assert.notNull(authorizationResponseMatcher, "authorizationResponseMatcher cannot be null");
this.authorizationResponseMatcher = authorizationResponseMatcher;
return this;
}
AuthorizationCodeAuthenticationFilterConfigurer<H, R> authorizationCodeTokenExchanger(
AuthorizationGrantTokenExchanger<AuthorizationCodeAuthenticationToken> authorizationCodeTokenExchanger) {
Assert.notNull(authorizationCodeTokenExchanger, "authorizationCodeTokenExchanger cannot be null");
this.authorizationCodeTokenExchanger = authorizationCodeTokenExchanger;
return this;
}
AuthorizationCodeAuthenticationFilterConfigurer<H, R> accessTokenRepository(SecurityTokenRepository<AccessToken> accessTokenRepository) {
Assert.notNull(accessTokenRepository, "accessTokenRepository cannot be null");
this.accessTokenRepository = accessTokenRepository;
return this;
}
AuthorizationCodeAuthenticationFilterConfigurer<H, R> userInfoService(OAuth2UserService userInfoService) {
Assert.notNull(userInfoService, "userInfoService cannot be null");
this.userInfoService = userInfoService;
return this;
}
AuthorizationCodeAuthenticationFilterConfigurer<H, R> customUserType(Class<? extends OAuth2User> customUserType, URI userInfoUri) {
Assert.notNull(customUserType, "customUserType cannot be null");
Assert.notNull(userInfoUri, "userInfoUri cannot be null");
this.customUserTypes.put(userInfoUri, customUserType);
return this;
}
AuthorizationCodeAuthenticationFilterConfigurer<H, R> userNameAttributeName(String userNameAttributeName, URI userInfoUri) {
Assert.hasText(userNameAttributeName, "userNameAttributeName cannot be empty");
Assert.notNull(userInfoUri, "userInfoUri cannot be null");
this.userNameAttributeNames.put(userInfoUri, userNameAttributeName);
return this;
}
AuthorizationCodeAuthenticationFilterConfigurer<H, R> userAuthoritiesMapper(GrantedAuthoritiesMapper userAuthoritiesMapper) {
Assert.notNull(userAuthoritiesMapper, "userAuthoritiesMapper cannot be null");
this.userAuthoritiesMapper = userAuthoritiesMapper;
return this;
}
AuthorizationCodeAuthenticationFilterConfigurer<H, R> clientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notEmpty(clientRegistrationRepository.getRegistrations(), "clientRegistrationRepository cannot be empty");
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
return this;
}
String getLoginUrl() {
return super.getLoginPage();
}
String getLoginFailureUrl() {
return super.getFailureUrl();
}
@Override
public void init(H http) throws Exception {
AuthorizationCodeAuthenticationProvider authenticationProvider = new AuthorizationCodeAuthenticationProvider(
this.getAuthorizationCodeTokenExchanger(), this.getAccessTokenRepository(),
this.getProviderJwtDecoderRegistry(), this.getUserInfoService());
if (this.userAuthoritiesMapper != null) {
authenticationProvider.setAuthoritiesMapper(this.userAuthoritiesMapper);
}
authenticationProvider = this.postProcess(authenticationProvider);
http.authenticationProvider(authenticationProvider);
super.init(http);
}
@Override
public void configure(H http) throws Exception {
AuthorizationCodeAuthenticationProcessingFilter authFilter = this.getAuthenticationFilter();
if (this.authorizationResponseMatcher != null) {
authFilter.setAuthorizationResponseMatcher(this.authorizationResponseMatcher);
}
authFilter.setClientRegistrationRepository(OAuth2LoginConfigurer.getClientRegistrationRepository(this.getBuilder()));
super.configure(http);
}
@Override
protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {
return (this.authorizationResponseMatcher != null ?
this.authorizationResponseMatcher : this.getAuthenticationFilter().getAuthorizationResponseMatcher());
}
private AuthorizationGrantTokenExchanger<AuthorizationCodeAuthenticationToken> getAuthorizationCodeTokenExchanger() {
if (this.authorizationCodeTokenExchanger == null) {
this.authorizationCodeTokenExchanger = new NimbusAuthorizationCodeTokenExchanger();
}
return this.authorizationCodeTokenExchanger;
}
private SecurityTokenRepository<AccessToken> getAccessTokenRepository() {
if (this.accessTokenRepository == null) {
this.accessTokenRepository = new InMemoryAccessTokenRepository();
}
return this.accessTokenRepository;
}
private ProviderJwtDecoderRegistry getProviderJwtDecoderRegistry() {
Map<ProviderMetadata, JwtDecoder> jwtDecoders = new HashMap<>();
ClientRegistrationRepository clientRegistrationRepository = OAuth2LoginConfigurer.getClientRegistrationRepository(this.getBuilder());
clientRegistrationRepository.getRegistrations().forEach(registration -> {
ClientRegistration.ProviderDetails providerDetails = registration.getProviderDetails();
if (StringUtils.hasText(providerDetails.getJwkSetUri())) {
DefaultProviderMetadata providerMetadata = new DefaultProviderMetadata();
// Default the Issuer to the host of the Authorization Endpoint
providerMetadata.setIssuer(this.toURL(
UriComponentsBuilder
.fromHttpUrl(providerDetails.getAuthorizationUri())
.replacePath(null)
.toUriString()
));
providerMetadata.setAuthorizationEndpoint(this.toURL(providerDetails.getAuthorizationUri()));
providerMetadata.setTokenEndpoint(this.toURL(providerDetails.getTokenUri()));
providerMetadata.setUserInfoEndpoint(this.toURL(providerDetails.getUserInfoUri()));
providerMetadata.setJwkSetUri(this.toURL(providerDetails.getJwkSetUri()));
NimbusJwtDecoderJwkSupport nimbusJwtDecoderJwkSupport =
new NimbusJwtDecoderJwkSupport(providerDetails.getJwkSetUri());
jwtDecoders.put(providerMetadata, nimbusJwtDecoderJwkSupport);
}
});
return new DefaultProviderJwtDecoderRegistry(jwtDecoders);
}
private OAuth2UserService getUserInfoService() {
if (this.userInfoService == null) {
NimbusOAuth2UserService nimbusOAuth2UserService = new NimbusOAuth2UserService();
if (!this.customUserTypes.isEmpty()) {
nimbusOAuth2UserService.setCustomUserTypes(this.customUserTypes);
}
if (!this.userNameAttributeNames.isEmpty()) {
nimbusOAuth2UserService.setUserNameAttributeNames(this.userNameAttributeNames);
}
this.userInfoService = nimbusOAuth2UserService;
}
return this.userInfoService;
}
private URL toURL(String urlStr) {
if (!StringUtils.hasText(urlStr)) {
return null;
}
try {
return new URL(urlStr);
} catch (MalformedURLException ex) {
throw new IllegalArgumentException("Failed to convert '" + urlStr + "' to a URL: " + ex.getMessage(), ex);
}
}
}
@@ -1,76 +0,0 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.oauth2.client.web.AuthorizationCodeRequestRedirectFilter;
import org.springframework.security.oauth2.client.web.AuthorizationRequestUriBuilder;
import org.springframework.security.oauth2.client.web.DefaultAuthorizationRequestUriBuilder;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.matcher.RequestVariablesExtractor;
import org.springframework.util.Assert;
/**
* @author Joe Grandja
*/
final class AuthorizationCodeRequestRedirectFilterConfigurer<H extends HttpSecurityBuilder<H>, R extends RequestMatcher & RequestVariablesExtractor> extends
AbstractHttpConfigurer<AuthorizationCodeRequestRedirectFilterConfigurer<H, R>, H> {
private R authorizationRequestMatcher;
private AuthorizationRequestUriBuilder authorizationRequestBuilder;
AuthorizationCodeRequestRedirectFilterConfigurer<H, R> authorizationRequestMatcher(R authorizationRequestMatcher) {
Assert.notNull(authorizationRequestMatcher, "authorizationRequestMatcher cannot be null");
this.authorizationRequestMatcher = authorizationRequestMatcher;
return this;
}
AuthorizationCodeRequestRedirectFilterConfigurer<H, R> authorizationRequestBuilder(AuthorizationRequestUriBuilder authorizationRequestBuilder) {
Assert.notNull(authorizationRequestBuilder, "authorizationRequestBuilder cannot be null");
this.authorizationRequestBuilder = authorizationRequestBuilder;
return this;
}
AuthorizationCodeRequestRedirectFilterConfigurer<H, R> clientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notEmpty(clientRegistrationRepository.getRegistrations(), "clientRegistrationRepository cannot be empty");
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
return this;
}
R getAuthorizationRequestMatcher() {
return this.authorizationRequestMatcher;
}
@Override
public void configure(H http) throws Exception {
AuthorizationCodeRequestRedirectFilter filter = new AuthorizationCodeRequestRedirectFilter(
OAuth2LoginConfigurer.getClientRegistrationRepository(this.getBuilder()), this.getAuthorizationRequestBuilder());
if (this.authorizationRequestMatcher != null) {
filter.setAuthorizationRequestMatcher(this.authorizationRequestMatcher);
}
http.addFilter(this.postProcess(filter));
}
private AuthorizationRequestUriBuilder getAuthorizationRequestBuilder() {
if (this.authorizationRequestBuilder == null) {
this.authorizationRequestBuilder = new DefaultAuthorizationRequestUriBuilder();
}
return this.authorizationRequestBuilder;
}
}
@@ -1,269 +0,0 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.authentication.AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.client.web.AuthorizationCodeRequestRedirectFilter;
import org.springframework.security.oauth2.client.web.AuthorizationGrantTokenExchanger;
import org.springframework.security.oauth2.client.web.AuthorizationRequestUriBuilder;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.token.SecurityTokenRepository;
import org.springframework.security.oauth2.client.user.OAuth2UserService;
import org.springframework.security.oauth2.core.AccessToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.matcher.RequestVariablesExtractor;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import java.net.URI;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import static org.springframework.security.oauth2.client.web.AuthorizationCodeRequestRedirectFilter.CLIENT_ALIAS_URI_VARIABLE_NAME;
/**
* @author Joe Grandja
*/
public final class OAuth2LoginConfigurer<H extends HttpSecurityBuilder<H>> extends
AbstractHttpConfigurer<OAuth2LoginConfigurer<H>, H> {
private final AuthorizationCodeRequestRedirectFilterConfigurer authorizationCodeRequestRedirectFilterConfigurer;
private final AuthorizationCodeAuthenticationFilterConfigurer authorizationCodeAuthenticationFilterConfigurer;
private final AuthorizationEndpointConfig authorizationEndpointConfig;
private final TokenEndpointConfig tokenEndpointConfig;
private final RedirectionEndpointConfig redirectionEndpointConfig;
private final UserInfoEndpointConfig userInfoEndpointConfig;
public OAuth2LoginConfigurer() {
this.authorizationCodeRequestRedirectFilterConfigurer = new AuthorizationCodeRequestRedirectFilterConfigurer<>();
this.authorizationCodeAuthenticationFilterConfigurer = new AuthorizationCodeAuthenticationFilterConfigurer<>();
this.authorizationEndpointConfig = new AuthorizationEndpointConfig();
this.tokenEndpointConfig = new TokenEndpointConfig();
this.redirectionEndpointConfig = new RedirectionEndpointConfig();
this.userInfoEndpointConfig = new UserInfoEndpointConfig();
}
public OAuth2LoginConfigurer<H> clients(ClientRegistration... clientRegistrations) {
Assert.notEmpty(clientRegistrations, "clientRegistrations cannot be empty");
return this.clients(new InMemoryClientRegistrationRepository(Arrays.asList(clientRegistrations)));
}
public OAuth2LoginConfigurer<H> clients(ClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notEmpty(clientRegistrationRepository.getRegistrations(), "clientRegistrationRepository cannot be empty");
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
return this;
}
public OAuth2LoginConfigurer<H> userAuthoritiesMapper(GrantedAuthoritiesMapper userAuthoritiesMapper) {
Assert.notNull(userAuthoritiesMapper, "userAuthoritiesMapper cannot be null");
this.authorizationCodeAuthenticationFilterConfigurer.userAuthoritiesMapper(userAuthoritiesMapper);
return this;
}
public OAuth2LoginConfigurer<H> successHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null");
this.authorizationCodeAuthenticationFilterConfigurer.successHandler(authenticationSuccessHandler);
return this;
}
public OAuth2LoginConfigurer<H> failureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null");
this.authorizationCodeAuthenticationFilterConfigurer.failureHandler(authenticationFailureHandler);
return this;
}
public AuthorizationEndpointConfig authorizationEndpoint() {
return this.authorizationEndpointConfig;
}
public class AuthorizationEndpointConfig {
private AuthorizationEndpointConfig() {
}
public AuthorizationEndpointConfig authorizationRequestBuilder(AuthorizationRequestUriBuilder authorizationRequestBuilder) {
Assert.notNull(authorizationRequestBuilder, "authorizationRequestBuilder cannot be null");
OAuth2LoginConfigurer.this.authorizationCodeRequestRedirectFilterConfigurer.authorizationRequestBuilder(authorizationRequestBuilder);
return this;
}
public <R extends RequestMatcher & RequestVariablesExtractor> AuthorizationEndpointConfig requestMatcher(R authorizationRequestMatcher) {
Assert.notNull(authorizationRequestMatcher, "authorizationRequestMatcher cannot be null");
OAuth2LoginConfigurer.this.authorizationCodeRequestRedirectFilterConfigurer.authorizationRequestMatcher(authorizationRequestMatcher);
return this;
}
public OAuth2LoginConfigurer<H> and() {
return OAuth2LoginConfigurer.this;
}
}
public TokenEndpointConfig tokenEndpoint() {
return this.tokenEndpointConfig;
}
public class TokenEndpointConfig {
private TokenEndpointConfig() {
}
public TokenEndpointConfig authorizationCodeTokenExchanger(
AuthorizationGrantTokenExchanger<AuthorizationCodeAuthenticationToken> authorizationCodeTokenExchanger) {
Assert.notNull(authorizationCodeTokenExchanger, "authorizationCodeTokenExchanger cannot be null");
OAuth2LoginConfigurer.this.authorizationCodeAuthenticationFilterConfigurer.authorizationCodeTokenExchanger(authorizationCodeTokenExchanger);
return this;
}
public TokenEndpointConfig accessTokenRepository(SecurityTokenRepository<AccessToken> accessTokenRepository) {
Assert.notNull(accessTokenRepository, "accessTokenRepository cannot be null");
OAuth2LoginConfigurer.this.authorizationCodeAuthenticationFilterConfigurer.accessTokenRepository(accessTokenRepository);
return this;
}
public OAuth2LoginConfigurer<H> and() {
return OAuth2LoginConfigurer.this;
}
}
public RedirectionEndpointConfig redirectionEndpoint() {
return this.redirectionEndpointConfig;
}
public class RedirectionEndpointConfig {
private RedirectionEndpointConfig() {
}
public <R extends RequestMatcher & RequestVariablesExtractor> RedirectionEndpointConfig requestMatcher(R authorizationResponseMatcher) {
Assert.notNull(authorizationResponseMatcher, "authorizationResponseMatcher cannot be null");
OAuth2LoginConfigurer.this.authorizationCodeAuthenticationFilterConfigurer.authorizationResponseMatcher(authorizationResponseMatcher);
return this;
}
public OAuth2LoginConfigurer<H> and() {
return OAuth2LoginConfigurer.this;
}
}
public UserInfoEndpointConfig userInfoEndpoint() {
return this.userInfoEndpointConfig;
}
public class UserInfoEndpointConfig {
private UserInfoEndpointConfig() {
}
public UserInfoEndpointConfig userInfoService(OAuth2UserService userInfoService) {
Assert.notNull(userInfoService, "userInfoService cannot be null");
OAuth2LoginConfigurer.this.authorizationCodeAuthenticationFilterConfigurer.userInfoService(userInfoService);
return this;
}
public UserInfoEndpointConfig customUserType(Class<? extends OAuth2User> customUserType, URI userInfoUri) {
Assert.notNull(customUserType, "customUserType cannot be null");
Assert.notNull(userInfoUri, "userInfoUri cannot be null");
OAuth2LoginConfigurer.this.authorizationCodeAuthenticationFilterConfigurer.customUserType(customUserType, userInfoUri);
return this;
}
public UserInfoEndpointConfig userNameAttributeName(String userNameAttributeName, URI userInfoUri) {
Assert.hasText(userNameAttributeName, "userNameAttributeName cannot be empty");
Assert.notNull(userInfoUri, "userInfoUri cannot be null");
OAuth2LoginConfigurer.this.authorizationCodeAuthenticationFilterConfigurer.userNameAttributeName(userNameAttributeName, userInfoUri);
return this;
}
public OAuth2LoginConfigurer<H> and() {
return OAuth2LoginConfigurer.this;
}
}
@Override
public void init(H http) throws Exception {
this.authorizationCodeRequestRedirectFilterConfigurer.setBuilder(http);
this.authorizationCodeAuthenticationFilterConfigurer.setBuilder(http);
this.authorizationCodeRequestRedirectFilterConfigurer.init(http);
this.authorizationCodeAuthenticationFilterConfigurer.init(http);
this.initDefaultLoginFilter(http);
}
@Override
public void configure(H http) throws Exception {
this.authorizationCodeRequestRedirectFilterConfigurer.configure(http);
this.authorizationCodeAuthenticationFilterConfigurer.configure(http);
}
static <H extends HttpSecurityBuilder<H>> ClientRegistrationRepository getClientRegistrationRepository(H http) {
ClientRegistrationRepository clientRegistrationRepository = http.getSharedObject(ClientRegistrationRepository.class);
if (clientRegistrationRepository == null) {
clientRegistrationRepository = getDefaultClientRegistrationRepository(http);
http.setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
}
return clientRegistrationRepository;
}
private static <H extends HttpSecurityBuilder<H>> ClientRegistrationRepository getDefaultClientRegistrationRepository(H http) {
return http.getSharedObject(ApplicationContext.class).getBean(ClientRegistrationRepository.class);
}
private void initDefaultLoginFilter(H http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http.getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null && !this.authorizationCodeAuthenticationFilterConfigurer.isCustomLoginPage()) {
ClientRegistrationRepository clientRegistrationRepository = getClientRegistrationRepository(this.getBuilder());
if (!CollectionUtils.isEmpty(clientRegistrationRepository.getRegistrations())) {
String authorizationRequestBaseUri;
RequestMatcher authorizationRequestMatcher = OAuth2LoginConfigurer.this.authorizationCodeRequestRedirectFilterConfigurer.getAuthorizationRequestMatcher();
if (authorizationRequestMatcher != null && AntPathRequestMatcher.class.isAssignableFrom(authorizationRequestMatcher.getClass())) {
String authorizationRequestPattern = ((AntPathRequestMatcher)authorizationRequestMatcher).getPattern();
String clientAliasTemplateVariable = "{" + CLIENT_ALIAS_URI_VARIABLE_NAME + "}";
if (authorizationRequestPattern.endsWith(clientAliasTemplateVariable)) {
authorizationRequestBaseUri = authorizationRequestPattern.substring(
0, authorizationRequestPattern.length() - clientAliasTemplateVariable.length() - 1);
} else {
authorizationRequestBaseUri = authorizationRequestPattern;
}
} else {
authorizationRequestBaseUri = AuthorizationCodeRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
}
Map<String, String> oauth2AuthenticationUrlToClientName = clientRegistrationRepository.getRegistrations().stream()
.collect(Collectors.toMap(
e -> authorizationRequestBaseUri + "/" + e.getClientAlias(),
e -> e.getClientName()));
loginPageGeneratingFilter.setOauth2LoginEnabled(true);
loginPageGeneratingFilter.setOauth2AuthenticationUrlToClientName(oauth2AuthenticationUrlToClientName);
loginPageGeneratingFilter.setLoginPageUrl(this.authorizationCodeAuthenticationFilterConfigurer.getLoginUrl());
loginPageGeneratingFilter.setFailureUrl(this.authorizationCodeAuthenticationFilterConfigurer.getLoginFailureUrl());
}
}
}
}
@@ -1,37 +0,0 @@
/*
*
* * Copyright 2002-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.config.annotation.web.reactive;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.*;
/**
* @author Rob Winch
* @since 5.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import({HttpSecurityConfiguration.class, WebFluxSecurityConfiguration.class})
@Configuration
public @interface EnableWebFluxSecurity {
}
@@ -1,90 +0,0 @@
/*
*
* * Copyright 2002-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.config.annotation.web.reactive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UserDetailsRepositoryAuthenticationManager;
import org.springframework.security.config.web.server.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.reactive.result.method.annotation.AuthenticationPrincipalArgumentResolver;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer;
import static org.springframework.security.config.web.server.HttpSecurity.http;
/**
* @author Rob Winch
* @since 5.0
*/
public class HttpSecurityConfiguration implements WebFluxConfigurer {
private static final String BEAN_NAME_PREFIX = "org.springframework.security.config.annotation.web.reactive.HttpSecurityConfiguration.";
private static final String HTTPSECURITY_BEAN_NAME = BEAN_NAME_PREFIX + "httpSecurity";
@Autowired(required = false)
private ReactiveAdapterRegistry adapterRegistry = new ReactiveAdapterRegistry();
@Autowired(required = false)
private ReactiveAuthenticationManager authenticationManager;
@Autowired(required = false)
private UserDetailsRepository userDetailsRepository;
@Autowired(required = false)
private PasswordEncoder passwordEncoder;
@Override
public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
configurer.addCustomResolver(authenticationPrincipalArgumentResolver());
}
@Bean
public AuthenticationPrincipalArgumentResolver authenticationPrincipalArgumentResolver() {
return new AuthenticationPrincipalArgumentResolver(this.adapterRegistry);
}
@Bean(HTTPSECURITY_BEAN_NAME)
@Scope("prototype")
public HttpSecurity httpSecurity() {
return http()
.authenticationManager(authenticationManager())
.headers().and()
.httpBasic().and()
.formLogin().and();
}
private ReactiveAuthenticationManager authenticationManager() {
if(this.authenticationManager != null) {
return this.authenticationManager;
}
if(this.userDetailsRepository != null) {
UserDetailsRepositoryAuthenticationManager manager =
new UserDetailsRepositoryAuthenticationManager(this.userDetailsRepository);
if(this.passwordEncoder != null) {
manager.setPasswordEncoder(this.passwordEncoder);
}
return manager;
}
return null;
}
}
@@ -1,73 +0,0 @@
/*
*
* * Copyright 2002-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.config.annotation.web.reactive;
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.core.annotation.Order;
import org.springframework.security.config.web.server.HttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.WebFilterChainFilter;
import org.springframework.util.ObjectUtils;
import java.util.Arrays;
import java.util.List;
/**
* @author Rob Winch
* @since 5.0
*/
@Configuration
public class WebFluxSecurityConfiguration {
public final int WEB_FILTER_CHAIN_FILTER_ORDER = 0 - 100;
private static final String BEAN_NAME_PREFIX = "org.springframework.security.config.annotation.web.reactive.WebFluxSecurityConfiguration.";
private static final String SPRING_SECURITY_WEBFILTERCHAINFILTER_BEAN_NAME = BEAN_NAME_PREFIX + "WebFilterChainFilter";
@Autowired(required = false)
private List<SecurityWebFilterChain> securityWebFilterChains;
@Autowired
ApplicationContext context;
@Bean(SPRING_SECURITY_WEBFILTERCHAINFILTER_BEAN_NAME)
@Order(value = WEB_FILTER_CHAIN_FILTER_ORDER)
public WebFilterChainFilter springSecurityWebFilterChainFilter() {
return WebFilterChainFilter.fromSecurityWebFilterChainsList(getSecurityWebFilterChains());
}
private List<SecurityWebFilterChain> getSecurityWebFilterChains() {
List<SecurityWebFilterChain> result = securityWebFilterChains;
if(ObjectUtils.isEmpty(result)) {
return defaultSecurityWebFilterChains();
}
return result;
}
private List<SecurityWebFilterChain> defaultSecurityWebFilterChains() {
HttpSecurity http = context.getBean(HttpSecurity.class);
http
.authorizeExchange()
.anyExchange().authenticated();
return Arrays.asList(http.build());
}
}
@@ -1,100 +0,0 @@
/*
*
* * Copyright 2002-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.config.core.userdetails;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.core.userdetails.MapUserDetailsRepository;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
/**
* Constructs an {@link MapUserDetailsRepository} from a resource using {@link UserDetailsResourceFactoryBean}.
*
* @author Rob Winch
* @since 5.0
* @see UserDetailsResourceFactoryBean
*/
public class UserDetailsRepositoryResourceFactoryBean implements ResourceLoaderAware, FactoryBean<MapUserDetailsRepository> {
private UserDetailsResourceFactoryBean userDetails = new UserDetailsResourceFactoryBean();
@Override
public MapUserDetailsRepository getObject() throws Exception {
Collection<UserDetails> users = userDetails.getObject();
return new MapUserDetailsRepository(users);
}
@Override
public Class<?> getObjectType() {
return MapUserDetailsRepository.class;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
userDetails.setResourceLoader(resourceLoader);
}
/**
* Sets a the location of a Resource that is a Properties file in the format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resourceLocation the location of the properties file that contains the users (i.e. "classpath:users.properties")
* @return the UserDetailsResourceFactoryBean
*/
public void setResourceLocation(String resourceLocation) {
this.userDetails.setResourceLocation(resourceLocation);
}
/**
* Sets a a Resource that is a Properties file in the format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resource the Resource to use
*/
public void setResource(Resource resource) {
this.userDetails.setResource(resource);
}
/**
* Create a UserDetailsRepositoryResourceFactoryBean with the location of a Resource that is a Properties file in the
* format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resourceLocatiton the location of the properties file that contains the users (i.e. "classpath:users.properties")
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsRepositoryResourceFactoryBean fromResourceLocation(String resourceLocatiton) {
UserDetailsRepositoryResourceFactoryBean result = new UserDetailsRepositoryResourceFactoryBean();
result.setResourceLocation(resourceLocatiton);
return result;
}
/**
* Create a UserDetailsRepositoryResourceFactoryBean with a Resource that is a Properties file in the
* format defined in {@link UserDetailsResourceFactoryBean}
*
* @param propertiesResource the Resource that is a properties file that contains the users
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsRepositoryResourceFactoryBean fromResource(Resource propertiesResource) {
UserDetailsRepositoryResourceFactoryBean result = new UserDetailsRepositoryResourceFactoryBean();
result.setResource(propertiesResource);
return result;
}
}
@@ -1,156 +0,0 @@
/*
*
* * Copyright 2002-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.config.core.userdetails;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.memory.UserAttribute;
import org.springframework.security.core.userdetails.memory.UserAttributeEditor;
import org.springframework.util.Assert;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Properties;
/**
* Parses a Resource that is a Properties file in the format of:
*
* <code>
* username=password[,enabled|disabled],roles...
* </code>
*
* The enabled and disabled properties are optional with enabled being the default. For example:
*
* <code>
* user=password,ROLE_USER
* admin=secret,ROLE_USER,ROLE_ADMIN
* disabled_user=does_not_matter,disabled,ROLE_USER
* </code>
*
* @author Rob Winch
* @since 5.0
*/
public class UserDetailsResourceFactoryBean implements ResourceLoaderAware, FactoryBean<Collection<UserDetails>> {
private ResourceLoader resourceLoader = new DefaultResourceLoader();
private String resourceLocation;
private Resource resource;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
Assert.notNull(resourceLoader,"resourceLoader cannot be null");
this.resourceLoader = resourceLoader;
}
@Override
public Collection<UserDetails> getObject() throws Exception {
Properties userProperties = new Properties();
Resource resource = getProperitesResource();
try(InputStream in = resource.getInputStream()){
userProperties.load(in);
}
Collection<UserDetails> users = new ArrayList<>(userProperties.size());
Enumeration<?> names = userProperties.propertyNames();
UserAttributeEditor editor = new UserAttributeEditor();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String property = userProperties.getProperty(name);
editor.setAsText(property);
UserAttribute attr = (UserAttribute) editor.getValue();
if(attr == null) {
throw new IllegalStateException("The entry with username '" + name + "' and value '" + property + "' could not be converted to a UserDetails.");
}
UserDetails user = User.withUsername(name)
.password(attr.getPassword())
.disabled(!attr.isEnabled())
.authorities(attr.getAuthorities())
.build();
users.add(user);
}
return users;
}
@Override
public Class<?> getObjectType() {
return Collection.class;
}
/**
* Sets a the location of a Resource that is a Properties file in the format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resourceLocation the location of the properties file that contains the users (i.e. "classpath:users.properties")
*/
public void setResourceLocation(String resourceLocation) {
this.resourceLocation = resourceLocation;
}
/**
* Sets a a Resource that is a Properties file in the format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resource the Resource to use
*/
public void setResource(Resource resource) {
this.resource = resource;
}
private Resource getProperitesResource() {
Resource result = resource;
if(result == null && resourceLocation != null) {
result = resourceLoader.getResource(resourceLocation);
}
Assert.notNull(result, "resource cannot be null if resourceLocation is null");
return result;
}
/**
* Create a UserDetailsResourceFactoryBean with the location of a Resource that is a Properties file in the
* format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resourceLocatiton the location of the properties file that contains the users (i.e. "classpath:users.properties")
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsResourceFactoryBean fromResourceLocation(String resourceLocatiton) {
UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean();
result.setResourceLocation(resourceLocatiton);
return result;
}
/**
* Create a UserDetailsResourceFactoryBean with a Resource that is a Properties file in the
* format defined in {@link UserDetailsResourceFactoryBean}
*
* @param propertiesResource the Resource that is a properties file that contains the users
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsResourceFactoryBean fromResource(Resource propertiesResource) {
UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean();
result.setResource(propertiesResource);
return result;
}
}
@@ -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);
@@ -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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.http;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
/**
* @author Rob Winch
* @since 4.2
*/
class GrantedAuthorityDefaultsParserUtils {
static RootBeanDefinition registerWithDefaultRolePrefix(ParserContext pc, Class<? extends AbstractGrantedAuthorityDefaultsBeanFactory> beanFactoryClass) {
RootBeanDefinition beanFactoryDefinition = new RootBeanDefinition(beanFactoryClass);
String beanFactoryRef = pc.getReaderContext().generateBeanName(beanFactoryDefinition);
pc.getRegistry().registerBeanDefinition(beanFactoryRef, beanFactoryDefinition);
RootBeanDefinition bean = new RootBeanDefinition();
bean.setFactoryBeanName(beanFactoryRef);
bean.setFactoryMethodName("getBean");
return bean;
}
static abstract class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware {
protected String rolePrefix = "ROLE_";
@Override
public final void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
String[] grantedAuthorityDefaultsBeanNames = applicationContext.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = applicationContext.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
this.rolePrefix = grantedAuthorityDefaults.getRolePrefix();
}
}
abstract Object getBean();
}
private GrantedAuthorityDefaultsParserUtils() {}
}
@@ -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);
@@ -1,101 +0,0 @@
/*
*
* * Copyright 2002-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.config.provisioning;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.config.core.userdetails.UserDetailsResourceFactoryBean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import java.util.Collection;
/**
* Constructs an {@link InMemoryUserDetailsManager} from a resource using {@link UserDetailsResourceFactoryBean}.
*
* @author Rob Winch
* @since 5.0
* @see UserDetailsResourceFactoryBean
*/
public class UserDetailsManagerResourceFactoryBean implements ResourceLoaderAware, FactoryBean<InMemoryUserDetailsManager> {
private UserDetailsResourceFactoryBean userDetails = new UserDetailsResourceFactoryBean();
@Override
public InMemoryUserDetailsManager getObject() throws Exception {
Collection<UserDetails> users = userDetails.getObject();
return new InMemoryUserDetailsManager(users);
}
@Override
public Class<?> getObjectType() {
return InMemoryUserDetailsManager.class;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
userDetails.setResourceLoader(resourceLoader);
}
/**
* Sets a the location of a Resource that is a Properties file in the format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resourceLocation the location of the properties file that contains the users (i.e. "classpath:users.properties")
* @return the UserDetailsResourceFactoryBean
*/
public void setResourceLocation(String resourceLocation) {
this.userDetails.setResourceLocation(resourceLocation);
}
/**
* Sets a a Resource that is a Properties file in the format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resource the Resource to use
*/
public void setResource(Resource resource) {
this.userDetails.setResource(resource);
}
/**
* Create a UserDetailsServiceResourceFactoryBean with the location of a Resource that is a Properties file in the
* format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resourceLocation the location of the properties file that contains the users (i.e. "classpath:users.properties")
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsManagerResourceFactoryBean fromResourceLocation(String resourceLocation) {
UserDetailsManagerResourceFactoryBean result = new UserDetailsManagerResourceFactoryBean();
result.setResourceLocation(resourceLocation);
return result;
}
/**
* Create a UserDetailsServiceResourceFactoryBean with a Resource that is a Properties file in the
* format defined in {@link UserDetailsResourceFactoryBean}
*
* @param resource the Resource that is a properties file that contains the users
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsManagerResourceFactoryBean fromResource(Resource resource) {
UserDetailsManagerResourceFactoryBean result = new UserDetailsManagerResourceFactoryBean();
result.setResource(resource);
return result;
}
}
@@ -1,117 +0,0 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.web.server;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.server.util.matcher.OrServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.PathPatternParserServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import java.util.List;
/**
* @author Rob Winch
* @since 5.0
*/
abstract class AbstractServerWebExchangeMatcherRegistry<T> {
/**
* Maps any request.
*
* @return the object that is chained after creating the {@link ServerWebExchangeMatcher}
*/
public T anyExchange() {
return matcher(ServerWebExchangeMatchers.anyExchange());
}
/**
* Maps a {@link List} of
* {@link PathPatternParserServerWebExchangeMatcher}
* instances.
*
* @param method the {@link HttpMethod} to use for any
* {@link HttpMethod}.
*
* @return the object that is chained after creating the {@link ServerWebExchangeMatcher}
*/
public T pathMatchers(HttpMethod method) {
return pathMatchers(method, new String[] { "/**" });
}
/**
* Maps a {@link List} of
* {@link PathPatternParserServerWebExchangeMatcher}
* instances.
*
* @param method the {@link HttpMethod} to use or {@code null} for any
* {@link HttpMethod}.
* @param antPatterns the ant patterns to create. If {@code null} or empty, then matches on nothing.
* {@link PathPatternParserServerWebExchangeMatcher} from
*
* @return the object that is chained after creating the {@link ServerWebExchangeMatcher}
*/
public T pathMatchers(HttpMethod method, String... antPatterns) {
return matcher(ServerWebExchangeMatchers.pathMatchers(method, antPatterns));
}
/**
* Maps a {@link List} of
* {@link PathPatternParserServerWebExchangeMatcher}
* instances that do not care which {@link HttpMethod} is used.
*
* @param antPatterns the ant patterns to create
* {@link PathPatternParserServerWebExchangeMatcher} from
*
* @return the object that is chained after creating the {@link ServerWebExchangeMatcher}
*/
public T pathMatchers(String... antPatterns) {
return matcher(ServerWebExchangeMatchers.pathMatchers(antPatterns));
}
/**
* Associates a list of {@link ServerWebExchangeMatcher} instances
*
* @param matchers the {@link ServerWebExchangeMatcher} instances
*
* @return the object that is chained after creating the {@link ServerWebExchangeMatcher}
*/
public T matchers(ServerWebExchangeMatcher... matchers) {
return registerMatcher(new OrServerWebExchangeMatcher(matchers));
}
/**
* Subclasses should implement this method for returning the object that is chained to
* the creation of the {@link ServerWebExchangeMatcher} instances.
*
* @param matcher the {@link ServerWebExchangeMatcher} instances that were created
* @return the chained Object for the subclass which allows association of something
* else to the {@link ServerWebExchangeMatcher}
*/
protected abstract T registerMatcher(ServerWebExchangeMatcher matcher);
/**
* Associates a {@link ServerWebExchangeMatcher} instances
*
* @param matcher the {@link ServerWebExchangeMatcher} instance
*
* @return the object that is chained after creating the {@link ServerWebExchangeMatcher}
*/
private T matcher(ServerWebExchangeMatcher matcher) {
return registerMatcher(matcher);
}
}
@@ -1,521 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.web.server;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.security.web.server.DelegatingAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.server.authentication.logout.LogoutWebFiter;
import org.springframework.security.web.server.util.matcher.MediaTypeServerWebExchangeMatcher;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
import org.springframework.security.authorization.AuthorityAuthorizationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.web.server.AuthenticationEntryPoint;
import org.springframework.security.web.server.FormLoginAuthenticationConverter;
import org.springframework.security.web.server.HttpBasicAuthenticationConverter;
import org.springframework.security.web.server.MatcherSecurityWebFilterChain;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.AuthenticationEntryPointFailureHandler;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.web.server.authentication.RedirectAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.RedirectAuthenticationSuccessHandler;
import org.springframework.security.web.server.authentication.www.HttpBasicAuthenticationEntryPoint;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.security.web.server.authorization.AuthorizationWebFilter;
import org.springframework.security.web.server.authorization.DelegatingReactiveAuthorizationManager;
import org.springframework.security.web.server.authorization.ExceptionTranslationWebFilter;
import org.springframework.security.web.server.context.AuthenticationReactorContextFilter;
import org.springframework.security.web.server.context.SecurityContextRepository;
import org.springframework.security.web.server.context.SecurityContextRepositoryWebFilter;
import org.springframework.security.web.server.context.ServerWebExchangeAttributeSecurityContextRepository;
import org.springframework.security.web.server.context.WebSessionSecurityContextRepository;
import org.springframework.security.web.server.header.CacheControlHttpHeadersWriter;
import org.springframework.security.web.server.header.CompositeHttpHeadersWriter;
import org.springframework.security.web.server.header.ContentTypeOptionsHttpHeadersWriter;
import org.springframework.security.web.server.header.HttpHeaderWriterWebFilter;
import org.springframework.security.web.server.header.HttpHeadersWriter;
import org.springframework.security.web.server.header.StrictTransportSecurityHttpHeadersWriter;
import org.springframework.security.web.server.header.XFrameOptionsHttpHeadersWriter;
import org.springframework.security.web.server.header.XXssProtectionHttpHeadersWriter;
import org.springframework.security.web.server.ui.LoginPageGeneratingWebFilter;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcherEntry;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.util.Assert;
import org.springframework.web.server.WebFilter;
import static org.springframework.security.web.server.DelegatingAuthenticationEntryPoint.*;
/**
* @author Rob Winch
* @since 5.0
*/
public class HttpSecurity {
private ServerWebExchangeMatcher securityMatcher = ServerWebExchangeMatchers.anyExchange();
private AuthorizeExchangeBuilder authorizeExchangeBuilder;
private HeaderBuilder headers;
private HttpBasicBuilder httpBasic;
private FormLoginBuilder formLogin;
private ReactiveAuthenticationManager authenticationManager;
private SecurityContextRepository securityContextRepository;
private AuthenticationEntryPoint authenticationEntryPoint;
private List<DelegateEntry> defaultEntryPoints = new ArrayList<>();
/**
* The ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
*
* @param matcher the ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
* Default is all requests.
*/
public HttpSecurity securityMatcher(ServerWebExchangeMatcher matcher) {
Assert.notNull(matcher, "matcher cannot be null");
this.securityMatcher = matcher;
return this;
}
/**
* Gets the ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
* @return the ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
*/
private ServerWebExchangeMatcher getSecurityMatcher() {
return this.securityMatcher;
}
public HttpSecurity securityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
return this;
}
public HttpBasicBuilder httpBasic() {
if(this.httpBasic == null) {
this.httpBasic = new HttpBasicBuilder();
}
return this.httpBasic;
}
public FormLoginBuilder formLogin() {
if(this.formLogin == null) {
this.formLogin = new FormLoginBuilder();
}
return this.formLogin;
}
public HeaderBuilder headers() {
if(this.headers == null) {
this.headers = new HeaderBuilder();
}
return this.headers;
}
public AuthorizeExchangeBuilder authorizeExchange() {
if(this.authorizeExchangeBuilder == null) {
this.authorizeExchangeBuilder = new AuthorizeExchangeBuilder();
}
return this.authorizeExchangeBuilder;
}
public HttpSecurity authenticationManager(ReactiveAuthenticationManager manager) {
this.authenticationManager = manager;
return this;
}
public SecurityWebFilterChain build() {
List<WebFilter> filters = new ArrayList<>();
if(this.headers != null) {
filters.add(this.headers.build());
}
SecurityContextRepositoryWebFilter securityContextRepositoryWebFilter = securityContextRepositoryWebFilter();
if(securityContextRepositoryWebFilter != null) {
filters.add(securityContextRepositoryWebFilter);
}
if(this.httpBasic != null) {
this.httpBasic.authenticationManager(this.authenticationManager);
if(this.securityContextRepository != null) {
this.httpBasic.securityContextRepository(this.securityContextRepository);
}
filters.add(this.httpBasic.build());
}
if(this.formLogin != null) {
this.formLogin.authenticationManager(this.authenticationManager);
if(this.securityContextRepository != null) {
this.formLogin.securityContextRepository(this.securityContextRepository);
}
if(this.formLogin.authenticationEntryPoint == null) {
filters.add(new LoginPageGeneratingWebFilter());
}
filters.add(this.formLogin.build());
filters.add(new LogoutWebFiter());
}
filters.add(new AuthenticationReactorContextFilter());
if(this.authorizeExchangeBuilder != null) {
AuthenticationEntryPoint authenticationEntryPoint = getAuthenticationEntryPoint();
ExceptionTranslationWebFilter exceptionTranslationWebFilter = new ExceptionTranslationWebFilter();
if(authenticationEntryPoint != null) {
exceptionTranslationWebFilter.setAuthenticationEntryPoint(authenticationEntryPoint);
}
filters.add(exceptionTranslationWebFilter);
filters.add(this.authorizeExchangeBuilder.build());
}
return new MatcherSecurityWebFilterChain(getSecurityMatcher(), filters);
}
private AuthenticationEntryPoint getAuthenticationEntryPoint() {
if(this.authenticationEntryPoint != null || this.defaultEntryPoints.isEmpty()) {
return this.authenticationEntryPoint;
}
if(this.defaultEntryPoints.size() == 1) {
return this.defaultEntryPoints.get(0).getEntryPoint();
}
DelegatingAuthenticationEntryPoint result = new DelegatingAuthenticationEntryPoint(this.defaultEntryPoints);
result.setDefaultEntryPoint(this.defaultEntryPoints.get(this.defaultEntryPoints.size() - 1).getEntryPoint());
return result;
}
public static HttpSecurity http() {
return new HttpSecurity();
}
private SecurityContextRepositoryWebFilter securityContextRepositoryWebFilter() {
SecurityContextRepository repository = this.securityContextRepository;
return repository == null ? null :
new SecurityContextRepositoryWebFilter(repository);
}
private HttpSecurity() {}
/**
* @author Rob Winch
* @since 5.0
*/
public class AuthorizeExchangeBuilder extends AbstractServerWebExchangeMatcherRegistry<AuthorizeExchangeBuilder.Access> {
private DelegatingReactiveAuthorizationManager.Builder managerBldr = DelegatingReactiveAuthorizationManager.builder();
private ServerWebExchangeMatcher matcher;
private boolean anyExchangeRegistered;
public HttpSecurity and() {
return HttpSecurity.this;
}
@Override
public Access anyExchange() {
Access result = super.anyExchange();
this.anyExchangeRegistered = true;
return result;
}
@Override
protected Access registerMatcher(ServerWebExchangeMatcher matcher) {
if(this.anyExchangeRegistered) {
throw new IllegalStateException("Cannot register " + matcher + " which would be unreachable because anyExchange() has already been registered.");
}
if(this.matcher != null) {
throw new IllegalStateException("The matcher " + matcher + " does not have an access rule defined");
}
this.matcher = matcher;
return new Access();
}
protected WebFilter build() {
if(this.matcher != null) {
throw new IllegalStateException("The matcher " + this.matcher + " does not have an access rule defined");
}
return new AuthorizationWebFilter(this.managerBldr.build());
}
public final class Access {
public AuthorizeExchangeBuilder permitAll() {
return access( (a,e) -> Mono.just(new AuthorizationDecision(true)));
}
public AuthorizeExchangeBuilder denyAll() {
return access( (a,e) -> Mono.just(new AuthorizationDecision(false)));
}
public AuthorizeExchangeBuilder hasRole(String role) {
return access(AuthorityAuthorizationManager.hasRole(role));
}
public AuthorizeExchangeBuilder hasAuthority(String authority) {
return access(AuthorityAuthorizationManager.hasAuthority(authority));
}
public AuthorizeExchangeBuilder authenticated() {
return access(AuthenticatedAuthorizationManager.authenticated());
}
public AuthorizeExchangeBuilder access(ReactiveAuthorizationManager<AuthorizationContext> manager) {
AuthorizeExchangeBuilder.this.managerBldr
.add(new ServerWebExchangeMatcherEntry<>(
AuthorizeExchangeBuilder.this.matcher, manager));
AuthorizeExchangeBuilder.this.matcher = null;
return AuthorizeExchangeBuilder.this;
}
}
}
/**
* @author Rob Winch
* @since 5.0
*/
public class HttpBasicBuilder {
private ReactiveAuthenticationManager authenticationManager;
private SecurityContextRepository securityContextRepository = new ServerWebExchangeAttributeSecurityContextRepository();
private AuthenticationEntryPoint entryPoint = new HttpBasicAuthenticationEntryPoint();
public HttpBasicBuilder authenticationManager(ReactiveAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
return this;
}
public HttpBasicBuilder securityContextRepository(SecurityContextRepository securityContextRepository) {
this.securityContextRepository = securityContextRepository;
return this;
}
public HttpSecurity and() {
return HttpSecurity.this;
}
public HttpSecurity disable() {
HttpSecurity.this.httpBasic = null;
return HttpSecurity.this;
}
protected AuthenticationWebFilter build() {
MediaTypeServerWebExchangeMatcher restMatcher = new MediaTypeServerWebExchangeMatcher(
MediaType.APPLICATION_ATOM_XML,
MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_XML,
MediaType.MULTIPART_FORM_DATA, MediaType.TEXT_XML);
restMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
HttpSecurity.this.defaultEntryPoints.add(new DelegateEntry(restMatcher, this.entryPoint));
AuthenticationWebFilter authenticationFilter = new AuthenticationWebFilter(
this.authenticationManager);
authenticationFilter.setAuthenticationFailureHandler(new AuthenticationEntryPointFailureHandler(this.entryPoint));
authenticationFilter.setAuthenticationConverter(new HttpBasicAuthenticationConverter());
if(this.securityContextRepository != null) {
authenticationFilter.setSecurityContextRepository(this.securityContextRepository);
}
return authenticationFilter;
}
private HttpBasicBuilder() {}
}
/**
* @author Rob Winch
* @since 5.0
*/
public class FormLoginBuilder {
private ReactiveAuthenticationManager authenticationManager;
private SecurityContextRepository securityContextRepository = new WebSessionSecurityContextRepository();
private AuthenticationEntryPoint authenticationEntryPoint;
private ServerWebExchangeMatcher requiresAuthenticationMatcher;
private AuthenticationFailureHandler authenticationFailureHandler;
public FormLoginBuilder authenticationManager(ReactiveAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
return this;
}
public FormLoginBuilder loginPage(String loginPage) {
this.authenticationEntryPoint = new RedirectAuthenticationEntryPoint(loginPage);
this.requiresAuthenticationMatcher = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, loginPage);
this.authenticationFailureHandler = new AuthenticationEntryPointFailureHandler(new RedirectAuthenticationEntryPoint(loginPage + "?error"));
return this;
}
public FormLoginBuilder authenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
this.authenticationEntryPoint = authenticationEntryPoint;
return this;
}
public FormLoginBuilder requiresAuthenticationMatcher(ServerWebExchangeMatcher requiresAuthenticationMatcher) {
this.requiresAuthenticationMatcher = requiresAuthenticationMatcher;
return this;
}
public FormLoginBuilder authenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
this.authenticationFailureHandler = authenticationFailureHandler;
return this;
}
public FormLoginBuilder securityContextRepository(SecurityContextRepository securityContextRepository) {
this.securityContextRepository = securityContextRepository;
return this;
}
public HttpSecurity and() {
return HttpSecurity.this;
}
public HttpSecurity disable() {
HttpSecurity.this.formLogin = null;
return HttpSecurity.this;
}
protected AuthenticationWebFilter build() {
if(this.authenticationEntryPoint == null) {
loginPage("/login");
}
MediaTypeServerWebExchangeMatcher htmlMatcher = new MediaTypeServerWebExchangeMatcher(
MediaType.TEXT_HTML);
htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
HttpSecurity.this.defaultEntryPoints.add(0, new DelegateEntry(htmlMatcher, this.authenticationEntryPoint));
AuthenticationWebFilter authenticationFilter = new AuthenticationWebFilter(
this.authenticationManager);
authenticationFilter.setRequiresAuthenticationMatcher(this.requiresAuthenticationMatcher);
authenticationFilter.setAuthenticationFailureHandler(this.authenticationFailureHandler);
authenticationFilter.setAuthenticationConverter(new FormLoginAuthenticationConverter());
authenticationFilter.setAuthenticationSuccessHandler(new RedirectAuthenticationSuccessHandler("/"));
authenticationFilter.setSecurityContextRepository(this.securityContextRepository);
return authenticationFilter;
}
private FormLoginBuilder() {
}
}
/**
* @author Rob Winch
* @since 5.0
*/
public class HeaderBuilder {
private final List<HttpHeadersWriter> writers;
private CacheControlHttpHeadersWriter cacheControl = new CacheControlHttpHeadersWriter();
private ContentTypeOptionsHttpHeadersWriter contentTypeOptions = new ContentTypeOptionsHttpHeadersWriter();
private StrictTransportSecurityHttpHeadersWriter hsts = new StrictTransportSecurityHttpHeadersWriter();
private XFrameOptionsHttpHeadersWriter frameOptions = new XFrameOptionsHttpHeadersWriter();
private XXssProtectionHttpHeadersWriter xss = new XXssProtectionHttpHeadersWriter();
public HttpSecurity and() {
return HttpSecurity.this;
}
public CacheSpec cache() {
return new CacheSpec();
}
public ContentTypeOptionsSpec contentTypeOptions() {
return new ContentTypeOptionsSpec();
}
public FrameOptionsSpec frameOptions() {
return new FrameOptionsSpec();
}
public HstsSpec hsts() {
return new HstsSpec();
}
protected HttpHeaderWriterWebFilter build() {
HttpHeadersWriter writer = new CompositeHttpHeadersWriter(this.writers);
return new HttpHeaderWriterWebFilter(writer);
}
public XssProtectionSpec xssProtection() {
return new XssProtectionSpec();
}
public class CacheSpec {
public void disable() {
HeaderBuilder.this.writers.remove(HeaderBuilder.this.cacheControl);
}
private CacheSpec() {}
}
public class ContentTypeOptionsSpec {
public void disable() {
HeaderBuilder.this.writers.remove(HeaderBuilder.this.contentTypeOptions);
}
private ContentTypeOptionsSpec() {}
}
public class FrameOptionsSpec {
public void mode(XFrameOptionsHttpHeadersWriter.Mode mode) {
HeaderBuilder.this.frameOptions.setMode(mode);
}
public void disable() {
HeaderBuilder.this.writers.remove(HeaderBuilder.this.frameOptions);
}
private FrameOptionsSpec() {}
}
public class HstsSpec {
public void maxAge(Duration maxAge) {
HeaderBuilder.this.hsts.setMaxAge(maxAge);
}
public void includeSubdomains(boolean includeSubDomains) {
HeaderBuilder.this.hsts.setIncludeSubDomains(includeSubDomains);
}
public void disable() {
HeaderBuilder.this.writers.remove(HeaderBuilder.this.hsts);
}
private HstsSpec() {}
}
public class XssProtectionSpec {
public void disable() {
HeaderBuilder.this.writers.remove(HeaderBuilder.this.xss);
}
private XssProtectionSpec() {}
}
private HeaderBuilder() {
this.writers = new ArrayList<>(
Arrays.asList(this.cacheControl, this.contentTypeOptions, this.hsts,
this.frameOptions, this.xss));
}
}
}
@@ -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,919 +0,0 @@
namespace a = "http://relaxng.org/ns/compatibility/annotations/1.0"
datatypes xsd = "http://www.w3.org/2001/XMLSchema-datatypes"
default namespace = "http://www.springframework.org/schema/security"
start = http | ldap-server | authentication-provider | ldap-authentication-provider | any-user-service | ldap-server | ldap-authentication-provider
hash =
## Defines the hashing algorithm used on user passwords. Bcrypt is recommended.
attribute hash {"bcrypt" | "plaintext" | "sha" | "sha-256" | "md5" | "md4" | "{sha}" | "{ssha}"}
base64 =
## Whether a string should be base64 encoded
attribute base64 {xsd:boolean}
request-matcher =
## Defines the strategy use for matching incoming requests. Currently the options are 'mvc' (for Spring MVC matcher), 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions.
attribute request-matcher {"mvc" | "ant" | "regex" | "ciRegex"}
port =
## Specifies an IP port number. Used to configure an embedded LDAP server, for example.
attribute port { xsd:positiveInteger }
url =
## Specifies a URL.
attribute url { xsd:token }
id =
## A bean identifier, used for referring to the bean elsewhere in the context.
attribute id {xsd:token}
name =
## A bean identifier, used for referring to the bean elsewhere in the context.
attribute name {xsd:token}
ref =
## Defines a reference to a Spring bean Id.
attribute ref {xsd:token}
cache-ref =
## Defines a reference to a cache for use with a UserDetailsService.
attribute cache-ref {xsd:token}
user-service-ref =
## A reference to a user-service (or UserDetailsService bean) Id
attribute user-service-ref {xsd:token}
authentication-manager-ref =
## A reference to an AuthenticationManager bean
attribute authentication-manager-ref {xsd:token}
data-source-ref =
## A reference to a DataSource bean
attribute data-source-ref {xsd:token}
debug =
## Enables Spring Security debugging infrastructure. This will provide human-readable (multi-line) debugging information to monitor requests coming into the security filters. This may include sensitive information, such as request parameters or headers, and should only be used in a development environment.
element debug {empty}
password-encoder =
## element which defines a password encoding strategy. Used by an authentication provider to convert submitted passwords to hashed versions, for example.
element password-encoder {password-encoder.attlist, salt-source?}
password-encoder.attlist &=
ref | (hash? & base64?)
salt-source =
## Password salting strategy. A system-wide constant or a property from the UserDetails object can be used.
element salt-source {user-property | system-wide | ref}
user-property =
## A property of the UserDetails object which will be used as salt by a password encoder. Typically something like "username" might be used.
attribute user-property {xsd:token}
system-wide =
## A single value that will be used as the salt for a password encoder.
attribute system-wide {xsd:token}
role-prefix =
## A non-empty string prefix that will be added to role strings loaded from persistent storage (e.g. "ROLE_"). Use the value "none" for no prefix in cases where the default is non-empty.
attribute role-prefix {xsd:token}
use-expressions =
## Enables the use of expressions in the 'access' attributes in <intercept-url> elements rather than the traditional list of configuration attributes. Defaults to 'true'. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to 'true', access will be granted.
attribute use-expressions {xsd:boolean}
ldap-server =
## Defines an LDAP server location or starts an embedded server. The url indicates the location of a remote server. If no url is given, an embedded server will be started, listening on the supplied port number. The port is optional and defaults to 33389. A Spring LDAP ContextSource bean will be registered for the server with the id supplied.
element ldap-server {ldap-server.attlist}
ldap-server.attlist &= id?
ldap-server.attlist &= (url | port)?
ldap-server.attlist &=
## Username (DN) of the "manager" user identity which will be used to authenticate to a (non-embedded) LDAP server. If omitted, anonymous access will be used.
attribute manager-dn {xsd:string}?
ldap-server.attlist &=
## The password for the manager DN. This is required if the manager-dn is specified.
attribute manager-password {xsd:string}?
ldap-server.attlist &=
## Explicitly specifies an ldif file resource to load into an embedded LDAP server. The default is classpath*:*.ldiff
attribute ldif { xsd:string }?
ldap-server.attlist &=
## Optional root suffix for the embedded LDAP server. Default is "dc=springframework,dc=org"
attribute root { xsd:string }?
ldap-server-ref-attribute =
## The optional server to use. If omitted, and a default LDAP server is registered (using <ldap-server> with no Id), that server will be used.
attribute server-ref {xsd:token}
group-search-filter-attribute =
## Group search filter. Defaults to (uniqueMember={0}). The substituted parameter is the DN of the user.
attribute group-search-filter {xsd:token}
group-search-base-attribute =
## Search base for group membership searches. Defaults to "" (searching from the root).
attribute group-search-base {xsd:token}
user-search-filter-attribute =
## The LDAP filter used to search for users (optional). For example "(uid={0})". The substituted parameter is the user's login name.
attribute user-search-filter {xsd:token}
user-search-base-attribute =
## Search base for user searches. Defaults to "". Only used with a 'user-search-filter'.
attribute user-search-base {xsd:token}
group-role-attribute-attribute =
## The LDAP attribute name which contains the role name which will be used within Spring Security. Defaults to "cn".
attribute group-role-attribute {xsd:token}
user-details-class-attribute =
## Allows the objectClass of the user entry to be specified. If set, the framework will attempt to load standard attributes for the defined class into the returned UserDetails object
attribute user-details-class {"person" | "inetOrgPerson"}
user-context-mapper-attribute =
## Allows explicit customization of the loaded user object by specifying a UserDetailsContextMapper bean which will be called with the context information from the user's directory entry
attribute user-context-mapper-ref {xsd:token}
ldap-user-service =
## This element configures a LdapUserDetailsService which is a combination of a FilterBasedLdapUserSearch and a DefaultLdapAuthoritiesPopulator.
element ldap-user-service {ldap-us.attlist}
ldap-us.attlist &= id?
ldap-us.attlist &=
ldap-server-ref-attribute?
ldap-us.attlist &=
user-search-filter-attribute?
ldap-us.attlist &=
user-search-base-attribute?
ldap-us.attlist &=
group-search-filter-attribute?
ldap-us.attlist &=
group-search-base-attribute?
ldap-us.attlist &=
group-role-attribute-attribute?
ldap-us.attlist &=
cache-ref?
ldap-us.attlist &=
role-prefix?
ldap-us.attlist &=
(user-details-class-attribute | user-context-mapper-attribute)?
ldap-authentication-provider =
## Sets up an ldap authentication provider
element ldap-authentication-provider {ldap-ap.attlist, password-compare-element?}
ldap-ap.attlist &=
ldap-server-ref-attribute?
ldap-ap.attlist &=
user-search-base-attribute?
ldap-ap.attlist &=
user-search-filter-attribute?
ldap-ap.attlist &=
group-search-base-attribute?
ldap-ap.attlist &=
group-search-filter-attribute?
ldap-ap.attlist &=
group-role-attribute-attribute?
ldap-ap.attlist &=
## A specific pattern used to build the user's DN, for example "uid={0},ou=people". The key "{0}" must be present and will be substituted with the username.
attribute user-dn-pattern {xsd:token}?
ldap-ap.attlist &=
role-prefix?
ldap-ap.attlist &=
(user-details-class-attribute | user-context-mapper-attribute)?
password-compare-element =
## Specifies that an LDAP provider should use an LDAP compare operation of the user's password to authenticate the user
element password-compare {password-compare.attlist, password-encoder?}
password-compare.attlist &=
## The attribute in the directory which contains the user password. Defaults to "userPassword".
attribute password-attribute {xsd:token}?
password-compare.attlist &=
hash?
intercept-methods =
## Can be used inside a bean definition to add a security interceptor to the bean and set up access configuration attributes for the bean's methods
element intercept-methods {intercept-methods.attlist, protect+}
intercept-methods.attlist &=
## Optional AccessDecisionManager bean ID to be used by the created method security interceptor.
attribute access-decision-manager-ref {xsd:token}?
protect =
## Defines a protected method and the access control configuration attributes that apply to it. We strongly advise you NOT to mix "protect" declarations with any services provided "global-method-security".
element protect {protect.attlist, empty}
protect.attlist &=
## A method name
attribute method {xsd:token}
protect.attlist &=
## Access configuration attributes list that applies to the method, e.g. "ROLE_A,ROLE_B".
attribute access {xsd:token}
method-security-metadata-source =
## Creates a MethodSecurityMetadataSource instance
element method-security-metadata-source {msmds.attlist, protect+}
msmds.attlist &= id?
msmds.attlist &= use-expressions?
global-method-security =
## Provides method security for all beans registered in the Spring application context. Specifically, beans will be scanned for matches with the ordered list of "protect-pointcut" sub-elements, Spring Security annotations and/or. Where there is a match, the beans will automatically be proxied and security authorization applied to the methods accordingly. If you use and enable all four sources of method security metadata (ie "protect-pointcut" declarations, expression annotations, @Secured and also JSR250 security annotations), the metadata sources will be queried in that order. In practical terms, this enables you to use XML to override method security metadata expressed in annotations. If using annotations, the order of precedence is EL-based (@PreAuthorize etc.), @Secured and finally JSR-250.
element global-method-security {global-method-security.attlist, (pre-post-annotation-handling | expression-handler)?, protect-pointcut*, after-invocation-provider*}
global-method-security.attlist &=
## Specifies whether the use of Spring Security's pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) should be enabled for this application context. Defaults to "disabled".
attribute pre-post-annotations {"disabled" | "enabled" }?
global-method-security.attlist &=
## Specifies whether the use of Spring Security's @Secured annotations should be enabled for this application context. Defaults to "disabled".
attribute secured-annotations {"disabled" | "enabled" }?
global-method-security.attlist &=
## Specifies whether JSR-250 style attributes are to be used (for example "RolesAllowed"). This will require the javax.annotation.security classes on the classpath. Defaults to "disabled".
attribute jsr250-annotations {"disabled" | "enabled" }?
global-method-security.attlist &=
## Optional AccessDecisionManager bean ID to override the default used for method security.
attribute access-decision-manager-ref {xsd:token}?
global-method-security.attlist &=
## Optional RunAsmanager implementation which will be used by the configured MethodSecurityInterceptor
attribute run-as-manager-ref {xsd:token}?
global-method-security.attlist &=
## Allows the advice "order" to be set for the method security interceptor.
attribute order {xsd:token}?
global-method-security.attlist &=
## If true, class based proxying will be used instead of interface based proxying.
attribute proxy-target-class {xsd:boolean}?
global-method-security.attlist &=
## Can be used to specify that AspectJ should be used instead of the default Spring AOP. If set, secured classes must be woven with the AnnotationSecurityAspect from the spring-security-aspects module.
attribute mode {"aspectj"}?
global-method-security.attlist &=
## An external MethodSecurityMetadataSource instance can be supplied which will take priority over other sources (such as the default annotations).
attribute metadata-source-ref {xsd:token}?
global-method-security.attlist &=
authentication-manager-ref?
after-invocation-provider =
## Allows addition of extra AfterInvocationProvider beans which should be called by the MethodSecurityInterceptor created by global-method-security.
element after-invocation-provider {ref}
pre-post-annotation-handling =
## Allows the default expression-based mechanism for handling Spring Security's pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) to be replace entirely. Only applies if these annotations are enabled.
element pre-post-annotation-handling {invocation-attribute-factory, pre-invocation-advice, post-invocation-advice}
invocation-attribute-factory =
## Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods.
element invocation-attribute-factory {ref}
pre-invocation-advice =
## Customizes the PreInvocationAuthorizationAdviceVoter with the ref as the PreInvocationAuthorizationAdviceVoter for the <pre-post-annotation-handling> element.
element pre-invocation-advice {ref}
post-invocation-advice =
## Customizes the PostInvocationAdviceProvider with the ref as the PostInvocationAuthorizationAdvice for the <pre-post-annotation-handling> element.
element post-invocation-advice {ref}
expression-handler =
## Defines the SecurityExpressionHandler instance which will be used if expression-based access-control is enabled. A default implementation (with no ACL support) will be used if not supplied.
element expression-handler {ref}
protect-pointcut =
## Defines a protected pointcut and the access control configuration attributes that apply to it. Every bean registered in the Spring application context that provides a method that matches the pointcut will receive security authorization.
element protect-pointcut {protect-pointcut.attlist, empty}
protect-pointcut.attlist &=
## An AspectJ expression, including the 'execution' keyword. For example, 'execution(int com.foo.TargetObject.countLength(String))' (without the quotes).
attribute expression {xsd:string}
protect-pointcut.attlist &=
## Access configuration attributes list that applies to all methods matching the pointcut, e.g. "ROLE_A,ROLE_B"
attribute access {xsd:token}
websocket-message-broker =
## Allows securing a Message Broker. There are two modes. If no id is specified: ensures that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver; ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel; and that a ChannelSecurityInterceptor is registered with the clientInboundChannel. If the id is specified, creates a ChannelSecurityInterceptor that can be manually registered with the clientInboundChannel.
element websocket-message-broker { websocket-message-broker.attrlist, (intercept-message* & expression-handler?) }
websocket-message-broker.attrlist &=
## A bean identifier, used for referring to the bean elsewhere in the context. If specified, explicit configuration within clientInboundChannel is required. If not specified, ensures that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver; ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel; and that a ChannelSecurityInterceptor is registered with the clientInboundChannel.
attribute id {xsd:token}?
websocket-message-broker.attrlist &=
## Disables the requirement for CSRF token to be present in the Stomp headers (default false). Changing the default is useful if it is necessary to allow other origins to make SockJS connections.
attribute same-origin-disabled {xsd:boolean}?
intercept-message =
## Creates an authorization rule for a websocket message.
element intercept-message {intercept-message.attrlist}
intercept-message.attrlist &=
## The destination ant pattern which will be mapped to the access attribute. For example, /** matches any message with a destination, /admin/** matches any message that has a destination that starts with admin.
attribute pattern {xsd:token}?
intercept-message.attrlist &=
## The access configuration attributes that apply for the configured message. For example, permitAll grants access to anyone, hasRole('ROLE_ADMIN') requires the user have the role 'ROLE_ADMIN'.
attribute access {xsd:token}?
intercept-message.attrlist &=
## The type of message to match on. Valid values are defined in SimpMessageType (i.e. CONNECT, CONNECT_ACK, HEARTBEAT, MESSAGE, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, DISCONNECT_ACK, OTHER).
attribute type {"CONNECT" | "CONNECT_ACK" | "HEARTBEAT" | "MESSAGE" | "SUBSCRIBE"| "UNSUBSCRIBE" | "DISCONNECT" | "DISCONNECT_ACK" | "OTHER"}?
http-firewall =
## Allows a custom instance of HttpFirewall to be injected into the FilterChainProxy created by the namespace.
element http-firewall {ref}
http =
## Container element for HTTP security configuration. Multiple elements can now be defined, each with a specific pattern to which the enclosed security configuration applies. A pattern can also be configured to bypass Spring Security's filters completely by setting the "security" attribute to "none".
element http {http.attlist, (intercept-url* & access-denied-handler? & form-login? & openid-login? & x509? & jee? & http-basic? & logout? & session-management & remember-me? & anonymous? & port-mappings & custom-filter* & request-cache? & expression-handler? & headers? & csrf? & cors?) }
http.attlist &=
## The request URL pattern which will be mapped to the filter chain created by this <http> element. If omitted, the filter chain will match all requests.
attribute pattern {xsd:token}?
http.attlist &=
## When set to 'none', requests matching the pattern attribute will be ignored by Spring Security. No security filters will be applied and no SecurityContext will be available. If set, the <http> element must be empty, with no children.
attribute security {"none"}?
http.attlist &=
## Allows a RequestMatcher instance to be used, as an alternative to pattern-matching.
attribute request-matcher-ref { xsd:token }?
http.attlist &=
## A legacy attribute which automatically registers a login form, BASIC authentication and a logout URL and logout services. If unspecified, defaults to "false". We'd recommend you avoid using this and instead explicitly configure the services you require.
attribute auto-config {xsd:boolean}?
http.attlist &=
use-expressions?
http.attlist &=
## Controls the eagerness with which an HTTP session is created by Spring Security classes. If not set, defaults to "ifRequired". If "stateless" is used, this implies that the application guarantees that it will not create a session. This differs from the use of "never" which means that Spring Security will not create a session, but will make use of one if the application does.
attribute create-session {"ifRequired" | "always" | "never" | "stateless"}?
http.attlist &=
## A reference to a SecurityContextRepository bean. This can be used to customize how the SecurityContext is stored between requests.
attribute security-context-repository-ref {xsd:token}?
http.attlist &=
request-matcher?
http.attlist &=
## Provides versions of HttpServletRequest security methods such as isUserInRole() and getPrincipal() which are implemented by accessing the Spring SecurityContext. Defaults to "true".
attribute servlet-api-provision {xsd:boolean}?
http.attlist &=
## If available, runs the request as the Subject acquired from the JaasAuthenticationToken. Defaults to "false".
attribute jaas-api-provision {xsd:boolean}?
http.attlist &=
## Optional attribute specifying the ID of the AccessDecisionManager implementation which should be used for authorizing HTTP requests.
attribute access-decision-manager-ref {xsd:token}?
http.attlist &=
## Optional attribute specifying the realm name that will be used for all authentication features that require a realm name (eg BASIC and Digest authentication). If unspecified, defaults to "Spring Security Application".
attribute realm {xsd:token}?
http.attlist &=
## Allows a customized AuthenticationEntryPoint to be set on the ExceptionTranslationFilter.
attribute entry-point-ref {xsd:token}?
http.attlist &=
## Corresponds to the observeOncePerRequest property of FilterSecurityInterceptor. Defaults to "true"
attribute once-per-request {xsd:boolean}?
http.attlist &=
## Prevents the jsessionid parameter from being added to rendered URLs. Defaults to "true" (rewriting is disabled).
attribute disable-url-rewriting {xsd:boolean}?
http.attlist &=
## Exposes the list of filters defined by this configuration under this bean name in the application context.
name?
http.attlist &=
authentication-manager-ref?
access-denied-handler =
## Defines the access-denied strategy that should be used. An access denied page can be defined or a reference to an AccessDeniedHandler instance.
element access-denied-handler {access-denied-handler.attlist, empty}
access-denied-handler.attlist &= (ref | access-denied-handler-page)
access-denied-handler-page =
## The access denied page that an authenticated user will be redirected to if they request a page which they don't have the authority to access.
attribute error-page {xsd:token}
intercept-url =
## Specifies the access attributes and/or filter list for a particular set of URLs.
element intercept-url {intercept-url.attlist, empty}
intercept-url.attlist &=
(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, http://axschema.org/contact/email. See your OP's documentation for valid attribute types.
attribute type {xsd:token}
openid-attribute.attlist &=
## Specifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. Default is false.
attribute required {xsd:boolean}?
openid-attribute.attlist &=
## Specifies the number of attributes that you wish to get back. For example, return 3 emails. The default value is 1.
attribute count {xsd:int}?
filter-chain-map =
## Used to explicitly configure a FilterChainProxy instance with a FilterChainMap
element filter-chain-map {filter-chain-map.attlist, filter-chain+}
filter-chain-map.attlist &=
request-matcher?
filter-chain =
## Used within to define a specific URL pattern and the list of filters which apply to the URLs matching that pattern. When multiple filter-chain elements are assembled in a list in order to configure a FilterChainProxy, the most specific patterns must be placed at the top of the list, with most general ones at the bottom.
element filter-chain {filter-chain.attlist, empty}
filter-chain.attlist &=
(pattern | request-matcher-ref)
filter-chain.attlist &=
## A comma separated list of bean names that implement Filter that should be processed for this FilterChain. If the value is none, then no Filters will be used for this FilterChain.
attribute filters {xsd:token}
pattern =
## The request URL pattern which will be mapped to the FilterChain.
attribute pattern {xsd:token}
request-matcher-ref =
## Allows a RequestMatcher instance to be used, as an alternative to pattern-matching.
attribute request-matcher-ref {xsd:token}
filter-security-metadata-source =
## Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the <http> element. The intercept-url elements used should only contain pattern, method and access attributes. Any others will result in a configuration error.
element filter-security-metadata-source {fsmds.attlist, intercept-url+}
fsmds.attlist &=
use-expressions?
fsmds.attlist &=
id?
fsmds.attlist &=
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
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 ammount of time the host should be considered a Known HSTS Host. Default one year.
attribute max-age-seconds {xsd:integer}?
hsts-options.attlist &=
## The RequestMatcher instance to be used to determine if the header should be set. Default is if HttpServletRequest.isSecure() is true.
attribute request-matcher-ref { xsd:token }?
cors =
## Element for configuration of CorsFilter. If no CorsFilter or CorsConfigurationSource is specified a HandlerMappingIntrospector is used as the CorsConfigurationSource
element cors { cors-options.attlist }
cors-options.attlist &=
ref?
cors-options.attlist &=
## Specifies a bean id that is a CorsConfigurationSource used to construct the CorsFilter to use
attribute configuration-source-ref {xsd:token}?
hpkp =
## Adds support for HTTP Public Key Pinning (HPKP).
element hpkp {hpkp.pins,hpkp.attlist}
hpkp.pins =
## The list with pins
element pins {hpkp.pin+}
hpkp.pin =
## A pin is specified using the base64-encoded SPKI fingerprint as value and the cryptographic hash algorithm as attribute
element pin {
## The cryptographic hash algorithm
attribute algorithm { xsd:string }?,
text
}
hpkp.attlist &=
## Specifies if HTTP Public Key Pinning (HPKP) should be disabled. Default false.
attribute disabled {xsd:boolean}?
hpkp.attlist &=
## Specifies if subdomains should be included. Default false.
attribute include-subdomains {xsd:boolean}?
hpkp.attlist &=
## Sets the value for the max-age directive of the Public-Key-Pins header. Default 60 days.
attribute max-age-seconds {xsd:integer}?
hpkp.attlist &=
## Specifies if the browser should only report pin validation failures. Default true.
attribute report-only {xsd:boolean}?
hpkp.attlist &=
## Specifies the URI to which the browser should report pin validation failures.
attribute report-uri {xsd:string}?
content-security-policy =
## Adds support for Content Security Policy (CSP)
element content-security-policy {csp-options.attlist}
csp-options.attlist &=
## The security policy directive(s) for the Content-Security-Policy header or if report-only is set to true, then the Content-Security-Policy-Report-Only header is used.
attribute policy-directives {xsd:token}?
csp-options.attlist &=
## Set to true, to enable the Content-Security-Policy-Report-Only header for reporting policy violations only. Defaults to false.
attribute report-only {xsd:boolean}?
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"
@@ -51,7 +51,6 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon
* @author Rob Winch
*/
abstract class BaseSpringSpec extends Specification {
boolean allowCircularReferences = false
@AutoCleanup
ConfigurableApplicationContext context
@AutoCleanup
@@ -90,7 +89,6 @@ abstract class BaseSpringSpec extends Specification {
def loadConfig(Class<?>... configs) {
context = new AnnotationConfigWebApplicationContext()
context.setAllowCircularReferences(allowCircularReferences)
context.register(configs)
context.setServletContext(new MockServletContext())
context.refresh()
@@ -171,4 +169,4 @@ abstract class BaseSpringSpec extends Specification {
def getObjectPostProcessor() {
oppContext.getBean(ObjectPostProcessor)
}
}
}
@@ -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
@@ -33,7 +33,7 @@ class UserDetailsManagerConfigurerTests extends Specification {
setup:
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager([])
when:
UserDetails userDetails = new UserDetailsManagerConfigurer<InMemoryUserDetailsManager,UserDetailsManagerConfigurer<InMemoryUserDetailsManager>>(userDetailsManager)
UserDetails userDetails = new UserDetailsManagerConfigurer<UserDetailsManagerConfigurer<InMemoryUserDetailsManager>>(userDetailsManager)
.withUser("user")
.password("password")
.roles("USER")
@@ -57,7 +57,7 @@ class UserDetailsManagerConfigurerTests extends Specification {
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager([])
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER")
when:
UserDetails userDetails = new UserDetailsManagerConfigurer<InMemoryUserDetailsManager,UserDetailsManagerConfigurer<InMemoryUserDetailsManager>>(userDetailsManager)
UserDetails userDetails = new UserDetailsManagerConfigurer<UserDetailsManagerConfigurer<InMemoryUserDetailsManager>>(userDetailsManager)
.withUser("user")
.password("password")
.authorities(authority)
@@ -71,7 +71,7 @@ class UserDetailsManagerConfigurerTests extends Specification {
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager([])
String authority = "ROLE_USER"
when:
UserDetails userDetails = new UserDetailsManagerConfigurer<InMemoryUserDetailsManager,UserDetailsManagerConfigurer<InMemoryUserDetailsManager>>(userDetailsManager)
UserDetails userDetails = new UserDetailsManagerConfigurer<UserDetailsManagerConfigurer<InMemoryUserDetailsManager>>(userDetailsManager)
.withUser("user")
.password("password")
.authorities(authority)
@@ -86,7 +86,7 @@ class UserDetailsManagerConfigurerTests extends Specification {
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager([])
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER")
when:
UserDetails userDetails = new UserDetailsManagerConfigurer<InMemoryUserDetailsManager,UserDetailsManagerConfigurer<InMemoryUserDetailsManager>>(userDetailsManager)
UserDetails userDetails = new UserDetailsManagerConfigurer<UserDetailsManagerConfigurer<InMemoryUserDetailsManager>>(userDetailsManager)
.withUser("user")
.password("password")
.authorities([authority])
@@ -176,7 +176,7 @@ class WebSecurityConfigurerAdapterTests extends BaseSpringSpec {
static ContentNegotiationStrategy CNS
@Bean
public static ContentNegotiationStrategy cns() {
public ContentNegotiationStrategy cns() {
return CNS
}
}
@@ -193,7 +193,6 @@ class WebSecurityConfigurerAdapterTests extends BaseSpringSpec {
def "UserDetailsService lazy"() {
setup:
allowCircularReferences = true
loadConfig(RequiresUserDetailsServiceConfig,UserDetailsServiceConfig)
when:
findFilter(MyFilter).userDetailsService.loadUserByUsername("user")
@@ -275,7 +274,7 @@ class WebSecurityConfigurerAdapterTests extends BaseSpringSpec {
static AuthenticationTrustResolver TR
@Bean
public static AuthenticationTrustResolver tr() {
public AuthenticationTrustResolver tr() {
return TR
}
}
@@ -346,7 +346,7 @@ public class NamespaceHttpTests extends BaseSpringSpec {
}
}
// http@request-matcher is not available (instead request securityMatcher instances are used)
// http@request-matcher is not available (instead request matcher instances are used)
def "http@request-matcher-ref ant"() {
when:
@@ -78,7 +78,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<p style='color:red;'>Your login attempt was not successful, try again.<br/><br/>Reason: Bad credentials</p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<p><font color='red'>Your login attempt was not successful, try again.<br/><br/>Reason: Bad credentials</font></p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
@@ -107,7 +107,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
springSecurityFilterChain.doFilter(request,response,chain)
then: "sent to default success page"
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<p style='color:green;'>You have been logged out</p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<p><font color='green'>You have been logged out</font></p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
@@ -155,7 +155,7 @@ class ExceptionHandlingConfigurerTests extends BaseSpringSpec {
static ContentNegotiationStrategy CNS
@Bean
public static ContentNegotiationStrategy cns() {
public ContentNegotiationStrategy cns() {
return CNS
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,9 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
package org.springframework.security.config.annotation.web.configurers;
import static org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurerConfigs.*
@@ -295,7 +293,7 @@ public class ExpressionUrlAuthorizationConfigurerTests extends BaseSpringSpec {
response.status == HttpServletResponse.SC_UNAUTHORIZED
when:
super.setup()
login(new UsernamePasswordAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_FORBIDDEN
@@ -341,12 +339,16 @@ public class ExpressionUrlAuthorizationConfigurerTests extends BaseSpringSpec {
def "authorizeRequests() fullyAuthenticated"() {
setup:
loadConfig(FullyAuthenticatedConfig)
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
when:
super.setup()
login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
response.status == HttpServletResponse.SC_FORBIDDEN
when:
super.setup()
login()
@@ -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 {
@@ -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);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -42,6 +42,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.web.AuthenticationEntryPoint
import org.springframework.security.web.FilterChainProxy
import org.springframework.security.web.FilterInvocation
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -38,6 +38,7 @@ import org.springframework.security.config.annotation.web.configuration.BaseWebC
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextImpl
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.web.AuthenticationEntryPoint
import org.springframework.security.web.FilterChainProxy
import org.springframework.security.web.FilterInvocation
@@ -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) {
@@ -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 ->
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2012 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,6 +28,7 @@ import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.mock.web.MockServletContext
import org.springframework.security.access.SecurityConfig
import org.springframework.security.crypto.codec.Base64
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@@ -382,7 +383,7 @@ class InterceptUrlConfigTests extends AbstractHttpConfigTests {
def login(MockHttpServletRequest request, String username, String password) {
String toEncode = username + ':' + password
request.addHeader('Authorization','Basic ' + Base64.encoder.encodeToString(toEncode.getBytes('UTF-8')))
request.addHeader('Authorization','Basic ' + new String(Base64.encode(toEncode.getBytes('UTF-8'))))
}
@RestController
@@ -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

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