Compare commits
174 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 081f0c4d94 | |||
| 247f54dc41 | |||
| 017e9834bd | |||
| 49719480a8 | |||
| f3edaa673a | |||
| f99fe36e02 | |||
| 546d44d6e7 | |||
| 901a4e183a | |||
| 72d08a2a5f | |||
| 2ac51c9c7f | |||
| b64cdb5765 | |||
| aa31f1f695 | |||
| 8353984733 | |||
| c31bdb6390 | |||
| 168f4b8f70 | |||
| 9c03571bbb | |||
| 4c79107e01 | |||
| 3f543d0fbd | |||
| 08104eb06c | |||
| b54d350e54 | |||
| b5e0886bde | |||
| 38492a5794 | |||
| b7541d56d0 | |||
| 7a7ce11ebb | |||
| 028854b936 | |||
| aa5df61eff | |||
| 6df5b76f24 | |||
| c8ed130008 | |||
| d39f3385b6 | |||
| 6bec625e68 | |||
| 666e356ebc | |||
| fc516b55a6 | |||
| bb834bccf6 | |||
| 09436649cc | |||
| f94399cff9 | |||
| 94fb1893de | |||
| 3185876a7d | |||
| 2cb38ae115 | |||
| 24fcb6c45a | |||
| a9024de734 | |||
| fd9f57eb5f | |||
| 7259759f8d | |||
| 14e5e06ae0 | |||
| 697daeab7c | |||
| f97f38fd57 | |||
| a853d38076 | |||
| f0a9421aa4 | |||
| 36f4f7d081 | |||
| 07d1c7c5eb | |||
| d2c28c58e2 | |||
| 14a656186d | |||
| 2a197c72eb | |||
| ab5af87953 | |||
| 23294c4c57 | |||
| eb2870bf82 | |||
| 9fa42117f7 | |||
| cf3d6e7167 | |||
| 08f0b57243 | |||
| 97b4cb0b73 | |||
| 8ca4b55d32 | |||
| 8e546454a5 | |||
| 406bb1d4d5 | |||
| 8437d0fea3 | |||
| df3b8bc284 | |||
| 57d7ad05f9 | |||
| e62596f36d | |||
| d3685d89c5 | |||
| a98389fa98 | |||
| dc9f9b140f | |||
| f432c04111 | |||
| 50b72dddbc | |||
| 94e580fe64 | |||
| af9139b613 | |||
| f019ea89e7 | |||
| 0d700628dc | |||
| aaa9708b95 | |||
| df9e6c973c | |||
| 1da9c06f3b | |||
| 0c35209d77 | |||
| badb466cc5 | |||
| 46bb855737 | |||
| 6a3a5f7beb | |||
| 52c6e3cf89 | |||
| 17cfd4707b | |||
| 2c99cd3bbf | |||
| 8a7ac398e6 | |||
| 5e35e37a2b | |||
| c1e9140940 | |||
| 1222fc5f10 | |||
| 08c1f500a7 | |||
| a18707c870 | |||
| 48ff518a41 | |||
| 0b1e3b4e4a | |||
| 6b4a52715b | |||
| 7fb052e7ae | |||
| c1b8150439 | |||
| 8b89e804e3 | |||
| c0f5aaee78 | |||
| 6fb564a629 | |||
| 9ae163e92d | |||
| a8120e74a7 | |||
| b443baef04 | |||
| eabeaf35d6 | |||
| 2e6656e9d3 | |||
| 4a1f00b90f | |||
| d8690a59e2 | |||
| 49f7c98c3e | |||
| 81ebdecd8a | |||
| 6834467389 | |||
| c75a5b7279 | |||
| 06c67070a6 | |||
| 7f54c8b8b4 | |||
| 12173c04ee | |||
| 4cc899feab | |||
| 6650429283 | |||
| 67c9f12964 | |||
| b88418b94a | |||
| a82cab7afd | |||
| 2b6821622e | |||
| d6397c2362 | |||
| aceba1f1cf | |||
| 37c6605062 | |||
| 92a59e0df7 | |||
| 8ad0003456 | |||
| 3531cc93c2 | |||
| bd925313af | |||
| d4c48dd3e1 | |||
| df613ed4cc | |||
| 3fb77f3b59 | |||
| c2d8ea92d0 | |||
| 6f2b24a62b | |||
| 6d2003722e | |||
| 03d8904a03 | |||
| d77ca17e95 | |||
| 4d02a5c0a0 | |||
| 22fe8b33c6 | |||
| 927ef9ba05 | |||
| 995d88952d | |||
| 53352e336d | |||
| 422bc37115 | |||
| 91c8cebf99 | |||
| a1f771251a | |||
| c266930483 | |||
| 4d460b2ec9 | |||
| c6366baee2 | |||
| 1171e25bc7 | |||
| f8bfe19a98 | |||
| 2deb722a1f | |||
| fe117bc445 | |||
| bb997eecde | |||
| e080905a79 | |||
| 3befb1c8a6 | |||
| 050198e51b | |||
| 519c15efb3 | |||
| d2a37cb1d6 | |||
| c23c7982ca | |||
| 0b14664a8c | |||
| ca170f8479 | |||
| ada146244e | |||
| 945e2e2ad4 | |||
| 80ff267749 | |||
| 69306a8b46 | |||
| 8a17c23277 | |||
| 0f608d59b6 | |||
| 70787fc548 | |||
| 1effc1882a | |||
| e5b1cb842e | |||
| 885f074ddf | |||
| e297706e8b | |||
| e3ff4130a5 | |||
| 50d7d3287f | |||
| 26fa4a4bf0 | |||
| 13b0ddb7e6 | |||
| b4ab0483b1 |
+1
-5
@@ -6,10 +6,6 @@ jdk:
|
||||
os:
|
||||
- linux
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
|
||||
before_cache:
|
||||
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
|
||||
cache:
|
||||
@@ -17,4 +13,4 @@ cache:
|
||||
- $HOME/.gradle/caches/
|
||||
- $HOME/.gradle/wrapper/
|
||||
|
||||
script: ./gradlew build
|
||||
script: ./gradlew build
|
||||
|
||||
+11
-2
@@ -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,12 +104,21 @@ e.g.
|
||||
*/
|
||||
</pre>
|
||||
|
||||
#Submit JUnit test cases for all behavior changes
|
||||
# Submit JUnit test cases for all behavior changes
|
||||
Search the codebase to find related unit tests and add additional `@Test` methods within.
|
||||
|
||||
1. Any new tests should end in the name Tests (note this is plural). For example, a valid name would be `FilterChainProxyTests`. An invalid name would be `FilterChainProxyTest`.
|
||||
2. New test methods should not start with test. This is an old JUnit3 convention and is not necessary since the method is annotated with @Test.
|
||||
|
||||
# Update spring-security-x.y.rnc for schema changes
|
||||
Update the [RELAX NG](http://www.relaxng.org) schema `spring-security-x.y.rnc` instead of `spring-security-x.y.xsd` if you contribute changes to supported XML configuration. The XML schema file can be generated the following Gradle task:
|
||||
|
||||
<pre>
|
||||
./gradlew spring-security-config:rncToXsd
|
||||
</pre>
|
||||
|
||||
Changes to the XML schema will be overwritten by the Gradle build task.
|
||||
|
||||
# Squash commits
|
||||
Use git rebase --interactive, git add --patch and other tools to "squash" multiple commits into atomic changes. In addition to the man pages for git, there are many resources online to help you understand how these tools work. Here is one: http://book.git-scm.com/4_interactive_rebasing.html.
|
||||
|
||||
|
||||
+2
-2
@@ -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[JDK7 build].
|
||||
http://help.github.com/set-up-git-redirect[Git] and the http://www.oracle.com/technetwork/java/javase/downloads[JDK8 build].
|
||||
|
||||
Be sure that your `JAVA_HOME` environment variable points to the `jdk1.7.0` folder extracted from the JDK download.
|
||||
Be sure that your `JAVA_HOME` environment variable points to the `jdk1.8.0` folder extracted from the JDK download.
|
||||
|
||||
=== Check out sources
|
||||
[indent=0]
|
||||
|
||||
+3
-3
@@ -3,7 +3,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-acl</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<name>spring-security-acl</name>
|
||||
<description>spring-security-acl</description>
|
||||
<url>http://spring.io/spring-security</url>
|
||||
@@ -35,7 +35,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-framework-bom</artifactId>
|
||||
<version>4.3.1.RELEASE</version>
|
||||
<version>4.3.5.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -51,7 +51,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
||||
+7
-4
@@ -16,18 +16,20 @@
|
||||
|
||||
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>
|
||||
@@ -118,7 +120,8 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
|
||||
}
|
||||
|
||||
// Iterate this principal's authorities to determine right
|
||||
if (authentication.getAuthorities().contains(requiredAuthority)) {
|
||||
Set<String> authorities = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
|
||||
if (authorities.contains(requiredAuthority.getAuthority())) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+6
-5
@@ -26,6 +26,8 @@ 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;
|
||||
|
||||
@@ -37,7 +39,6 @@ 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);
|
||||
@@ -48,8 +49,8 @@ public class AclPermissionEvaluatorTests {
|
||||
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
|
||||
Acl acl = mock(Acl.class);
|
||||
|
||||
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
|
||||
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true);
|
||||
when(service.readAclById(any(ObjectIdentity.class), anyListOf(Sid.class))).thenReturn(acl);
|
||||
when(acl.isGranted(anyListOf(Permission.class), anyListOf(Sid.class), eq(false))).thenReturn(true);
|
||||
|
||||
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
|
||||
}
|
||||
@@ -68,8 +69,8 @@ public class AclPermissionEvaluatorTests {
|
||||
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
|
||||
Acl acl = mock(Acl.class);
|
||||
|
||||
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
|
||||
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true);
|
||||
when(service.readAclById(any(ObjectIdentity.class), anyListOf(Sid.class))).thenReturn(acl);
|
||||
when(acl.isGranted(anyListOf(Permission.class), anyListOf(Sid.class), eq(false))).thenReturn(true);
|
||||
|
||||
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();
|
||||
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -3,7 +3,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-aspects</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<name>spring-security-aspects</name>
|
||||
<description>spring-security-aspects</description>
|
||||
<url>http://spring.io/spring-security</url>
|
||||
@@ -35,7 +35,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-framework-bom</artifactId>
|
||||
<version>4.3.1.RELEASE</version>
|
||||
<version>4.3.5.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -45,7 +45,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
||||
+12
-8
@@ -1,20 +1,21 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
maven { url "https://repo.spring.io/plugins-release" }
|
||||
maven { url "https://repo.spring.io/plugins-snapshot" }
|
||||
}
|
||||
dependencies {
|
||||
classpath("org.springframework.build.gradle:propdeps-plugin:0.0.7")
|
||||
classpath("io.spring.gradle:spring-io-plugin:0.0.4.RELEASE")
|
||||
classpath("io.spring.gradle:spring-io-plugin:0.0.6.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")
|
||||
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.0.BUILD-SNAPSHOT")
|
||||
}
|
||||
}
|
||||
|
||||
plugins {
|
||||
id "org.sonarqube" version "1.2"
|
||||
id "org.sonarqube" version "2.1-rc1"
|
||||
}
|
||||
|
||||
apply plugin: 'base'
|
||||
@@ -27,8 +28,8 @@ allprojects {
|
||||
|
||||
ext.releaseBuild = version.endsWith('RELEASE')
|
||||
ext.snapshotBuild = version.endsWith('SNAPSHOT')
|
||||
ext.springVersion = '4.3.1.RELEASE'
|
||||
ext.springLdapVersion = '2.0.2.RELEASE'
|
||||
ext.springVersion = '4.3.5.RELEASE'
|
||||
ext.springLdapVersion = '2.2.0.RELEASE'
|
||||
|
||||
group = 'org.springframework.security'
|
||||
|
||||
@@ -39,7 +40,6 @@ allprojects {
|
||||
maven { url "http://repo.terracotta.org/maven2/" }
|
||||
}
|
||||
|
||||
eclipse.project.name = "${project.name}-4.1.x"
|
||||
}
|
||||
|
||||
sonarqube {
|
||||
@@ -106,7 +106,7 @@ configure(coreModuleProjects) {
|
||||
apply plugin: 'emma'
|
||||
apply plugin: 'spring-io'
|
||||
|
||||
ext.springIoVersion = project.hasProperty('platformVersion') ? platformVersion : '2.0.1.RELEASE'
|
||||
ext.springIoVersion = project.hasProperty('platformVersion') ? platformVersion : 'Athens-BUILD-SNAPSHOT'
|
||||
|
||||
configurations {
|
||||
jacoco //Configuration Group used by Sonar to provide Code Coverage using JaCoCo
|
||||
@@ -115,7 +115,11 @@ configure(coreModuleProjects) {
|
||||
dependencyManagement {
|
||||
springIoTestRuntime {
|
||||
imports {
|
||||
mavenBom "io.spring.platform:platform-bom:${springIoVersion}"
|
||||
mavenBom("io.spring.platform:platform-bom:${springIoVersion}") {
|
||||
bomProperties([
|
||||
'mockito.version': '1.10.19'
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,12 +4,13 @@ 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.FileCollection
|
||||
import org.gradle.api.file.*
|
||||
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
|
||||
@@ -41,28 +42,25 @@ class AspectJPlugin implements Plugin<Project> {
|
||||
project.configurations.create('aspectpath')
|
||||
}
|
||||
|
||||
project.tasks.create(name: 'compileAspect', overwrite: true, description: 'Compiles AspectJ Source', type: Ajc) {
|
||||
dependsOn project.configurations*.getTaskDependencyFromProjectDependency(true, "compileJava")
|
||||
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
|
||||
|
||||
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 ->
|
||||
@@ -91,7 +89,9 @@ class AspectJPlugin implements Plugin<Project> {
|
||||
}
|
||||
|
||||
class Ajc extends DefaultTask {
|
||||
SourceSet sourceSet
|
||||
Set<File> sourceRoots = []
|
||||
FileCollection compileClasspath
|
||||
File destinationDir
|
||||
FileCollection aspectPath
|
||||
|
||||
Ajc() {
|
||||
@@ -103,15 +103,18 @@ class Ajc extends DefaultTask {
|
||||
logger.info("="*30)
|
||||
logger.info("="*30)
|
||||
logger.info("Running ajc ...")
|
||||
logger.info("classpath: ${sourceSet.compileClasspath.asPath}")
|
||||
logger.info("srcDirs $sourceSet.java.srcDirs")
|
||||
logger.info("classpath: ${compileClasspath?.files}")
|
||||
logger.info("srcDirs ${sourceRoots}")
|
||||
ant.taskdef(resource: "org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: project.configurations.ajtools.asPath)
|
||||
ant.iajc(classpath: sourceSet.compileClasspath.asPath, fork: 'true', destDir: sourceSet.output.classesDir.absolutePath,
|
||||
if(sourceRoots.empty) {
|
||||
return
|
||||
}
|
||||
ant.iajc(classpath: compileClasspath.asPath, fork: 'true', destDir: destinationDir.absolutePath,
|
||||
source: project.convention.plugins.java.sourceCompatibility,
|
||||
target: project.convention.plugins.java.targetCompatibility,
|
||||
aspectPath: aspectPath.asPath, sourceRootCopyFilter: '**/*.java', showWeaveInfo: 'true') {
|
||||
sourceroots {
|
||||
sourceSet.java.srcDirs.each {
|
||||
sourceRoots.each {
|
||||
logger.info(" sourceRoot $it")
|
||||
pathelement(location: it.absolutePath)
|
||||
}
|
||||
|
||||
+4
-1
@@ -8,7 +8,10 @@ dependencies {
|
||||
"org.springframework:spring-web:$springVersion",
|
||||
"org.jasig.cas.client:cas-client-core:$casClientVersion"
|
||||
|
||||
optional "net.sf.ehcache:ehcache:$ehcacheVersion"
|
||||
optional "net.sf.ehcache:ehcache:$ehcacheVersion",
|
||||
"com.fasterxml.jackson.core:jackson-databind:$jacksonDatabindVersion"
|
||||
|
||||
testCompile "org.skyscreamer:jsonassert:$jsonassertVersion"
|
||||
|
||||
provided "javax.servlet:javax.servlet-api:$servletApiVersion"
|
||||
}
|
||||
|
||||
+18
-5
@@ -3,7 +3,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-cas</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<name>spring-security-cas</name>
|
||||
<description>spring-security-cas</description>
|
||||
<url>http://spring.io/spring-security</url>
|
||||
@@ -35,7 +35,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-framework-bom</artifactId>
|
||||
<version>4.3.1.RELEASE</version>
|
||||
<version>4.3.5.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -51,13 +51,13 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -86,6 +86,13 @@
|
||||
<artifactId>spring-web</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.8.4</version>
|
||||
<scope>compile</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
@@ -103,7 +110,7 @@
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.0.1</version>
|
||||
<version>3.1.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -130,6 +137,12 @@
|
||||
<version>1.10.19</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.skyscreamer</groupId>
|
||||
<artifactId>jsonassert</artifactId>
|
||||
<version>1.3.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
|
||||
+47
-16
@@ -24,6 +24,7 @@ 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>.
|
||||
@@ -50,29 +51,54 @@ 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) {
|
||||
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) {
|
||||
super(authorities);
|
||||
|
||||
if ((key == null) || ("".equals(key)) || (principal == null)
|
||||
if ((principal == null)
|
||||
|| "".equals(principal) || (credentials == null)
|
||||
|| "".equals(credentials) || (authorities == null)
|
||||
|| (userDetails == null) || (assertion == null)) {
|
||||
@@ -80,7 +106,7 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
|
||||
"Cannot pass null or empty values to constructor");
|
||||
}
|
||||
|
||||
this.keyHash = key.hashCode();
|
||||
this.keyHash = keyHash;
|
||||
this.principal = principal;
|
||||
this.credentials = credentials;
|
||||
this.userDetails = userDetails;
|
||||
@@ -91,6 +117,11 @@ 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;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 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){
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* 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) {
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 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) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -132,7 +132,7 @@ final class DefaultServiceAuthenticationDetails extends WebAuthenticationDetails
|
||||
* @return
|
||||
*/
|
||||
static Pattern createArtifactPattern(String artifactParameterName) {
|
||||
Assert.hasLength(artifactParameterName);
|
||||
Assert.hasLength(artifactParameterName, "artifactParameterName is expected to have a length");
|
||||
return Pattern.compile("&?" + Pattern.quote(artifactParameterName) + "=[^&]*");
|
||||
}
|
||||
|
||||
|
||||
+7
@@ -19,6 +19,7 @@ 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;
|
||||
@@ -102,6 +103,12 @@ 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");
|
||||
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
@@ -39,8 +39,8 @@ dependencies {
|
||||
"org.springframework:spring-orm:$springVersion",
|
||||
"org.springframework:spring-tx:$springVersion",
|
||||
"org.slf4j:jcl-over-slf4j:$slf4jVersion",
|
||||
"org.eclipse.persistence:javax.persistence:2.0.5",
|
||||
"org.hibernate:hibernate-entitymanager:4.1.0.Final",
|
||||
"org.eclipse.persistence:javax.persistence:$javaPersistenceVersion",
|
||||
"org.hibernate:hibernate-entitymanager:$hibernateVersion",
|
||||
"org.codehaus.groovy:groovy-all:$groovyVersion",
|
||||
"org.apache.directory.server:apacheds-core:$apacheDsVersion",
|
||||
"org.apache.directory.server:apacheds-core-entry:$apacheDsVersion",
|
||||
@@ -50,7 +50,6 @@ dependencies {
|
||||
'org.apache.directory.shared:shared-ldap:0.9.15',
|
||||
'ldapsdk:ldapsdk:4.1',
|
||||
powerMockDependencies,
|
||||
"org.hibernate:hibernate-entitymanager:3.6.10.Final",
|
||||
"org.hsqldb:hsqldb:$hsqlVersion",
|
||||
spockDependencies
|
||||
|
||||
|
||||
+14
-14
@@ -3,7 +3,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<name>spring-security-config</name>
|
||||
<description>spring-security-config</description>
|
||||
<url>http://spring.io/spring-security</url>
|
||||
@@ -35,7 +35,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-framework-bom</artifactId>
|
||||
<version>4.3.1.RELEASE</version>
|
||||
<version>4.3.5.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -51,7 +51,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -97,28 +97,28 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-ldap</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-messaging</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-openid</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
@@ -155,7 +155,7 @@
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.0.1</version>
|
||||
<version>3.1.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -239,13 +239,13 @@
|
||||
<dependency>
|
||||
<groupId>org.eclipse.persistence</groupId>
|
||||
<artifactId>javax.persistence</artifactId>
|
||||
<version>2.0.5</version>
|
||||
<version>2.1.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<version>4.1.0.Final</version>
|
||||
<version>5.0.11.Final</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -347,7 +347,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>1.7.1.RELEASE</version>
|
||||
<version>1.10.2.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
@@ -359,19 +359,19 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.ldap</groupId>
|
||||
<artifactId>spring-ldap-core</artifactId>
|
||||
<version>2.0.2.RELEASE</version>
|
||||
<version>2.2.0.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-aspects</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-cas</artifactId>
|
||||
<version>4.1.1.RELEASE</version>
|
||||
<version>4.2.2.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
||||
+15
-10
@@ -15,11 +15,12 @@
|
||||
*/
|
||||
package org.springframework.security.config.ldap;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.*;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import org.junit.*;
|
||||
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
@@ -32,13 +33,19 @@ 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 java.util.*;
|
||||
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;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
* @author Eddú Meléndez
|
||||
*/
|
||||
public class LdapUserServiceBeanDefinitionParserTests {
|
||||
private InMemoryXmlApplicationContext appCtx;
|
||||
@@ -102,13 +109,11 @@ 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
|
||||
|
||||
+2
-2
@@ -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.1. Please update your schema declarations to the 4.1 schema.",
|
||||
+ "with Spring Security 4.2. Please update your schema declarations to the 4.2 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\\.1.*.xsd.*")
|
||||
return schemaLocation.matches("(?m).*spring-security-4\\.2.*.xsd.*")
|
||||
|| schemaLocation.matches("(?m).*spring-security.xsd.*")
|
||||
|| !schemaLocation.matches("(?m).*spring-security.*");
|
||||
}
|
||||
|
||||
+3
@@ -31,11 +31,13 @@ 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;
|
||||
@@ -48,6 +50,7 @@ import org.springframework.util.Assert;
|
||||
*
|
||||
*/
|
||||
@Configuration
|
||||
@Import(ObjectPostProcessorConfiguration.class)
|
||||
public class AuthenticationConfiguration {
|
||||
|
||||
private AtomicBoolean buildingAuthenticationManager = new AtomicBoolean();
|
||||
|
||||
+7
-6
@@ -15,6 +15,9 @@
|
||||
*/
|
||||
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;
|
||||
@@ -24,6 +27,7 @@ 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;
|
||||
@@ -43,9 +47,6 @@ import org.springframework.security.ldap.userdetails.PersonContextMapper;
|
||||
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
|
||||
/**
|
||||
* Configures LDAP {@link AuthenticationProvider} in the {@link ProviderManagerBuilder}.
|
||||
*
|
||||
@@ -128,7 +129,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
|
||||
contextSource, groupSearchBase);
|
||||
defaultAuthoritiesPopulator.setGroupRoleAttribute(groupRoleAttribute);
|
||||
defaultAuthoritiesPopulator.setGroupSearchFilter(groupSearchFilter);
|
||||
defaultAuthoritiesPopulator.setRolePrefix(rolePrefix);
|
||||
defaultAuthoritiesPopulator.setRolePrefix(this.rolePrefix);
|
||||
|
||||
this.ldapAuthoritiesPopulator = defaultAuthoritiesPopulator;
|
||||
return defaultAuthoritiesPopulator;
|
||||
@@ -161,7 +162,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
|
||||
}
|
||||
|
||||
SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper();
|
||||
simpleAuthorityMapper.setPrefix(rolePrefix);
|
||||
simpleAuthorityMapper.setPrefix(this.rolePrefix);
|
||||
simpleAuthorityMapper.afterPropertiesSet();
|
||||
this.authoritiesMapper = simpleAuthorityMapper;
|
||||
return simpleAuthorityMapper;
|
||||
@@ -615,4 +616,4 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
|
||||
return new PasswordCompareConfigurer().passwordAttribute("password")
|
||||
.passwordEncoder(new PlaintextPasswordEncoder());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-32
@@ -16,19 +16,16 @@
|
||||
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
|
||||
@@ -82,13 +79,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* should provided. The remaining attributes have reasonable defaults.
|
||||
*/
|
||||
public class UserDetailsBuilder {
|
||||
private String username;
|
||||
private String password;
|
||||
private List<GrantedAuthority> authorities;
|
||||
private boolean accountExpired;
|
||||
private boolean accountLocked;
|
||||
private boolean credentialsExpired;
|
||||
private boolean disabled;
|
||||
private UserBuilder user;
|
||||
private final C builder;
|
||||
|
||||
/**
|
||||
@@ -117,8 +108,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* additional attributes for this user)
|
||||
*/
|
||||
private UserDetailsBuilder username(String username) {
|
||||
Assert.notNull(username, "username cannot be null");
|
||||
this.username = username;
|
||||
this.user = User.withUsername(username);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -130,8 +120,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* additional attributes for this user)
|
||||
*/
|
||||
public UserDetailsBuilder password(String password) {
|
||||
Assert.notNull(password, "password cannot be null");
|
||||
this.password = password;
|
||||
this.user.password(password);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -161,14 +150,8 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* additional attributes for this user)
|
||||
*/
|
||||
public UserDetailsBuilder roles(String... roles) {
|
||||
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);
|
||||
this.user.roles(roles);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,7 +164,8 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* @see #roles(String...)
|
||||
*/
|
||||
public UserDetailsBuilder authorities(GrantedAuthority... authorities) {
|
||||
return authorities(Arrays.asList(authorities));
|
||||
this.user.authorities(authorities);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -194,7 +178,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* @see #roles(String...)
|
||||
*/
|
||||
public UserDetailsBuilder authorities(List<? extends GrantedAuthority> authorities) {
|
||||
this.authorities = new ArrayList<GrantedAuthority>(authorities);
|
||||
this.user.authorities(authorities);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -208,7 +192,8 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* @see #roles(String...)
|
||||
*/
|
||||
public UserDetailsBuilder authorities(String... authorities) {
|
||||
return authorities(AuthorityUtils.createAuthorityList(authorities));
|
||||
this.user.authorities(authorities);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -219,7 +204,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* additional attributes for this user)
|
||||
*/
|
||||
public UserDetailsBuilder accountExpired(boolean accountExpired) {
|
||||
this.accountExpired = accountExpired;
|
||||
this.user.accountExpired(accountExpired);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -231,7 +216,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* additional attributes for this user)
|
||||
*/
|
||||
public UserDetailsBuilder accountLocked(boolean accountLocked) {
|
||||
this.accountLocked = accountLocked;
|
||||
this.user.accountLocked(accountLocked);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -243,7 +228,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* additional attributes for this user)
|
||||
*/
|
||||
public UserDetailsBuilder credentialsExpired(boolean credentialsExpired) {
|
||||
this.credentialsExpired = credentialsExpired;
|
||||
this.user.credentialsExpired(credentialsExpired);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -255,13 +240,12 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* additional attributes for this user)
|
||||
*/
|
||||
public UserDetailsBuilder disabled(boolean disabled) {
|
||||
this.disabled = disabled;
|
||||
this.user.disabled(disabled);
|
||||
return this;
|
||||
}
|
||||
|
||||
private UserDetails build() {
|
||||
return new User(username, password, !disabled, !accountExpired,
|
||||
!credentialsExpired, !accountLocked, authorities);
|
||||
return this.user.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-1
@@ -24,6 +24,7 @@ import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.factory.Aware;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
import org.springframework.security.config.annotation.ObjectPostProcessor;
|
||||
import org.springframework.util.Assert;
|
||||
@@ -37,10 +38,11 @@ import org.springframework.util.Assert;
|
||||
* @since 3.2
|
||||
*/
|
||||
final class AutowireBeanFactoryObjectPostProcessor
|
||||
implements ObjectPostProcessor<Object>, DisposableBean {
|
||||
implements ObjectPostProcessor<Object>, DisposableBean, SmartInitializingSingleton {
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
private final AutowireCapableBeanFactory autowireBeanFactory;
|
||||
private final List<DisposableBean> disposableBeans = new ArrayList<DisposableBean>();
|
||||
private final List<SmartInitializingSingleton> smartSingletons = new ArrayList<SmartInitializingSingleton>();
|
||||
|
||||
public AutowireBeanFactoryObjectPostProcessor(
|
||||
AutowireCapableBeanFactory autowireBeanFactory) {
|
||||
@@ -74,9 +76,22 @@ final class AutowireBeanFactoryObjectPostProcessor
|
||||
if (result instanceof DisposableBean) {
|
||||
this.disposableBeans.add((DisposableBean) result);
|
||||
}
|
||||
if (result instanceof SmartInitializingSingleton) {
|
||||
this.smartSingletons.add((SmartInitializingSingleton) result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
|
||||
*/
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
for(SmartInitializingSingleton singleton : smartSingletons) {
|
||||
singleton.afterSingletonsInstantiated();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
|
||||
+1
-2
@@ -25,7 +25,6 @@ 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>
|
||||
@@ -45,7 +44,7 @@ import org.springframework.security.config.annotation.configuration.ObjectPostPr
|
||||
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
|
||||
@Target(value = { java.lang.annotation.ElementType.TYPE })
|
||||
@Documented
|
||||
@Import({ GlobalMethodSecuritySelector.class, ObjectPostProcessorConfiguration.class })
|
||||
@Import({ GlobalMethodSecuritySelector.class })
|
||||
@EnableGlobalAuthentication
|
||||
@Configuration
|
||||
public @interface EnableGlobalMethodSecurity {
|
||||
|
||||
+44
-23
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -66,6 +66,7 @@ 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;
|
||||
|
||||
/**
|
||||
@@ -74,6 +75,7 @@ import org.springframework.util.Assert;
|
||||
* {@link EnableGlobalMethodSecurity} annotation on the subclass.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @author Eddú Meléndez
|
||||
* @since 3.2
|
||||
* @see EnableGlobalMethodSecurity
|
||||
*/
|
||||
@@ -150,6 +152,39 @@ public class GlobalMethodSecurityConfiguration
|
||||
catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
PermissionEvaluator permissionEvaluator = getSingleBeanOrNull(
|
||||
PermissionEvaluator.class);
|
||||
if (permissionEvaluator != null) {
|
||||
this.defaultMethodExpressionHandler
|
||||
.setPermissionEvaluator(permissionEvaluator);
|
||||
}
|
||||
|
||||
RoleHierarchy roleHierarchy = getSingleBeanOrNull(RoleHierarchy.class);
|
||||
if (roleHierarchy != null) {
|
||||
this.defaultMethodExpressionHandler.setRoleHierarchy(roleHierarchy);
|
||||
}
|
||||
|
||||
AuthenticationTrustResolver trustResolver = getSingleBeanOrNull(
|
||||
AuthenticationTrustResolver.class);
|
||||
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) {
|
||||
String[] beanNamesForType = this.context.getBeanNamesForType(type);
|
||||
if (beanNamesForType == null || beanNamesForType.length != 1) {
|
||||
return null;
|
||||
}
|
||||
return this.context.getBean(beanNamesForType[0], type);
|
||||
}
|
||||
|
||||
private void initializeMethodSecurityInterceptor() throws Exception {
|
||||
@@ -329,6 +364,12 @@ 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);
|
||||
@@ -357,16 +398,6 @@ public class GlobalMethodSecurityConfiguration
|
||||
enableMethodSecurity = AnnotationAttributes.fromMap(annotationAttributes);
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setAuthenticationTrustResolver(AuthenticationTrustResolver trustResolver) {
|
||||
this.defaultMethodExpressionHandler.setTrustResolver(trustResolver);
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setRoleHierarchy(RoleHierarchy roleHierarchy){
|
||||
this.defaultMethodExpressionHandler.setRoleHierarchy(roleHierarchy);
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||
this.objectPostProcessor = objectPostProcessor;
|
||||
@@ -380,21 +411,11 @@ public class GlobalMethodSecurityConfiguration
|
||||
this.jsr250MethodSecurityMetadataSource = jsr250MethodSecurityMetadataSource;
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setPermissionEvaluator(List<PermissionEvaluator> permissionEvaluators) {
|
||||
if (permissionEvaluators.size() != 1) {
|
||||
logger.debug("Not autwiring PermissionEvaluator since size != 1. Got "
|
||||
+ permissionEvaluators);
|
||||
}
|
||||
this.defaultMethodExpressionHandler.setPermissionEvaluator(permissionEvaluators
|
||||
.get(0));
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setMethodSecurityExpressionHandler(
|
||||
List<MethodSecurityExpressionHandler> handlers) {
|
||||
if (handlers.size() != 1) {
|
||||
logger.debug("Not autwiring PermissionEvaluator since size != 1. Got "
|
||||
logger.debug("Not autowiring MethodSecurityExpressionHandler since size != 1. Got "
|
||||
+ handlers);
|
||||
return;
|
||||
}
|
||||
@@ -443,4 +464,4 @@ public class GlobalMethodSecurityConfiguration
|
||||
}
|
||||
return this.enableMethodSecurity;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+36
-10
@@ -15,20 +15,22 @@
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.ObjectPostProcessor;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractConfigAttributeRequestMatcherRegistry;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RegexRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A base class for registering {@link RequestMatcher}'s. For example, it might allow for
|
||||
* specifying which {@link RequestMatcher} require a certain level of authorization.
|
||||
@@ -48,6 +50,15 @@ public abstract class AbstractRequestMatcherRegistry<C> {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link ApplicationContext}
|
||||
*
|
||||
* @return the {@link ApplicationContext}
|
||||
*/
|
||||
protected final ApplicationContext getApplicationContext() {
|
||||
return this.context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps any request.
|
||||
*
|
||||
@@ -117,9 +128,7 @@ public abstract class AbstractRequestMatcherRegistry<C> {
|
||||
* Spring MVC
|
||||
* @return the object that is chained after creating the {@link RequestMatcher}.
|
||||
*/
|
||||
public C mvcMatchers(String... mvcPatterns) {
|
||||
return mvcMatchers(null, mvcPatterns);
|
||||
}
|
||||
public abstract C mvcMatchers(String... mvcPatterns);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
@@ -138,18 +147,34 @@ public abstract class AbstractRequestMatcherRegistry<C> {
|
||||
* Spring MVC
|
||||
* @return the object that is chained after creating the {@link RequestMatcher}.
|
||||
*/
|
||||
public C mvcMatchers(HttpMethod method, String... mvcPatterns) {
|
||||
public abstract C mvcMatchers(HttpMethod method, String... mvcPatterns);
|
||||
|
||||
/**
|
||||
* Creates {@link MvcRequestMatcher} instances for the method and patterns passed in
|
||||
*
|
||||
* @param method the HTTP method to use or null if any should be used
|
||||
* @param mvcPatterns the Spring MVC patterns to match on
|
||||
* @return a List of {@link MvcRequestMatcher} instances
|
||||
*/
|
||||
protected final List<MvcRequestMatcher> createMvcMatchers(HttpMethod method,
|
||||
String... mvcPatterns) {
|
||||
boolean isServlet30 = ClassUtils.isPresent("javax.servlet.ServletRegistration", getClass().getClassLoader());
|
||||
ObjectPostProcessor<Object> opp = this.context.getBean(ObjectPostProcessor.class);
|
||||
HandlerMappingIntrospector introspector = new HandlerMappingIntrospector(
|
||||
this.context);
|
||||
List<RequestMatcher> matchers = new ArrayList<RequestMatcher>(mvcPatterns.length);
|
||||
List<MvcRequestMatcher> matchers = new ArrayList<MvcRequestMatcher>(
|
||||
mvcPatterns.length);
|
||||
for (String mvcPattern : mvcPatterns) {
|
||||
MvcRequestMatcher matcher = new MvcRequestMatcher(introspector, mvcPattern);
|
||||
if (isServlet30) {
|
||||
opp.postProcess(matcher);
|
||||
}
|
||||
if (method != null) {
|
||||
matcher.setMethod(method);
|
||||
}
|
||||
matchers.add(matcher);
|
||||
}
|
||||
return chainRequestMatchers(matchers);
|
||||
return matchers;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -281,4 +306,5 @@ public abstract class AbstractRequestMatcherRegistry<C> {
|
||||
private RequestMatchers() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+80
-11
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -24,6 +24,7 @@ import javax.servlet.Filter;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder;
|
||||
@@ -65,6 +66,7 @@ import org.springframework.security.web.PortMapper;
|
||||
import org.springframework.security.web.PortMapperImpl;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
import org.springframework.security.web.session.HttpSessionEventPublisher;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
|
||||
@@ -1080,12 +1082,12 @@ public final class HttpSecurity extends
|
||||
* Allows specifying which {@link HttpServletRequest} instances this
|
||||
* {@link HttpSecurity} will be invoked on. This method allows for easily invoking the
|
||||
* {@link HttpSecurity} for multiple different {@link RequestMatcher} instances. If
|
||||
* only a single {@link RequestMatcher} is necessary consider using
|
||||
* only a single {@link RequestMatcher} is necessary consider using {@link #mvcMatcher(String)},
|
||||
* {@link #antMatcher(String)}, {@link #regexMatcher(String)}, or
|
||||
* {@link #requestMatcher(RequestMatcher)}.
|
||||
*
|
||||
* <p>
|
||||
* Invoking {@link #requestMatchers()} will not override previous invocations of
|
||||
* Invoking {@link #requestMatchers()} will not override previous invocations of {@link #mvcMatcher(String)}},
|
||||
* {@link #requestMatchers()}, {@link #antMatcher(String)},
|
||||
* {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
|
||||
* </p>
|
||||
@@ -1194,7 +1196,7 @@ public final class HttpSecurity extends
|
||||
*
|
||||
* <p>
|
||||
* Invoking {@link #requestMatcher(RequestMatcher)} will override previous invocations
|
||||
* of {@link #requestMatchers()}, {@link #antMatcher(String)},
|
||||
* of {@link #requestMatchers()}, {@link #mvcMatcher(String)}, {@link #antMatcher(String)},
|
||||
* {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
|
||||
* </p>
|
||||
*
|
||||
@@ -1216,7 +1218,7 @@ public final class HttpSecurity extends
|
||||
* {@link #requestMatchers()} or {@link #requestMatcher(RequestMatcher)}.
|
||||
*
|
||||
* <p>
|
||||
* Invoking {@link #antMatcher(String)} will override previous invocations of
|
||||
* Invoking {@link #antMatcher(String)} will override previous invocations of {@link #mvcMatcher(String)}},
|
||||
* {@link #requestMatchers()}, {@link #antMatcher(String)},
|
||||
* {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
|
||||
* </p>
|
||||
@@ -1229,13 +1231,33 @@ public final class HttpSecurity extends
|
||||
return requestMatcher(new AntPathRequestMatcher(antPattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows configuring the {@link HttpSecurity} to only be invoked when matching the
|
||||
* provided Spring MVC pattern. If more advanced configuration is necessary, consider using
|
||||
* {@link #requestMatchers()} or {@link #requestMatcher(RequestMatcher)}.
|
||||
*
|
||||
* <p>
|
||||
* Invoking {@link #mvcMatcher(String)} will override previous invocations of {@link #mvcMatcher(String)}},
|
||||
* {@link #requestMatchers()}, {@link #antMatcher(String)},
|
||||
* {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
|
||||
* </p>
|
||||
*
|
||||
* @param mvcPattern the Spring MVC Pattern to match on (i.e. "/admin/**")
|
||||
* @return the {@link HttpSecurity} for further customizations
|
||||
* @see MvcRequestMatcher
|
||||
*/
|
||||
public HttpSecurity mvcMatcher(String mvcPattern) {
|
||||
HandlerMappingIntrospector introspector = new HandlerMappingIntrospector(getContext());
|
||||
return requestMatcher(new MvcRequestMatcher(introspector, mvcPattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows configuring the {@link HttpSecurity} to only be invoked when matching the
|
||||
* provided regex pattern. If more advanced configuration is necessary, consider using
|
||||
* {@link #requestMatchers()} or {@link #requestMatcher(RequestMatcher)}.
|
||||
*
|
||||
* <p>
|
||||
* Invoking {@link #regexMatcher(String)} will override previous invocations of
|
||||
* Invoking {@link #regexMatcher(String)} will override previous invocations of {@link #mvcMatcher(String)}},
|
||||
* {@link #requestMatchers()}, {@link #antMatcher(String)},
|
||||
* {@link #regexMatcher(String)}, and {@link #requestMatcher(RequestMatcher)}.
|
||||
* </p>
|
||||
@@ -1248,16 +1270,45 @@ public final class HttpSecurity extends
|
||||
return requestMatcher(new RegexRequestMatcher(pattern, null));
|
||||
}
|
||||
|
||||
/**
|
||||
* An extension to {@link RequestMatcherConfigurer} that allows optionally configuring
|
||||
* the servlet path.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public final class MvcMatchersRequestMatcherConfigurer extends RequestMatcherConfigurer {
|
||||
|
||||
/**
|
||||
* Creates a new instance
|
||||
* @param context the {@link ApplicationContext} to use
|
||||
* @param matchers the {@link MvcRequestMatcher} instances to set the servlet path
|
||||
* on if {@link #servletPath(String)} is set.
|
||||
*/
|
||||
private MvcMatchersRequestMatcherConfigurer(ApplicationContext context,
|
||||
List<MvcRequestMatcher> matchers) {
|
||||
super(context);
|
||||
this.matchers = new ArrayList<RequestMatcher>(matchers);
|
||||
}
|
||||
|
||||
public RequestMatcherConfigurer servletPath(String servletPath) {
|
||||
for (RequestMatcher matcher : this.matchers) {
|
||||
((MvcRequestMatcher) matcher).setServletPath(servletPath);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows mapping HTTP requests that this {@link HttpSecurity} will be used for
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public final class RequestMatcherConfigurer extends
|
||||
AbstractRequestMatcherRegistry<RequestMatcherConfigurer> {
|
||||
public class RequestMatcherConfigurer
|
||||
extends AbstractRequestMatcherRegistry<RequestMatcherConfigurer> {
|
||||
|
||||
private List<RequestMatcher> matchers = new ArrayList<RequestMatcher>();
|
||||
protected List<RequestMatcher> matchers = new ArrayList<RequestMatcher>();
|
||||
|
||||
/**
|
||||
* @param context
|
||||
@@ -1266,13 +1317,31 @@ public final class HttpSecurity extends
|
||||
setApplicationContext(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersRequestMatcherConfigurer mvcMatchers(HttpMethod method,
|
||||
String... mvcPatterns) {
|
||||
List<MvcRequestMatcher> mvcMatchers = createMvcMatchers(method, mvcPatterns);
|
||||
setMatchers(mvcMatchers);
|
||||
return new MvcMatchersRequestMatcherConfigurer(getContext(), mvcMatchers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersRequestMatcherConfigurer mvcMatchers(String... patterns) {
|
||||
return mvcMatchers(null, patterns);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected RequestMatcherConfigurer chainRequestMatchers(
|
||||
List<RequestMatcher> requestMatchers) {
|
||||
matchers.addAll(requestMatchers);
|
||||
requestMatcher(new OrRequestMatcher(matchers));
|
||||
setMatchers(requestMatchers);
|
||||
return this;
|
||||
}
|
||||
|
||||
private void setMatchers(List<? extends RequestMatcher> requestMatchers) {
|
||||
this.matchers.addAll(requestMatchers);
|
||||
requestMatcher(new OrRequestMatcher(this.matchers));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the {@link HttpSecurity} for further customizations
|
||||
*
|
||||
|
||||
+44
-4
@@ -27,6 +27,7 @@ import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.access.expression.SecurityExpressionHandler;
|
||||
import org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.ObjectPostProcessor;
|
||||
@@ -48,6 +49,7 @@ import org.springframework.security.web.access.intercept.FilterSecurityIntercept
|
||||
import org.springframework.security.web.debug.DebugFilter;
|
||||
import org.springframework.security.web.firewall.DefaultHttpFirewall;
|
||||
import org.springframework.security.web.firewall.HttpFirewall;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.filter.DelegatingFilterProxy;
|
||||
@@ -111,7 +113,7 @@ public final class WebSecurity extends
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Allows adding {@link RequestMatcher} instances that should that Spring Security
|
||||
* Allows adding {@link RequestMatcher} instances that Spring Security
|
||||
* should ignore. Web Security provided by Spring Security (including the
|
||||
* {@link SecurityContext}) will not be available on {@link HttpServletRequest} that
|
||||
* match. Typically the requests that are registered should be that of only static
|
||||
@@ -307,6 +309,30 @@ public final class WebSecurity extends
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* An {@link IgnoredRequestConfigurer} that allows optionally configuring the
|
||||
* {@link MvcRequestMatcher#setMethod(HttpMethod)}
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public final class MvcMatchersIgnoredRequestConfigurer
|
||||
extends IgnoredRequestConfigurer {
|
||||
private final List<MvcRequestMatcher> mvcMatchers;
|
||||
|
||||
private MvcMatchersIgnoredRequestConfigurer(ApplicationContext context,
|
||||
List<MvcRequestMatcher> mvcMatchers) {
|
||||
super(context);
|
||||
this.mvcMatchers = mvcMatchers;
|
||||
}
|
||||
|
||||
public IgnoredRequestConfigurer servletPath(String servletPath) {
|
||||
for (MvcRequestMatcher matcher : this.mvcMatchers) {
|
||||
matcher.setServletPath(servletPath);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows registering {@link RequestMatcher} instances that should be ignored by
|
||||
* Spring Security.
|
||||
@@ -314,17 +340,31 @@ public final class WebSecurity extends
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public final class IgnoredRequestConfigurer extends
|
||||
AbstractRequestMatcherRegistry<IgnoredRequestConfigurer> {
|
||||
public class IgnoredRequestConfigurer
|
||||
extends AbstractRequestMatcherRegistry<IgnoredRequestConfigurer> {
|
||||
|
||||
private IgnoredRequestConfigurer(ApplicationContext context) {
|
||||
setApplicationContext(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersIgnoredRequestConfigurer mvcMatchers(HttpMethod method,
|
||||
String... mvcPatterns) {
|
||||
List<MvcRequestMatcher> mvcMatchers = createMvcMatchers(method, mvcPatterns);
|
||||
WebSecurity.this.ignoredRequests.addAll(mvcMatchers);
|
||||
return new MvcMatchersIgnoredRequestConfigurer(getApplicationContext(),
|
||||
mvcMatchers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersIgnoredRequestConfigurer mvcMatchers(String... mvcPatterns) {
|
||||
return mvcMatchers(null, mvcPatterns);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IgnoredRequestConfigurer chainRequestMatchers(
|
||||
List<RequestMatcher> requestMatchers) {
|
||||
ignoredRequests.addAll(requestMatchers);
|
||||
WebSecurity.this.ignoredRequests.addAll(requestMatchers);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
+1
-2
@@ -22,7 +22,6 @@ 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;
|
||||
|
||||
/**
|
||||
@@ -73,7 +72,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, ObjectPostProcessorConfiguration.class,
|
||||
@Import({ WebSecurityConfiguration.class,
|
||||
SpringWebMvcImportSelector.class })
|
||||
@EnableGlobalAuthentication
|
||||
@Configuration
|
||||
|
||||
+17
-4
@@ -15,7 +15,14 @@
|
||||
*/
|
||||
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;
|
||||
@@ -24,8 +31,6 @@ 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
|
||||
@@ -36,12 +41,15 @@ import java.util.List;
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
class WebMvcSecurityConfiguration extends WebMvcConfigurerAdapter {
|
||||
class WebMvcSecurityConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware {
|
||||
private BeanResolver beanResolver;
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
argumentResolvers.add(new AuthenticationPrincipalArgumentResolver());
|
||||
AuthenticationPrincipalArgumentResolver authenticationPrincipalResolver = new AuthenticationPrincipalArgumentResolver();
|
||||
authenticationPrincipalResolver.setBeanResolver(beanResolver);
|
||||
argumentResolvers.add(authenticationPrincipalResolver);
|
||||
argumentResolvers
|
||||
.add(new org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver());
|
||||
argumentResolvers.add(new CsrfTokenArgumentResolver());
|
||||
@@ -51,4 +59,9 @@ class WebMvcSecurityConfiguration extends WebMvcConfigurerAdapter {
|
||||
public RequestDataValueProcessor requestDataValueProcessor() {
|
||||
return new CsrfRequestDataValueProcessor();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
this.beanResolver = new BeanFactoryResolver(applicationContext.getAutowireCapableBeanFactory());
|
||||
}
|
||||
}
|
||||
+49
-8
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -18,8 +18,10 @@ package org.springframework.security.config.annotation.web.configuration;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
@@ -32,6 +34,7 @@ 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;
|
||||
@@ -42,6 +45,7 @@ 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;
|
||||
@@ -57,8 +61,23 @@ 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.
|
||||
* 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>
|
||||
*
|
||||
* @see EnableWebSecurity
|
||||
*
|
||||
@@ -163,6 +182,7 @@ 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;
|
||||
@@ -174,12 +194,10 @@ public abstract class WebSecurityConfigurerAdapter implements
|
||||
|
||||
AuthenticationManager authenticationManager = authenticationManager();
|
||||
authenticationBuilder.parentAuthenticationManager(authenticationManager);
|
||||
Map<Class<? extends Object>, Object> sharedObjects = createSharedObjects();
|
||||
|
||||
http = new HttpSecurity(objectPostProcessor, authenticationBuilder,
|
||||
localConfigureAuthenticationBldr.getSharedObjects());
|
||||
http.setSharedObject(UserDetailsService.class, userDetailsService());
|
||||
http.setSharedObject(ApplicationContext.class, context);
|
||||
http.setSharedObject(ContentNegotiationStrategy.class, contentNegotiationStrategy);
|
||||
http.setSharedObject(AuthenticationTrustResolver.class, trustResolver);
|
||||
sharedObjects);
|
||||
if (!disableDefaults) {
|
||||
// @formatter:off
|
||||
http
|
||||
@@ -195,6 +213,13 @@ 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;
|
||||
@@ -375,6 +400,21 @@ public abstract class WebSecurityConfigurerAdapter implements
|
||||
this.authenticationConfiguration = authenticationConfiguration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the shared objects
|
||||
*
|
||||
* @return the shared Objects
|
||||
*/
|
||||
private Map<Class<? extends Object>, Object> createSharedObjects() {
|
||||
Map<Class<? extends Object>, Object> sharedObjects = new HashMap<Class<? extends Object>, Object>();
|
||||
sharedObjects.putAll(localConfigureAuthenticationBldr.getSharedObjects());
|
||||
sharedObjects.put(UserDetailsService.class, userDetailsService());
|
||||
sharedObjects.put(ApplicationContext.class, context);
|
||||
sharedObjects.put(ContentNegotiationStrategy.class, contentNegotiationStrategy);
|
||||
sharedObjects.put(AuthenticationTrustResolver.class, trustResolver);
|
||||
return sharedObjects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delays the use of the {@link UserDetailsService} from the
|
||||
* {@link AuthenticationManagerBuilder} to ensure that it has been fully configured.
|
||||
@@ -489,4 +529,5 @@ public abstract class WebSecurityConfigurerAdapter implements
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
abstract class AbstractHttpConfigurer<T extends AbstractHttpConfigurer<T, B>, B extends HttpSecurityBuilder<B>>
|
||||
public abstract class AbstractHttpConfigurer<T extends AbstractHttpConfigurer<T, B>, B extends HttpSecurityBuilder<B>>
|
||||
extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, B> {
|
||||
|
||||
/**
|
||||
|
||||
+34
-6
@@ -21,6 +21,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
import org.springframework.security.access.SecurityConfig;
|
||||
import org.springframework.security.config.annotation.ObjectPostProcessor;
|
||||
@@ -37,6 +38,7 @@ import org.springframework.security.web.access.channel.RetryWithHttpEntryPoint;
|
||||
import org.springframework.security.web.access.channel.RetryWithHttpsEntryPoint;
|
||||
import org.springframework.security.web.access.channel.SecureChannelProcessor;
|
||||
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
|
||||
/**
|
||||
@@ -136,7 +138,7 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>> e
|
||||
}
|
||||
|
||||
private ChannelRequestMatcherRegistry addAttribute(String attribute,
|
||||
List<RequestMatcher> matchers) {
|
||||
List<? extends RequestMatcher> matchers) {
|
||||
for (RequestMatcher matcher : matchers) {
|
||||
Collection<ConfigAttribute> attrs = Arrays
|
||||
.<ConfigAttribute> asList(new SecurityConfig(attribute));
|
||||
@@ -145,13 +147,25 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>> e
|
||||
return REGISTRY;
|
||||
}
|
||||
|
||||
public final class ChannelRequestMatcherRegistry extends
|
||||
AbstractConfigAttributeRequestMatcherRegistry<RequiresChannelUrl> {
|
||||
public final class ChannelRequestMatcherRegistry
|
||||
extends AbstractConfigAttributeRequestMatcherRegistry<RequiresChannelUrl> {
|
||||
|
||||
private ChannelRequestMatcherRegistry(ApplicationContext context) {
|
||||
setApplicationContext(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersRequiresChannelUrl mvcMatchers(HttpMethod method,
|
||||
String... mvcPatterns) {
|
||||
List<MvcRequestMatcher> mvcMatchers = createMvcMatchers(method, mvcPatterns);
|
||||
return new MvcMatchersRequiresChannelUrl(mvcMatchers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersRequiresChannelUrl mvcMatchers(String... patterns) {
|
||||
return mvcMatchers(null, patterns);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected RequiresChannelUrl chainRequestMatchersInternal(
|
||||
List<RequestMatcher> requestMatchers) {
|
||||
@@ -193,10 +207,24 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>> e
|
||||
}
|
||||
}
|
||||
|
||||
public final class RequiresChannelUrl {
|
||||
private List<RequestMatcher> requestMatchers;
|
||||
public final class MvcMatchersRequiresChannelUrl extends RequiresChannelUrl {
|
||||
|
||||
private RequiresChannelUrl(List<RequestMatcher> requestMatchers) {
|
||||
private MvcMatchersRequiresChannelUrl(List<MvcRequestMatcher> matchers) {
|
||||
super(matchers);
|
||||
}
|
||||
|
||||
public RequiresChannelUrl servletPath(String servletPath) {
|
||||
for (RequestMatcher matcher : this.requestMatchers) {
|
||||
((MvcRequestMatcher) matcher).setServletPath(servletPath);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public class RequiresChannelUrl {
|
||||
protected List<? extends RequestMatcher> requestMatchers;
|
||||
|
||||
private RequiresChannelUrl(List<? extends RequestMatcher> requestMatchers) {
|
||||
this.requestMatchers = requestMatchers;
|
||||
}
|
||||
|
||||
|
||||
+40
@@ -22,6 +22,7 @@ import java.util.List;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
@@ -36,6 +37,7 @@ import org.springframework.security.web.csrf.CsrfTokenRepository;
|
||||
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
|
||||
import org.springframework.security.web.csrf.LazyCsrfTokenRepository;
|
||||
import org.springframework.security.web.csrf.MissingCsrfTokenException;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
import org.springframework.security.web.session.InvalidSessionAccessDeniedHandler;
|
||||
import org.springframework.security.web.session.InvalidSessionStrategy;
|
||||
import org.springframework.security.web.util.matcher.AndRequestMatcher;
|
||||
@@ -276,6 +278,20 @@ public final class CsrfConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
setApplicationContext(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersIgnoreCsrfProtectionRegistry mvcMatchers(HttpMethod method,
|
||||
String... mvcPatterns) {
|
||||
List<MvcRequestMatcher> mvcMatchers = createMvcMatchers(method, mvcPatterns);
|
||||
CsrfConfigurer.this.ignoredCsrfProtectionMatchers.addAll(mvcMatchers);
|
||||
return new MvcMatchersIgnoreCsrfProtectionRegistry(getApplicationContext(),
|
||||
mvcMatchers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersIgnoreCsrfProtectionRegistry mvcMatchers(String... mvcPatterns) {
|
||||
return mvcMatchers(null, mvcPatterns);
|
||||
}
|
||||
|
||||
public CsrfConfigurer<H> and() {
|
||||
return CsrfConfigurer.this;
|
||||
}
|
||||
@@ -287,4 +303,28 @@ public final class CsrfConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An {@link IgnoreCsrfProtectionRegistry} that allows optionally configuring the
|
||||
* {@link MvcRequestMatcher#setMethod(HttpMethod)}
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
private final class MvcMatchersIgnoreCsrfProtectionRegistry
|
||||
extends IgnoreCsrfProtectionRegistry {
|
||||
private final List<MvcRequestMatcher> mvcMatchers;
|
||||
|
||||
private MvcMatchersIgnoreCsrfProtectionRegistry(ApplicationContext context,
|
||||
List<MvcRequestMatcher> mvcMatchers) {
|
||||
super(context);
|
||||
this.mvcMatchers = mvcMatchers;
|
||||
}
|
||||
|
||||
public IgnoreCsrfProtectionRegistry servletPath(String servletPath) {
|
||||
for (MvcRequestMatcher matcher : this.mvcMatchers) {
|
||||
matcher.setServletPath(servletPath);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
-3
@@ -21,6 +21,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.access.AccessDecisionVoter;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
import org.springframework.security.access.SecurityConfig;
|
||||
@@ -30,10 +31,12 @@ 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;
|
||||
import org.springframework.security.web.access.expression.WebExpressionVoter;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -111,6 +114,16 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
|
||||
setApplicationContext(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersAuthorizedUrl mvcMatchers(HttpMethod method, String... mvcPatterns) {
|
||||
return new MvcMatchersAuthorizedUrl(createMvcMatchers(method, mvcPatterns));
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersAuthorizedUrl mvcMatchers(String... patterns) {
|
||||
return mvcMatchers(null, patterns);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final AuthorizedUrl chainRequestMatchersInternal(
|
||||
List<RequestMatcher> requestMatchers) {
|
||||
@@ -204,6 +217,11 @@ 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);
|
||||
@@ -241,8 +259,32 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
|
||||
return "hasIpAddress('" + ipAddressExpression + "')";
|
||||
}
|
||||
|
||||
public final class AuthorizedUrl {
|
||||
private List<RequestMatcher> requestMatchers;
|
||||
/**
|
||||
* An {@link AuthorizedUrl} that allows optionally configuring the
|
||||
* {@link MvcRequestMatcher#setMethod(HttpMethod)}
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class MvcMatchersAuthorizedUrl extends AuthorizedUrl {
|
||||
/**
|
||||
* Creates a new instance
|
||||
*
|
||||
* @param requestMatchers the {@link RequestMatcher} instances to map
|
||||
*/
|
||||
private MvcMatchersAuthorizedUrl(List<MvcRequestMatcher> requestMatchers) {
|
||||
super(requestMatchers);
|
||||
}
|
||||
|
||||
public AuthorizedUrl servletPath(String servletPath) {
|
||||
for (MvcRequestMatcher matcher : (List<MvcRequestMatcher>) getMatchers()) {
|
||||
matcher.setServletPath(servletPath);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public class AuthorizedUrl {
|
||||
private List<? extends RequestMatcher> requestMatchers;
|
||||
private boolean not;
|
||||
|
||||
/**
|
||||
@@ -250,10 +292,14 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
|
||||
*
|
||||
* @param requestMatchers the {@link RequestMatcher} instances to map
|
||||
*/
|
||||
private AuthorizedUrl(List<RequestMatcher> requestMatchers) {
|
||||
private AuthorizedUrl(List<? extends RequestMatcher> requestMatchers) {
|
||||
this.requestMatchers = requestMatchers;
|
||||
}
|
||||
|
||||
protected List<? extends RequestMatcher> getMatchers() {
|
||||
return this.requestMatchers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Negates the following expression.
|
||||
*
|
||||
|
||||
+69
@@ -28,6 +28,7 @@ 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;
|
||||
@@ -56,6 +57,7 @@ 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
|
||||
@@ -78,6 +80,8 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
|
||||
private final ContentSecurityPolicyConfig contentSecurityPolicy = new ContentSecurityPolicyConfig();
|
||||
|
||||
private final ReferrerPolicyConfig referrerPolicy = new ReferrerPolicyConfig();
|
||||
|
||||
/**
|
||||
* Creates a new instance
|
||||
*
|
||||
@@ -770,6 +774,7 @@ 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;
|
||||
}
|
||||
@@ -779,4 +784,68 @@ 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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+10
-3
@@ -38,6 +38,7 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi
|
||||
import org.springframework.security.web.util.matcher.AndRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.OrRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.web.accept.ContentNegotiationStrategy;
|
||||
@@ -78,6 +79,10 @@ import org.springframework.web.accept.HeaderContentNegotiationStrategy;
|
||||
*/
|
||||
public final class HttpBasicConfigurer<B extends HttpSecurityBuilder<B>> extends
|
||||
AbstractHttpConfigurer<HttpBasicConfigurer<B>, B> {
|
||||
|
||||
private static final RequestHeaderRequestMatcher X_REQUESTED_WITH = new RequestHeaderRequestMatcher("X-Requested-With",
|
||||
"XMLHttpRequest");
|
||||
|
||||
private static final String DEFAULT_REALM = "Realm";
|
||||
|
||||
private AuthenticationEntryPoint authenticationEntryPoint;
|
||||
@@ -93,8 +98,7 @@ public final class HttpBasicConfigurer<B extends HttpSecurityBuilder<B>> extends
|
||||
realmName(DEFAULT_REALM);
|
||||
|
||||
LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<RequestMatcher, AuthenticationEntryPoint>();
|
||||
entryPoints.put(new RequestHeaderRequestMatcher("X-Requested-With",
|
||||
"XMLHttpRequest"), new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
|
||||
entryPoints.put(X_REQUESTED_WITH, new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
|
||||
|
||||
DelegatingAuthenticationEntryPoint defaultEntryPoint = new DelegatingAuthenticationEntryPoint(
|
||||
entryPoints);
|
||||
@@ -157,6 +161,7 @@ public final class HttpBasicConfigurer<B extends HttpSecurityBuilder<B>> extends
|
||||
if (contentNegotiationStrategy == null) {
|
||||
contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
|
||||
}
|
||||
|
||||
MediaTypeRequestMatcher restMatcher = new MediaTypeRequestMatcher(
|
||||
contentNegotiationStrategy, MediaType.APPLICATION_ATOM_XML,
|
||||
MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON,
|
||||
@@ -167,9 +172,11 @@ public final class HttpBasicConfigurer<B extends HttpSecurityBuilder<B>> extends
|
||||
RequestMatcher notHtmlMatcher = new NegatedRequestMatcher(
|
||||
new MediaTypeRequestMatcher(contentNegotiationStrategy,
|
||||
MediaType.TEXT_HTML));
|
||||
RequestMatcher preferredMatcher = new AndRequestMatcher(
|
||||
RequestMatcher restNotHtmlMatcher = new AndRequestMatcher(
|
||||
Arrays.<RequestMatcher>asList(notHtmlMatcher, restMatcher));
|
||||
|
||||
RequestMatcher preferredMatcher = new OrRequestMatcher(Arrays.asList(X_REQUESTED_WITH, restNotHtmlMatcher));
|
||||
|
||||
registerDefaultEntryPoint(http, preferredMatcher);
|
||||
registerDefaultLogoutSuccessHandler(http, preferredMatcher);
|
||||
}
|
||||
|
||||
+11
-1
@@ -19,10 +19,12 @@ 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;
|
||||
@@ -91,7 +93,15 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+140
-51
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -33,6 +33,7 @@ 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;
|
||||
@@ -48,8 +49,10 @@ 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;
|
||||
|
||||
/**
|
||||
@@ -89,13 +92,14 @@ 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 = DEFAULT_SESSION_FIXATION_STRATEGY;
|
||||
private SessionAuthenticationStrategy sessionFixationAuthenticationStrategy = this.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;
|
||||
@@ -105,6 +109,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
private boolean enableSessionUrlRewriting;
|
||||
private String invalidSessionUrl;
|
||||
private String sessionAuthenticationErrorUrl;
|
||||
private AuthenticationFailureHandler sessionAuthenticationFailureHandler;
|
||||
|
||||
/**
|
||||
* Creates a new instance
|
||||
@@ -131,10 +136,12 @@ 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;
|
||||
@@ -156,6 +163,22 @@ 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
|
||||
@@ -198,7 +221,8 @@ 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
|
||||
@@ -244,7 +268,8 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
*/
|
||||
private void setSessionFixationAuthenticationStrategy(
|
||||
SessionAuthenticationStrategy sessionFixationAuthenticationStrategy) {
|
||||
this.sessionFixationAuthenticationStrategy = postProcess(sessionFixationAuthenticationStrategy);
|
||||
this.sessionFixationAuthenticationStrategy = postProcess(
|
||||
sessionFixationAuthenticationStrategy);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -273,7 +298,8 @@ 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;
|
||||
}
|
||||
|
||||
@@ -288,7 +314,8 @@ 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;
|
||||
}
|
||||
|
||||
@@ -301,7 +328,8 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -326,6 +354,12 @@ 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
|
||||
@@ -384,7 +418,8 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
}
|
||||
else {
|
||||
HttpSessionSecurityContextRepository httpSecurityRepository = new HttpSessionSecurityContextRepository();
|
||||
httpSecurityRepository.setDisableUrlRewriting(!enableSessionUrlRewriting);
|
||||
httpSecurityRepository
|
||||
.setDisableUrlRewriting(!this.enableSessionUrlRewriting);
|
||||
httpSecurityRepository.setAllowSessionCreation(isAllowSessionCreation());
|
||||
AuthenticationTrustResolver trustResolver = http
|
||||
.getSharedObject(AuthenticationTrustResolver.class);
|
||||
@@ -413,15 +448,18 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
.getSharedObject(SecurityContextRepository.class);
|
||||
SessionManagementFilter sessionManagementFilter = new SessionManagementFilter(
|
||||
securityContextRepository, getSessionAuthenticationStrategy(http));
|
||||
if (sessionAuthenticationErrorUrl != null) {
|
||||
sessionManagementFilter
|
||||
.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(
|
||||
sessionAuthenticationErrorUrl));
|
||||
if (this.sessionAuthenticationErrorUrl != null) {
|
||||
sessionManagementFilter.setAuthenticationFailureHandler(
|
||||
new SimpleUrlAuthenticationFailureHandler(
|
||||
this.sessionAuthenticationErrorUrl));
|
||||
}
|
||||
InvalidSessionStrategy strategy = getInvalidSessionStrategy();
|
||||
if (strategy != null) {
|
||||
sessionManagementFilter
|
||||
.setInvalidSessionStrategy(strategy);
|
||||
sessionManagementFilter.setInvalidSessionStrategy(strategy);
|
||||
}
|
||||
AuthenticationFailureHandler failureHandler = getSessionAuthenticationFailureHandler();
|
||||
if (failureHandler != null) {
|
||||
sessionManagementFilter.setAuthenticationFailureHandler(failureHandler);
|
||||
}
|
||||
AuthenticationTrustResolver trustResolver = http
|
||||
.getSharedObject(AuthenticationTrustResolver.class);
|
||||
@@ -432,13 +470,23 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
|
||||
http.addFilter(sessionManagementFilter);
|
||||
if (isConcurrentSessionControlEnabled()) {
|
||||
ConcurrentSessionFilter concurrentSessionFilter = new ConcurrentSessionFilter(
|
||||
getSessionRegistry(http), expiredUrl);
|
||||
ConcurrentSessionFilter concurrentSessionFilter = createConccurencyFilter(http);
|
||||
|
||||
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
|
||||
@@ -447,14 +495,53 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return the {@link InvalidSessionStrategy} to use
|
||||
*/
|
||||
InvalidSessionStrategy getInvalidSessionStrategy() {
|
||||
if(invalidSessionStrategy != null) {
|
||||
return invalidSessionStrategy;
|
||||
if (this.invalidSessionStrategy != null) {
|
||||
return this.invalidSessionStrategy;
|
||||
}
|
||||
if (invalidSessionUrl != null) {
|
||||
invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy(
|
||||
invalidSessionUrl);
|
||||
if (this.invalidSessionUrl != null) {
|
||||
this.invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy(
|
||||
this.invalidSessionUrl);
|
||||
}
|
||||
return invalidSessionStrategy;
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -462,7 +549,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return the {@link SessionCreationPolicy}
|
||||
*/
|
||||
SessionCreationPolicy getSessionCreationPolicy() {
|
||||
return sessionPolicy;
|
||||
return this.sessionPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -471,8 +558,8 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return true if the {@link SessionCreationPolicy} allows session creation
|
||||
*/
|
||||
private boolean isAllowSessionCreation() {
|
||||
return SessionCreationPolicy.ALWAYS == sessionPolicy
|
||||
|| SessionCreationPolicy.IF_REQUIRED == sessionPolicy;
|
||||
return SessionCreationPolicy.ALWAYS == this.sessionPolicy
|
||||
|| SessionCreationPolicy.IF_REQUIRED == this.sessionPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -480,7 +567,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return
|
||||
*/
|
||||
private boolean isStateless() {
|
||||
return SessionCreationPolicy.STATELESS == sessionPolicy;
|
||||
return SessionCreationPolicy.STATELESS == this.sessionPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -491,50 +578,52 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return the {@link SessionAuthenticationStrategy} to use
|
||||
*/
|
||||
private SessionAuthenticationStrategy getSessionAuthenticationStrategy(H http) {
|
||||
if (sessionAuthenticationStrategy != null) {
|
||||
return sessionAuthenticationStrategy;
|
||||
if (this.sessionAuthenticationStrategy != null) {
|
||||
return this.sessionAuthenticationStrategy;
|
||||
}
|
||||
List<SessionAuthenticationStrategy> delegateStrategies = sessionAuthenticationStrategies;
|
||||
List<SessionAuthenticationStrategy> delegateStrategies = this.sessionAuthenticationStrategies;
|
||||
SessionAuthenticationStrategy defaultSessionAuthenticationStrategy;
|
||||
if (providedSessionAuthenticationStrategy == null) {
|
||||
if (this.providedSessionAuthenticationStrategy == null) {
|
||||
// If a user provided SessionAuthenticationStrategy is not supplied
|
||||
// then default to SessionFixationProtectionStrategy
|
||||
defaultSessionAuthenticationStrategy = postProcess(sessionFixationAuthenticationStrategy);
|
||||
} else {
|
||||
defaultSessionAuthenticationStrategy = providedSessionAuthenticationStrategy;
|
||||
defaultSessionAuthenticationStrategy = postProcess(
|
||||
this.sessionFixationAuthenticationStrategy);
|
||||
}
|
||||
else {
|
||||
defaultSessionAuthenticationStrategy = this.providedSessionAuthenticationStrategy;
|
||||
}
|
||||
if (isConcurrentSessionControlEnabled()) {
|
||||
SessionRegistry sessionRegistry = getSessionRegistry(http);
|
||||
ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlStrategy = new ConcurrentSessionControlAuthenticationStrategy(
|
||||
sessionRegistry);
|
||||
concurrentSessionControlStrategy.setMaximumSessions(maximumSessions);
|
||||
concurrentSessionControlStrategy.setMaximumSessions(this.maximumSessions);
|
||||
concurrentSessionControlStrategy
|
||||
.setExceptionIfMaximumExceeded(maxSessionsPreventsLogin);
|
||||
concurrentSessionControlStrategy = postProcess(concurrentSessionControlStrategy);
|
||||
.setExceptionIfMaximumExceeded(this.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);
|
||||
}
|
||||
sessionAuthenticationStrategy = postProcess(new CompositeSessionAuthenticationStrategy(
|
||||
delegateStrategies));
|
||||
return sessionAuthenticationStrategy;
|
||||
this.sessionAuthenticationStrategy = postProcess(
|
||||
new CompositeSessionAuthenticationStrategy(delegateStrategies));
|
||||
return this.sessionAuthenticationStrategy;
|
||||
}
|
||||
|
||||
private SessionRegistry getSessionRegistry(H http) {
|
||||
if (sessionRegistry == null) {
|
||||
if (this.sessionRegistry == null) {
|
||||
SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
|
||||
registerDelegateApplicationListener(http, sessionRegistry);
|
||||
this.sessionRegistry = sessionRegistry;
|
||||
}
|
||||
return sessionRegistry;
|
||||
return this.sessionRegistry;
|
||||
}
|
||||
|
||||
private void registerDelegateApplicationListener(H http,
|
||||
@@ -558,7 +647,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return
|
||||
*/
|
||||
private boolean isConcurrentSessionControlEnabled() {
|
||||
return maximumSessions != null;
|
||||
return this.maximumSessions != null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+46
-3
@@ -20,6 +20,7 @@ import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.access.AccessDecisionManager;
|
||||
import org.springframework.security.access.AccessDecisionVoter;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
@@ -28,8 +29,10 @@ import org.springframework.security.access.vote.AuthenticatedVoter;
|
||||
import org.springframework.security.access.vote.RoleVoter;
|
||||
import org.springframework.security.config.annotation.ObjectPostProcessor;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer.AuthorizedUrl;
|
||||
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
|
||||
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
@@ -126,6 +129,17 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
setApplicationContext(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersAuthorizedUrl mvcMatchers(HttpMethod method,
|
||||
String... mvcPatterns) {
|
||||
return new MvcMatchersAuthorizedUrl(createMvcMatchers(method, mvcPatterns));
|
||||
}
|
||||
|
||||
@Override
|
||||
public MvcMatchersAuthorizedUrl mvcMatchers(String... patterns) {
|
||||
return mvcMatchers(null, patterns);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final AuthorizedUrl chainRequestMatchersInternal(
|
||||
List<RequestMatcher> requestMatchers) {
|
||||
@@ -237,6 +251,31 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
return authorities;
|
||||
}
|
||||
|
||||
/**
|
||||
* An {@link AuthorizedUrl} that allows optionally configuring the
|
||||
* {@link MvcRequestMatcher#setMethod(HttpMethod)}
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public final class MvcMatchersAuthorizedUrl extends AuthorizedUrl {
|
||||
/**
|
||||
* Creates a new instance
|
||||
*
|
||||
* @param requestMatchers the {@link RequestMatcher} instances to map
|
||||
*/
|
||||
private MvcMatchersAuthorizedUrl(List<MvcRequestMatcher> requestMatchers) {
|
||||
super(requestMatchers);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public AuthorizedUrl servletPath(String servletPath) {
|
||||
for (MvcRequestMatcher matcher : (List<MvcRequestMatcher>) getMatchers()) {
|
||||
matcher.setServletPath(servletPath);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps the specified {@link RequestMatcher} instances to {@link ConfigAttribute}
|
||||
* instances.
|
||||
@@ -244,15 +283,15 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public final class AuthorizedUrl {
|
||||
private final List<RequestMatcher> requestMatchers;
|
||||
public class AuthorizedUrl {
|
||||
private final List<? extends RequestMatcher> requestMatchers;
|
||||
|
||||
/**
|
||||
* Creates a new instance
|
||||
* @param requestMatchers the {@link RequestMatcher} instances to map to some
|
||||
* {@link ConfigAttribute} instances.
|
||||
*/
|
||||
private AuthorizedUrl(List<RequestMatcher> requestMatchers) {
|
||||
private AuthorizedUrl(List<? extends RequestMatcher> requestMatchers) {
|
||||
Assert.notEmpty(requestMatchers,
|
||||
"requestMatchers must contain at least one value");
|
||||
this.requestMatchers = requestMatchers;
|
||||
@@ -318,5 +357,9 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
addMapping(requestMatchers, SecurityConfig.createList(attributes));
|
||||
return UrlAuthorizationConfigurer.this.REGISTRY;
|
||||
}
|
||||
|
||||
protected List<? extends RequestMatcher> getMatchers() {
|
||||
return this.requestMatchers;
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-10
@@ -13,22 +13,30 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.integration;
|
||||
package org.springframework.security.config.core;
|
||||
|
||||
import org.testng.annotations.*;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
* Allows providing defaults for {@link GrantedAuthority}
|
||||
*
|
||||
* @author Eddú Meléndez
|
||||
* @since 4.2.0
|
||||
*/
|
||||
public class LdapWebAppTests extends AbstractWebServerIntegrationTests {
|
||||
public final class GrantedAuthorityDefaults {
|
||||
|
||||
protected String getContextConfigLocations() {
|
||||
return "/WEB-INF/http-security.xml /WEB-INF/ldap-provider.xml";
|
||||
private final String rolePrefix;
|
||||
|
||||
public GrantedAuthorityDefaults(String rolePrefix) {
|
||||
this.rolePrefix = rolePrefix;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doSomething() {
|
||||
|
||||
/**
|
||||
* The default prefix used with role based authorization. Default is "ROLE_".
|
||||
*
|
||||
* @return the default role prefix
|
||||
*/
|
||||
public String getRolePrefix() {
|
||||
return this.rolePrefix;
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -481,7 +481,7 @@ final class AuthenticationConfigBuilder {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper.class));
|
||||
|
||||
String roles = jeeElt.getAttribute(ATT_MAPPABLE_ROLES);
|
||||
Assert.state(StringUtils.hasText(roles));
|
||||
Assert.hasLength(roles, "roles is expected to have length");
|
||||
BeanDefinitionBuilder rolesBuilder = BeanDefinitionBuilder
|
||||
.rootBeanDefinition(StringUtils.class);
|
||||
rolesBuilder.addConstructorArgValue(roles);
|
||||
|
||||
+39
-11
@@ -15,11 +15,16 @@
|
||||
*/
|
||||
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;
|
||||
@@ -35,7 +40,6 @@ 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;
|
||||
|
||||
/**
|
||||
* Allows for convenient creation of a {@link FilterInvocationSecurityMetadataSource} bean
|
||||
@@ -48,12 +52,13 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
|
||||
private static final String ATT_HTTP_METHOD = "method";
|
||||
private static final String ATT_PATTERN = "pattern";
|
||||
private static final String ATT_ACCESS = "access";
|
||||
private static final String ATT_SERVLET_PATH = "servlet-path";
|
||||
private static final Log logger = LogFactory
|
||||
.getLog(FilterInvocationSecurityMetadataSourceParser.class);
|
||||
|
||||
public BeanDefinition parse(Element element, ParserContext parserContext) {
|
||||
List<Element> interceptUrls = DomUtils.getChildElementsByTagName(element,
|
||||
"intercept-url");
|
||||
Elements.INTERCEPT_URL);
|
||||
|
||||
// Check for attributes that aren't allowed in this context
|
||||
for (Element elt : interceptUrls) {
|
||||
@@ -71,6 +76,12 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
|
||||
"The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS
|
||||
+ "' isn't allowed here.", elt);
|
||||
}
|
||||
|
||||
if (StringUtils.hasLength(elt.getAttribute(ATT_SERVLET_PATH))) {
|
||||
parserContext.getReaderContext().error(
|
||||
"The attribute '" + ATT_SERVLET_PATH
|
||||
+ "' isn't allowed here.", elt);
|
||||
}
|
||||
}
|
||||
|
||||
BeanDefinition mds = createSecurityMetadataSource(interceptUrls, false, element,
|
||||
@@ -91,7 +102,7 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
|
||||
MatcherType matcherType = MatcherType.fromElement(httpElt);
|
||||
boolean useExpressions = isUseExpressions(httpElt);
|
||||
|
||||
ManagedMap<BeanDefinition, BeanDefinition> requestToAttributesMap = parseInterceptUrlsForFilterInvocationRequestMap(
|
||||
ManagedMap<BeanMetadataElement, BeanDefinition> requestToAttributesMap = parseInterceptUrlsForFilterInvocationRequestMap(
|
||||
matcherType, interceptUrls, useExpressions, addAllAuth, pc);
|
||||
BeanDefinitionBuilder fidsBuilder;
|
||||
|
||||
@@ -126,8 +137,7 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
|
||||
}
|
||||
|
||||
static String registerDefaultExpressionHandler(ParserContext pc) {
|
||||
BeanDefinition expressionHandler = BeanDefinitionBuilder.rootBeanDefinition(
|
||||
DefaultWebSecurityExpressionHandler.class).getBeanDefinition();
|
||||
BeanDefinition expressionHandler = GrantedAuthorityDefaultsParserUtils.registerWithDefaultRolePrefix(pc, DefaultWebSecurityExpressionHandlerBeanFactory.class);
|
||||
String expressionHandlerRef = pc.getReaderContext().generateBeanName(
|
||||
expressionHandler);
|
||||
pc.registerBeanComponent(new BeanComponentDefinition(expressionHandler,
|
||||
@@ -141,11 +151,11 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
|
||||
return !StringUtils.hasText(useExpressions) || "true".equals(useExpressions);
|
||||
}
|
||||
|
||||
private static ManagedMap<BeanDefinition, BeanDefinition> parseInterceptUrlsForFilterInvocationRequestMap(
|
||||
private static ManagedMap<BeanMetadataElement, BeanDefinition> parseInterceptUrlsForFilterInvocationRequestMap(
|
||||
MatcherType matcherType, List<Element> urlElts, boolean useExpressions,
|
||||
boolean addAuthenticatedAll, ParserContext parserContext) {
|
||||
|
||||
ManagedMap<BeanDefinition, BeanDefinition> filterInvocationDefinitionMap = new ManagedMap<BeanDefinition, BeanDefinition>();
|
||||
ManagedMap<BeanMetadataElement, BeanDefinition> filterInvocationDefinitionMap = new ManagedMap<BeanMetadataElement, BeanDefinition>();
|
||||
|
||||
for (Element urlElt : urlElts) {
|
||||
String access = urlElt.getAttribute(ATT_ACCESS);
|
||||
@@ -154,8 +164,10 @@ 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 (!StringUtils.hasText(path)) {
|
||||
if (!hasMatcherRef && !StringUtils.hasText(path)) {
|
||||
parserContext.getReaderContext().error(
|
||||
"path attribute cannot be empty or null", urlElt);
|
||||
}
|
||||
@@ -165,8 +177,16 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
|
||||
method = null;
|
||||
}
|
||||
|
||||
BeanDefinition matcher = matcherType.createMatcher(parserContext, path,
|
||||
method);
|
||||
String servletPath = urlElt.getAttribute(ATT_SERVLET_PATH);
|
||||
if (!StringUtils.hasText(servletPath)) {
|
||||
servletPath = null;
|
||||
} else if (!MatcherType.mvc.equals(matcherType)) {
|
||||
parserContext.getReaderContext().error(
|
||||
ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'", urlElt);
|
||||
}
|
||||
|
||||
BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference(matcherRef) : matcherType.createMatcher(parserContext, path,
|
||||
method, servletPath);
|
||||
BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder
|
||||
.rootBeanDefinition(SecurityConfig.class);
|
||||
|
||||
@@ -174,7 +194,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
|
||||
// ExpressionFilterInvocationSecurityMetadataSource
|
||||
// ExpressionBasedFilterInvocationSecurityMetadataSource
|
||||
attributeBuilder.addConstructorArgValue(new String[] { access });
|
||||
attributeBuilder.setFactoryMethod("createList");
|
||||
|
||||
@@ -208,4 +228,12 @@ 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* 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() {}
|
||||
}
|
||||
+29
-7
@@ -31,6 +31,7 @@ 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;
|
||||
@@ -45,6 +46,7 @@ import org.w3c.dom.Node;
|
||||
*
|
||||
* @author Marten Deinum
|
||||
* @author Tim Ysewyn
|
||||
* @author Eddú Meléndez
|
||||
* @since 3.2
|
||||
*/
|
||||
public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
|
||||
@@ -82,6 +84,7 @@ 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";
|
||||
|
||||
@@ -109,15 +112,17 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
|
||||
|
||||
parseContentSecurityPolicyElement(disabled, element, parserContext);
|
||||
|
||||
parseReferrerPolicyElement(element, parserContext);
|
||||
|
||||
parseHeaderElements(element);
|
||||
|
||||
if (disabled) {
|
||||
if (!headerWriters.isEmpty()) {
|
||||
parserContext
|
||||
.getReaderContext()
|
||||
.error("Cannot specify <headers disabled=\"true\"> with child elements.",
|
||||
element);
|
||||
}
|
||||
boolean noWriters = headerWriters.isEmpty();
|
||||
if (disabled && !noWriters) {
|
||||
parserContext
|
||||
.getReaderContext()
|
||||
.error("Cannot specify <headers disabled=\"true\"> with child elements.",
|
||||
element);
|
||||
} else if (noWriters) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -291,6 +296,23 @@ 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(
|
||||
|
||||
+75
-15
@@ -15,9 +15,6 @@
|
||||
*/
|
||||
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;
|
||||
@@ -25,6 +22,8 @@ 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;
|
||||
@@ -41,6 +40,7 @@ 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,12 +70,30 @@ 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 org.w3c.dom.Element;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Stateful class which helps HttpSecurityBDP to create the configuration for the
|
||||
@@ -97,7 +115,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";
|
||||
@@ -289,6 +307,7 @@ class HttpConfigurationBuilder {
|
||||
|
||||
String sessionFixationAttribute = null;
|
||||
String invalidSessionUrl = null;
|
||||
String invalidSessionStrategyRef = null;
|
||||
String sessionAuthStratRef = null;
|
||||
String errorUrl = null;
|
||||
|
||||
@@ -304,6 +323,8 @@ 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);
|
||||
@@ -311,6 +332,11 @@ 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(
|
||||
@@ -438,12 +464,16 @@ 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);
|
||||
@@ -454,6 +484,7 @@ 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";
|
||||
|
||||
@@ -489,10 +520,20 @@ 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)) {
|
||||
WebConfigUtils.validateHttpRedirect(expiryUrl, pc, source);
|
||||
filterBuilder.addConstructorArgValue(expiryUrl);
|
||||
BeanDefinitionBuilder expiredSessionBldr = BeanDefinitionBuilder
|
||||
.rootBeanDefinition(SimpleRedirectSessionInformationExpiredStrategy.class);
|
||||
expiredSessionBldr.addConstructorArgValue(expiryUrl);
|
||||
filterBuilder.addConstructorArgValue(expiredSessionBldr.getBeanDefinition());
|
||||
} else if (StringUtils.hasText(expiredSessionStrategyRef)) {
|
||||
filterBuilder.addConstructorArgReference(expiredSessionStrategyRef);
|
||||
}
|
||||
|
||||
pc.popAndRegisterContainingComponent();
|
||||
@@ -520,8 +561,7 @@ class HttpConfigurationBuilder {
|
||||
}
|
||||
|
||||
if ("true".equals(provideServletApi)) {
|
||||
servApiFilter = new RootBeanDefinition(
|
||||
SecurityContextHolderAwareRequestFilter.class);
|
||||
servApiFilter = GrantedAuthorityDefaultsParserUtils.registerWithDefaultRolePrefix(pc, SecurityContextHolderAwareRequestFilterBeanFactory.class);
|
||||
servApiFilter.getPropertyValues().add("authenticationManager",
|
||||
authenticationManager);
|
||||
}
|
||||
@@ -543,7 +583,7 @@ class HttpConfigurationBuilder {
|
||||
}
|
||||
|
||||
private void createChannelProcessingFilter() {
|
||||
ManagedMap<BeanDefinition, BeanDefinition> channelRequestMap = parseInterceptUrlsForChannelSecurity();
|
||||
ManagedMap<BeanMetadataElement, BeanDefinition> channelRequestMap = parseInterceptUrlsForChannelSecurity();
|
||||
|
||||
if (channelRequestMap.isEmpty()) {
|
||||
return;
|
||||
@@ -597,15 +637,17 @@ class HttpConfigurationBuilder {
|
||||
* will be empty unless the <tt>requires-channel</tt> attribute has been used on a URL
|
||||
* path.
|
||||
*/
|
||||
private ManagedMap<BeanDefinition, BeanDefinition> parseInterceptUrlsForChannelSecurity() {
|
||||
private ManagedMap<BeanMetadataElement, BeanDefinition> parseInterceptUrlsForChannelSecurity() {
|
||||
|
||||
ManagedMap<BeanDefinition, BeanDefinition> channelRequestMap = new ManagedMap<BeanDefinition, BeanDefinition>();
|
||||
ManagedMap<BeanMetadataElement, BeanDefinition> channelRequestMap = new ManagedMap<BeanMetadataElement, 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 (!StringUtils.hasText(path)) {
|
||||
if (!hasMatcherRef && !StringUtils.hasText(path)) {
|
||||
pc.getReaderContext().error("pattern attribute cannot be empty or null",
|
||||
urlElt);
|
||||
}
|
||||
@@ -613,7 +655,7 @@ class HttpConfigurationBuilder {
|
||||
String requiredChannel = urlElt.getAttribute(ATT_REQUIRES_CHANNEL);
|
||||
|
||||
if (StringUtils.hasText(requiredChannel)) {
|
||||
BeanDefinition matcher = matcherType.createMatcher(pc, path, method);
|
||||
BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference(matcherRef) : matcherType.createMatcher(pc, path, method);
|
||||
|
||||
RootBeanDefinition channelAttributes = new RootBeanDefinition(
|
||||
ChannelAttributeFactory.class);
|
||||
@@ -692,7 +734,7 @@ class HttpConfigurationBuilder {
|
||||
voters.add(expressionVoter.getBeanDefinition());
|
||||
}
|
||||
else {
|
||||
voters.add(new RootBeanDefinition(RoleVoter.class));
|
||||
voters.add(GrantedAuthorityDefaultsParserUtils.registerWithDefaultRolePrefix(pc, RoleVoterBeanFactory.class));
|
||||
voters.add(new RootBeanDefinition(AuthenticatedVoter.class));
|
||||
}
|
||||
accessDecisionMgr = new RootBeanDefinition(AffirmativeBased.class);
|
||||
@@ -829,4 +871,22 @@ 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
|
||||
.getLog(HttpSecurityBeanDefinitionParser.class);
|
||||
|
||||
private static final String ATT_AUTHENTICATION_MANAGER_REF = "authentication-manager-ref";
|
||||
private static final String ATT_REQUEST_MATCHER_REF = "request-matcher-ref";
|
||||
static final String ATT_REQUEST_MATCHER_REF = "request-matcher-ref";
|
||||
static final String ATT_PATH_PATTERN = "pattern";
|
||||
static final String ATT_HTTP_METHOD = "method";
|
||||
|
||||
|
||||
@@ -49,6 +49,10 @@ public enum MatcherType {
|
||||
}
|
||||
|
||||
public BeanDefinition createMatcher(ParserContext pc, String path, String method) {
|
||||
return createMatcher(pc, path, method, null);
|
||||
}
|
||||
|
||||
public BeanDefinition createMatcher(ParserContext pc, String path, String method, String servletPath) {
|
||||
if (("/**".equals(path) || "**".equals(path)) && method == null) {
|
||||
return new RootBeanDefinition(AnyRequestMatcher.class);
|
||||
}
|
||||
@@ -74,6 +78,7 @@ public enum MatcherType {
|
||||
matcherBldr.addConstructorArgValue(path);
|
||||
if (this == mvc) {
|
||||
matcherBldr.addPropertyValue("method", method);
|
||||
matcherBldr.addPropertyValue("servletPath", servletPath);
|
||||
}
|
||||
else {
|
||||
matcherBldr.addConstructorArgValue(method);
|
||||
|
||||
+50
-4
@@ -45,6 +45,8 @@ 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;
|
||||
@@ -71,6 +73,7 @@ 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;
|
||||
@@ -198,8 +201,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
|
||||
expressionHandlerRef));
|
||||
}
|
||||
else {
|
||||
BeanDefinition expressionHandler = new RootBeanDefinition(
|
||||
DefaultMethodSecurityExpressionHandler.class);
|
||||
RootBeanDefinition expressionHandler = registerWithDefaultRolePrefix(pc, DefaultMethodSecurityExpressionHandlerBeanFactory.class);
|
||||
|
||||
expressionHandlerRef = pc.getReaderContext().generateBeanName(
|
||||
expressionHandler);
|
||||
pc.registerBeanComponent(new BeanComponentDefinition(
|
||||
@@ -240,8 +243,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
|
||||
}
|
||||
|
||||
if (jsr250Enabled) {
|
||||
delegates.add(BeanDefinitionBuilder.rootBeanDefinition(
|
||||
Jsr250MethodSecurityMetadataSource.class).getBeanDefinition());
|
||||
RootBeanDefinition jsrMetadataSource = registerWithDefaultRolePrefix(pc, Jsr250MethodSecurityMetadataSourceBeanFactory.class);
|
||||
delegates.add(jsrMetadataSource);
|
||||
}
|
||||
|
||||
// Now create a Map<String, ConfigAttribute> for each <protect-pointcut>
|
||||
@@ -474,6 +477,17 @@ 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.
|
||||
@@ -522,6 +536,38 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
|
||||
}
|
||||
}
|
||||
|
||||
static class Jsr250MethodSecurityMetadataSourceBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
|
||||
private Jsr250MethodSecurityMetadataSource source = new Jsr250MethodSecurityMetadataSource();
|
||||
|
||||
public Jsr250MethodSecurityMetadataSource getBean() {
|
||||
source.setDefaultRolePrefix(this.rolePrefix);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
|
||||
static class DefaultMethodSecurityExpressionHandlerBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
|
||||
private DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
|
||||
|
||||
public DefaultMethodSecurityExpressionHandler getBean() {
|
||||
handler.setDefaultRolePrefix(this.rolePrefix);
|
||||
return handler;
|
||||
}
|
||||
}
|
||||
|
||||
static abstract class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware {
|
||||
protected String rolePrefix = "ROLE_";
|
||||
|
||||
@Override
|
||||
public final void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
String[] grantedAuthorityDefaultsBeanNames = applicationContext.getBeanNamesForType(GrantedAuthorityDefaults.class);
|
||||
if(grantedAuthorityDefaultsBeanNames.length == 1) {
|
||||
GrantedAuthorityDefaults grantedAuthorityDefaults = applicationContext.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
|
||||
this.rolePrefix = grantedAuthorityDefaults.getRolePrefix();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delays setting a bean of a given name to be lazyily initialized until after all the
|
||||
* beans are registered.
|
||||
|
||||
+1
-1
@@ -163,7 +163,7 @@ final class ProtectPointcutPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
public void setPointcutMap(Map<String, List<ConfigAttribute>> map) {
|
||||
Assert.notEmpty(map);
|
||||
Assert.notEmpty(map, "configAttributes cannot be empty");
|
||||
for (String expression : map.keySet()) {
|
||||
List<ConfigAttribute> value = map.get(expression);
|
||||
addPointcut(expression, value);
|
||||
|
||||
+8
-8
@@ -255,8 +255,8 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
|
||||
for (String beanName : beanNames) {
|
||||
BeanDefinition bd = registry.getBeanDefinition(beanName);
|
||||
String beanClassName = bd.getBeanClassName();
|
||||
if (beanClassName.equals(SimpAnnotationMethodMessageHandler.class
|
||||
.getName()) || beanClassName.equals(WEB_SOCKET_AMMH_CLASS_NAME)) {
|
||||
if (SimpAnnotationMethodMessageHandler.class.getName().equals(beanClassName) ||
|
||||
WEB_SOCKET_AMMH_CLASS_NAME.equals(beanClassName)) {
|
||||
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 (beanClassName
|
||||
.equals("org.springframework.web.socket.server.support.WebSocketHttpRequestHandler")) {
|
||||
else if ("org.springframework.web.socket.server.support.WebSocketHttpRequestHandler"
|
||||
.equals(beanClassName)) {
|
||||
addCsrfTokenHandshakeInterceptor(bd);
|
||||
}
|
||||
else if (beanClassName
|
||||
.equals("org.springframework.web.socket.sockjs.transport.TransportHandlingSockJsService")) {
|
||||
else if ("org.springframework.web.socket.sockjs.transport.TransportHandlingSockJsService"
|
||||
.equals(beanClassName)) {
|
||||
addCsrfTokenHandshakeInterceptor(bd);
|
||||
}
|
||||
else if (beanClassName
|
||||
.equals("org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService")) {
|
||||
else if ("org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService"
|
||||
.equals(beanClassName)) {
|
||||
addCsrfTokenHandshakeInterceptor(bd);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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.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-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
|
||||
|
||||
@@ -381,6 +381,9 @@ intercept-url.attlist &=
|
||||
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.
|
||||
|
||||
@@ -1345,6 +1345,16 @@
|
||||
</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="servlet-path" type="xs:token">
|
||||
<xs:annotation>
|
||||
<xs:documentation>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 '/'.
|
||||
</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:attributeGroup>
|
||||
|
||||
<xs:attributeGroup name="logout.attlist">
|
||||
|
||||
+919
@@ -0,0 +1,919 @@
|
||||
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"
|
||||
+2825
File diff suppressed because it is too large
Load Diff
+33
-11
@@ -1,26 +1,25 @@
|
||||
package org.springframework.security.config
|
||||
|
||||
import groovy.xml.MarkupBuilder
|
||||
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.context.support.AbstractXmlApplicationContext
|
||||
import org.mockito.Mockito
|
||||
import org.springframework.context.ApplicationListener
|
||||
import org.springframework.context.support.AbstractRefreshableApplicationContext
|
||||
import org.springframework.mock.web.MockServletContext
|
||||
import org.springframework.security.CollectingAppListener
|
||||
import org.springframework.security.config.util.InMemoryXmlApplicationContext
|
||||
import org.springframework.security.config.util.InMemoryXmlWebApplicationContext
|
||||
import org.springframework.security.core.context.SecurityContextHolder
|
||||
import spock.lang.Specification
|
||||
import static org.springframework.security.config.ConfigTestUtils.AUTH_PROVIDER_XML
|
||||
import org.springframework.context.ApplicationListener
|
||||
import org.springframework.context.ApplicationEvent
|
||||
import org.springframework.security.authentication.event.AbstractAuthenticationEvent
|
||||
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent
|
||||
import org.springframework.security.access.event.AbstractAuthorizationEvent
|
||||
import org.springframework.security.CollectingAppListener
|
||||
|
||||
import javax.servlet.ServletContext
|
||||
|
||||
import static org.springframework.security.config.ConfigTestUtils.AUTH_PROVIDER_XML
|
||||
/**
|
||||
*
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
abstract class AbstractXmlConfigTests extends Specification {
|
||||
AbstractXmlApplicationContext appContext;
|
||||
AbstractRefreshableApplicationContext appContext;
|
||||
Writer writer;
|
||||
MarkupBuilder xml;
|
||||
ApplicationListener appListener;
|
||||
@@ -81,4 +80,27 @@ abstract class AbstractXmlConfigTests extends Specification {
|
||||
appContext = new InMemoryXmlApplicationContext(writer.toString() + extraXml);
|
||||
appContext.addApplicationListener(appListener);
|
||||
}
|
||||
|
||||
def createWebAppContext() {
|
||||
createWebAppContext(AUTH_PROVIDER_XML);
|
||||
}
|
||||
|
||||
def createWebAppContext(ServletContext servletContext) {
|
||||
createWebAppContext(AUTH_PROVIDER_XML, servletContext);
|
||||
}
|
||||
|
||||
def createWebAppContext(String extraXml) {
|
||||
createWebAppContext(extraXml, null);
|
||||
}
|
||||
|
||||
def createWebAppContext(String extraXml, ServletContext servletContext) {
|
||||
appContext = new InMemoryXmlWebApplicationContext(writer.toString() + extraXml);
|
||||
appContext.addApplicationListener(appListener);
|
||||
if (servletContext != null) {
|
||||
appContext.setServletContext(servletContext);
|
||||
} else {
|
||||
appContext.setServletContext(new MockServletContext());
|
||||
}
|
||||
appContext.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
+33
@@ -18,6 +18,7 @@ package org.springframework.security.config.annotation.configuration
|
||||
import org.springframework.beans.factory.BeanClassLoaderAware
|
||||
import org.springframework.beans.factory.BeanFactoryAware
|
||||
import org.springframework.beans.factory.DisposableBean
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory
|
||||
import org.springframework.beans.factory.support.BeanNameGenerator;
|
||||
@@ -138,4 +139,36 @@ class AutowireBeanFactoryObjectPostProcessorTests extends BaseSpringSpec {
|
||||
p.postProcess(new Object())
|
||||
}
|
||||
}
|
||||
|
||||
def "SmartInitializingSingleton"() {
|
||||
when:
|
||||
context = new AnnotationConfigWebApplicationContext([servletConfig:new MockServletConfig(),servletContext:new MockServletContext()])
|
||||
context.register(SmartConfig)
|
||||
context.refresh()
|
||||
context.start()
|
||||
then:
|
||||
context.getBean(SmartConfig).smart.instantiated
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class SmartConfig {
|
||||
SmartInitializingSingleton smart = new SmartInitializingSingletonStub()
|
||||
|
||||
@Bean
|
||||
public static ObjectPostProcessor objectPostProcessor(AutowireCapableBeanFactory beanFactory) {
|
||||
return new AutowireBeanFactoryObjectPostProcessor(beanFactory)
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void configure(ObjectPostProcessor<Object> p) {
|
||||
p.postProcess(smart)
|
||||
}
|
||||
}
|
||||
|
||||
static class SmartInitializingSingletonStub implements SmartInitializingSingleton {
|
||||
boolean instantiated
|
||||
void afterSingletonsInstantiated() {
|
||||
instantiated = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+25
-1
@@ -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,6 +27,7 @@ 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
|
||||
|
||||
@@ -496,4 +497,27 @@ 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:")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
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
|
||||
@@ -48,7 +49,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
|
||||
|
||||
|
||||
+8
@@ -67,5 +67,13 @@ class AbstractConfigAttributeRequestMatcherRegistryTests extends Specification {
|
||||
List<RequestMatcher> chainRequestMatchersInternal(List<RequestMatcher> requestMatchers) {
|
||||
return requestMatchers;
|
||||
}
|
||||
|
||||
List<RequestMatcher> mvcMatchers(String... mvcPatterns) {
|
||||
null
|
||||
}
|
||||
|
||||
List<RequestMatcher> mvcMatchers(HttpMethod method, String... mvcPatterns) {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -92,7 +92,7 @@ class ExceptionHandlingConfigurerTests extends BaseSpringSpec {
|
||||
DelegatingAuthenticationEntryPoint delegateEntryPoint = findFilter(ExceptionTranslationFilter).authenticationEntryPoint
|
||||
then:
|
||||
def entryPoints = delegateEntryPoint.entryPoints.keySet() as List
|
||||
entryPoints[0].requestMatchers[1].contentNegotiationStrategy.class == HeaderContentNegotiationStrategy
|
||||
entryPoints[0].requestMatchers[1].requestMatchers[1].contentNegotiationStrategy.class == HeaderContentNegotiationStrategy
|
||||
entryPoints[1].requestMatchers[1].contentNegotiationStrategy.class == HeaderContentNegotiationStrategy
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ class ExceptionHandlingConfigurerTests extends BaseSpringSpec {
|
||||
then:
|
||||
def entryPoints = delegateEntryPoint.entryPoints.keySet() as List
|
||||
entryPoints[0].requestMatchers[1].contentNegotiationStrategy == OverrideContentNegotiationStrategySharedObjectConfig.CNS
|
||||
entryPoints[1].requestMatchers[1].contentNegotiationStrategy == OverrideContentNegotiationStrategySharedObjectConfig.CNS
|
||||
entryPoints[1].requestMatchers[1].requestMatchers[1].contentNegotiationStrategy == OverrideContentNegotiationStrategySharedObjectConfig.CNS
|
||||
}
|
||||
|
||||
def "Override ContentNegotiationStrategy with @Bean"() {
|
||||
|
||||
+6
-8
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -13,7 +13,9 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers;
|
||||
package org.springframework.security.config.annotation.web.configurers
|
||||
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
|
||||
import static org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurerConfigs.*
|
||||
|
||||
@@ -293,7 +295,7 @@ public class ExpressionUrlAuthorizationConfigurerTests extends BaseSpringSpec {
|
||||
response.status == HttpServletResponse.SC_UNAUTHORIZED
|
||||
when:
|
||||
super.setup()
|
||||
login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
|
||||
login(new UsernamePasswordAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_FORBIDDEN
|
||||
@@ -339,16 +341,12 @@ 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_FORBIDDEN
|
||||
response.status == HttpServletResponse.SC_UNAUTHORIZED
|
||||
when:
|
||||
super.setup()
|
||||
login()
|
||||
|
||||
+44
@@ -20,12 +20,14 @@ 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 {
|
||||
|
||||
@@ -453,4 +455,46 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+19
@@ -232,4 +232,23 @@ class LogoutConfigurerTests extends BaseSpringSpec {
|
||||
@EnableWebSecurity
|
||||
static class LogoutHandlerContentNegotiationForChrome extends WebSecurityConfigurerAdapter {
|
||||
}
|
||||
|
||||
// gh-3997
|
||||
def "LogoutConfigurer for XMLHttpRequest is 204"() {
|
||||
setup:
|
||||
loadConfig(LogoutXMLHttpRequestConfig)
|
||||
when:
|
||||
login()
|
||||
request.method = 'POST'
|
||||
request.servletPath = '/logout'
|
||||
request.addHeader('Accept', 'text/html,application/json')
|
||||
request.addHeader('X-Requested-With', 'XMLHttpRequest')
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == 204
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class LogoutXMLHttpRequestConfig extends WebSecurityConfigurerAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -67,7 +67,7 @@ class NamespaceSessionManagementTests extends BaseSpringSpec {
|
||||
concurrentStrategy.maximumSessions == 1
|
||||
concurrentStrategy.exceptionIfMaximumExceeded
|
||||
concurrentStrategy.sessionRegistry == CustomSessionManagementConfig.SR
|
||||
findFilter(ConcurrentSessionFilter).expiredUrl == "/expired-session"
|
||||
findFilter(ConcurrentSessionFilter).sessionInformationExpiredStrategy.destinationUrl == "/expired-session"
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
+107
-80
@@ -15,13 +15,11 @@
|
||||
*/
|
||||
package org.springframework.security.config.doc
|
||||
|
||||
import groovy.util.slurpersupport.GPathResult;
|
||||
import groovy.util.slurpersupport.NodeChild
|
||||
import groovy.util.slurpersupport.GPathResult
|
||||
import spock.lang.*
|
||||
|
||||
import org.springframework.security.config.http.SecurityFilters
|
||||
|
||||
import spock.lang.*
|
||||
|
||||
/**
|
||||
* Tests to ensure that the xsd is properly documented.
|
||||
*
|
||||
@@ -29,11 +27,19 @@ import spock.lang.*
|
||||
*/
|
||||
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.1.xsd')
|
||||
@Shared File schemaDocument = new File('src/main/resources/org/springframework/security/config/spring-security-4.2.xsd')
|
||||
@Shared Map<String,Element> elementNameToElement
|
||||
@Shared GPathResult schemaRootElement
|
||||
|
||||
@@ -52,32 +58,53 @@ 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
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -89,8 +116,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 8, if not then schemaDocument needs updated'
|
||||
schemas.size() == 10
|
||||
then: 'the count is equal to 11, if not then schemaDocument needs updated'
|
||||
schemas.size() == 11
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,22 +127,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
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,55 +152,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
|
||||
}
|
||||
}
|
||||
|
||||
if(docAttrName) {
|
||||
def expression = '^\\* <<(nsa-.*),.*>>$'
|
||||
if(line.matches(expression)) {
|
||||
String elmtId = line.replaceAll(expression, '$1')
|
||||
currentDocAttrNameToElmt.get(docAttrName, []).add(elmtId)
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
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()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+44
@@ -109,6 +109,18 @@ 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) {
|
||||
@@ -908,6 +920,38 @@ 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 ->
|
||||
|
||||
+116
-7
@@ -15,19 +15,25 @@
|
||||
*/
|
||||
package org.springframework.security.config.http
|
||||
|
||||
import javax.servlet.Filter
|
||||
import javax.servlet.ServletContext
|
||||
import javax.servlet.ServletRegistration
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
import org.mockito.invocation.InvocationOnMock
|
||||
import org.mockito.stubbing.Answer
|
||||
|
||||
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException
|
||||
import org.springframework.mock.web.MockFilterChain
|
||||
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;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
|
||||
import static org.mockito.Mockito.*
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
@@ -201,6 +207,7 @@ class InterceptUrlConfigTests extends AbstractHttpConfigTests {
|
||||
|
||||
def "intercept-url supports mvc matchers"() {
|
||||
setup:
|
||||
MockServletContext servletContext = mockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
|
||||
MockHttpServletResponse response = new MockHttpServletResponse()
|
||||
MockFilterChain chain = new MockFilterChain()
|
||||
@@ -211,7 +218,7 @@ class InterceptUrlConfigTests extends AbstractHttpConfigTests {
|
||||
bean('pathController',PathController)
|
||||
xml.'mvc:annotation-driven'()
|
||||
|
||||
createAppContext()
|
||||
createWebAppContext(servletContext)
|
||||
when:
|
||||
request.servletPath = "/path"
|
||||
springSecurityFilterChain.doFilter(request, response, chain)
|
||||
@@ -237,6 +244,7 @@ class InterceptUrlConfigTests extends AbstractHttpConfigTests {
|
||||
|
||||
def "intercept-url mvc supports path variables"() {
|
||||
setup:
|
||||
MockServletContext servletContext = mockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
|
||||
MockHttpServletResponse response = new MockHttpServletResponse()
|
||||
MockFilterChain chain = new MockFilterChain()
|
||||
@@ -244,7 +252,7 @@ class InterceptUrlConfigTests extends AbstractHttpConfigTests {
|
||||
'http-basic'()
|
||||
'intercept-url'(pattern: '/user/{un}/**', access: "#un == 'user'")
|
||||
}
|
||||
createAppContext()
|
||||
createWebAppContext(servletContext)
|
||||
when: 'user can access'
|
||||
request.servletPath = '/user/user/abc'
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
@@ -266,12 +274,113 @@ class InterceptUrlConfigTests extends AbstractHttpConfigTests {
|
||||
response.status == HttpServletResponse.SC_FORBIDDEN
|
||||
}
|
||||
|
||||
def "intercept-url mvc matchers with servlet path"() {
|
||||
setup:
|
||||
MockServletContext servletContext = mockServletContext("/spring");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
|
||||
MockHttpServletResponse response = new MockHttpServletResponse()
|
||||
MockFilterChain chain = new MockFilterChain()
|
||||
xml.http('request-matcher':'mvc') {
|
||||
'http-basic'()
|
||||
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
|
||||
}
|
||||
bean('pathController',PathController)
|
||||
xml.'mvc:annotation-driven'()
|
||||
createWebAppContext(servletContext)
|
||||
when:
|
||||
request.servletPath = "/spring"
|
||||
request.requestURI = "/spring/path"
|
||||
springSecurityFilterChain.doFilter(request, response, chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_UNAUTHORIZED
|
||||
when:
|
||||
request = new MockHttpServletRequest(method:'GET')
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
request.servletPath = "/spring"
|
||||
request.requestURI = "/spring/path.html"
|
||||
springSecurityFilterChain.doFilter(request, response, chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_UNAUTHORIZED
|
||||
when:
|
||||
request = new MockHttpServletRequest(method:'GET')
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
request.servletPath = "/spring"
|
||||
request.requestURI = "/spring/path/"
|
||||
springSecurityFilterChain.doFilter(request, response, chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_UNAUTHORIZED
|
||||
}
|
||||
|
||||
def "intercept-url ant matcher with servlet path fails"() {
|
||||
when:
|
||||
xml.http('request-matcher':'ant') {
|
||||
'http-basic'()
|
||||
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
|
||||
}
|
||||
createAppContext()
|
||||
then:
|
||||
thrown(BeanDefinitionParsingException)
|
||||
}
|
||||
|
||||
def "intercept-url regex matcher with servlet path fails"() {
|
||||
when:
|
||||
xml.http('request-matcher':'regex') {
|
||||
'http-basic'()
|
||||
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
|
||||
}
|
||||
createAppContext()
|
||||
then:
|
||||
thrown(BeanDefinitionParsingException)
|
||||
}
|
||||
|
||||
def "intercept-url ciRegex matcher with servlet path fails"() {
|
||||
when:
|
||||
xml.http('request-matcher':'ciRegex') {
|
||||
'http-basic'()
|
||||
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
|
||||
}
|
||||
createAppContext()
|
||||
then:
|
||||
thrown(BeanDefinitionParsingException)
|
||||
}
|
||||
|
||||
def "intercept-url default matcher with servlet path fails"() {
|
||||
when:
|
||||
xml.http() {
|
||||
'http-basic'()
|
||||
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
|
||||
}
|
||||
createAppContext()
|
||||
then:
|
||||
thrown(BeanDefinitionParsingException)
|
||||
}
|
||||
|
||||
public static class Id {
|
||||
public boolean isOne(int i) {
|
||||
return i == 1;
|
||||
}
|
||||
}
|
||||
|
||||
private ServletContext mockServletContext() {
|
||||
return mockServletContext("/");
|
||||
}
|
||||
|
||||
private ServletContext mockServletContext(String servletPath) {
|
||||
MockServletContext servletContext = spy(new MockServletContext());
|
||||
final ServletRegistration registration = mock(ServletRegistration.class);
|
||||
when(registration.getMappings()).thenReturn(Collections.singleton(servletPath));
|
||||
Answer<Map<String, ? extends ServletRegistration>> answer = new Answer<Map<String, ? extends ServletRegistration>>() {
|
||||
@Override
|
||||
public Map<String, ? extends ServletRegistration> answer(InvocationOnMock invocation) throws Throwable {
|
||||
return Collections.<String, ServletRegistration>singletonMap("spring", registration);
|
||||
}
|
||||
};
|
||||
when(servletContext.getServletRegistrations()).thenAnswer(answer);
|
||||
return servletContext;
|
||||
}
|
||||
|
||||
def login(MockHttpServletRequest request, String username, String password) {
|
||||
String toEncode = username + ':' + password
|
||||
request.addHeader('Authorization','Basic ' + new String(Base64.encode(toEncode.getBytes('UTF-8'))))
|
||||
@@ -284,4 +393,4 @@ class InterceptUrlConfigTests extends AbstractHttpConfigTests {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -419,7 +419,7 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
|
||||
'form-login'()
|
||||
}
|
||||
createAppContext()
|
||||
def handlers = getFilter(LogoutFilter).handlers
|
||||
def handlers = getFilter(LogoutFilter).handler.logoutHandlers
|
||||
|
||||
expect:
|
||||
handlers[2] instanceof CookieClearingLogoutHandler
|
||||
|
||||
+2
-2
@@ -101,7 +101,7 @@ class RememberMeConfigTests extends AbstractHttpConfigTests {
|
||||
|
||||
createAppContext(AUTH_PROVIDER_XML)
|
||||
|
||||
List logoutHandlers = FieldUtils.getFieldValue(getFilter(LogoutFilter.class), "handlers");
|
||||
List logoutHandlers = FieldUtils.getFieldValue(getFilter(LogoutFilter.class), "handler").logoutHandlers;
|
||||
Map ams = appContext.getBeansOfType(ProviderManager.class);
|
||||
ProviderManager am = (ams.values() as List).find { it instanceof ProviderManager && it.providers.size() == 2}
|
||||
RememberMeAuthenticationProvider rmp = am.providers.find { it instanceof RememberMeAuthenticationProvider}
|
||||
@@ -124,7 +124,7 @@ class RememberMeConfigTests extends AbstractHttpConfigTests {
|
||||
createAppContext(AUTH_PROVIDER_XML)
|
||||
|
||||
def rememberMeServices = rememberMeServices()
|
||||
List logoutHandlers = getFilter(LogoutFilter.class).handlers
|
||||
List logoutHandlers = getFilter(LogoutFilter.class).handler.logoutHandlers
|
||||
|
||||
expect:
|
||||
rememberMeServices
|
||||
|
||||
+14
-15
@@ -15,13 +15,6 @@
|
||||
*/
|
||||
package org.springframework.security.config.http
|
||||
|
||||
import static org.junit.Assert.assertSame
|
||||
import static org.mockito.Mockito.*
|
||||
|
||||
import javax.servlet.http.HttpServletRequest
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
import org.mockito.Mockito
|
||||
import org.springframework.mock.web.MockFilterChain
|
||||
import org.springframework.mock.web.MockHttpServletRequest
|
||||
import org.springframework.mock.web.MockHttpServletResponse
|
||||
@@ -41,7 +34,6 @@ import org.springframework.security.web.authentication.logout.CookieClearingLogo
|
||||
import org.springframework.security.web.authentication.logout.LogoutFilter
|
||||
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler
|
||||
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter
|
||||
import org.springframework.security.web.authentication.session.SessionAuthenticationException
|
||||
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy
|
||||
import org.springframework.security.web.context.NullSecurityContextRepository
|
||||
import org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper
|
||||
@@ -50,6 +42,13 @@ import org.springframework.security.web.savedrequest.RequestCacheAwareFilter
|
||||
import org.springframework.security.web.session.ConcurrentSessionFilter
|
||||
import org.springframework.security.web.session.SessionManagementFilter
|
||||
|
||||
import javax.servlet.http.HttpServletRequest
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
import static org.junit.Assert.assertSame
|
||||
import static org.mockito.Matchers.any
|
||||
import static org.mockito.Mockito.verify
|
||||
|
||||
/**
|
||||
* Tests session-related functionality for the <http> namespace element and <session-management>
|
||||
*
|
||||
@@ -164,13 +163,13 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
|
||||
|
||||
then:
|
||||
concurrentSessionFilter instanceof ConcurrentSessionFilter
|
||||
concurrentSessionFilter.expiredUrl == '/expired'
|
||||
concurrentSessionFilter.sessionInformationExpiredStrategy.destinationUrl == '/expired'
|
||||
appContext.getBean("sr") != null
|
||||
getFilter(SessionManagementFilter.class) != null
|
||||
sessionRegistryIsValid();
|
||||
|
||||
concurrentSessionFilter.handlers.size() == 1
|
||||
def logoutHandler = concurrentSessionFilter.handlers[0]
|
||||
concurrentSessionFilter.handlers.logoutHandlers.size() == 1
|
||||
def logoutHandler = concurrentSessionFilter.handlers.logoutHandlers[0]
|
||||
logoutHandler instanceof SecurityContextLogoutHandler
|
||||
logoutHandler.invalidateHttpSession
|
||||
|
||||
@@ -190,7 +189,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
|
||||
|
||||
List filters = getFilters("/someurl")
|
||||
ConcurrentSessionFilter concurrentSessionFilter = filters.get(1)
|
||||
def logoutHandlers = concurrentSessionFilter.handlers
|
||||
def logoutHandlers = concurrentSessionFilter.handlers.logoutHandlers
|
||||
|
||||
then: 'ConcurrentSessionFilter contains the customized LogoutHandlers'
|
||||
logoutHandlers.size() == 3
|
||||
@@ -216,7 +215,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
|
||||
|
||||
List filters = getFilters("/someurl")
|
||||
ConcurrentSessionFilter concurrentSessionFilter = filters.get(1)
|
||||
def logoutHandlers = concurrentSessionFilter.handlers
|
||||
def logoutHandlers = concurrentSessionFilter.handlers.logoutHandlers
|
||||
|
||||
then: 'SecurityContextLogoutHandler and RememberMeServices are in ConcurrentSessionFilter logoutHandlers'
|
||||
!filters.find { it instanceof LogoutFilter }
|
||||
@@ -238,7 +237,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
|
||||
|
||||
List filters = getFilters("/someurl")
|
||||
ConcurrentSessionFilter concurrentSessionFilter = filters.get(1)
|
||||
def logoutHandlers = concurrentSessionFilter.handlers
|
||||
def logoutHandlers = concurrentSessionFilter.handlers.logoutHandlers
|
||||
|
||||
then: 'Only SecurityContextLogoutHandler is found in ConcurrentSessionFilter logoutHandlers'
|
||||
!filters.find { it instanceof LogoutFilter }
|
||||
@@ -271,7 +270,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
|
||||
List filters = getFilters("/someurl");
|
||||
|
||||
expect:
|
||||
filters.get(1).expiredUrl == null
|
||||
filters.get(1).sessionInformationExpiredStrategy.class.name == 'org.springframework.security.web.session.ConcurrentSessionFilter$ResponseBodySessionInformationExpiredStrategy'
|
||||
}
|
||||
|
||||
def externalSessionStrategyIsSupported() {
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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.annotation.authentication.configuration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
public class EnableGlobalAuthenticationTests {
|
||||
@Autowired
|
||||
AuthenticationConfiguration auth;
|
||||
|
||||
// gh-4086
|
||||
@Test
|
||||
public void authenticationConfigurationWhenGetAuthenticationManagerThenNotNull() throws Exception {
|
||||
assertThat(auth.getAuthenticationManager()).isNotNull();
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableGlobalAuthentication
|
||||
static class Config {
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* 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.annotation.web;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
@WebAppConfiguration
|
||||
public class HttpSecurityHeadersTests {
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
@Autowired
|
||||
Filter springSecurityFilterChain;
|
||||
|
||||
MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
mockMvc = MockMvcBuilders
|
||||
.webAppContextSetup(wac)
|
||||
.addFilters(springSecurityFilterChain)
|
||||
.build();
|
||||
}
|
||||
|
||||
// gh-2953
|
||||
// gh-3975
|
||||
@Test
|
||||
public void headerWhenSpringMvcResourceThenCacheRelatedHeadersReset() throws Exception {
|
||||
mockMvc.perform(get("/resources/file.js"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL,"max-age=12345"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, ""))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, ""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void headerWhenNotSpringResourceThenCacheRelatedHeadersSet() throws Exception {
|
||||
mockMvc.perform(get("/notresource"))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL,"no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
}
|
||||
}
|
||||
|
||||
@EnableWebMvc
|
||||
@Configuration
|
||||
static class WebMvcConfig extends WebMvcConfigurerAdapter {
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/").setCachePeriod(12345);
|
||||
}
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* 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.annotation.web;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.powermock.api.mockito.PowerMockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.springframework.core.io.support.SpringFactoriesLoader;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.web.context.ConfigurableWebApplicationContext;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest({ SpringFactoriesLoader.class })
|
||||
public class WebSecurityConfigurerAdapterPowermockTests {
|
||||
ConfigurableWebApplicationContext context;
|
||||
|
||||
@After
|
||||
public void close() {
|
||||
if(context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() {
|
||||
spy(SpringFactoriesLoader.class);
|
||||
DefaultConfigurer configurer = new DefaultConfigurer();
|
||||
when(SpringFactoriesLoader
|
||||
.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
|
||||
.thenReturn(Arrays.<AbstractHttpConfigurer>asList(configurer));
|
||||
|
||||
loadConfig(Config.class);
|
||||
|
||||
assertThat(configurer.init).isTrue();
|
||||
assertThat(configurer.configure).isTrue();
|
||||
}
|
||||
|
||||
private void loadConfig(Class<?>... classes) {
|
||||
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
|
||||
context.setClassLoader(getClass().getClassLoader());
|
||||
context.register(classes);
|
||||
context.refresh();
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class Config extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
}
|
||||
}
|
||||
|
||||
static class DefaultConfigurer extends AbstractHttpConfigurer<DefaultConfigurer,HttpSecurity> {
|
||||
boolean init;
|
||||
boolean configure;
|
||||
|
||||
@Override
|
||||
public void init(HttpSecurity builder) throws Exception {
|
||||
this.init = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity builder) throws Exception {
|
||||
this.configure = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
/*
|
||||
* 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.annotation.web.builders;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class WebSecurityTests {
|
||||
AnnotationConfigWebApplicationContext context;
|
||||
|
||||
MockHttpServletRequest request;
|
||||
MockHttpServletResponse response;
|
||||
MockFilterChain chain;
|
||||
|
||||
@Autowired
|
||||
FilterChainProxy springSecurityFilterChain;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.request.setMethod("GET");
|
||||
this.response = new MockHttpServletResponse();
|
||||
this.chain = new MockFilterChain();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
if (this.context != null) {
|
||||
this.context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoringMvcMatcher() throws Exception {
|
||||
loadConfig(MvcMatcherConfig.class);
|
||||
|
||||
this.request.setRequestURI("/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setRequestURI("/path.html");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setRequestURI("/path/");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setRequestURI("/other");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
static class MvcMatcherConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
public void configure(WebSecurity web) throws Exception {
|
||||
// @formatter:off
|
||||
web
|
||||
.ignoring()
|
||||
.mvcMatchers("/path");
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.anyRequest().denyAll();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter:off
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class PathController {
|
||||
@RequestMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoringMvcMatcherServletPath() throws Exception {
|
||||
loadConfig(MvcMatcherServletPathConfig.class);
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path.html");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path/");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/other");
|
||||
this.request.setRequestURI("/other/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
static class MvcMatcherServletPathConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
public void configure(WebSecurity web) throws Exception {
|
||||
// @formatter:off
|
||||
web
|
||||
.ignoring()
|
||||
.mvcMatchers("/path").servletPath("/spring")
|
||||
.mvcMatchers("/notused");
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.anyRequest().denyAll();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter:off
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class PathController {
|
||||
@RequestMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConfig(Class<?>... configs) {
|
||||
this.context = new AnnotationConfigWebApplicationContext();
|
||||
this.context.register(configs);
|
||||
this.context.setServletContext(new MockServletContext());
|
||||
this.context.refresh();
|
||||
|
||||
this.context.getAutowireCapableBeanFactory().autowireBean(this);
|
||||
}
|
||||
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* 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.annotation.web.configuration;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
@WebAppConfiguration
|
||||
public class AuthenticationPrincipalArgumentResolverTests {
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticationPrincipalExpressionWhenBeanExpressionSuppliedThenBeanUsed() throws Exception {
|
||||
User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()));
|
||||
SecurityContextHolder.setContext(context);
|
||||
|
||||
MockMvc mockMvc = MockMvcBuilders
|
||||
.webAppContextSetup(wac)
|
||||
.build();
|
||||
|
||||
mockMvc.perform(get("/users/self"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("extracted-user"));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@EnableWebMvc
|
||||
static class Config {
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public UsernameExtractor usernameExtractor() {
|
||||
return new UsernameExtractor();
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class UserController {
|
||||
@GetMapping("/users/self")
|
||||
public String usersSelf(@AuthenticationPrincipal(expression = "@usernameExtractor.extract(#this)") String userName) {
|
||||
return userName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static class UsernameExtractor {
|
||||
public String extract(User u) {
|
||||
return "extracted-" + u.getUsername();
|
||||
}
|
||||
}
|
||||
}
|
||||
+119
-7
@@ -48,6 +48,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.spy;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
@@ -59,12 +60,14 @@ public class AuthorizeRequestsTests {
|
||||
MockHttpServletRequest request;
|
||||
MockHttpServletResponse response;
|
||||
MockFilterChain chain;
|
||||
MockServletContext servletContext;
|
||||
|
||||
@Autowired
|
||||
FilterChainProxy springSecurityFilterChain;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.servletContext = spy(new MockServletContext());
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.request.setMethod("GET");
|
||||
this.response = new MockHttpServletResponse();
|
||||
@@ -257,7 +260,7 @@ public class AuthorizeRequestsTests {
|
||||
public void mvcMatcher() throws Exception {
|
||||
loadConfig(MvcMatcherConfig.class);
|
||||
|
||||
this.request.setServletPath("/path");
|
||||
this.request.setRequestURI("/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
@@ -265,7 +268,7 @@ public class AuthorizeRequestsTests {
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/path.html");
|
||||
this.request.setRequestURI("/path.html");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
@@ -311,22 +314,100 @@ public class AuthorizeRequestsTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mvcMatcherServletPath() throws Exception {
|
||||
loadConfig(MvcMatcherServletPathConfig.class);
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path.html");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path/");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/foo");
|
||||
this.request.setRequestURI("/foo/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/");
|
||||
this.request.setRequestURI("/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
static class MvcMatcherServletPathConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.mvcMatchers("/path").servletPath("/spring").denyAll();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter:off
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class PathController {
|
||||
@RequestMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mvcMatcherPathVariables() throws Exception {
|
||||
loadConfig(MvcMatcherPathVariablesConfig.class);
|
||||
|
||||
this.request.setServletPath("/user/user");
|
||||
this.request.setRequestURI("/user/user");
|
||||
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
this.setup();
|
||||
this.request.setServletPath("/user/deny");
|
||||
this.request.setRequestURI("/user/deny");
|
||||
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@@ -360,12 +441,43 @@ public class AuthorizeRequestsTests {
|
||||
}
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
static class MvcMatcherPathServletPathRequiredConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.mvcMatchers("/user").denyAll();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter:off
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class PathController {
|
||||
@RequestMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConfig(Class<?>... configs) {
|
||||
this.context = new AnnotationConfigWebApplicationContext();
|
||||
this.context.register(configs);
|
||||
this.context.setServletContext(new MockServletContext());
|
||||
this.context.setServletContext(this.servletContext);
|
||||
this.context.refresh();
|
||||
|
||||
this.context.getAutowireCapableBeanFactory().autowireBean(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+271
@@ -0,0 +1,271 @@
|
||||
/*
|
||||
* 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.annotation.web.configurers;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
public class HttpSecurityRequestMatchersTests {
|
||||
AnnotationConfigWebApplicationContext context;
|
||||
|
||||
MockHttpServletRequest request;
|
||||
MockHttpServletResponse response;
|
||||
MockFilterChain chain;
|
||||
|
||||
@Autowired
|
||||
FilterChainProxy springSecurityFilterChain;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.request.setMethod("GET");
|
||||
this.response = new MockHttpServletResponse();
|
||||
this.chain = new MockFilterChain();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
if (this.context != null) {
|
||||
this.context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mvcMatcher() throws Exception {
|
||||
loadConfig(MvcMatcherConfig.class);
|
||||
|
||||
this.request.setServletPath("/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/path.html");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/path/");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mvcMatcherGetFiltersNoUnsupportedMethodExceptionFromDummyRequest() {
|
||||
loadConfig(MvcMatcherConfig.class);
|
||||
|
||||
assertThat(springSecurityFilterChain.getFilters("/path")).isNotEmpty();
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
static class MvcMatcherConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.mvcMatcher("/path")
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.anyRequest().denyAll();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter:off
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class PathController {
|
||||
@RequestMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestMatchersMvcMatcher() throws Exception {
|
||||
loadConfig(RequestMatchersMvcMatcherConfig.class);
|
||||
|
||||
this.request.setServletPath("/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/path.html");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/path/");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
static class RequestMatchersMvcMatcherConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.requestMatchers()
|
||||
.mvcMatchers("/path")
|
||||
.and()
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.anyRequest().denyAll();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter:off
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class PathController {
|
||||
@RequestMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestMatchersMvcMatcherServletPath() throws Exception {
|
||||
loadConfig(RequestMatchersMvcMatcherServeltPathConfig.class);
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("");
|
||||
this.request.setRequestURI("/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/other");
|
||||
this.request.setRequestURI("/other/path");
|
||||
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
static class RequestMatchersMvcMatcherServeltPathConfig
|
||||
extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.requestMatchers()
|
||||
.mvcMatchers("/path").servletPath("/spring")
|
||||
.mvcMatchers("/never-match")
|
||||
.and()
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.anyRequest().denyAll();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter:off
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class PathController {
|
||||
@RequestMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConfig(Class<?>... configs) {
|
||||
this.context = new AnnotationConfigWebApplicationContext();
|
||||
this.context.register(configs);
|
||||
this.context.setServletContext(new MockServletContext());
|
||||
this.context.refresh();
|
||||
|
||||
this.context.getAutowireCapableBeanFactory().autowireBean(this);
|
||||
}
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
/*
|
||||
* 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.
|
||||
* 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;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
public class UrlAuthorizationConfigurerTests {
|
||||
AnnotationConfigWebApplicationContext context;
|
||||
|
||||
MockHttpServletRequest request;
|
||||
MockHttpServletResponse response;
|
||||
MockFilterChain chain;
|
||||
|
||||
@Autowired
|
||||
FilterChainProxy springSecurityFilterChain;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.request.setMethod("GET");
|
||||
this.response = new MockHttpServletResponse();
|
||||
this.chain = new MockFilterChain();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
if (this.context != null) {
|
||||
this.context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mvcMatcher() throws Exception {
|
||||
loadConfig(MvcMatcherConfig.class);
|
||||
|
||||
this.request.setRequestURI("/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setRequestURI("/path.html");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/path/");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
static class MvcMatcherConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.httpBasic().and()
|
||||
.apply(new UrlAuthorizationConfigurer(getApplicationContext())).getRegistry()
|
||||
.mvcMatchers("/path").hasRole("ADMIN");
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter:off
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class PathController {
|
||||
@RequestMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mvcMatcherServletPath() throws Exception {
|
||||
loadConfig(MvcMatcherServletPathConfig.class);
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path.html");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/spring");
|
||||
this.request.setRequestURI("/spring/path/");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus())
|
||||
.isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/foo");
|
||||
this.request.setRequestURI("/foo/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
|
||||
setup();
|
||||
|
||||
this.request.setServletPath("/");
|
||||
this.request.setRequestURI("/path");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
static class MvcMatcherServletPathConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.httpBasic().and()
|
||||
.apply(new UrlAuthorizationConfigurer(getApplicationContext())).getRegistry()
|
||||
.mvcMatchers("/path").servletPath("/spring").hasRole("ADMIN");
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter:off
|
||||
auth
|
||||
.inMemoryAuthentication();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class PathController {
|
||||
@RequestMapping("/path")
|
||||
public String path() {
|
||||
return "path";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConfig(Class<?>... configs) {
|
||||
this.context = new AnnotationConfigWebApplicationContext();
|
||||
this.context.register(configs);
|
||||
this.context.setServletContext(new MockServletContext());
|
||||
this.context.refresh();
|
||||
|
||||
this.context.getAutowireCapableBeanFactory().autowireBean(this);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -444,7 +444,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
// @formatter:on
|
||||
|
||||
@Bean
|
||||
public SecurityExpressionHandler<Message<Object>> messageSecurityExpressionHandler() {
|
||||
public static SecurityExpressionHandler<Message<Object>> messageSecurityExpressionHandler() {
|
||||
return new DefaultMessageSecurityExpressionHandler<Object>() {
|
||||
@Override
|
||||
protected SecurityExpressionOperations createSecurityExpressionRoot(
|
||||
|
||||
+10
-10
@@ -15,29 +15,29 @@
|
||||
*/
|
||||
package org.springframework.security.config.authentication;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.ProviderManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.authentication
|
||||
.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.BeanIds;
|
||||
import org.springframework.security.config.authentication.AbstractUserDetailsServiceBeanDefinitionParser;
|
||||
import org.springframework.security.config.authentication.CachingUserDetailsService;
|
||||
import org.springframework.security.config.authentication.JdbcUserServiceBeanDefinitionParser;
|
||||
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.provisioning.JdbcUserDetailsManager;
|
||||
import org.springframework.security.util.FieldUtils;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* @author Ben Alex
|
||||
* @author Luke Taylor
|
||||
* @author Eddú Meléndez
|
||||
*/
|
||||
public class JdbcUserServiceBeanDefinitionParserTests {
|
||||
private static String USER_CACHE_XML = "<b:bean id='userCache' class='org.springframework.security.authentication.dao.MockUserCache'/>";
|
||||
@@ -154,8 +154,8 @@ public class JdbcUserServiceBeanDefinitionParserTests {
|
||||
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext
|
||||
.getBean("myUserService");
|
||||
UserDetails rod = mgr.loadUserByUsername("rod");
|
||||
assertThat(AuthorityUtils.authorityListToSet(rod.getAuthorities()).contains(
|
||||
"PREFIX_ROLE_SUPERVISOR"));
|
||||
assertThat(AuthorityUtils.authorityListToSet(rod.getAuthorities()))
|
||||
.contains("PREFIX_ROLE_SUPERVISOR");
|
||||
}
|
||||
|
||||
private void setContext(String context) {
|
||||
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.core;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
public class GrantedAuthorityDefaultsJcTests {
|
||||
@Autowired
|
||||
FilterChainProxy springSecurityFilterChain;
|
||||
@Autowired
|
||||
MessageService messageService;
|
||||
|
||||
MockHttpServletRequest request;
|
||||
MockHttpServletResponse response;
|
||||
MockFilterChain chain;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
setup("USER");
|
||||
|
||||
request = new MockHttpServletRequest();
|
||||
request.setMethod("GET");
|
||||
response = new MockHttpServletResponse();
|
||||
chain = new MockFilterChain();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilter() throws Exception {
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
|
||||
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterDenied() throws Exception {
|
||||
setup("DENIED");
|
||||
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
|
||||
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void message() {
|
||||
messageService.getMessage();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jsrMessage() {
|
||||
messageService.getJsrMessage();
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
public void messageDenied() {
|
||||
setup("DENIED");
|
||||
|
||||
messageService.getMessage();
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
public void jsrMessageDenied() {
|
||||
setup("DENIED");
|
||||
|
||||
messageService.getJsrMessage();
|
||||
}
|
||||
|
||||
// SEC-2926
|
||||
@Test
|
||||
public void doFilterIsUserInRole() throws Exception {
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
|
||||
|
||||
chain = new MockFilterChain() {
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
assertThat(httpRequest.isUserInRole("USER")).isTrue();
|
||||
assertThat(httpRequest.isUserInRole("INVALID")).isFalse();
|
||||
super.doFilter(request, response);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
|
||||
assertThat(chain.getRequest()).isNotNull();
|
||||
}
|
||||
|
||||
private void setup(String role) {
|
||||
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password", role);
|
||||
SecurityContextHolder.getContext().setAuthentication(user);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled=true, jsr250Enabled=true)
|
||||
static class Config extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth
|
||||
.inMemoryAuthentication()
|
||||
.withUser("user").password("password").roles("USER");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.anyRequest().access("hasRole('USER')");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageService messageService() {
|
||||
return new HelloWorldMessageService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public static GrantedAuthorityDefaults grantedAuthorityDefaults() {
|
||||
return new GrantedAuthorityDefaults("");
|
||||
}
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.core;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
public class GrantedAuthorityDefaultsXmlTests {
|
||||
@Autowired
|
||||
FilterChainProxy springSecurityFilterChain;
|
||||
@Autowired
|
||||
MessageService messageService;
|
||||
|
||||
MockHttpServletRequest request;
|
||||
MockHttpServletResponse response;
|
||||
MockFilterChain chain;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
setup("USER");
|
||||
|
||||
request = new MockHttpServletRequest();
|
||||
request.setMethod("GET");
|
||||
response = new MockHttpServletResponse();
|
||||
chain = new MockFilterChain();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilter() throws Exception {
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
|
||||
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterDenied() throws Exception {
|
||||
setup("DENIED");
|
||||
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
|
||||
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void message() {
|
||||
messageService.getMessage();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jsrMessage() {
|
||||
messageService.getJsrMessage();
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
public void messageDenied() {
|
||||
setup("DENIED");
|
||||
|
||||
messageService.getMessage();
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
public void jsrMessageDenied() {
|
||||
setup("DENIED");
|
||||
|
||||
messageService.getJsrMessage();
|
||||
}
|
||||
|
||||
// SEC-2926
|
||||
@Test
|
||||
public void doFilterIsUserInRole() throws Exception {
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
|
||||
|
||||
chain = new MockFilterChain() {
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
assertThat(httpRequest.isUserInRole("USER")).isTrue();
|
||||
assertThat(httpRequest.isUserInRole("INVALID")).isFalse();
|
||||
super.doFilter(request, response);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
|
||||
assertThat(chain.getRequest()).isNotNull();
|
||||
}
|
||||
|
||||
private void setup(String role) {
|
||||
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password", role);
|
||||
SecurityContextHolder.getContext().setAuthentication(user);
|
||||
}
|
||||
}
|
||||
Regular → Executable
+13
-9
@@ -13,20 +13,24 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package sample.mvc;
|
||||
package org.springframework.security.config.core;
|
||||
|
||||
import org.springframework.security.web.csrf.CsrfToken;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
*/
|
||||
@RestController
|
||||
public class CsrfController {
|
||||
public class HelloWorldMessageService implements MessageService {
|
||||
|
||||
@RequestMapping("/csrf")
|
||||
public CsrfToken csrf(CsrfToken csrfToken) {
|
||||
return csrfToken;
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
public String getMessage() {
|
||||
return "Hello World";
|
||||
}
|
||||
|
||||
@RolesAllowed("USER")
|
||||
public String getJsrMessage() {
|
||||
return "Hello JSR";
|
||||
}
|
||||
}
|
||||
Regular → Executable
+4
-5
@@ -13,13 +13,12 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package sample.config;
|
||||
|
||||
import java.io.IOException;
|
||||
package org.springframework.security.config.core;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public interface RedisConnectionProperties {
|
||||
int getPort() throws IOException;
|
||||
public interface MessageService {
|
||||
String getMessage();
|
||||
String getJsrMessage();
|
||||
}
|
||||
+10
-3
@@ -15,11 +15,9 @@
|
||||
*/
|
||||
package org.springframework.security.config.http;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
|
||||
import org.springframework.context.support.AbstractXmlApplicationContext;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
@@ -33,6 +31,8 @@ import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource;
|
||||
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
@@ -118,6 +118,13 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
|
||||
+ ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
}
|
||||
|
||||
@Test(expected = BeanDefinitionParsingException.class)
|
||||
public void parsingInterceptUrlServletPathFails() {
|
||||
setContext("<filter-security-metadata-source id='fids' use-expressions='false'>"
|
||||
+ " <intercept-url pattern='/secure' access='ROLE_USER' servlet-path='/spring' />"
|
||||
+ "</filter-security-metadata-source>");
|
||||
}
|
||||
|
||||
private FilterInvocation createFilterInvocation(String path, String method) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI(null);
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* 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.http;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.ConfigurableWebApplicationContext;
|
||||
import org.springframework.web.context.support.XmlWebApplicationContext;
|
||||
|
||||
public class HttpInterceptUrlTests {
|
||||
ConfigurableWebApplicationContext context;
|
||||
|
||||
MockMvc mockMvc;
|
||||
|
||||
@After
|
||||
public void close() {
|
||||
if(context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void interceptUrlWhenRequestMatcherRefThenWorks() throws Exception {
|
||||
loadConfig("interceptUrlWhenRequestMatcherRefThenWorks.xml");
|
||||
|
||||
mockMvc.perform(get("/foo"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
|
||||
mockMvc.perform(get("/FOO"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
|
||||
mockMvc.perform(get("/other"))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
private void loadConfig(String... configLocations) {
|
||||
for(int i=0;i<configLocations.length;i++) {
|
||||
configLocations[i] = getClass().getName().replaceAll("\\.", "/") + "-" + configLocations[i];
|
||||
}
|
||||
XmlWebApplicationContext context = new XmlWebApplicationContext();
|
||||
context.setConfigLocations(configLocations);
|
||||
context.setServletContext(new MockServletContext());
|
||||
context.refresh();
|
||||
this.context = context;
|
||||
|
||||
context.getAutowireCapableBeanFactory().autowireBean(this);
|
||||
|
||||
Filter springSecurityFilterChain = context.getBean("springSecurityFilterChain", Filter.class);
|
||||
mockMvc = MockMvcBuilders
|
||||
.standaloneSetup(new FooController())
|
||||
.addFilters(springSecurityFilterChain)
|
||||
.build();
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class FooController {
|
||||
@GetMapping("/*")
|
||||
String foo() {
|
||||
return "foo";
|
||||
}
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* 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.method.configuration;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.PermissionEvaluator;
|
||||
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.authentication.AuthenticationTrustResolver;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
public class Gh4020GlobalMethodSecurityConfigurationTests {
|
||||
@Autowired
|
||||
DenyAllService denyAll;
|
||||
|
||||
// gh-4020
|
||||
@Test(expected = AuthenticationCredentialsNotFoundException.class)
|
||||
public void denyAll() {
|
||||
this.denyAll.denyAll();
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
static class SecurityConfig {
|
||||
@Bean
|
||||
PermissionEvaluator permissionEvaluator() {
|
||||
return mock(PermissionEvaluator.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
RoleHierarchy RoleHierarchy() {
|
||||
return mock(RoleHierarchy.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
AuthenticationTrustResolver trustResolver() {
|
||||
return mock(AuthenticationTrustResolver.class);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
DenyAllService denyAll;
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class ServiceConfig {
|
||||
@Bean
|
||||
DenyAllService denyAllService() {
|
||||
return new DenyAllService();
|
||||
}
|
||||
}
|
||||
|
||||
@PreAuthorize("denyAll")
|
||||
static class DenyAllService {
|
||||
void denyAll() {
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -25,7 +25,7 @@ import org.springframework.security.util.InMemoryResource;
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class InMemoryXmlApplicationContext extends AbstractXmlApplicationContext {
|
||||
private static final String BEANS_OPENING = "<b:beans xmlns='http://www.springframework.org/schema/security'\n"
|
||||
static final String BEANS_OPENING = "<b:beans xmlns='http://www.springframework.org/schema/security'\n"
|
||||
+ " xmlns:context='http://www.springframework.org/schema/context'\n"
|
||||
+ " xmlns:b='http://www.springframework.org/schema/beans'\n"
|
||||
+ " xmlns:aop='http://www.springframework.org/schema/aop'\n"
|
||||
@@ -38,16 +38,18 @@ public class InMemoryXmlApplicationContext extends AbstractXmlApplicationContext
|
||||
+ "http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd\n"
|
||||
+ "http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd\n"
|
||||
+ "http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-";
|
||||
private static final String BEANS_CLOSE = "</b:beans>\n";
|
||||
static final String BEANS_CLOSE = "</b:beans>\n";
|
||||
|
||||
static final String SPRING_SECURITY_VERSION = "4.2";
|
||||
|
||||
Resource inMemoryXml;
|
||||
|
||||
public InMemoryXmlApplicationContext(String xml) {
|
||||
this(xml, "4.1", null);
|
||||
this(xml, SPRING_SECURITY_VERSION, null);
|
||||
}
|
||||
|
||||
public InMemoryXmlApplicationContext(String xml, ApplicationContext parent) {
|
||||
this(xml, "4.1", parent);
|
||||
this(xml, SPRING_SECURITY_VERSION, parent);
|
||||
}
|
||||
|
||||
public InMemoryXmlApplicationContext(String xml, String secVersion,
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.security.util.InMemoryResource;
|
||||
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.springframework.security.config.util.InMemoryXmlApplicationContext.BEANS_CLOSE;
|
||||
import static org.springframework.security.config.util.InMemoryXmlApplicationContext.BEANS_OPENING;
|
||||
import static org.springframework.security.config.util.InMemoryXmlApplicationContext.SPRING_SECURITY_VERSION;
|
||||
|
||||
/**
|
||||
* @author Joe Grandja
|
||||
*/
|
||||
public class InMemoryXmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {
|
||||
private Resource inMemoryXml;
|
||||
|
||||
public InMemoryXmlWebApplicationContext(String xml) {
|
||||
this(xml, SPRING_SECURITY_VERSION, null);
|
||||
}
|
||||
|
||||
public InMemoryXmlWebApplicationContext(String xml, ApplicationContext parent) {
|
||||
this(xml, SPRING_SECURITY_VERSION, parent);
|
||||
}
|
||||
|
||||
public InMemoryXmlWebApplicationContext(String xml, String secVersion,
|
||||
ApplicationContext parent) {
|
||||
String fullXml = BEANS_OPENING + secVersion + ".xsd'>\n" + xml + BEANS_CLOSE;
|
||||
inMemoryXml = new InMemoryResource(fullXml);
|
||||
setAllowBeanDefinitionOverriding(true);
|
||||
setParent(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
|
||||
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
|
||||
reader.loadBeanDefinitions(new Resource[] { inMemoryXml });
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.websocket;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.beans.factory.support.GenericBeanDefinition;
|
||||
import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry;
|
||||
|
||||
public class MessageSecurityPostProcessorTest {
|
||||
|
||||
private WebSocketMessageBrokerSecurityBeanDefinitionParser.MessageSecurityPostProcessor postProcessor =
|
||||
new WebSocketMessageBrokerSecurityBeanDefinitionParser.MessageSecurityPostProcessor("id", false);
|
||||
|
||||
@Test
|
||||
public void handlesBeansWithoutClass() {
|
||||
BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
|
||||
registry.registerBeanDefinition("beanWithoutClass", new GenericBeanDefinition());
|
||||
postProcessor.postProcessBeanDefinitionRegistry(registry);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<b:beans xmlns:b="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://www.springframework.org/schema/security"
|
||||
xmlns:c="http://www.springframework.org/schema/c"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
|
||||
|
||||
<http use-expressions="true">
|
||||
<intercept-url access="hasRole('USER')" pattern="/**" />
|
||||
<form-login/>
|
||||
<logout/>
|
||||
</http>
|
||||
|
||||
<authentication-manager>
|
||||
<authentication-provider>
|
||||
<user-service>
|
||||
<user name="user" password="password" authorities="USER"/>
|
||||
<user name="admin" password="password" authorities="USER,ADMIN"/>
|
||||
</user-service>
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
|
||||
<global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled"/>
|
||||
|
||||
<b:bean class="org.springframework.security.config.core.HelloWorldMessageService"/>
|
||||
<b:bean class="org.springframework.security.config.core.GrantedAuthorityDefaults"
|
||||
c:rolePrefix=""/>
|
||||
</b:beans>
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<b:beans xmlns:b="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://www.springframework.org/schema/security"
|
||||
xmlns:c="http://www.springframework.org/schema/c"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<http>
|
||||
<http-basic/>
|
||||
<intercept-url request-matcher-ref="matcherRef" access="denyAll"/>
|
||||
</http>
|
||||
|
||||
<user-service>
|
||||
<user name="user" password="password" authorities="ROLE_USER"/>
|
||||
</user-service>
|
||||
|
||||
<b:bean id="matcherRef" class="org.springframework.security.web.util.matcher.AntPathRequestMatcher"
|
||||
c:pattern="/foo"
|
||||
c:httpMethod="GET"
|
||||
c:caseSensitive="false"/>
|
||||
</b:beans>
|
||||
@@ -131,7 +131,7 @@
|
||||
<constructor-arg ref="fooMatcher"/>
|
||||
<constructor-arg>
|
||||
<list>
|
||||
<ref local="mockFilter"/>
|
||||
<ref bean="mockFilter"/>
|
||||
</list>
|
||||
</constructor-arg>
|
||||
</bean>
|
||||
@@ -143,9 +143,9 @@
|
||||
</constructor-arg>
|
||||
<constructor-arg>
|
||||
<list>
|
||||
<ref local="sif"/>
|
||||
<ref local="mockFilter"/>
|
||||
<ref local="mockFilter2"/>
|
||||
<ref bean="sif"/>
|
||||
<ref bean="mockFilter"/>
|
||||
<ref bean="mockFilter2"/>
|
||||
</list>
|
||||
</constructor-arg>
|
||||
</bean>
|
||||
@@ -167,9 +167,9 @@
|
||||
</constructor-arg>
|
||||
<constructor-arg>
|
||||
<list>
|
||||
<ref local="sif"/>
|
||||
<ref local="apf"/>
|
||||
<ref local="mockFilter"/>
|
||||
<ref bean="sif"/>
|
||||
<ref bean="apf"/>
|
||||
<ref bean="mockFilter"/>
|
||||
</list>
|
||||
</constructor-arg>
|
||||
</bean>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user