Compare commits
145 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c33fc00507 | |||
| 1150dafd55 | |||
| 4f80b9d737 | |||
| e6f5d4f13b | |||
| 23dfe33877 | |||
| 0e2b75e994 | |||
| e9e57b7509 | |||
| c60a3e165e | |||
| 3a756bfa57 | |||
| 800157fe42 | |||
| ba32758b92 | |||
| 05e940692a | |||
| 5e74da9b4f | |||
| 9a49795abc | |||
| 566fb939ca | |||
| 5b26158f4d | |||
| a7eaaec431 | |||
| 5fde56d84a | |||
| 10d53be70b | |||
| 93e0ce5236 | |||
| 677a9634b8 | |||
| 6d72c3f3aa | |||
| 67fcd51d59 | |||
| 15a777d534 | |||
| 7e0622c7be | |||
| 07dd883d6d | |||
| 8170e47ff2 | |||
| c408fb7edf | |||
| 4ff0fdfff9 | |||
| 47b82ccd83 | |||
| 54cc2e4509 | |||
| 31650d7eaa | |||
| 5888a3f6b7 | |||
| 87a5c16b53 | |||
| 4b407189c2 | |||
| 96c944c4fc | |||
| 1bbae835a4 | |||
| de640a10d6 | |||
| 85c8d53b36 | |||
| 2d6bcf2cc3 | |||
| 18b98fc607 | |||
| 7bf8091e22 | |||
| d19d03dea8 | |||
| 35df3ff89b | |||
| 5f75e137d8 | |||
| b988f656c6 | |||
| 06fff9441e | |||
| edb354a2a9 | |||
| 1ce0cf44a8 | |||
| ffd8f7c8e4 | |||
| ecaa2c5b1c | |||
| a1c381c276 | |||
| 1b213d65d2 | |||
| eb897ac69c | |||
| bd8180da12 | |||
| 5dabff25c3 | |||
| 09429479fe | |||
| dc602c0840 | |||
| fedc183b5b | |||
| d3f12f0ee7 | |||
| 2a723cf5c7 | |||
| 6f32303866 | |||
| 400adaef1c | |||
| 9924d6e920 | |||
| 6cfd30aee8 | |||
| 1abdb69615 | |||
| b07f6b0178 | |||
| f0eec1b03b | |||
| 6ca6d80184 | |||
| ce5eec8761 | |||
| 86e03b3fb4 | |||
| c909264b31 | |||
| f52ab9a146 | |||
| ad2cb501b8 | |||
| 8659a4b555 | |||
| e04b29426b | |||
| 350d434e28 | |||
| bbfc3d2b4b | |||
| a7e4f36dbe | |||
| e61aafe115 | |||
| ff95388ce1 | |||
| 545228cf8d | |||
| 7b8fa90d96 | |||
| c30e218f1f | |||
| 70d284865f | |||
| a4b5523063 | |||
| 8883ec17e5 | |||
| f524da3edc | |||
| e1e464387e | |||
| a5dc48f9d9 | |||
| 9b722a9c85 | |||
| 884a4e46df | |||
| 01c2d57d46 | |||
| c9e42ce756 | |||
| 9b0b933736 | |||
| 0169b8746b | |||
| 25a87051a6 | |||
| 7edf9fc6c8 | |||
| a06f1e3936 | |||
| b296d2eaa5 | |||
| 11a8c76991 | |||
| 2f441f18e6 | |||
| a7de1e363f | |||
| 32f5fb5eb2 | |||
| f7f6798f71 | |||
| 0b72f93027 | |||
| 5b751baf61 | |||
| ec9ab1965a | |||
| 30aede82da | |||
| 2686452b99 | |||
| 7e470ff5bd | |||
| df6a6e5991 | |||
| 1500a22439 | |||
| 64cb256bb9 | |||
| e6d68acfd6 | |||
| bc2a7ac394 | |||
| 55019b2f0b | |||
| 151b545ed0 | |||
| c67ce144b9 | |||
| 6729c39905 | |||
| 197439f9e1 | |||
| 70a11267fa | |||
| 4e0c165d47 | |||
| 93844b1823 | |||
| a30b3321c4 | |||
| ffb8c1978a | |||
| 4722ab21bf | |||
| 335735e227 | |||
| 501269a51f | |||
| 6b58218256 | |||
| de1137fc5e | |||
| e68657216c | |||
| bfada59a1e | |||
| bc17860cb6 | |||
| 5e351a4f75 | |||
| 0458ca88e6 | |||
| a7a71d6cef | |||
| a7f180b2c7 | |||
| 87f266133b | |||
| 8f8deac0f4 | |||
| 9830d01acc | |||
| d8fea5c6f1 | |||
| 4d410b0b61 | |||
| 24a4fbfe56 | |||
| d5d1c30d1d |
+6
-11
@@ -1,22 +1,17 @@
|
||||
# EditorConfig for Spring Security
|
||||
# see https://github.com/spring-projects/spring-security/blob/master/CONTRIBUTING.md#mind-the-whitespace
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
# Unix-style newlines with a newline ending every file
|
||||
[*]
|
||||
end_of_line = lf
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
max_line_length = 120
|
||||
|
||||
[*.java]
|
||||
indent_style = tab
|
||||
indent_size = 4
|
||||
charset = latin1
|
||||
continuation_indent_size = 8
|
||||
|
||||
[*.xml]
|
||||
# 4 tabs indentation
|
||||
indent_style = tab
|
||||
indent_size = 4
|
||||
charset = latin1
|
||||
continuation_indent_size = 8
|
||||
tab_width = 4
|
||||
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
<!--
|
||||
For Security Vulnerabilities, please use https://pivotal.io/security#reporting
|
||||
-->
|
||||
|
||||
### Summary
|
||||
|
||||
<!--
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
<!--
|
||||
For Security Vulnerabilities, please use https://pivotal.io/security#reporting
|
||||
-->
|
||||
|
||||
<!--
|
||||
Thanks for contributing to Spring Security. Please provide a brief description of your pull-request and reference any related issue numbers (prefix references with #).
|
||||
-->
|
||||
|
||||
+2
-3
@@ -8,7 +8,7 @@ By participating, you are expected to uphold this code. Please report unaccepta
|
||||
|
||||
# Similar but different
|
||||
|
||||
Each Spring module is slightly different than another in terms of team size, number of issues, etc. Therefore each project is managed slightly different. You will notice that this document is very similar to the [Spring Framework Contributor guidelines](https://github.com/spring-projects/spring-framework/wiki/Contributor-guidelines). However, there are some subtle differences between the two documents, so please be sure to read this document thoroughly.
|
||||
Each Spring module is slightly different than another in terms of team size, number of issues, etc. Therefore each project is managed slightly different. You will notice that this document is very similar to the [Spring Framework Contributor guidelines](https://github.com/SpringSource/spring-framework/wiki/Contributor-guidelines). However, there are some subtle differences between the two documents, so please be sure to read this document thoroughly.
|
||||
|
||||
# Importing into IDE
|
||||
|
||||
@@ -47,7 +47,7 @@ Create your topic branch to be submitted as a pull request from master. The Spri
|
||||
# Use short branch names
|
||||
Branches used when submitting pull requests should preferably be named according to GitHub issues, e.g. 'gh-1234' or 'gh-1234-fix-npe'. Otherwise, use succinct, lower-case, dash (-) delimited names, such as 'fix-warnings', 'fix-typo', etc. This is important, because branch names show up in the merge commits that result from accepting pull requests, and should be as expressive and concise as possible.
|
||||
|
||||
# Keep commits focused
|
||||
#Keep commits focused
|
||||
|
||||
Remember each ticket should be focused on a single item of interest since the tickets are used to produce the changelog. Since each commit should be tied to a single GitHub issue, ensure that your commits are focused. For example, do not include an update to a transitive library in your commit unless the GitHub is to update the library. Reviewing your commits is essential before sending a pull request.
|
||||
|
||||
@@ -180,7 +180,6 @@ Fixes gh-123
|
||||
2. Do not end the subject line with a period
|
||||
3. In the body of the commit message, explain how things worked before this commit, what has changed, and how things work now
|
||||
3. Include Fixes gh-<issue-number> at the end if this fixes a GitHub issue
|
||||
5. Avoid markdown, including back-ticks identifying code
|
||||
|
||||
# Run all tests prior to submission
|
||||
|
||||
|
||||
Vendored
+8
-54
@@ -19,7 +19,7 @@ try {
|
||||
currentBuild.result = 'FAILED: check'
|
||||
throw e
|
||||
} finally {
|
||||
junit '**/build/test-results/*/*.xml'
|
||||
junit '**/build/*-results/*.xml'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ try {
|
||||
checkout scm
|
||||
withCredentials([string(credentialsId: 'spring-sonar.login', variable: 'SONAR_LOGIN')]) {
|
||||
try {
|
||||
sh "./gradlew clean jacocoTestReport sonarqube -Dsonar.jacoco.reportPaths='**/build/jacoco/*.exec' -PexcludeProjects='**/samples/**' -Dsonar.host.url=$SPRING_SONAR_HOST_URL -Dsonar.login=$SONAR_LOGIN --refresh-dependencies --no-daemon --stacktrace"
|
||||
sh "./gradlew clean sonarqube -PexcludeProjects='**/samples/**' -Dsonar.host.url=$SPRING_SONAR_HOST_URL -Dsonar.login=$SONAR_LOGIN --refresh-dependencies --no-daemon --stacktrace"
|
||||
} catch(Exception e) {
|
||||
currentBuild.result = 'FAILED: sonar'
|
||||
throw e
|
||||
@@ -39,60 +39,17 @@ try {
|
||||
}
|
||||
}
|
||||
},
|
||||
snapshots: {
|
||||
stage('Snapshot Tests') {
|
||||
springio: {
|
||||
stage('Spring IO') {
|
||||
node {
|
||||
checkout scm
|
||||
try {
|
||||
sh "./gradlew clean test -PforceMavenRepositories=snapshot -PspringVersion='5.+' -PreactorVersion=Californium-BUILD-SNAPSHOT -PspringDataVersion=Lovelace-BUILD-SNAPSHOT --refresh-dependencies --no-daemon --stacktrace"
|
||||
sh "./gradlew clean springIoCheck -PplatformVersion=Cairo-BUILD-SNAPSHOT -PexcludeProjects='**/samples/**' --refresh-dependencies --no-daemon --stacktrace"
|
||||
} catch(Exception e) {
|
||||
currentBuild.result = 'FAILED: snapshots'
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
jdk9: {
|
||||
stage('JDK 9') {
|
||||
node {
|
||||
checkout scm
|
||||
try {
|
||||
withEnv(["JAVA_HOME=${ tool 'jdk9' }"]) {
|
||||
sh "./gradlew clean test --refresh-dependencies --no-daemon --stacktrace"
|
||||
}
|
||||
} catch(Exception e) {
|
||||
currentBuild.result = 'FAILED: jdk9'
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
jdk10: {
|
||||
stage('JDK 10') {
|
||||
node {
|
||||
checkout scm
|
||||
try {
|
||||
withEnv(["JAVA_HOME=${ tool 'jdk10' }"]) {
|
||||
sh "./gradlew clean test --refresh-dependencies --no-daemon --stacktrace"
|
||||
}
|
||||
} catch(Exception e) {
|
||||
currentBuild.result = 'FAILED: jdk10'
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
jdk11: {
|
||||
stage('JDK 11') {
|
||||
node {
|
||||
checkout scm
|
||||
try {
|
||||
withEnv(["JAVA_HOME=${ tool 'jdk11' }"]) {
|
||||
sh "./gradlew clean test --refresh-dependencies --no-daemon --stacktrace"
|
||||
}
|
||||
} catch(Exception e) {
|
||||
currentBuild.result = 'FAILED: jdk11'
|
||||
currentBuild.result = 'FAILED: springio'
|
||||
throw e
|
||||
} finally {
|
||||
junit '**/build/spring-io*-results/*.xml'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -136,9 +93,6 @@ try {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch(Exception e) {
|
||||
currentBuild.result = 'FAILED: deploys'
|
||||
throw e
|
||||
} finally {
|
||||
def buildStatus = currentBuild.result
|
||||
def buildNotSuccess = !SUCCESS.equals(buildStatus)
|
||||
|
||||
@@ -92,11 +92,11 @@ public abstract class AclFormattingUtils {
|
||||
*/
|
||||
public static String printBinary(int mask, char code) {
|
||||
Assert.doesNotContain(Character.toString(code),
|
||||
Character.toString(Permission.RESERVED_ON),
|
||||
() -> Permission.RESERVED_ON + " is a reserved character code");
|
||||
Character.toString(Permission.RESERVED_ON), Permission.RESERVED_ON
|
||||
+ " is a reserved character code");
|
||||
Assert.doesNotContain(Character.toString(code),
|
||||
Character.toString(Permission.RESERVED_OFF),
|
||||
() -> Permission.RESERVED_OFF + " is a reserved character code");
|
||||
Character.toString(Permission.RESERVED_OFF), Permission.RESERVED_OFF
|
||||
+ " is a reserved character code");
|
||||
|
||||
return printBinary(mask, Permission.RESERVED_ON, Permission.RESERVED_OFF)
|
||||
.replace(Permission.RESERVED_ON, code);
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -104,9 +104,9 @@ public class DefaultPermissionFactory implements PermissionFactory {
|
||||
|
||||
// Ensure no existing Permission uses this integer or code
|
||||
Assert.isTrue(!registeredPermissionsByInteger.containsKey(mask),
|
||||
() -> "An existing Permission already provides mask " + mask);
|
||||
"An existing Permission already provides mask " + mask);
|
||||
Assert.isTrue(!registeredPermissionsByName.containsKey(permissionName),
|
||||
() -> "An existing Permission already provides name '" + permissionName + "'");
|
||||
"An existing Permission already provides name '" + permissionName + "'");
|
||||
|
||||
// Register the new Permission
|
||||
registeredPermissionsByInteger.put(mask, perm);
|
||||
|
||||
@@ -111,7 +111,7 @@ public class JdbcAclService implements AclService {
|
||||
throws NotFoundException {
|
||||
Map<ObjectIdentity, Acl> map = readAclsById(Arrays.asList(object), sids);
|
||||
Assert.isTrue(map.containsKey(object),
|
||||
() -> "There should have been an Acl entry for ObjectIdentity " + object);
|
||||
"There should have been an Acl entry for ObjectIdentity " + object);
|
||||
|
||||
return (Acl) map.get(object);
|
||||
}
|
||||
|
||||
+2
-2
@@ -154,11 +154,11 @@ public class EhCacheBasedAclCacheTests {
|
||||
|
||||
Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy",
|
||||
retrieved);
|
||||
assertThat(retrieved1).isNull();
|
||||
assertThat(retrieved1).isEqualTo(null);
|
||||
|
||||
Object retrieved2 = FieldUtils.getProtectedFieldValue(
|
||||
"permissionGrantingStrategy", retrieved);
|
||||
assertThat(retrieved2).isNull();
|
||||
assertThat(retrieved2).isEqualTo(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-2
@@ -1,11 +1,10 @@
|
||||
buildscript {
|
||||
dependencies {
|
||||
classpath 'io.spring.gradle:spring-build-conventions:0.0.22.RELEASE'
|
||||
classpath 'io.spring.gradle:spring-build-conventions:0.0.15.RELEASE'
|
||||
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
|
||||
}
|
||||
repositories {
|
||||
maven { url 'https://repo.spring.io/plugins-snapshot' }
|
||||
maven { url 'https://plugins.gradle.org/m2/' }
|
||||
}
|
||||
}
|
||||
apply plugin: 'io.spring.convention.root'
|
||||
|
||||
+2
-2
@@ -353,7 +353,7 @@ public class CasAuthenticationProviderTests {
|
||||
assertThat(cap.supports(TestingAuthenticationToken.class)).isFalse();
|
||||
|
||||
// Try it anyway
|
||||
assertThat(cap.authenticate(token)).isNull();
|
||||
assertThat(cap.authenticate(token)).isEqualTo(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -370,7 +370,7 @@ public class CasAuthenticationProviderTests {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
|
||||
"some_normal_user", "password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_A"));
|
||||
assertThat(cap.authenticate(token)).isNull();
|
||||
assertThat(cap.authenticate(token)).isEqualTo(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -13,7 +13,6 @@ dependencies {
|
||||
optional project(':spring-security-messaging')
|
||||
optional project(':spring-security-oauth2-client')
|
||||
optional project(':spring-security-oauth2-jose')
|
||||
optional project(':spring-security-oauth2-resource-server')
|
||||
optional project(':spring-security-openid')
|
||||
optional project(':spring-security-web')
|
||||
optional 'io.projectreactor:reactor-core'
|
||||
@@ -31,14 +30,11 @@ dependencies {
|
||||
testCompile project(':spring-security-cas')
|
||||
testCompile project(':spring-security-test')
|
||||
testCompile project(path : ':spring-security-core', configuration : 'tests')
|
||||
testCompile project(path : ':spring-security-oauth2-client', configuration : 'tests')
|
||||
testCompile project(path : ':spring-security-web', configuration : 'tests')
|
||||
testCompile apachedsDependencies
|
||||
testCompile powerMock2Dependencies
|
||||
testCompile spockDependencies
|
||||
testCompile 'com.squareup.okhttp3:mockwebserver'
|
||||
testCompile 'ch.qos.logback:logback-classic'
|
||||
testCompile 'io.projectreactor.netty:reactor-netty'
|
||||
testCompile 'javax.annotation:jsr250-api:1.0'
|
||||
testCompile 'javax.xml.bind:jaxb-api'
|
||||
testCompile 'ldapsdk:ldapsdk:4.1'
|
||||
|
||||
+7
-7
@@ -122,7 +122,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
|
||||
* invokes {@link SecurityConfigurerAdapter#setBuilder(SecurityBuilder)}.
|
||||
*
|
||||
* @param configurer
|
||||
* @return the {@link SecurityConfigurerAdapter} for further customizations
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -140,7 +140,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
|
||||
* are not considered.
|
||||
*
|
||||
* @param configurer
|
||||
* @return the {@link SecurityConfigurerAdapter} for further customizations
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public <C extends SecurityConfigurer<O, B>> C apply(C configurer) throws Exception {
|
||||
@@ -172,7 +172,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
|
||||
|
||||
/**
|
||||
* Gets the shared objects
|
||||
* @return the shared Objects
|
||||
* @return
|
||||
*/
|
||||
public Map<Class<? extends Object>, Object> getSharedObjects() {
|
||||
return Collections.unmodifiableMap(this.sharedObjects);
|
||||
@@ -214,7 +214,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
|
||||
* List if not found. Note that object hierarchies are not considered.
|
||||
*
|
||||
* @param clazz the {@link SecurityConfigurer} class to look for
|
||||
* @return a list of {@link SecurityConfigurer}s for further customization
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <C extends SecurityConfigurer<O, B>> List<C> getConfigurers(Class<C> clazz) {
|
||||
@@ -230,7 +230,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
|
||||
* List if not found. Note that object hierarchies are not considered.
|
||||
*
|
||||
* @param clazz the {@link SecurityConfigurer} class to look for
|
||||
* @return a list of {@link SecurityConfigurer}s for further customization
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <C extends SecurityConfigurer<O, B>> List<C> removeConfigurers(Class<C> clazz) {
|
||||
@@ -246,7 +246,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
|
||||
* found. Note that object hierarchies are not considered.
|
||||
*
|
||||
* @param clazz
|
||||
* @return the {@link SecurityConfigurer} for further customizations
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <C extends SecurityConfigurer<O, B>> C getConfigurer(Class<C> clazz) {
|
||||
@@ -359,7 +359,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
|
||||
/**
|
||||
* Subclasses must implement this method to build the object that is being returned.
|
||||
*
|
||||
* @return the Object to be buit or null if the implementation allows it
|
||||
* @return
|
||||
*/
|
||||
protected abstract O performBuild() throws Exception;
|
||||
|
||||
|
||||
+1
-1
@@ -51,7 +51,7 @@ public abstract class SecurityConfigurerAdapter<O, B extends SecurityBuilder<O>>
|
||||
* Return the {@link SecurityBuilder} when done using the {@link SecurityConfigurer}.
|
||||
* This is useful for method chaining.
|
||||
*
|
||||
* @return the {@link SecurityBuilder} for further customizations
|
||||
* @return
|
||||
*/
|
||||
public B and() {
|
||||
return getBuilder();
|
||||
|
||||
+1
-1
@@ -258,7 +258,7 @@ public class AuthenticationManagerBuilder
|
||||
* default configuration in the {@link SecurityConfigurer#configure(SecurityBuilder)}
|
||||
* method.
|
||||
*
|
||||
* @return true, if {@link AuthenticationManagerBuilder} is configured, otherwise false
|
||||
* @return
|
||||
*/
|
||||
public boolean isConfigured() {
|
||||
return !authenticationProviders.isEmpty() || parentAuthenticationManager != null;
|
||||
|
||||
+2
-7
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -152,7 +152,7 @@ public class AuthenticationConfiguration {
|
||||
return null;
|
||||
}
|
||||
Assert.isTrue(beanNamesForType.length == 1,
|
||||
() -> "Expecting to only find a single bean for type " + interfaceName
|
||||
"Expecting to only find a single bean for type " + interfaceName
|
||||
+ ", but found " + Arrays.asList(beanNamesForType));
|
||||
lazyTargetSource.setTargetBeanName(beanNamesForType[0]);
|
||||
lazyTargetSource.setBeanFactory(applicationContext);
|
||||
@@ -289,11 +289,6 @@ public class AuthenticationConfiguration {
|
||||
return getPasswordEncoder().matches(rawPassword, encodedPassword);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean upgradeEncoding(String encodedPassword) {
|
||||
return getPasswordEncoder().upgradeEncoding(encodedPassword);
|
||||
}
|
||||
|
||||
private PasswordEncoder getPasswordEncoder() {
|
||||
if (this.passwordEncoder != null) {
|
||||
return this.passwordEncoder;
|
||||
|
||||
+1
-6
@@ -22,7 +22,6 @@ import org.springframework.security.authentication.dao.DaoAuthenticationProvider
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
|
||||
|
||||
/**
|
||||
* Lazily initializes the global authentication with a {@link UserDetailsService} if it is
|
||||
@@ -66,16 +65,12 @@ class InitializeUserDetailsBeanManagerConfigurer
|
||||
}
|
||||
|
||||
PasswordEncoder passwordEncoder = getBeanOrNull(PasswordEncoder.class);
|
||||
UserDetailsPasswordService passwordManager = getBeanOrNull(UserDetailsPasswordService.class);
|
||||
|
||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
if (passwordEncoder != null) {
|
||||
provider.setPasswordEncoder(passwordEncoder);
|
||||
}
|
||||
if (passwordManager != null) {
|
||||
provider.setUserDetailsPasswordService(passwordManager);
|
||||
}
|
||||
provider.afterPropertiesSet();
|
||||
|
||||
auth.authenticationProvider(provider);
|
||||
@@ -95,4 +90,4 @@ class InitializeUserDetailsBeanManagerConfigurer
|
||||
.getBean(userDetailsBeanNames[0], type);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -158,7 +158,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
|
||||
* @throws Exception if errors in {@link SimpleAuthorityMapper#afterPropertiesSet()}
|
||||
*/
|
||||
protected GrantedAuthoritiesMapper getAuthoritiesMapper() throws Exception {
|
||||
if (authoritiesMapper != null) {
|
||||
if(authoritiesMapper != null) {
|
||||
return authoritiesMapper;
|
||||
}
|
||||
|
||||
@@ -302,7 +302,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
|
||||
/**
|
||||
* Specifies the attribute name which contains the role name. Default is "cn".
|
||||
* @param groupRoleAttribute the attribute name that maps a group to a role.
|
||||
* @return the {@link LdapAuthenticationProviderConfigurer} for further customizations
|
||||
* @return
|
||||
*/
|
||||
public LdapAuthenticationProviderConfigurer<B> groupRoleAttribute(
|
||||
String groupRoleAttribute) {
|
||||
@@ -384,11 +384,11 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
|
||||
*/
|
||||
public final class PasswordCompareConfigurer {
|
||||
|
||||
/**Us
|
||||
/**
|
||||
* Allows specifying the {@link PasswordEncoder} to use. The default is
|
||||
* {@link org.springframework.security.crypto.password.NoOpPasswordEncoder}.
|
||||
* @param passwordEncoder the {@link PasswordEncoder} to use
|
||||
* @return the {@link PasswordCompareConfigurer} for further customizations
|
||||
* @return the {@link PasswordEncoder} to use
|
||||
*/
|
||||
public PasswordCompareConfigurer passwordEncoder(PasswordEncoder passwordEncoder) {
|
||||
LdapAuthenticationProviderConfigurer.this.passwordEncoder = passwordEncoder;
|
||||
@@ -602,7 +602,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the {@link PasswordCompareConfigurer} for further customizations
|
||||
* @return
|
||||
*/
|
||||
public PasswordCompareConfigurer passwordCompare() {
|
||||
return new PasswordCompareConfigurer().passwordAttribute("password")
|
||||
|
||||
+2
-2
@@ -63,7 +63,7 @@ public class JdbcUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B
|
||||
* Populates the {@link DataSource} to be used. This is the only required attribute.
|
||||
*
|
||||
* @param dataSource the {@link DataSource} to be used. Cannot be null.
|
||||
* @return The {@link JdbcUserDetailsManagerConfigurer} used for additional customizations
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public JdbcUserDetailsManagerConfigurer<B> dataSource(DataSource dataSource)
|
||||
@@ -142,7 +142,7 @@ public class JdbcUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B
|
||||
* storage (default is "").
|
||||
*
|
||||
* @param rolePrefix
|
||||
* @return The {@link JdbcUserDetailsManagerConfigurer} used for additional customizations
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public JdbcUserDetailsManagerConfigurer<B> rolePrefix(String rolePrefix)
|
||||
|
||||
+3
-3
@@ -69,7 +69,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* method can be invoked multiple times to add multiple users.
|
||||
*
|
||||
* @param userDetails the user to add. Cannot be null.
|
||||
* @return the {@link UserDetailsBuilder} for further customizations
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public final C withUser(UserDetails userDetails) {
|
||||
@@ -82,7 +82,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* method can be invoked multiple times to add multiple users.
|
||||
*
|
||||
* @param userBuilder the user to add. Cannot be null.
|
||||
* @return the {@link UserDetailsBuilder} for further customizations
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public final C withUser(User.UserBuilder userBuilder) {
|
||||
@@ -95,7 +95,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
|
||||
* method can be invoked multiple times to add multiple users.
|
||||
*
|
||||
* @param username the username for the user being added. Cannot be null.
|
||||
* @return the {@link UserDetailsBuilder} for further customizations
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public final UserDetailsBuilder withUser(String username) {
|
||||
|
||||
+1
-10
@@ -21,7 +21,6 @@ import org.springframework.security.config.annotation.SecurityBuilder;
|
||||
import org.springframework.security.config.annotation.authentication.ProviderManagerBuilder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
|
||||
|
||||
/**
|
||||
* Allows configuring a {@link DaoAuthenticationProvider}
|
||||
@@ -47,9 +46,6 @@ abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuil
|
||||
protected AbstractDaoAuthenticationConfigurer(U userDetailsService) {
|
||||
this.userDetailsService = userDetailsService;
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
if (userDetailsService instanceof UserDetailsPasswordService) {
|
||||
this.provider.setUserDetailsPasswordService((UserDetailsPasswordService) userDetailsService);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,7 +65,7 @@ abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuil
|
||||
* {@link DaoAuthenticationProvider}. The default is to use plain text.
|
||||
*
|
||||
* @param passwordEncoder The {@link PasswordEncoder} to use.
|
||||
* @return the {@link AbstractDaoAuthenticationConfigurer} for further customizations
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public C passwordEncoder(PasswordEncoder passwordEncoder) {
|
||||
@@ -77,11 +73,6 @@ abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuil
|
||||
return (C) this;
|
||||
}
|
||||
|
||||
public C userDetailsPasswordManager(UserDetailsPasswordService passwordManager) {
|
||||
provider.setUserDetailsPasswordService(passwordManager);
|
||||
return (C) this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(B builder) throws Exception {
|
||||
provider = postProcess(provider);
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -87,7 +87,7 @@ final class AutowireBeanFactoryObjectPostProcessor
|
||||
*/
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
for (SmartInitializingSingleton singleton : smartSingletons) {
|
||||
for(SmartInitializingSingleton singleton : smartSingletons) {
|
||||
singleton.afterSingletonsInstantiated();
|
||||
}
|
||||
}
|
||||
|
||||
+33
-40
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -23,12 +23,9 @@ import org.aopalliance.intercept.MethodInterceptor;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.BeanFactoryAware;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.AdviceMode;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -84,7 +81,7 @@ import org.springframework.util.Assert;
|
||||
*/
|
||||
@Configuration
|
||||
public class GlobalMethodSecurityConfiguration
|
||||
implements ImportAware, SmartInitializingSingleton, BeanFactoryAware {
|
||||
implements ImportAware, SmartInitializingSingleton {
|
||||
private static final Log logger = LogFactory
|
||||
.getLog(GlobalMethodSecurityConfiguration.class);
|
||||
private ObjectPostProcessor<Object> objectPostProcessor = new ObjectPostProcessor<Object>() {
|
||||
@@ -99,8 +96,9 @@ public class GlobalMethodSecurityConfiguration
|
||||
private AuthenticationManagerBuilder auth;
|
||||
private boolean disableAuthenticationRegistry;
|
||||
private AnnotationAttributes enableMethodSecurity;
|
||||
private BeanFactory context;
|
||||
private ApplicationContext context;
|
||||
private MethodSecurityExpressionHandler expressionHandler;
|
||||
private Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource;
|
||||
private MethodSecurityInterceptor methodSecurityInterceptor;
|
||||
|
||||
/**
|
||||
@@ -120,7 +118,7 @@ public class GlobalMethodSecurityConfiguration
|
||||
* {@link MethodInterceptor}.
|
||||
* </p>
|
||||
*
|
||||
* @return the {@link MethodInterceptor}.
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@Bean
|
||||
@@ -182,14 +180,15 @@ public class GlobalMethodSecurityConfiguration
|
||||
}
|
||||
|
||||
private <T> T getSingleBeanOrNull(Class<T> type) {
|
||||
try {
|
||||
return context.getBean(type);
|
||||
} catch (NoSuchBeanDefinitionException e) {}
|
||||
return null;
|
||||
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 {
|
||||
if (this.methodSecurityInterceptor == null) {
|
||||
if(this.methodSecurityInterceptor == null) {
|
||||
return;
|
||||
}
|
||||
this.methodSecurityInterceptor.setAuthenticationManager(authenticationManager());
|
||||
@@ -205,7 +204,7 @@ public class GlobalMethodSecurityConfiguration
|
||||
* {@link AfterInvocationManager}
|
||||
* </p>
|
||||
*
|
||||
* @return the {@link AfterInvocationManager} to use
|
||||
* @return
|
||||
*/
|
||||
protected AfterInvocationManager afterInvocationManager() {
|
||||
if (prePostEnabled()) {
|
||||
@@ -226,7 +225,7 @@ public class GlobalMethodSecurityConfiguration
|
||||
* Provide a custom {@link RunAsManager} for the default implementation of
|
||||
* {@link #methodSecurityInterceptor()}. The default is null.
|
||||
*
|
||||
* @return the {@link RunAsManager} to use
|
||||
* @return
|
||||
*/
|
||||
protected RunAsManager runAsManager() {
|
||||
return null;
|
||||
@@ -242,7 +241,7 @@ public class GlobalMethodSecurityConfiguration
|
||||
* <li>{@link AuthenticatedVoter}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @return the {@link AccessDecisionManager} to use
|
||||
* @return
|
||||
*/
|
||||
protected AccessDecisionManager accessDecisionManager() {
|
||||
List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList<AccessDecisionVoter<? extends Object>>();
|
||||
@@ -271,7 +270,7 @@ public class GlobalMethodSecurityConfiguration
|
||||
* {@link MethodSecurityExpressionHandler}
|
||||
* </p>
|
||||
*
|
||||
* @return the {@link MethodSecurityExpressionHandler} to use
|
||||
* @return
|
||||
*/
|
||||
protected MethodSecurityExpressionHandler createExpressionHandler() {
|
||||
return defaultMethodExpressionHandler;
|
||||
@@ -308,7 +307,7 @@ public class GlobalMethodSecurityConfiguration
|
||||
* {@link #configure(AuthenticationManagerBuilder)} was not overridden, then an
|
||||
* {@link AuthenticationManager} is attempted to be autowired by type.
|
||||
*
|
||||
* @return the {@link AuthenticationManager} to use
|
||||
* @return
|
||||
*/
|
||||
protected AuthenticationManager authenticationManager() throws Exception {
|
||||
if (authenticationManager == null) {
|
||||
@@ -347,7 +346,7 @@ public class GlobalMethodSecurityConfiguration
|
||||
* {@link #customMethodSecurityMetadataSource()} and the attributes on
|
||||
* {@link EnableGlobalMethodSecurity}.
|
||||
*
|
||||
* @return the {@link MethodSecurityMetadataSource}
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public MethodSecurityMetadataSource methodSecurityMetadataSource() {
|
||||
@@ -358,29 +357,17 @@ public class GlobalMethodSecurityConfiguration
|
||||
if (customMethodSecurityMetadataSource != null) {
|
||||
sources.add(customMethodSecurityMetadataSource);
|
||||
}
|
||||
|
||||
boolean hasCustom = customMethodSecurityMetadataSource != null;
|
||||
boolean isPrePostEnabled = prePostEnabled();
|
||||
boolean isSecuredEnabled = securedEnabled();
|
||||
boolean isJsr250Enabled = jsr250Enabled();
|
||||
|
||||
if (!isPrePostEnabled && !isSecuredEnabled && !isJsr250Enabled && !hasCustom) {
|
||||
throw new IllegalStateException("In the composition of all global method configuration, " +
|
||||
"no annotation support was actually activated");
|
||||
}
|
||||
|
||||
if (isPrePostEnabled) {
|
||||
if (prePostEnabled()) {
|
||||
sources.add(new PrePostAnnotationSecurityMetadataSource(attributeFactory));
|
||||
}
|
||||
if (isSecuredEnabled) {
|
||||
if (securedEnabled()) {
|
||||
sources.add(new SecuredAnnotationSecurityMetadataSource());
|
||||
}
|
||||
if (isJsr250Enabled) {
|
||||
if (jsr250Enabled()) {
|
||||
GrantedAuthorityDefaults grantedAuthorityDefaults =
|
||||
getSingleBeanOrNull(GrantedAuthorityDefaults.class);
|
||||
Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource = this.context.getBean(Jsr250MethodSecurityMetadataSource.class);
|
||||
if (grantedAuthorityDefaults != null) {
|
||||
jsr250MethodSecurityMetadataSource.setDefaultRolePrefix(
|
||||
this.jsr250MethodSecurityMetadataSource.setDefaultRolePrefix(
|
||||
grantedAuthorityDefaults.getRolePrefix());
|
||||
}
|
||||
sources.add(jsr250MethodSecurityMetadataSource);
|
||||
@@ -392,7 +379,7 @@ public class GlobalMethodSecurityConfiguration
|
||||
* Creates the {@link PreInvocationAuthorizationAdvice} to be used. The default is
|
||||
* {@link ExpressionBasedPreInvocationAdvice}.
|
||||
*
|
||||
* @return the {@link PreInvocationAuthorizationAdvice}
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public PreInvocationAuthorizationAdvice preInvocationAuthorizationAdvice() {
|
||||
@@ -418,6 +405,12 @@ public class GlobalMethodSecurityConfiguration
|
||||
.postProcess(defaultMethodExpressionHandler);
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setJsr250MethodSecurityMetadataSource(
|
||||
Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource) {
|
||||
this.jsr250MethodSecurityMetadataSource = jsr250MethodSecurityMetadataSource;
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setMethodSecurityExpressionHandler(
|
||||
List<MethodSecurityExpressionHandler> handlers) {
|
||||
@@ -429,9 +422,9 @@ public class GlobalMethodSecurityConfiguration
|
||||
this.expressionHandler = handlers.get(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
|
||||
this.context = beanFactory;
|
||||
@Autowired
|
||||
public void setApplicationContext(ApplicationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
private AuthenticationConfiguration getAuthenticationConfiguration() {
|
||||
@@ -464,7 +457,7 @@ public class GlobalMethodSecurityConfiguration
|
||||
EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils
|
||||
.findAnnotation(getClass(), EnableGlobalMethodSecurity.class);
|
||||
Assert.notNull(methodSecurityAnnotation,
|
||||
() -> EnableGlobalMethodSecurity.class.getName() + " is required");
|
||||
EnableGlobalMethodSecurity.class.getName() + " is required");
|
||||
Map<String, Object> methodSecurityAttrs = AnnotationUtils
|
||||
.getAnnotationAttributes(methodSecurityAnnotation);
|
||||
this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs);
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -42,7 +42,7 @@ final class GlobalMethodSecuritySelector implements ImportSelector {
|
||||
.getAnnotationAttributes(annoType.getName(), false);
|
||||
AnnotationAttributes attributes = AnnotationAttributes
|
||||
.fromMap(annotationAttributes);
|
||||
Assert.notNull(attributes, () -> String.format(
|
||||
Assert.notNull(attributes, String.format(
|
||||
"@%s is not present on importing class '%s' as expected",
|
||||
annoType.getSimpleName(), importingClassMetadata.getClassName()));
|
||||
|
||||
@@ -62,7 +62,7 @@ final class GlobalMethodSecuritySelector implements ImportSelector {
|
||||
boolean jsr250Enabled = attributes.getBoolean("jsr250Enabled");
|
||||
|
||||
List<String> classNames = new ArrayList<>(4);
|
||||
if (isProxy) {
|
||||
if(isProxy) {
|
||||
classNames.add(MethodSecurityMetadataSourceAdvisorRegistrar.class.getName());
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -52,7 +52,7 @@ class MethodSecurityMetadataSourceAdvisorRegistrar implements
|
||||
|
||||
MultiValueMap<String, Object> attributes = importingClassMetadata.getAllAnnotationAttributes(EnableGlobalMethodSecurity.class.getName());
|
||||
Integer order = (Integer) attributes.getFirst("order");
|
||||
if (order != null) {
|
||||
if(order != null) {
|
||||
advisor.addPropertyValue("order", order);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -163,7 +163,7 @@ public abstract class AbstractRequestMatcherRegistry<C> {
|
||||
String... mvcPatterns) {
|
||||
boolean isServlet30 = ClassUtils.isPresent("javax.servlet.ServletRegistration", getClass().getClassLoader());
|
||||
ObjectPostProcessor<Object> opp = this.context.getBean(ObjectPostProcessor.class);
|
||||
if (!this.context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) {
|
||||
if(!this.context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) {
|
||||
throw new NoSuchBeanDefinitionException("A Bean named " + HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME +" of type " + HandlerMappingIntrospector.class.getName()
|
||||
+ " is required to use MvcRequestMatcher. Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext.");
|
||||
}
|
||||
|
||||
-2
@@ -146,10 +146,8 @@ public interface HttpSecurityBuilder<H extends HttpSecurityBuilder<H>> extends
|
||||
* <li>{@link ConcurrentSessionFilter}</li>
|
||||
* <li>{@link OpenIDAuthenticationFilter}</li>
|
||||
* <li>{@link org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter}</li>
|
||||
* <li>{@link org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter}</li>
|
||||
* <li>{@link ConcurrentSessionFilter}</li>
|
||||
* <li>{@link DigestAuthenticationFilter}</li>
|
||||
* <li>{@link org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter}</li>
|
||||
* <li>{@link BasicAuthenticationFilter}</li>
|
||||
* <li>{@link RequestCacheAwareFilter}</li>
|
||||
* <li>{@link SecurityContextHolderAwareRequestFilter}</li>
|
||||
|
||||
+61
-59
@@ -19,6 +19,7 @@ import java.io.Serializable;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import org.springframework.security.web.access.ExceptionTranslationFilter;
|
||||
@@ -32,7 +33,6 @@ import org.springframework.security.web.authentication.preauth.x509.X509Authenti
|
||||
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter;
|
||||
import org.springframework.security.web.authentication.switchuser.SwitchUserFilter;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
import org.springframework.security.web.authentication.www.DigestAuthenticationFilter;
|
||||
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
|
||||
@@ -56,53 +56,74 @@ import org.springframework.web.filter.CorsFilter;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
final class FilterComparator implements Comparator<Filter>, Serializable {
|
||||
private static final int INITIAL_ORDER = 100;
|
||||
private static final int ORDER_STEP = 100;
|
||||
private final Map<String, Integer> filterToOrder = new HashMap<>();
|
||||
private static final int STEP = 100;
|
||||
private Map<String, Integer> filterToOrder = new HashMap<>();
|
||||
|
||||
FilterComparator() {
|
||||
Step order = new Step(INITIAL_ORDER, ORDER_STEP);
|
||||
put(ChannelProcessingFilter.class, order.next());
|
||||
put(ConcurrentSessionFilter.class, order.next());
|
||||
put(WebAsyncManagerIntegrationFilter.class, order.next());
|
||||
put(SecurityContextPersistenceFilter.class, order.next());
|
||||
put(HeaderWriterFilter.class, order.next());
|
||||
put(CorsFilter.class, order.next());
|
||||
put(CsrfFilter.class, order.next());
|
||||
put(LogoutFilter.class, order.next());
|
||||
int order = 100;
|
||||
put(ChannelProcessingFilter.class, order);
|
||||
order += STEP;
|
||||
put(ConcurrentSessionFilter.class, order);
|
||||
order += STEP;
|
||||
put(WebAsyncManagerIntegrationFilter.class, order);
|
||||
order += STEP;
|
||||
put(SecurityContextPersistenceFilter.class, order);
|
||||
order += STEP;
|
||||
put(HeaderWriterFilter.class, order);
|
||||
order += STEP;
|
||||
put(CorsFilter.class, order);
|
||||
order += STEP;
|
||||
put(CsrfFilter.class, order);
|
||||
order += STEP;
|
||||
put(LogoutFilter.class, order);
|
||||
order += STEP;
|
||||
filterToOrder.put(
|
||||
"org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter",
|
||||
order.next());
|
||||
put(X509AuthenticationFilter.class, order.next());
|
||||
put(AbstractPreAuthenticatedProcessingFilter.class, order.next());
|
||||
order);
|
||||
order += STEP;
|
||||
put(X509AuthenticationFilter.class, order);
|
||||
order += STEP;
|
||||
put(AbstractPreAuthenticatedProcessingFilter.class, order);
|
||||
order += STEP;
|
||||
filterToOrder.put("org.springframework.security.cas.web.CasAuthenticationFilter",
|
||||
order.next());
|
||||
order);
|
||||
order += STEP;
|
||||
filterToOrder.put(
|
||||
"org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter",
|
||||
order.next());
|
||||
put(UsernamePasswordAuthenticationFilter.class, order.next());
|
||||
put(ConcurrentSessionFilter.class, order.next());
|
||||
order);
|
||||
order += STEP;
|
||||
put(UsernamePasswordAuthenticationFilter.class, order);
|
||||
order += STEP;
|
||||
put(ConcurrentSessionFilter.class, order);
|
||||
order += STEP;
|
||||
filterToOrder.put(
|
||||
"org.springframework.security.openid.OpenIDAuthenticationFilter", order.next());
|
||||
put(DefaultLoginPageGeneratingFilter.class, order.next());
|
||||
put(DefaultLogoutPageGeneratingFilter.class, order.next());
|
||||
put(ConcurrentSessionFilter.class, order.next());
|
||||
put(DigestAuthenticationFilter.class, order.next());
|
||||
filterToOrder.put(
|
||||
"org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter", order.next());
|
||||
put(BasicAuthenticationFilter.class, order.next());
|
||||
put(RequestCacheAwareFilter.class, order.next());
|
||||
put(SecurityContextHolderAwareRequestFilter.class, order.next());
|
||||
put(JaasApiIntegrationFilter.class, order.next());
|
||||
put(RememberMeAuthenticationFilter.class, order.next());
|
||||
put(AnonymousAuthenticationFilter.class, order.next());
|
||||
filterToOrder.put(
|
||||
"org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter",
|
||||
order.next());
|
||||
put(SessionManagementFilter.class, order.next());
|
||||
put(ExceptionTranslationFilter.class, order.next());
|
||||
put(FilterSecurityInterceptor.class, order.next());
|
||||
put(SwitchUserFilter.class, order.next());
|
||||
"org.springframework.security.openid.OpenIDAuthenticationFilter", order);
|
||||
order += STEP;
|
||||
put(DefaultLoginPageGeneratingFilter.class, order);
|
||||
order += STEP;
|
||||
put(ConcurrentSessionFilter.class, order);
|
||||
order += STEP;
|
||||
put(DigestAuthenticationFilter.class, order);
|
||||
order += STEP;
|
||||
put(BasicAuthenticationFilter.class, order);
|
||||
order += STEP;
|
||||
put(RequestCacheAwareFilter.class, order);
|
||||
order += STEP;
|
||||
put(SecurityContextHolderAwareRequestFilter.class, order);
|
||||
order += STEP;
|
||||
put(JaasApiIntegrationFilter.class, order);
|
||||
order += STEP;
|
||||
put(RememberMeAuthenticationFilter.class, order);
|
||||
order += STEP;
|
||||
put(AnonymousAuthenticationFilter.class, order);
|
||||
order += STEP;
|
||||
put(SessionManagementFilter.class, order);
|
||||
order += STEP;
|
||||
put(ExceptionTranslationFilter.class, order);
|
||||
order += STEP;
|
||||
put(FilterSecurityInterceptor.class, order);
|
||||
order += STEP;
|
||||
put(SwitchUserFilter.class, order);
|
||||
}
|
||||
|
||||
public int compare(Filter lhs, Filter rhs) {
|
||||
@@ -196,23 +217,4 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static class Step {
|
||||
|
||||
private int value;
|
||||
private final int stepSize;
|
||||
|
||||
Step(int initialValue, int stepSize) {
|
||||
this.value = initialValue;
|
||||
this.stepSize = stepSize;
|
||||
}
|
||||
|
||||
int next() {
|
||||
int value = this.value;
|
||||
this.value += this.stepSize;
|
||||
return value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+16
-50
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -15,6 +15,14 @@
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.builders;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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;
|
||||
@@ -48,14 +56,12 @@ import org.springframework.security.config.annotation.web.configurers.SecurityCo
|
||||
import org.springframework.security.config.annotation.web.configurers.ServletApiConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.X509Configurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2ClientConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.openid.OpenIDLoginConfigurer;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer;
|
||||
import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
import org.springframework.security.web.PortMapper;
|
||||
import org.springframework.security.web.PortMapperImpl;
|
||||
@@ -73,13 +79,6 @@ import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.filter.CorsFilter;
|
||||
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A {@link HttpSecurity} is similar to Spring Security's XML <http> element in the
|
||||
* namespace configuration. It allows configuring web based security for specific http
|
||||
@@ -112,7 +111,6 @@ import java.util.Map;
|
||||
* </pre>
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @author Joe Grandja
|
||||
* @since 3.2
|
||||
* @see EnableWebSecurity
|
||||
*/
|
||||
@@ -329,7 +327,7 @@ public final class HttpSecurity extends
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @return the {@link HeadersConfigurer} for further customizations
|
||||
* @return
|
||||
* @throws Exception
|
||||
* @see HeadersConfigurer
|
||||
*/
|
||||
@@ -645,7 +643,7 @@ public final class HttpSecurity extends
|
||||
*
|
||||
* @see #requestMatcher(RequestMatcher)
|
||||
*
|
||||
* @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests()
|
||||
@@ -765,7 +763,7 @@ public final class HttpSecurity extends
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @return the {@link LogoutConfigurer} for further customizations
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public LogoutConfigurer<HttpSecurity> logout() throws Exception {
|
||||
@@ -828,7 +826,7 @@ public final class HttpSecurity extends
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @return the {@link AnonymousConfigurer} for further customizations
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public AnonymousConfigurer<HttpSecurity> anonymous() throws Exception {
|
||||
@@ -892,7 +890,7 @@ public final class HttpSecurity extends
|
||||
*
|
||||
* @see FormLoginConfigurer#loginPage(String)
|
||||
*
|
||||
* @return the {@link FormLoginConfigurer} for further customizations
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public FormLoginConfigurer<HttpSecurity> formLogin() throws Exception {
|
||||
@@ -980,6 +978,7 @@ public final class HttpSecurity extends
|
||||
* <p>
|
||||
* For more advanced configuration, see {@link OAuth2LoginConfigurer} for available options to customize the defaults.
|
||||
*
|
||||
* @author Joe Grandja
|
||||
* @since 5.0
|
||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section 4.1 Authorization Code Grant</a>
|
||||
* @see <a target="_blank" href="http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth">Section 3.1 Authorization Code Flow</a>
|
||||
@@ -992,34 +991,6 @@ public final class HttpSecurity extends
|
||||
return getOrApply(new OAuth2LoginConfigurer<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures OAuth 2.0 Client support.
|
||||
*
|
||||
* @since 5.1
|
||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.1">OAuth 2.0 Authorization Framework</a>
|
||||
* @return the {@link OAuth2ClientConfigurer} for further customizations
|
||||
* @throws Exception
|
||||
*/
|
||||
public OAuth2ClientConfigurer<HttpSecurity> oauth2Client() throws Exception {
|
||||
OAuth2ClientConfigurer<HttpSecurity> configurer = getOrApply(new OAuth2ClientConfigurer<>());
|
||||
this.postProcess(configurer);
|
||||
return configurer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures OAuth 2.0 Resource Server support.
|
||||
*
|
||||
* @since 5.1
|
||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.1">OAuth 2.0 Authorization Framework</a>
|
||||
* @return the {@link OAuth2ResourceServerConfigurer} for further customizations
|
||||
* @throws Exception
|
||||
*/
|
||||
public OAuth2ResourceServerConfigurer<HttpSecurity> oauth2ResourceServer() throws Exception {
|
||||
OAuth2ResourceServerConfigurer<HttpSecurity> configurer = getOrApply(new OAuth2ResourceServerConfigurer<>(getContext()));
|
||||
this.postProcess(configurer);
|
||||
return configurer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures channel security. In order for this configuration to be useful at least
|
||||
* one mapping to a required channel must be provided.
|
||||
@@ -1192,11 +1163,6 @@ public final class HttpSecurity extends
|
||||
* addFilterAt(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
|
||||
* </pre>
|
||||
*
|
||||
* Registration of multiple Filters in the same location means their ordering is not
|
||||
* deterministic. More concretely, registering multiple Filters in the same location
|
||||
* does not override existing Filters. Instead, do not register Filters you do not
|
||||
* want to use.
|
||||
*
|
||||
* @param filter the Filter to register
|
||||
* @param atFilter the location of another {@link Filter} that is already registered
|
||||
* (i.e. known) with Spring Security.
|
||||
|
||||
+4
-6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -235,7 +235,7 @@ public final class WebSecurity extends
|
||||
|
||||
/**
|
||||
* Gets the {@link SecurityExpressionHandler} to be used.
|
||||
* @return the {@link SecurityExpressionHandler} for further customizations
|
||||
* @return
|
||||
*/
|
||||
public SecurityExpressionHandler<FilterInvocation> getExpressionHandler() {
|
||||
return expressionHandler;
|
||||
@@ -243,7 +243,7 @@ public final class WebSecurity extends
|
||||
|
||||
/**
|
||||
* Gets the {@link WebInvocationPrivilegeEvaluator} to be used.
|
||||
* @return the {@link WebInvocationPrivilegeEvaluator} for further customizations
|
||||
* @return
|
||||
*/
|
||||
public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() {
|
||||
if (privilegeEvaluator != null) {
|
||||
@@ -279,9 +279,7 @@ public final class WebSecurity extends
|
||||
protected Filter performBuild() throws Exception {
|
||||
Assert.state(
|
||||
!securityFilterChainBuilders.isEmpty(),
|
||||
() -> "At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. "
|
||||
+ "Typically this done by adding a @Configuration that extends WebSecurityConfigurerAdapter. "
|
||||
+ "More advanced users can invoke "
|
||||
"At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. Typically this done by adding a @Configuration that extends WebSecurityConfigurerAdapter. More advanced users can invoke "
|
||||
+ WebSecurity.class.getSimpleName()
|
||||
+ ".addSecurityFilterChainBuilder directly");
|
||||
int chainSize = ignoredRequests.size() + securityFilterChainBuilders.size();
|
||||
|
||||
+4
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -52,7 +52,7 @@ import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
|
||||
* }
|
||||
*
|
||||
* @Override
|
||||
* protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
* protected void configure(AuthenticationManagerBuilder auth) {
|
||||
* auth
|
||||
* // enable in memory based authentication with a user named "user" and "admin"
|
||||
* .inMemoryAuthentication().withUser("user").password("password").roles("USER")
|
||||
@@ -73,8 +73,7 @@ import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
|
||||
@Target(value = { java.lang.annotation.ElementType.TYPE })
|
||||
@Documented
|
||||
@Import({ WebSecurityConfiguration.class,
|
||||
SpringWebMvcImportSelector.class,
|
||||
OAuth2ImportSelector.class })
|
||||
SpringWebMvcImportSelector.class })
|
||||
@EnableGlobalAuthentication
|
||||
@Configuration
|
||||
public @interface EnableWebSecurity {
|
||||
@@ -84,4 +83,4 @@ public @interface EnableWebSecurity {
|
||||
* @return if true, enables debug support with Spring Security
|
||||
*/
|
||||
boolean debug() default false;
|
||||
}
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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 org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.ImportSelector;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
|
||||
import org.springframework.security.oauth2.client.web.method.annotation.OAuth2AuthorizedClientArgumentResolver;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* {@link Configuration} for OAuth 2.0 Client support.
|
||||
*
|
||||
* <p>
|
||||
* This {@code Configuration} is conditionally imported by {@link OAuth2ImportSelector}
|
||||
* when the {@code spring-security-oauth2-client} module is present on the classpath.
|
||||
*
|
||||
* @author Joe Grandja
|
||||
* @since 5.1
|
||||
* @see OAuth2ImportSelector
|
||||
*/
|
||||
@Import(OAuth2ClientConfiguration.OAuth2ClientWebMvcImportSelector.class)
|
||||
final class OAuth2ClientConfiguration {
|
||||
|
||||
static class OAuth2ClientWebMvcImportSelector implements ImportSelector {
|
||||
|
||||
@Override
|
||||
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
|
||||
boolean webmvcPresent = ClassUtils.isPresent(
|
||||
"org.springframework.web.servlet.DispatcherServlet", getClass().getClassLoader());
|
||||
|
||||
return webmvcPresent ?
|
||||
new String[] { "org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration.OAuth2ClientWebMvcSecurityConfiguration" } :
|
||||
new String[] {};
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class OAuth2ClientWebMvcSecurityConfiguration implements WebMvcConfigurer {
|
||||
private ClientRegistrationRepository clientRegistrationRepository;
|
||||
private OAuth2AuthorizedClientRepository authorizedClientRepository;
|
||||
|
||||
@Override
|
||||
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) {
|
||||
OAuth2AuthorizedClientArgumentResolver authorizedClientArgumentResolver =
|
||||
new OAuth2AuthorizedClientArgumentResolver(
|
||||
this.clientRegistrationRepository, this.authorizedClientRepository);
|
||||
argumentResolvers.add(authorizedClientArgumentResolver);
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setClientRegistrationRepository(List<ClientRegistrationRepository> clientRegistrationRepositories) {
|
||||
if (clientRegistrationRepositories.size() == 1) {
|
||||
this.clientRegistrationRepository = clientRegistrationRepositories.get(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setAuthorizedClientRepository(List<OAuth2AuthorizedClientRepository> authorizedClientRepositories) {
|
||||
if (authorizedClientRepositories.size() == 1) {
|
||||
this.authorizedClientRepository = authorizedClientRepositories.get(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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 org.springframework.context.annotation.ImportSelector;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* Used by {@link EnableWebSecurity} to conditionally import {@link OAuth2ClientConfiguration}
|
||||
* when the {@code spring-security-oauth2-client} module is present on the classpath.
|
||||
|
||||
* @author Joe Grandja
|
||||
* @since 5.1
|
||||
* @see OAuth2ClientConfiguration
|
||||
*/
|
||||
final class OAuth2ImportSelector implements ImportSelector {
|
||||
|
||||
@Override
|
||||
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
|
||||
boolean oauth2ClientPresent = ClassUtils.isPresent(
|
||||
"org.springframework.security.oauth2.client.registration.ClientRegistration", getClass().getClassLoader());
|
||||
|
||||
return oauth2ClientPresent ?
|
||||
new String[] { "org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration" } :
|
||||
new String[] {};
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -88,7 +88,7 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
|
||||
|
||||
/**
|
||||
* Creates the Spring Security Filter Chain
|
||||
* @return the {@link Filter} that represents the security filter chain
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
|
||||
|
||||
+5
-11
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -200,7 +200,6 @@ public abstract class WebSecurityConfigurerAdapter implements
|
||||
|
||||
AuthenticationManager authenticationManager = authenticationManager();
|
||||
authenticationBuilder.parentAuthenticationManager(authenticationManager);
|
||||
authenticationBuilder.authenticationEventPublisher(eventPublisher);
|
||||
Map<Class<? extends Object>, Object> sharedObjects = createSharedObjects();
|
||||
|
||||
http = new HttpSecurity(objectPostProcessor, authenticationBuilder,
|
||||
@@ -224,7 +223,7 @@ public abstract class WebSecurityConfigurerAdapter implements
|
||||
List<AbstractHttpConfigurer> defaultHttpConfigurers =
|
||||
SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader);
|
||||
|
||||
for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
|
||||
for(AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
|
||||
http.apply(configurer);
|
||||
}
|
||||
}
|
||||
@@ -258,7 +257,7 @@ public abstract class WebSecurityConfigurerAdapter implements
|
||||
* {@link AuthenticationManagerBuilder} that was passed in. Otherwise, autowire the
|
||||
* {@link AuthenticationManager} by type.
|
||||
*
|
||||
* @return the {@link AuthenticationManager} to use
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
protected AuthenticationManager authenticationManager() throws Exception {
|
||||
@@ -292,7 +291,7 @@ public abstract class WebSecurityConfigurerAdapter implements
|
||||
*
|
||||
* To change the instance returned, developers should change
|
||||
* {@link #userDetailsService()} instead
|
||||
* @return the {@link UserDetailsService}
|
||||
* @return
|
||||
* @throws Exception
|
||||
* @see #userDetailsService()
|
||||
*/
|
||||
@@ -309,7 +308,7 @@ public abstract class WebSecurityConfigurerAdapter implements
|
||||
* {@link ApplicationContext}. Developers should override this method when changing
|
||||
* the instance of {@link #userDetailsServiceBean()}.
|
||||
*
|
||||
* @return the {@link UserDetailsService} to use
|
||||
* @return
|
||||
*/
|
||||
protected UserDetailsService userDetailsService() {
|
||||
AuthenticationManagerBuilder globalAuthBuilder = context
|
||||
@@ -594,11 +593,6 @@ public abstract class WebSecurityConfigurerAdapter implements
|
||||
return getPasswordEncoder().matches(rawPassword, encodedPassword);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean upgradeEncoding(String encodedPassword) {
|
||||
return getPasswordEncoder().upgradeEncoding(encodedPassword);
|
||||
}
|
||||
|
||||
private PasswordEncoder getPasswordEncoder() {
|
||||
if (this.passwordEncoder != null) {
|
||||
return this.passwordEncoder;
|
||||
|
||||
+14
-44
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -32,7 +32,6 @@ import org.springframework.security.web.authentication.SavedRequestAwareAuthenti
|
||||
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
|
||||
import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.security.web.util.matcher.AndRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;
|
||||
@@ -66,8 +65,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
|
||||
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
|
||||
|
||||
private SavedRequestAwareAuthenticationSuccessHandler defaultSuccessHandler = new SavedRequestAwareAuthenticationSuccessHandler();
|
||||
private AuthenticationSuccessHandler successHandler = this.defaultSuccessHandler;
|
||||
private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
|
||||
|
||||
private LoginUrlAuthenticationEntryPoint authenticationEntryPoint;
|
||||
|
||||
@@ -130,7 +128,6 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
|
||||
handler.setDefaultTargetUrl(defaultSuccessUrl);
|
||||
handler.setAlwaysUseDefaultTargetUrl(alwaysUse);
|
||||
this.defaultSuccessHandler = handler;
|
||||
return successHandler(handler);
|
||||
}
|
||||
|
||||
@@ -184,7 +181,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
|
||||
/**
|
||||
* Equivalent of invoking permitAll(true)
|
||||
* @return the {@link FormLoginConfigurer} for additional customization
|
||||
* @return
|
||||
*/
|
||||
public final T permitAll() {
|
||||
return permitAll(true);
|
||||
@@ -237,27 +234,20 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
@Override
|
||||
public void init(B http) throws Exception {
|
||||
updateAuthenticationDefaults();
|
||||
updateAccessDefaults(http);
|
||||
if (permitAll) {
|
||||
PermitAllSupport.permitAll(http, loginPage, loginProcessingUrl, failureUrl);
|
||||
}
|
||||
|
||||
registerDefaultAuthenticationEntryPoint(http);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected final void registerDefaultAuthenticationEntryPoint(B http) {
|
||||
registerAuthenticationEntryPoint(http, this.authenticationEntryPoint);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected final void registerAuthenticationEntryPoint(B http, AuthenticationEntryPoint authenticationEntryPoint) {
|
||||
private void registerDefaultAuthenticationEntryPoint(B http) {
|
||||
ExceptionHandlingConfigurer<B> exceptionHandling = http
|
||||
.getConfigurer(ExceptionHandlingConfigurer.class);
|
||||
if (exceptionHandling == null) {
|
||||
return;
|
||||
}
|
||||
exceptionHandling.defaultAuthenticationEntryPointFor(
|
||||
postProcess(authenticationEntryPoint), getAuthenticationEntryPointMatcher(http));
|
||||
}
|
||||
|
||||
protected final RequestMatcher getAuthenticationEntryPointMatcher(B http) {
|
||||
ContentNegotiationStrategy contentNegotiationStrategy = http
|
||||
.getSharedObject(ContentNegotiationStrategy.class);
|
||||
if (contentNegotiationStrategy == null) {
|
||||
@@ -272,7 +262,10 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
RequestMatcher notXRequestedWith = new NegatedRequestMatcher(
|
||||
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"));
|
||||
|
||||
return new AndRequestMatcher(Arrays.asList(notXRequestedWith, mediaMatcher));
|
||||
RequestMatcher preferredMatcher = new AndRequestMatcher(Arrays.asList(notXRequestedWith, mediaMatcher));
|
||||
|
||||
exceptionHandling.defaultAuthenticationEntryPointFor(
|
||||
postProcess(authenticationEntryPoint), preferredMatcher);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -282,11 +275,6 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
authenticationEntryPoint.setPortMapper(portMapper);
|
||||
}
|
||||
|
||||
RequestCache requestCache = http.getSharedObject(RequestCache.class);
|
||||
if (requestCache != null) {
|
||||
this.defaultSuccessHandler.setRequestCache(requestCache);
|
||||
}
|
||||
|
||||
authFilter.setAuthenticationManager(http
|
||||
.getSharedObject(AuthenticationManager.class));
|
||||
authFilter.setAuthenticationSuccessHandler(successHandler);
|
||||
@@ -363,15 +351,6 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
return loginPage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Authentication Entry Point
|
||||
*
|
||||
* @return the Authentication Entry Point
|
||||
*/
|
||||
protected final AuthenticationEntryPoint getAuthenticationEntryPoint() {
|
||||
return authenticationEntryPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the URL to submit an authentication request to (i.e. where username/password
|
||||
* must be submitted)
|
||||
@@ -385,7 +364,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
/**
|
||||
* Gets the URL to send users to if authentication fails
|
||||
*
|
||||
* @return the URL to send users if authentication fails (e.g. "/login?error").
|
||||
* @return
|
||||
*/
|
||||
protected final String getFailureUrl() {
|
||||
return failureUrl;
|
||||
@@ -396,7 +375,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
protected final void updateAuthenticationDefaults() {
|
||||
private void updateAuthenticationDefaults() {
|
||||
if (loginProcessingUrl == null) {
|
||||
loginProcessingUrl(loginPage);
|
||||
}
|
||||
@@ -411,15 +390,6 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the default values for access.
|
||||
*/
|
||||
protected final void updateAccessDefaults(B http) {
|
||||
if (permitAll) {
|
||||
PermitAllSupport.permitAll(http, loginPage, loginProcessingUrl, failureUrl);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the loginPage and updates the {@link AuthenticationEntryPoint}.
|
||||
* @param loginPage
|
||||
|
||||
+2
-2
@@ -188,7 +188,7 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>> e
|
||||
* Sets the {@link ChannelProcessor} instances to use in
|
||||
* {@link ChannelDecisionManagerImpl}
|
||||
* @param channelProcessors
|
||||
* @return the {@link ChannelSecurityConfigurer} for further customizations
|
||||
* @return
|
||||
*/
|
||||
public ChannelRequestMatcherRegistry channelProcessors(
|
||||
List<ChannelProcessor> channelProcessors) {
|
||||
@@ -200,7 +200,7 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>> e
|
||||
* Return the {@link SecurityBuilder} when done using the
|
||||
* {@link SecurityConfigurer}. This is useful for method chaining.
|
||||
*
|
||||
* @return the type of {@link HttpSecurityBuilder} that is being configured
|
||||
* @return
|
||||
*/
|
||||
public H and() {
|
||||
return ChannelSecurityConfigurer.this.and();
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -109,7 +109,7 @@ public class CorsConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return
|
||||
*/
|
||||
private static CorsFilter getMvcCorsFilter(ApplicationContext context) {
|
||||
if (!context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) {
|
||||
if(!context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) {
|
||||
throw new NoSuchBeanDefinitionException(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, "A Bean named " + HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME +" of type " + HandlerMappingIntrospector.class.getName()
|
||||
+ " is required to use MvcRequestMatcher. Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext.");
|
||||
}
|
||||
|
||||
+2
-31
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -128,7 +128,7 @@ public final class CsrfConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For example, the following configuration will ensure CSRF protection ignores:
|
||||
* The following will ensure CSRF protection ignores:
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>Any GET, HEAD, TRACE, OPTIONS (this is the default)</li>
|
||||
@@ -150,35 +150,6 @@ public final class CsrfConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
.and();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Allows specifying {@link HttpServletRequest}s that should not use CSRF Protection
|
||||
* even if they match the {@link #requireCsrfProtectionMatcher(RequestMatcher)}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For example, the following configuration will ensure CSRF protection ignores:
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>Any GET, HEAD, TRACE, OPTIONS (this is the default)</li>
|
||||
* <li>We also explicitly state to ignore any request that has a "X-Requested-With: XMLHttpRequest" header</li>
|
||||
* </ul>
|
||||
*
|
||||
* <pre>
|
||||
* http
|
||||
* .csrf()
|
||||
* .ignoringRequestMatchers(request -> "XMLHttpRequest".equals(request.getHeader("X-Requested-With")))
|
||||
* .and()
|
||||
* ...
|
||||
* </pre>
|
||||
*
|
||||
* @since 5.1
|
||||
*/
|
||||
public CsrfConfigurer<H> ignoringRequestMatchers(RequestMatcher... requestMatchers) {
|
||||
return new IgnoreCsrfProtectionRegistry(this.context).requestMatchers(requestMatchers)
|
||||
.and();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public void configure(H http) throws Exception {
|
||||
|
||||
+4
-13
@@ -19,13 +19,9 @@ import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter;
|
||||
import org.springframework.security.web.csrf.CsrfToken;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Adds a Filter that will generate a login page if one is not specified otherwise when
|
||||
@@ -70,19 +66,15 @@ public final class DefaultLoginPageConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
|
||||
private DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = new DefaultLoginPageGeneratingFilter();
|
||||
|
||||
private DefaultLogoutPageGeneratingFilter logoutPageGeneratingFilter = new DefaultLogoutPageGeneratingFilter();
|
||||
|
||||
@Override
|
||||
public void init(H http) throws Exception {
|
||||
Function<HttpServletRequest, Map<String, String>> hiddenInputs = request -> {
|
||||
this.loginPageGeneratingFilter.setResolveHiddenInputs( request -> {
|
||||
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
||||
if (token == null) {
|
||||
if(token == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return Collections.singletonMap(token.getParameterName(), token.getToken());
|
||||
};
|
||||
this.loginPageGeneratingFilter.setResolveHiddenInputs(hiddenInputs);
|
||||
this.logoutPageGeneratingFilter.setResolveHiddenInputs(hiddenInputs);
|
||||
});
|
||||
http.setSharedObject(DefaultLoginPageGeneratingFilter.class,
|
||||
loginPageGeneratingFilter);
|
||||
}
|
||||
@@ -100,8 +92,7 @@ public final class DefaultLoginPageConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
if (loginPageGeneratingFilter.isEnabled() && authenticationEntryPoint == null) {
|
||||
loginPageGeneratingFilter = postProcess(loginPageGeneratingFilter);
|
||||
http.addFilter(loginPageGeneratingFilter);
|
||||
http.addFilter(this.logoutPageGeneratingFilter);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+9
-58
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -23,7 +23,6 @@ import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
|
||||
import org.springframework.security.web.access.ExceptionTranslationFilter;
|
||||
import org.springframework.security.web.access.RequestMatcherDelegatingAccessDeniedHandler;
|
||||
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
@@ -71,8 +70,6 @@ public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
|
||||
private LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> defaultEntryPointMappings = new LinkedHashMap<>();
|
||||
|
||||
private LinkedHashMap<RequestMatcher, AccessDeniedHandler> defaultDeniedHandlerMappings = new LinkedHashMap<>();
|
||||
|
||||
/**
|
||||
* Creates a new instance
|
||||
* @see HttpSecurity#exceptionHandling()
|
||||
@@ -107,26 +104,6 @@ public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a default {@link AccessDeniedHandler} to be used which prefers being
|
||||
* invoked for the provided {@link RequestMatcher}. If only a single default
|
||||
* {@link AccessDeniedHandler} is specified, it will be what is used for the
|
||||
* default {@link AccessDeniedHandler}. If multiple default
|
||||
* {@link AccessDeniedHandler} instances are configured, then a
|
||||
* {@link RequestMatcherDelegatingAccessDeniedHandler} will be used.
|
||||
*
|
||||
* @param deniedHandler the {@link AccessDeniedHandler} to use
|
||||
* @param preferredMatcher the {@link RequestMatcher} for this default
|
||||
* {@link AccessDeniedHandler}
|
||||
* @return the {@link ExceptionHandlingConfigurer} for further customizations
|
||||
* @since 5.1
|
||||
*/
|
||||
public ExceptionHandlingConfigurer<H> defaultAccessDeniedHandlerFor(
|
||||
AccessDeniedHandler deniedHandler, RequestMatcher preferredMatcher) {
|
||||
this.defaultDeniedHandlerMappings.put(preferredMatcher, deniedHandler);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link AuthenticationEntryPoint} to be used.
|
||||
*
|
||||
@@ -192,27 +169,13 @@ public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
AuthenticationEntryPoint entryPoint = getAuthenticationEntryPoint(http);
|
||||
ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(
|
||||
entryPoint, getRequestCache(http));
|
||||
AccessDeniedHandler deniedHandler = getAccessDeniedHandler(http);
|
||||
exceptionTranslationFilter.setAccessDeniedHandler(deniedHandler);
|
||||
if (accessDeniedHandler != null) {
|
||||
exceptionTranslationFilter.setAccessDeniedHandler(accessDeniedHandler);
|
||||
}
|
||||
exceptionTranslationFilter = postProcess(exceptionTranslationFilter);
|
||||
http.addFilter(exceptionTranslationFilter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link AccessDeniedHandler} according to the rules specified by
|
||||
* {@link #accessDeniedHandler(AccessDeniedHandler)}
|
||||
* @param http the {@link HttpSecurity} used to look up shared
|
||||
* {@link AccessDeniedHandler}
|
||||
* @return the {@link AccessDeniedHandler} to use
|
||||
*/
|
||||
AccessDeniedHandler getAccessDeniedHandler(H http) {
|
||||
AccessDeniedHandler deniedHandler = this.accessDeniedHandler;
|
||||
if (deniedHandler == null) {
|
||||
deniedHandler = createDefaultDeniedHandler(http);
|
||||
}
|
||||
return deniedHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link AuthenticationEntryPoint} according to the rules specified by
|
||||
* {@link #authenticationEntryPoint(AuthenticationEntryPoint)}
|
||||
@@ -228,28 +191,16 @@ public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
return entryPoint;
|
||||
}
|
||||
|
||||
private AccessDeniedHandler createDefaultDeniedHandler(H http) {
|
||||
if (this.defaultDeniedHandlerMappings.isEmpty()) {
|
||||
return new AccessDeniedHandlerImpl();
|
||||
}
|
||||
if (this.defaultDeniedHandlerMappings.size() == 1) {
|
||||
return this.defaultDeniedHandlerMappings.values().iterator().next();
|
||||
}
|
||||
return new RequestMatcherDelegatingAccessDeniedHandler(
|
||||
this.defaultDeniedHandlerMappings,
|
||||
new AccessDeniedHandlerImpl());
|
||||
}
|
||||
|
||||
private AuthenticationEntryPoint createDefaultEntryPoint(H http) {
|
||||
if (this.defaultEntryPointMappings.isEmpty()) {
|
||||
if (defaultEntryPointMappings.isEmpty()) {
|
||||
return new Http403ForbiddenEntryPoint();
|
||||
}
|
||||
if (this.defaultEntryPointMappings.size() == 1) {
|
||||
return this.defaultEntryPointMappings.values().iterator().next();
|
||||
if (defaultEntryPointMappings.size() == 1) {
|
||||
return defaultEntryPointMappings.values().iterator().next();
|
||||
}
|
||||
DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(
|
||||
this.defaultEntryPointMappings);
|
||||
entryPoint.setDefaultEntryPoint(this.defaultEntryPointMappings.values().iterator()
|
||||
defaultEntryPointMappings);
|
||||
entryPoint.setDefaultEntryPoint(defaultEntryPointMappings.values().iterator()
|
||||
.next());
|
||||
return entryPoint;
|
||||
}
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -213,18 +213,18 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
|
||||
defaultHandler.setTrustResolver(trustResolver);
|
||||
}
|
||||
ApplicationContext context = http.getSharedObject(ApplicationContext.class);
|
||||
if (context != null) {
|
||||
if(context != null) {
|
||||
String[] roleHiearchyBeanNames = context.getBeanNamesForType(RoleHierarchy.class);
|
||||
if (roleHiearchyBeanNames.length == 1) {
|
||||
if(roleHiearchyBeanNames.length == 1) {
|
||||
defaultHandler.setRoleHierarchy(context.getBean(roleHiearchyBeanNames[0], RoleHierarchy.class));
|
||||
}
|
||||
String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class);
|
||||
if (grantedAuthorityDefaultsBeanNames.length == 1) {
|
||||
if(grantedAuthorityDefaultsBeanNames.length == 1) {
|
||||
GrantedAuthorityDefaults grantedAuthorityDefaults = context.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
|
||||
defaultHandler.setDefaultRolePrefix(grantedAuthorityDefaults.getRolePrefix());
|
||||
}
|
||||
String[] permissionEvaluatorBeanNames = context.getBeanNamesForType(PermissionEvaluator.class);
|
||||
if (permissionEvaluatorBeanNames.length == 1) {
|
||||
if(permissionEvaluatorBeanNames.length == 1) {
|
||||
PermissionEvaluator permissionEvaluator = context.getBean(permissionEvaluatorBeanNames[0], PermissionEvaluator.class);
|
||||
defaultHandler.setPermissionEvaluator(permissionEvaluator);
|
||||
}
|
||||
|
||||
+2
-47
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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,6 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.config.annotation.web.configurers;
|
||||
|
||||
import java.net.URI;
|
||||
@@ -59,7 +58,6 @@ import org.springframework.util.Assert;
|
||||
* @author Tim Ysewyn
|
||||
* @author Joe Grandja
|
||||
* @author Eddú Meléndez
|
||||
* @author Vedran Pavic
|
||||
* @since 3.2
|
||||
*/
|
||||
public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
@@ -84,8 +82,6 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
|
||||
private final ReferrerPolicyConfig referrerPolicy = new ReferrerPolicyConfig();
|
||||
|
||||
private final FeaturePolicyConfig featurePolicy = new FeaturePolicyConfig();
|
||||
|
||||
/**
|
||||
* Creates a new instance
|
||||
*
|
||||
@@ -446,7 +442,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
* application.
|
||||
* </p>
|
||||
*
|
||||
* @return the {@link HeadersConfigurer} for additional customization.
|
||||
* @return
|
||||
*/
|
||||
public HeadersConfigurer<H> sameOrigin() {
|
||||
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
|
||||
@@ -779,7 +775,6 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
addIfNotNull(writers, hpkp.writer);
|
||||
addIfNotNull(writers, contentSecurityPolicy.writer);
|
||||
addIfNotNull(writers, referrerPolicy.writer);
|
||||
addIfNotNull(writers, featurePolicy.writer);
|
||||
writers.addAll(headerWriters);
|
||||
return writers;
|
||||
}
|
||||
@@ -853,44 +848,4 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows configuration for <a href="https://wicg.github.io/feature-policy/">Feature
|
||||
* Policy</a>.
|
||||
* <p>
|
||||
* Calling this method automatically enables (includes) the {@code Feature-Policy}
|
||||
* header in the response using the supplied policy directive(s).
|
||||
* <p>
|
||||
* Configuration is provided to the {@link FeaturePolicyHeaderWriter} which is
|
||||
* responsible for writing the header.
|
||||
*
|
||||
* @see FeaturePolicyHeaderWriter
|
||||
* @since 5.1
|
||||
* @return the {@link FeaturePolicyHeaderWriter} for additional configuration
|
||||
* @throws IllegalArgumentException if policyDirectives is {@code null} or empty
|
||||
*/
|
||||
public FeaturePolicyConfig featurePolicy(String policyDirectives) {
|
||||
this.featurePolicy.writer = new FeaturePolicyHeaderWriter(policyDirectives);
|
||||
return featurePolicy;
|
||||
}
|
||||
|
||||
public final class FeaturePolicyConfig {
|
||||
|
||||
private FeaturePolicyHeaderWriter writer;
|
||||
|
||||
private FeaturePolicyConfig() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows completing configuration of Feature Policy and continuing configuration
|
||||
* of headers.
|
||||
*
|
||||
* @return the {@link HeadersConfigurer} for additional configuration
|
||||
*/
|
||||
public HeadersConfigurer<H> and() {
|
||||
return HeadersConfigurer.this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -215,7 +215,7 @@ public final class HttpBasicConfigurer<B extends HttpSecurityBuilder<B>> extends
|
||||
.setAuthenticationDetailsSource(this.authenticationDetailsSource);
|
||||
}
|
||||
RememberMeServices rememberMeServices = http.getSharedObject(RememberMeServices.class);
|
||||
if (rememberMeServices != null) {
|
||||
if(rememberMeServices != null) {
|
||||
basicAuthenticationFilter.setRememberMeServices(rememberMeServices);
|
||||
}
|
||||
basicAuthenticationFilter = postProcess(basicAuthenticationFilter);
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -261,7 +261,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
private LogoutSuccessHandler createDefaultSuccessHandler() {
|
||||
SimpleUrlLogoutSuccessHandler urlLogoutHandler = new SimpleUrlLogoutSuccessHandler();
|
||||
urlLogoutHandler.setDefaultTargetUrl(logoutSuccessUrl);
|
||||
if (defaultLogoutSuccessHandlerMappings.isEmpty()) {
|
||||
if(defaultLogoutSuccessHandlerMappings.isEmpty()) {
|
||||
return urlLogoutHandler;
|
||||
}
|
||||
DelegatingLogoutSuccessHandler successHandler = new DelegatingLogoutSuccessHandler(defaultLogoutSuccessHandlerMappings);
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ public final class PortMapperConfigurer<H extends HttpSecurityBuilder<H>> extend
|
||||
/**
|
||||
* Allows specifying the {@link PortMapper} instance.
|
||||
* @param portMapper
|
||||
* @return the {@link PortMapperConfigurer} for further customizations
|
||||
* @return
|
||||
*/
|
||||
public PortMapperConfigurer<H> portMapper(PortMapper portMapper) {
|
||||
this.portMapper = portMapper;
|
||||
|
||||
+1
-25
@@ -19,13 +19,10 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
import org.springframework.security.web.savedrequest.NullRequestCache;
|
||||
import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter;
|
||||
import org.springframework.security.web.util.matcher.AndRequestMatcher;
|
||||
@@ -88,12 +85,6 @@ public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>> exte
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public H disable() {
|
||||
getBuilder().setSharedObject(RequestCache.class, new NullRequestCache());
|
||||
return super.disable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(H http) throws Exception {
|
||||
http.setSharedObject(RequestCache.class, getRequestCache(http));
|
||||
@@ -122,26 +113,11 @@ public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>> exte
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
result = getBeanOrNull(RequestCache.class);
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
HttpSessionRequestCache defaultCache = new HttpSessionRequestCache();
|
||||
defaultCache.setRequestMatcher(createDefaultSavedRequestMatcher(http));
|
||||
return defaultCache;
|
||||
}
|
||||
|
||||
private <T> T getBeanOrNull(Class<T> type) {
|
||||
ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class);
|
||||
if (context == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return context.getBean(type);
|
||||
} catch (NoSuchBeanDefinitionException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
private RequestMatcher createDefaultSavedRequestMatcher(H http) {
|
||||
ContentNegotiationStrategy contentNegotiationStrategy = http
|
||||
@@ -151,7 +127,7 @@ public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>> exte
|
||||
}
|
||||
|
||||
RequestMatcher notFavIcon = new NegatedRequestMatcher(new AntPathRequestMatcher(
|
||||
"/**/favicon.*"));
|
||||
"/**/favicon.ico"));
|
||||
|
||||
MediaTypeRequestMatcher jsonRequest = new MediaTypeRequestMatcher(
|
||||
contentNegotiationStrategy, MediaType.APPLICATION_JSON);
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -86,7 +86,7 @@ public final class SecurityContextConfigurer<H extends HttpSecurityBuilder<H>> e
|
||||
|
||||
SecurityContextRepository securityContextRepository = http
|
||||
.getSharedObject(SecurityContextRepository.class);
|
||||
if (securityContextRepository == null) {
|
||||
if(securityContextRepository == null) {
|
||||
securityContextRepository = new HttpSessionSecurityContextRepository();
|
||||
}
|
||||
SecurityContextPersistenceFilter securityContextFilter = new SecurityContextPersistenceFilter(
|
||||
@@ -101,4 +101,4 @@ public final class SecurityContextConfigurer<H extends HttpSecurityBuilder<H>> e
|
||||
securityContextFilter = postProcess(securityContextFilter);
|
||||
http.addFilter(securityContextFilter);
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -94,9 +94,9 @@ public final class ServletApiConfigurer<H extends HttpSecurityBuilder<H>> extend
|
||||
securityContextRequestFilter.setTrustResolver(trustResolver);
|
||||
}
|
||||
ApplicationContext context = http.getSharedObject(ApplicationContext.class);
|
||||
if (context != null) {
|
||||
if(context != null) {
|
||||
String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class);
|
||||
if (grantedAuthorityDefaultsBeanNames.length == 1) {
|
||||
if(grantedAuthorityDefaultsBeanNames.length == 1) {
|
||||
GrantedAuthorityDefaults grantedAuthorityDefaults = context.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
|
||||
securityContextRequestFilter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix());
|
||||
}
|
||||
|
||||
+17
-26
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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,6 +18,7 @@ package org.springframework.security.config.annotation.web.configurers;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
@@ -104,7 +105,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
private Integer maximumSessions;
|
||||
private String expiredUrl;
|
||||
private boolean maxSessionsPreventsLogin;
|
||||
private SessionCreationPolicy sessionPolicy;
|
||||
private SessionCreationPolicy sessionPolicy = SessionCreationPolicy.IF_REQUIRED;
|
||||
private boolean enableSessionUrlRewriting;
|
||||
private String invalidSessionUrl;
|
||||
private String sessionAuthenticationErrorUrl;
|
||||
@@ -211,25 +212,24 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows explicitly specifying the {@link SessionAuthenticationStrategy}.
|
||||
* The default is to use {@link SessionFixationProtectionStrategy} for Servlet 3.1 or
|
||||
* {@link ChangeSessionIdAuthenticationStrategy} for Servlet 3.1+.
|
||||
* If restricting the maximum number of sessions is configured, then
|
||||
* Allows explicitly specifying the {@link SessionAuthenticationStrategy}. The default
|
||||
* is to use {@link SessionFixationProtectionStrategy}. If restricting the maximum
|
||||
* number of sessions is configured, then
|
||||
* {@link CompositeSessionAuthenticationStrategy} delegating to
|
||||
* {@link ConcurrentSessionControlAuthenticationStrategy},
|
||||
* the default OR supplied {@code SessionAuthenticationStrategy} and
|
||||
* {@link SessionFixationProtectionStrategy} (the default) OR
|
||||
* {@link SessionAuthenticationStrategy} the supplied sessionAuthenticationStrategy,
|
||||
* {@link RegisterSessionAuthenticationStrategy}.
|
||||
*
|
||||
* <p>
|
||||
* NOTE: Supplying a custom {@link SessionAuthenticationStrategy} will override the
|
||||
* default session fixation strategy.
|
||||
* default provided {@link SessionFixationProtectionStrategy}.
|
||||
*
|
||||
* @param sessionAuthenticationStrategy
|
||||
* @return the {@link SessionManagementConfigurer} for further customizations
|
||||
*/
|
||||
public SessionManagementConfigurer<H> sessionAuthenticationStrategy(
|
||||
SessionAuthenticationStrategy sessionAuthenticationStrategy) {
|
||||
this.providedSessionAuthenticationStrategy = sessionAuthenticationStrategy;
|
||||
this.sessionFixationAuthenticationStrategy = sessionAuthenticationStrategy;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -480,7 +480,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
private ConcurrentSessionFilter createConccurencyFilter(H http) {
|
||||
SessionInformationExpiredStrategy expireStrategy = getExpiredSessionStrategy();
|
||||
SessionRegistry sessionRegistry = getSessionRegistry(http);
|
||||
if (expireStrategy == null) {
|
||||
if(expireStrategy == null) {
|
||||
return new ConcurrentSessionFilter(sessionRegistry);
|
||||
}
|
||||
|
||||
@@ -549,14 +549,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return the {@link SessionCreationPolicy}
|
||||
*/
|
||||
SessionCreationPolicy getSessionCreationPolicy() {
|
||||
if (this.sessionPolicy != null) {
|
||||
return this.sessionPolicy;
|
||||
}
|
||||
|
||||
SessionCreationPolicy sessionPolicy =
|
||||
getBuilder().getSharedObject(SessionCreationPolicy.class);
|
||||
return sessionPolicy == null ?
|
||||
SessionCreationPolicy.IF_REQUIRED : sessionPolicy;
|
||||
return this.sessionPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -565,9 +558,8 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return true if the {@link SessionCreationPolicy} allows session creation
|
||||
*/
|
||||
private boolean isAllowSessionCreation() {
|
||||
SessionCreationPolicy sessionPolicy = getSessionCreationPolicy();
|
||||
return SessionCreationPolicy.ALWAYS == sessionPolicy
|
||||
|| SessionCreationPolicy.IF_REQUIRED == sessionPolicy;
|
||||
return SessionCreationPolicy.ALWAYS == this.sessionPolicy
|
||||
|| SessionCreationPolicy.IF_REQUIRED == this.sessionPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -575,8 +567,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* @return
|
||||
*/
|
||||
private boolean isStateless() {
|
||||
SessionCreationPolicy sessionPolicy = getSessionCreationPolicy();
|
||||
return SessionCreationPolicy.STATELESS == sessionPolicy;
|
||||
return SessionCreationPolicy.STATELESS == this.sessionPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -593,8 +584,8 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
List<SessionAuthenticationStrategy> delegateStrategies = this.sessionAuthenticationStrategies;
|
||||
SessionAuthenticationStrategy defaultSessionAuthenticationStrategy;
|
||||
if (this.providedSessionAuthenticationStrategy == null) {
|
||||
// If the user did not provide a SessionAuthenticationStrategy
|
||||
// then default to sessionFixationAuthenticationStrategy
|
||||
// If a user provided SessionAuthenticationStrategy is not supplied
|
||||
// then default to SessionFixationProtectionStrategy
|
||||
defaultSessionAuthenticationStrategy = postProcess(
|
||||
this.sessionFixationAuthenticationStrategy);
|
||||
}
|
||||
|
||||
+4
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -99,7 +99,7 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* The StandardInterceptUrlRegistry is what users will interact with after applying
|
||||
* the {@link UrlAuthorizationConfigurer}.
|
||||
*
|
||||
* @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations
|
||||
* @return
|
||||
*/
|
||||
public StandardInterceptUrlRegistry getRegistry() {
|
||||
return REGISTRY;
|
||||
@@ -198,7 +198,7 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
* provided {@link ConfigAttribute} instances
|
||||
* @param configAttributes the {@link ConfigAttribute} instances that should be mapped
|
||||
* by the {@link RequestMatcher} instances
|
||||
* @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations
|
||||
* @return the {@link UrlAuthorizationConfigurer} for further customizations
|
||||
*/
|
||||
private StandardInterceptUrlRegistry addMapping(
|
||||
Iterable<? extends RequestMatcher> requestMatchers,
|
||||
@@ -220,7 +220,7 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
private static String hasRole(String role) {
|
||||
Assert.isTrue(
|
||||
!role.startsWith("ROLE_"),
|
||||
() -> role
|
||||
role
|
||||
+ " should not start with ROLE_ since ROLE_ is automatically prepended when using hasRole. Consider using hasAuthority or access instead.");
|
||||
return "ROLE_" + role;
|
||||
}
|
||||
|
||||
+15
-27
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -15,6 +15,8 @@
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationDetailsSource;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
@@ -30,9 +32,6 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedA
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails;
|
||||
import org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor;
|
||||
import org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter;
|
||||
import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* Adds X509 based pre authentication to an application. Since validating the certificate
|
||||
@@ -41,7 +40,7 @@ import javax.servlet.http.HttpServletRequest;
|
||||
* certificate to look up the {@link Authentication} for the user.
|
||||
*
|
||||
* <h2>Security Filters</h2>
|
||||
* <p>
|
||||
*
|
||||
* The following Filters are populated
|
||||
*
|
||||
* <ul>
|
||||
@@ -49,7 +48,7 @@ import javax.servlet.http.HttpServletRequest;
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Shared Objects Created</h2>
|
||||
* <p>
|
||||
*
|
||||
* The following shared objects are created
|
||||
*
|
||||
* <ul>
|
||||
@@ -62,7 +61,7 @@ import javax.servlet.http.HttpServletRequest;
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Shared Objects Used</h2>
|
||||
* <p>
|
||||
*
|
||||
* The following shared objects are used:
|
||||
*
|
||||
* <ul>
|
||||
@@ -76,13 +75,12 @@ import javax.servlet.http.HttpServletRequest;
|
||||
public final class X509Configurer<H extends HttpSecurityBuilder<H>> extends
|
||||
AbstractHttpConfigurer<X509Configurer<H>, H> {
|
||||
private X509AuthenticationFilter x509AuthenticationFilter;
|
||||
private X509PrincipalExtractor x509PrincipalExtractor;
|
||||
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> authenticationUserDetailsService;
|
||||
private String subjectPrincipalRegex;
|
||||
private AuthenticationDetailsSource<HttpServletRequest, PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails> authenticationDetailsSource;
|
||||
|
||||
/**
|
||||
* Creates a new instance
|
||||
*
|
||||
* @see HttpSecurity#x509()
|
||||
*/
|
||||
public X509Configurer() {
|
||||
@@ -102,17 +100,6 @@ public final class X509Configurer<H extends HttpSecurityBuilder<H>> extends
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the {@link X509PrincipalExtractor}
|
||||
*
|
||||
* @param x509PrincipalExtractor the {@link X509PrincipalExtractor} to use
|
||||
* @return the {@link X509Configurer} to use
|
||||
*/
|
||||
public X509Configurer<H> x509PrincipalExtractor(X509PrincipalExtractor x509PrincipalExtractor) {
|
||||
this.x509PrincipalExtractor = x509PrincipalExtractor;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the {@link AuthenticationDetailsSource}
|
||||
*
|
||||
@@ -144,7 +131,8 @@ public final class X509Configurer<H extends HttpSecurityBuilder<H>> extends
|
||||
* the shared {@link UserDetailsService} will be used to create a
|
||||
* {@link UserDetailsByNameServiceWrapper}.
|
||||
*
|
||||
* @param authenticationUserDetailsService the {@link AuthenticationUserDetailsService} to use
|
||||
* @param authenticationUserDetailsService the
|
||||
* {@link AuthenticationUserDetailsService} to use
|
||||
* @return the {@link X509Configurer} for further customizations
|
||||
*/
|
||||
public X509Configurer<H> authenticationUserDetailsService(
|
||||
@@ -159,13 +147,11 @@ public final class X509Configurer<H extends HttpSecurityBuilder<H>> extends
|
||||
* used.
|
||||
*
|
||||
* @param subjectPrincipalRegex the regex to extract the user principal from the
|
||||
* certificate (i.e. "CN=(.*?)(?:,|$)").
|
||||
* certificate (i.e. "CN=(.*?)(?:,|$)").
|
||||
* @return the {@link X509Configurer} for further customizations
|
||||
*/
|
||||
public X509Configurer<H> subjectPrincipalRegex(String subjectPrincipalRegex) {
|
||||
SubjectDnX509PrincipalExtractor principalExtractor = new SubjectDnX509PrincipalExtractor();
|
||||
principalExtractor.setSubjectDnRegex(subjectPrincipalRegex);
|
||||
this.x509PrincipalExtractor = principalExtractor;
|
||||
this.subjectPrincipalRegex = subjectPrincipalRegex;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -192,8 +178,10 @@ public final class X509Configurer<H extends HttpSecurityBuilder<H>> extends
|
||||
if (x509AuthenticationFilter == null) {
|
||||
x509AuthenticationFilter = new X509AuthenticationFilter();
|
||||
x509AuthenticationFilter.setAuthenticationManager(authenticationManager);
|
||||
if (x509PrincipalExtractor != null) {
|
||||
x509AuthenticationFilter.setPrincipalExtractor(x509PrincipalExtractor);
|
||||
if (subjectPrincipalRegex != null) {
|
||||
SubjectDnX509PrincipalExtractor principalExtractor = new SubjectDnX509PrincipalExtractor();
|
||||
principalExtractor.setSubjectDnRegex(subjectPrincipalRegex);
|
||||
x509AuthenticationFilter.setPrincipalExtractor(principalExtractor);
|
||||
}
|
||||
if (authenticationDetailsSource != null) {
|
||||
x509AuthenticationFilter
|
||||
|
||||
+15
-1
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
@@ -85,7 +86,7 @@ public final class ImplicitGrantConfigurer<B extends HttpSecurityBuilder<B>> ext
|
||||
@Override
|
||||
public void configure(B http) throws Exception {
|
||||
OAuth2AuthorizationRequestRedirectFilter authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
|
||||
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder()), this.getAuthorizationRequestBaseUri());
|
||||
this.getClientRegistrationRepository(), this.getAuthorizationRequestBaseUri());
|
||||
http.addFilter(this.postProcess(authorizationRequestFilter));
|
||||
}
|
||||
|
||||
@@ -94,4 +95,17 @@ public final class ImplicitGrantConfigurer<B extends HttpSecurityBuilder<B>> ext
|
||||
this.authorizationRequestBaseUri :
|
||||
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
|
||||
}
|
||||
|
||||
private ClientRegistrationRepository getClientRegistrationRepository() {
|
||||
ClientRegistrationRepository clientRegistrationRepository = this.getBuilder().getSharedObject(ClientRegistrationRepository.class);
|
||||
if (clientRegistrationRepository == null) {
|
||||
clientRegistrationRepository = this.getClientRegistrationRepositoryBean();
|
||||
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
|
||||
}
|
||||
return clientRegistrationRepository;
|
||||
}
|
||||
|
||||
private ClientRegistrationRepository getClientRegistrationRepositoryBean() {
|
||||
return this.getBuilder().getSharedObject(ApplicationContext.class).getBean(ClientRegistrationRepository.class);
|
||||
}
|
||||
}
|
||||
|
||||
-266
@@ -1,266 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationProvider;
|
||||
import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository;
|
||||
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
|
||||
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||
import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* An {@link AbstractHttpConfigurer} for OAuth 2.0 Client support.
|
||||
*
|
||||
* <p>
|
||||
* The following configuration options are available:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link #authorizationCodeGrant()} - support for the OAuth 2.0 Authorization Code Grant</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* Defaults are provided for all configuration options with the only required configuration
|
||||
* being {@link #clientRegistrationRepository(ClientRegistrationRepository)}.
|
||||
* Alternatively, a {@link ClientRegistrationRepository} {@code @Bean} may be registered instead.
|
||||
*
|
||||
* <h2>Security Filters</h2>
|
||||
*
|
||||
* The following {@code Filter}'s are populated for {@link #authorizationCodeGrant()}:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link OAuth2AuthorizationRequestRedirectFilter}</li>
|
||||
* <li>{@link OAuth2AuthorizationCodeGrantFilter}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Shared Objects Created</h2>
|
||||
*
|
||||
* The following shared objects are populated:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link ClientRegistrationRepository} (required)</li>
|
||||
* <li>{@link OAuth2AuthorizedClientRepository} (optional)</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Shared Objects Used</h2>
|
||||
*
|
||||
* The following shared objects are used:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link ClientRegistrationRepository}</li>
|
||||
* <li>{@link OAuth2AuthorizedClientRepository}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author Joe Grandja
|
||||
* @since 5.1
|
||||
* @see OAuth2AuthorizationRequestRedirectFilter
|
||||
* @see OAuth2AuthorizationCodeGrantFilter
|
||||
* @see ClientRegistrationRepository
|
||||
* @see OAuth2AuthorizedClientRepository
|
||||
* @see AbstractHttpConfigurer
|
||||
*/
|
||||
public final class OAuth2ClientConfigurer<B extends HttpSecurityBuilder<B>> extends
|
||||
AbstractHttpConfigurer<OAuth2ClientConfigurer<B>, B> {
|
||||
|
||||
private AuthorizationCodeGrantConfigurer authorizationCodeGrantConfigurer = new AuthorizationCodeGrantConfigurer();
|
||||
|
||||
/**
|
||||
* Sets the repository of client registrations.
|
||||
*
|
||||
* @param clientRegistrationRepository the repository of client registrations
|
||||
* @return the {@link OAuth2ClientConfigurer} for further configuration
|
||||
*/
|
||||
public OAuth2ClientConfigurer<B> clientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) {
|
||||
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
|
||||
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the repository for authorized client(s).
|
||||
*
|
||||
* @param authorizedClientRepository the authorized client repository
|
||||
* @return the {@link OAuth2ClientConfigurer} for further configuration
|
||||
*/
|
||||
public OAuth2ClientConfigurer<B> authorizedClientRepository(OAuth2AuthorizedClientRepository authorizedClientRepository) {
|
||||
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
|
||||
this.getBuilder().setSharedObject(OAuth2AuthorizedClientRepository.class, authorizedClientRepository);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the service for authorized client(s).
|
||||
*
|
||||
* @param authorizedClientService the authorized client service
|
||||
* @return the {@link OAuth2ClientConfigurer} for further configuration
|
||||
*/
|
||||
public OAuth2ClientConfigurer<B> authorizedClientService(OAuth2AuthorizedClientService authorizedClientService) {
|
||||
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
|
||||
this.authorizedClientRepository(new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the {@link AuthorizationCodeGrantConfigurer} for configuring the OAuth 2.0 Authorization Code Grant.
|
||||
*
|
||||
* @return the {@link AuthorizationCodeGrantConfigurer}
|
||||
*/
|
||||
public AuthorizationCodeGrantConfigurer authorizationCodeGrant() {
|
||||
return this.authorizationCodeGrantConfigurer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration options for the OAuth 2.0 Authorization Code Grant.
|
||||
*/
|
||||
public class AuthorizationCodeGrantConfigurer {
|
||||
private OAuth2AuthorizationRequestResolver authorizationRequestResolver;
|
||||
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
|
||||
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
|
||||
|
||||
private AuthorizationCodeGrantConfigurer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the resolver used for resolving {@link OAuth2AuthorizationRequest}'s.
|
||||
*
|
||||
* @param authorizationRequestResolver the resolver used for resolving {@link OAuth2AuthorizationRequest}'s
|
||||
* @return the {@link AuthorizationCodeGrantConfigurer} for further configuration
|
||||
*/
|
||||
public AuthorizationCodeGrantConfigurer authorizationRequestResolver(OAuth2AuthorizationRequestResolver authorizationRequestResolver) {
|
||||
Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null");
|
||||
this.authorizationRequestResolver = authorizationRequestResolver;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s.
|
||||
*
|
||||
* @param authorizationRequestRepository the repository used for storing {@link OAuth2AuthorizationRequest}'s
|
||||
* @return the {@link AuthorizationCodeGrantConfigurer} for further configuration
|
||||
*/
|
||||
public AuthorizationCodeGrantConfigurer authorizationRequestRepository(
|
||||
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
|
||||
|
||||
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
|
||||
this.authorizationRequestRepository = authorizationRequestRepository;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the client used for requesting the access token credential from the Token Endpoint.
|
||||
*
|
||||
* @param accessTokenResponseClient the client used for requesting the access token credential from the Token Endpoint
|
||||
* @return the {@link AuthorizationCodeGrantConfigurer} for further configuration
|
||||
*/
|
||||
public AuthorizationCodeGrantConfigurer accessTokenResponseClient(
|
||||
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient) {
|
||||
|
||||
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
|
||||
this.accessTokenResponseClient = accessTokenResponseClient;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the {@link OAuth2ClientConfigurer} for further configuration.
|
||||
*
|
||||
* @return the {@link OAuth2ClientConfigurer}
|
||||
*/
|
||||
public OAuth2ClientConfigurer<B> and() {
|
||||
return OAuth2ClientConfigurer.this;
|
||||
}
|
||||
|
||||
private void init(B builder) {
|
||||
OAuth2AuthorizationCodeAuthenticationProvider authorizationCodeAuthenticationProvider =
|
||||
new OAuth2AuthorizationCodeAuthenticationProvider(getAccessTokenResponseClient());
|
||||
builder.authenticationProvider(postProcess(authorizationCodeAuthenticationProvider));
|
||||
}
|
||||
|
||||
private void configure(B builder) {
|
||||
OAuth2AuthorizationRequestRedirectFilter authorizationRequestRedirectFilter = createAuthorizationRequestRedirectFilter(builder);
|
||||
builder.addFilter(postProcess(authorizationRequestRedirectFilter));
|
||||
OAuth2AuthorizationCodeGrantFilter authorizationCodeGrantFilter = createAuthorizationCodeGrantFilter(builder);
|
||||
builder.addFilter(postProcess(authorizationCodeGrantFilter));
|
||||
}
|
||||
|
||||
private OAuth2AuthorizationRequestRedirectFilter createAuthorizationRequestRedirectFilter(B builder) {
|
||||
OAuth2AuthorizationRequestResolver resolver = getAuthorizationRequestResolver();
|
||||
OAuth2AuthorizationRequestRedirectFilter authorizationRequestRedirectFilter =
|
||||
new OAuth2AuthorizationRequestRedirectFilter(resolver);
|
||||
|
||||
if (this.authorizationRequestRepository != null) {
|
||||
authorizationRequestRedirectFilter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
|
||||
}
|
||||
RequestCache requestCache = builder.getSharedObject(RequestCache.class);
|
||||
if (requestCache != null) {
|
||||
authorizationRequestRedirectFilter.setRequestCache(requestCache);
|
||||
}
|
||||
return authorizationRequestRedirectFilter;
|
||||
}
|
||||
|
||||
private OAuth2AuthorizationRequestResolver getAuthorizationRequestResolver() {
|
||||
if (this.authorizationRequestResolver != null) {
|
||||
return this.authorizationRequestResolver;
|
||||
}
|
||||
ClientRegistrationRepository clientRegistrationRepository = OAuth2ClientConfigurerUtils
|
||||
.getClientRegistrationRepository(getBuilder());
|
||||
return new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository,
|
||||
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
|
||||
}
|
||||
|
||||
private OAuth2AuthorizationCodeGrantFilter createAuthorizationCodeGrantFilter(B builder) {
|
||||
AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class);
|
||||
OAuth2AuthorizationCodeGrantFilter authorizationCodeGrantFilter = new OAuth2AuthorizationCodeGrantFilter(
|
||||
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(builder),
|
||||
OAuth2ClientConfigurerUtils.getAuthorizedClientRepository(builder),
|
||||
authenticationManager);
|
||||
|
||||
if (this.authorizationRequestRepository != null) {
|
||||
authorizationCodeGrantFilter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
|
||||
}
|
||||
return authorizationCodeGrantFilter;
|
||||
}
|
||||
|
||||
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> getAccessTokenResponseClient() {
|
||||
if (this.accessTokenResponseClient != null) {
|
||||
return this.accessTokenResponseClient;
|
||||
}
|
||||
return new DefaultAuthorizationCodeTokenResponseClient();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(B builder) throws Exception {
|
||||
this.authorizationCodeGrantConfigurer.init(builder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(B builder) throws Exception {
|
||||
this.authorizationCodeGrantConfigurer.configure(builder);
|
||||
}
|
||||
}
|
||||
-99
@@ -1,99 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
|
||||
|
||||
import org.springframework.beans.factory.BeanFactoryUtils;
|
||||
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Utility methods for the OAuth 2.0 Client {@link AbstractHttpConfigurer}'s.
|
||||
*
|
||||
* @author Joe Grandja
|
||||
* @since 5.1
|
||||
*/
|
||||
final class OAuth2ClientConfigurerUtils {
|
||||
|
||||
private OAuth2ClientConfigurerUtils() {
|
||||
}
|
||||
|
||||
static <B extends HttpSecurityBuilder<B>> ClientRegistrationRepository getClientRegistrationRepository(B builder) {
|
||||
ClientRegistrationRepository clientRegistrationRepository = builder.getSharedObject(ClientRegistrationRepository.class);
|
||||
if (clientRegistrationRepository == null) {
|
||||
clientRegistrationRepository = getClientRegistrationRepositoryBean(builder);
|
||||
builder.setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
|
||||
}
|
||||
return clientRegistrationRepository;
|
||||
}
|
||||
|
||||
private static <B extends HttpSecurityBuilder<B>> ClientRegistrationRepository getClientRegistrationRepositoryBean(B builder) {
|
||||
return builder.getSharedObject(ApplicationContext.class).getBean(ClientRegistrationRepository.class);
|
||||
}
|
||||
|
||||
static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientRepository getAuthorizedClientRepository(B builder) {
|
||||
OAuth2AuthorizedClientRepository authorizedClientRepository = builder.getSharedObject(OAuth2AuthorizedClientRepository.class);
|
||||
if (authorizedClientRepository == null) {
|
||||
authorizedClientRepository = getAuthorizedClientRepositoryBean(builder);
|
||||
if (authorizedClientRepository == null) {
|
||||
authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(
|
||||
getAuthorizedClientService((builder)));
|
||||
}
|
||||
builder.setSharedObject(OAuth2AuthorizedClientRepository.class, authorizedClientRepository);
|
||||
}
|
||||
return authorizedClientRepository;
|
||||
}
|
||||
|
||||
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientRepository getAuthorizedClientRepositoryBean(B builder) {
|
||||
Map<String, OAuth2AuthorizedClientRepository> authorizedClientRepositoryMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
|
||||
builder.getSharedObject(ApplicationContext.class), OAuth2AuthorizedClientRepository.class);
|
||||
if (authorizedClientRepositoryMap.size() > 1) {
|
||||
throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientRepository.class, authorizedClientRepositoryMap.size(),
|
||||
"Expected single matching bean of type '" + OAuth2AuthorizedClientRepository.class.getName() + "' but found " +
|
||||
authorizedClientRepositoryMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(authorizedClientRepositoryMap.keySet()));
|
||||
}
|
||||
return (!authorizedClientRepositoryMap.isEmpty() ? authorizedClientRepositoryMap.values().iterator().next() : null);
|
||||
}
|
||||
|
||||
|
||||
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientService(B builder) {
|
||||
OAuth2AuthorizedClientService authorizedClientService = getAuthorizedClientServiceBean(builder);
|
||||
if (authorizedClientService == null) {
|
||||
authorizedClientService = new InMemoryOAuth2AuthorizedClientService(getClientRegistrationRepository(builder));
|
||||
}
|
||||
return authorizedClientService;
|
||||
}
|
||||
|
||||
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientServiceBean(B builder) {
|
||||
Map<String, OAuth2AuthorizedClientService> authorizedClientServiceMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
|
||||
builder.getSharedObject(ApplicationContext.class), OAuth2AuthorizedClientService.class);
|
||||
if (authorizedClientServiceMap.size() > 1) {
|
||||
throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientService.class, authorizedClientServiceMap.size(),
|
||||
"Expected single matching bean of type '" + OAuth2AuthorizedClientService.class.getName() + "' but found " +
|
||||
authorizedClientServiceMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(authorizedClientServiceMap.keySet()));
|
||||
}
|
||||
return (!authorizedClientServiceMap.isEmpty() ? authorizedClientServiceMap.values().iterator().next() : null);
|
||||
}
|
||||
}
|
||||
+66
-120
@@ -26,11 +26,11 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHt
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider;
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
|
||||
import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.NimbusAuthorizationCodeTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
|
||||
import org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider;
|
||||
@@ -43,11 +43,8 @@ import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserServ
|
||||
import org.springframework.security.oauth2.client.userinfo.DelegatingOAuth2UserService;
|
||||
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
|
||||
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
|
||||
import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository;
|
||||
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||
@@ -55,23 +52,14 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequ
|
||||
import org.springframework.security.oauth2.core.oidc.OidcScopes;
|
||||
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
|
||||
import org.springframework.security.oauth2.core.user.OAuth2User;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
|
||||
import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.security.web.util.matcher.AndRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.OrRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -103,7 +91,7 @@ import java.util.Map;
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link ClientRegistrationRepository} (required)</li>
|
||||
* <li>{@link OAuth2AuthorizedClientRepository} (optional)</li>
|
||||
* <li>{@link OAuth2AuthorizedClientService} (optional)</li>
|
||||
* <li>{@link GrantedAuthoritiesMapper} (optional)</li>
|
||||
* </ul>
|
||||
*
|
||||
@@ -113,7 +101,7 @@ import java.util.Map;
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link ClientRegistrationRepository}</li>
|
||||
* <li>{@link OAuth2AuthorizedClientRepository}</li>
|
||||
* <li>{@link OAuth2AuthorizedClientService}</li>
|
||||
* <li>{@link GrantedAuthoritiesMapper}</li>
|
||||
* <li>{@link DefaultLoginPageGeneratingFilter} - if {@link #loginPage(String)} is not configured
|
||||
* and {@code DefaultLoginPageGeneratingFilter} is available, than a default login page will be made available</li>
|
||||
@@ -126,7 +114,6 @@ import java.util.Map;
|
||||
* @see OAuth2AuthorizationRequestRedirectFilter
|
||||
* @see OAuth2LoginAuthenticationFilter
|
||||
* @see ClientRegistrationRepository
|
||||
* @see OAuth2AuthorizedClientRepository
|
||||
* @see AbstractAuthenticationFilterConfigurer
|
||||
*/
|
||||
public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> extends
|
||||
@@ -151,19 +138,6 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the repository for authorized client(s).
|
||||
*
|
||||
* @since 5.1
|
||||
* @param authorizedClientRepository the authorized client repository
|
||||
* @return the {@link OAuth2LoginConfigurer} for further configuration
|
||||
*/
|
||||
public OAuth2LoginConfigurer<B> authorizedClientRepository(OAuth2AuthorizedClientRepository authorizedClientRepository) {
|
||||
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
|
||||
this.getBuilder().setSharedObject(OAuth2AuthorizedClientRepository.class, authorizedClientRepository);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the service for authorized client(s).
|
||||
*
|
||||
@@ -172,7 +146,7 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
*/
|
||||
public OAuth2LoginConfigurer<B> authorizedClientService(OAuth2AuthorizedClientService authorizedClientService) {
|
||||
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
|
||||
this.authorizedClientRepository(new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService));
|
||||
this.getBuilder().setSharedObject(OAuth2AuthorizedClientService.class, authorizedClientService);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -204,7 +178,6 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
*/
|
||||
public class AuthorizationEndpointConfig {
|
||||
private String authorizationRequestBaseUri;
|
||||
private OAuth2AuthorizationRequestResolver authorizationRequestResolver;
|
||||
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
|
||||
|
||||
private AuthorizationEndpointConfig() {
|
||||
@@ -222,19 +195,6 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the resolver used for resolving {@link OAuth2AuthorizationRequest}'s.
|
||||
*
|
||||
* @since 5.1
|
||||
* @param authorizationRequestResolver the resolver used for resolving {@link OAuth2AuthorizationRequest}'s
|
||||
* @return the {@link AuthorizationEndpointConfig} for further configuration
|
||||
*/
|
||||
public AuthorizationEndpointConfig authorizationRequestResolver(OAuth2AuthorizationRequestResolver authorizationRequestResolver) {
|
||||
Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null");
|
||||
this.authorizationRequestResolver = authorizationRequestResolver;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s.
|
||||
*
|
||||
@@ -424,37 +384,20 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
public void init(B http) throws Exception {
|
||||
OAuth2LoginAuthenticationFilter authenticationFilter =
|
||||
new OAuth2LoginAuthenticationFilter(
|
||||
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder()),
|
||||
OAuth2ClientConfigurerUtils.getAuthorizedClientRepository(this.getBuilder()),
|
||||
this.getClientRegistrationRepository(),
|
||||
this.getAuthorizedClientService(),
|
||||
this.loginProcessingUrl);
|
||||
this.setAuthenticationFilter(authenticationFilter);
|
||||
super.loginProcessingUrl(this.loginProcessingUrl);
|
||||
RequestMatcher authenticationNullMatcher = request -> SecurityContextHolder.getContext().getAuthentication() == null;
|
||||
authenticationFilter.setRequiresAuthenticationRequestMatcher(new AndRequestMatcher(createLoginProcessingUrlMatcher(this.loginProcessingUrl),
|
||||
authenticationNullMatcher));
|
||||
|
||||
if (this.loginPage != null) {
|
||||
// Set custom login page
|
||||
super.loginPage(this.loginPage);
|
||||
super.init(http);
|
||||
} else {
|
||||
Map<String, String> loginUrlToClientName = this.getLoginLinks();
|
||||
if (loginUrlToClientName.size() == 1) {
|
||||
// Setup auto-redirect to provider login page
|
||||
// when only 1 client is configured
|
||||
this.updateAuthenticationDefaults();
|
||||
this.updateAccessDefaults(http);
|
||||
String providerLoginPage = loginUrlToClientName.keySet().iterator().next();
|
||||
this.registerAuthenticationEntryPoint(http, this.getLoginEntryPoint(http, providerLoginPage));
|
||||
} else {
|
||||
super.init(http);
|
||||
}
|
||||
}
|
||||
super.init(http);
|
||||
|
||||
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient =
|
||||
this.tokenEndpointConfig.accessTokenResponseClient;
|
||||
if (accessTokenResponseClient == null) {
|
||||
accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
|
||||
accessTokenResponseClient = new NimbusAuthorizationCodeTokenResponseClient();
|
||||
}
|
||||
|
||||
OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService = this.userInfoEndpointConfig.userService;
|
||||
@@ -501,28 +444,18 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
|
||||
@Override
|
||||
public void configure(B http) throws Exception {
|
||||
OAuth2AuthorizationRequestRedirectFilter authorizationRequestFilter;
|
||||
|
||||
if (this.authorizationEndpointConfig.authorizationRequestResolver != null) {
|
||||
authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
|
||||
this.authorizationEndpointConfig.authorizationRequestResolver);
|
||||
} else {
|
||||
String authorizationRequestBaseUri = this.authorizationEndpointConfig.authorizationRequestBaseUri;
|
||||
if (authorizationRequestBaseUri == null) {
|
||||
authorizationRequestBaseUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
|
||||
}
|
||||
authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
|
||||
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder()), authorizationRequestBaseUri);
|
||||
String authorizationRequestBaseUri = this.authorizationEndpointConfig.authorizationRequestBaseUri;
|
||||
if (authorizationRequestBaseUri == null) {
|
||||
authorizationRequestBaseUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
|
||||
}
|
||||
|
||||
OAuth2AuthorizationRequestRedirectFilter authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
|
||||
this.getClientRegistrationRepository(), authorizationRequestBaseUri);
|
||||
|
||||
if (this.authorizationEndpointConfig.authorizationRequestRepository != null) {
|
||||
authorizationRequestFilter.setAuthorizationRequestRepository(
|
||||
this.authorizationEndpointConfig.authorizationRequestRepository);
|
||||
}
|
||||
RequestCache requestCache = http.getSharedObject(RequestCache.class);
|
||||
if (requestCache != null) {
|
||||
authorizationRequestFilter.setRequestCache(requestCache);
|
||||
}
|
||||
http.addFilter(this.postProcess(authorizationRequestFilter));
|
||||
|
||||
OAuth2LoginAuthenticationFilter authenticationFilter = this.getAuthenticationFilter();
|
||||
@@ -541,6 +474,41 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
return new AntPathRequestMatcher(loginProcessingUrl);
|
||||
}
|
||||
|
||||
private ClientRegistrationRepository getClientRegistrationRepository() {
|
||||
ClientRegistrationRepository clientRegistrationRepository =
|
||||
this.getBuilder().getSharedObject(ClientRegistrationRepository.class);
|
||||
if (clientRegistrationRepository == null) {
|
||||
clientRegistrationRepository = this.getClientRegistrationRepositoryBean();
|
||||
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
|
||||
}
|
||||
return clientRegistrationRepository;
|
||||
}
|
||||
|
||||
private ClientRegistrationRepository getClientRegistrationRepositoryBean() {
|
||||
return this.getBuilder().getSharedObject(ApplicationContext.class).getBean(ClientRegistrationRepository.class);
|
||||
}
|
||||
|
||||
private OAuth2AuthorizedClientService getAuthorizedClientService() {
|
||||
OAuth2AuthorizedClientService authorizedClientService =
|
||||
this.getBuilder().getSharedObject(OAuth2AuthorizedClientService.class);
|
||||
if (authorizedClientService == null) {
|
||||
authorizedClientService = this.getAuthorizedClientServiceBean();
|
||||
if (authorizedClientService == null) {
|
||||
authorizedClientService = new InMemoryOAuth2AuthorizedClientService(this.getClientRegistrationRepository());
|
||||
}
|
||||
this.getBuilder().setSharedObject(OAuth2AuthorizedClientService.class, authorizedClientService);
|
||||
}
|
||||
return authorizedClientService;
|
||||
}
|
||||
|
||||
private OAuth2AuthorizedClientService getAuthorizedClientServiceBean() {
|
||||
Map<String, OAuth2AuthorizedClientService> authorizedClientServiceMap =
|
||||
BeanFactoryUtils.beansOfTypeIncludingAncestors(
|
||||
this.getBuilder().getSharedObject(ApplicationContext.class),
|
||||
OAuth2AuthorizedClientService.class);
|
||||
return (!authorizedClientServiceMap.isEmpty() ? authorizedClientServiceMap.values().iterator().next() : null);
|
||||
}
|
||||
|
||||
private GrantedAuthoritiesMapper getGrantedAuthoritiesMapper() {
|
||||
GrantedAuthoritiesMapper grantedAuthoritiesMapper =
|
||||
this.getBuilder().getSharedObject(GrantedAuthoritiesMapper.class);
|
||||
@@ -555,9 +523,9 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
|
||||
private GrantedAuthoritiesMapper getGrantedAuthoritiesMapperBean() {
|
||||
Map<String, GrantedAuthoritiesMapper> grantedAuthoritiesMapperMap =
|
||||
BeanFactoryUtils.beansOfTypeIncludingAncestors(
|
||||
this.getBuilder().getSharedObject(ApplicationContext.class),
|
||||
GrantedAuthoritiesMapper.class);
|
||||
BeanFactoryUtils.beansOfTypeIncludingAncestors(
|
||||
this.getBuilder().getSharedObject(ApplicationContext.class),
|
||||
GrantedAuthoritiesMapper.class);
|
||||
return (!grantedAuthoritiesMapperMap.isEmpty() ? grantedAuthoritiesMapperMap.values().iterator().next() : null);
|
||||
}
|
||||
|
||||
@@ -567,51 +535,28 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
return;
|
||||
}
|
||||
|
||||
loginPageGeneratingFilter.setOauth2LoginEnabled(true);
|
||||
loginPageGeneratingFilter.setOauth2AuthenticationUrlToClientName(this.getLoginLinks());
|
||||
loginPageGeneratingFilter.setLoginPageUrl(this.getLoginPage());
|
||||
loginPageGeneratingFilter.setFailureUrl(this.getFailureUrl());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, String> getLoginLinks() {
|
||||
Iterable<ClientRegistration> clientRegistrations = null;
|
||||
ClientRegistrationRepository clientRegistrationRepository =
|
||||
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder());
|
||||
ClientRegistrationRepository clientRegistrationRepository = this.getClientRegistrationRepository();
|
||||
ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class);
|
||||
if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
|
||||
clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
|
||||
}
|
||||
if (clientRegistrations == null) {
|
||||
return Collections.emptyMap();
|
||||
return;
|
||||
}
|
||||
|
||||
String authorizationRequestBaseUri = this.authorizationEndpointConfig.authorizationRequestBaseUri != null ?
|
||||
this.authorizationEndpointConfig.authorizationRequestBaseUri :
|
||||
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
|
||||
Map<String, String> loginUrlToClientName = new HashMap<>();
|
||||
clientRegistrations.forEach(registration -> loginUrlToClientName.put(
|
||||
authorizationRequestBaseUri + "/" + registration.getRegistrationId(),
|
||||
registration.getClientName()));
|
||||
this.authorizationEndpointConfig.authorizationRequestBaseUri :
|
||||
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
|
||||
Map<String, String> authenticationUrlToClientName = new HashMap<>();
|
||||
|
||||
return loginUrlToClientName;
|
||||
}
|
||||
|
||||
private AuthenticationEntryPoint getLoginEntryPoint(B http, String providerLoginPage) {
|
||||
RequestMatcher loginPageMatcher = new AntPathRequestMatcher(this.getLoginPage());
|
||||
RequestMatcher faviconMatcher = new AntPathRequestMatcher("/favicon.ico");
|
||||
RequestMatcher defaultEntryPointMatcher = this.getAuthenticationEntryPointMatcher(http);
|
||||
RequestMatcher defaultLoginPageMatcher = new AndRequestMatcher(
|
||||
new OrRequestMatcher(loginPageMatcher, faviconMatcher), defaultEntryPointMatcher);
|
||||
|
||||
LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>();
|
||||
entryPoints.put(new NegatedRequestMatcher(defaultLoginPageMatcher),
|
||||
new LoginUrlAuthenticationEntryPoint(providerLoginPage));
|
||||
|
||||
DelegatingAuthenticationEntryPoint loginEntryPoint = new DelegatingAuthenticationEntryPoint(entryPoints);
|
||||
loginEntryPoint.setDefaultEntryPoint(this.getAuthenticationEntryPoint());
|
||||
|
||||
return loginEntryPoint;
|
||||
clientRegistrations.forEach(registration -> authenticationUrlToClientName.put(
|
||||
authorizationRequestBaseUri + "/" + registration.getRegistrationId(),
|
||||
registration.getClientName()));
|
||||
loginPageGeneratingFilter.setOauth2LoginEnabled(true);
|
||||
loginPageGeneratingFilter.setOauth2AuthenticationUrlToClientName(authenticationUrlToClientName);
|
||||
loginPageGeneratingFilter.setLoginPageUrl(this.getLoginPage());
|
||||
loginPageGeneratingFilter.setFailureUrl(this.getFailureUrl());
|
||||
}
|
||||
|
||||
private static class OidcAuthenticationRequestChecker implements AuthenticationProvider {
|
||||
@@ -643,4 +588,5 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
||||
return OAuth2LoginAuthenticationToken.class.isAssignableFrom(authentication);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-312
@@ -1,312 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.config.annotation.web.configurers.oauth2.server.resource;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoderJwkSupport;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
|
||||
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
|
||||
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter;
|
||||
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
|
||||
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
|
||||
import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
*
|
||||
* An {@link AbstractHttpConfigurer} for OAuth 2.0 Resource Server Support.
|
||||
*
|
||||
* By default, this wires a {@link BearerTokenAuthenticationFilter}, which can be used to parse the request
|
||||
* for bearer tokens and make an authentication attempt.
|
||||
*
|
||||
* <p>
|
||||
* The following configuration options are available:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link #accessDeniedHandler(AccessDeniedHandler)}</li> - customizes how access denied errors are handled
|
||||
* <li>{@link #authenticationEntryPoint(AuthenticationEntryPoint)}</li> - customizes how authentication failures are handled
|
||||
* <li>{@link #bearerTokenResolver(BearerTokenResolver)} - customizes how to resolve a bearer token from the request</li>
|
||||
* <li>{@link #jwt()} - enables Jwt-encoded bearer token support</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* When using {@link #jwt()}, either
|
||||
*
|
||||
* <ul>
|
||||
* <li>
|
||||
* supply a Jwk Set Uri via {@link JwtConfigurer#jwkSetUri}, or
|
||||
* </li>
|
||||
* <li>
|
||||
* supply a {@link JwtDecoder} instance via {@link JwtConfigurer#decoder}, or
|
||||
* </li>
|
||||
* <li>
|
||||
* expose a {@link JwtDecoder} bean
|
||||
* </li>
|
||||
* </ul>
|
||||
*
|
||||
* Also with {@link #jwt()} consider
|
||||
*
|
||||
* <ul>
|
||||
* <li>
|
||||
* customizing the conversion from a {@link Jwt} to an {@link org.springframework.security.core.Authentication} with
|
||||
* {@link JwtConfigurer#jwtAuthenticationConverter(Converter)}
|
||||
* </li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Security Filters</h2>
|
||||
*
|
||||
* The following {@code Filter}s are populated when {@link #jwt()} is configured:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link BearerTokenAuthenticationFilter}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Shared Objects Created</h2>
|
||||
*
|
||||
* The following shared objects are populated:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link SessionCreationPolicy} (optional)</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Shared Objects Used</h2>
|
||||
*
|
||||
* The following shared objects are used:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link AuthenticationManager}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author Josh Cummings
|
||||
* @since 5.1
|
||||
* @see BearerTokenAuthenticationFilter
|
||||
* @see JwtAuthenticationProvider
|
||||
* @see NimbusJwtDecoderJwkSupport
|
||||
* @see AbstractHttpConfigurer
|
||||
*/
|
||||
public final class OAuth2ResourceServerConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
AbstractHttpConfigurer<OAuth2ResourceServerConfigurer<H>, H> {
|
||||
|
||||
private final ApplicationContext context;
|
||||
|
||||
private BearerTokenResolver bearerTokenResolver;
|
||||
private JwtConfigurer jwtConfigurer;
|
||||
|
||||
private AccessDeniedHandler accessDeniedHandler = new BearerTokenAccessDeniedHandler();
|
||||
private AuthenticationEntryPoint authenticationEntryPoint = new BearerTokenAuthenticationEntryPoint();
|
||||
private BearerTokenRequestMatcher requestMatcher = new BearerTokenRequestMatcher();
|
||||
|
||||
public OAuth2ResourceServerConfigurer(ApplicationContext context) {
|
||||
Assert.notNull(context, "context cannot be null");
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public OAuth2ResourceServerConfigurer<H> accessDeniedHandler(AccessDeniedHandler accessDeniedHandler) {
|
||||
Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null");
|
||||
this.accessDeniedHandler = accessDeniedHandler;
|
||||
return this;
|
||||
}
|
||||
|
||||
public OAuth2ResourceServerConfigurer<H> authenticationEntryPoint(AuthenticationEntryPoint entryPoint) {
|
||||
Assert.notNull(entryPoint, "entryPoint cannot be null");
|
||||
this.authenticationEntryPoint = entryPoint;
|
||||
return this;
|
||||
}
|
||||
|
||||
public OAuth2ResourceServerConfigurer<H> bearerTokenResolver(BearerTokenResolver bearerTokenResolver) {
|
||||
Assert.notNull(bearerTokenResolver, "bearerTokenResolver cannot be null");
|
||||
this.bearerTokenResolver = bearerTokenResolver;
|
||||
return this;
|
||||
}
|
||||
|
||||
public JwtConfigurer jwt() {
|
||||
if ( this.jwtConfigurer == null ) {
|
||||
this.jwtConfigurer = new JwtConfigurer(this.context);
|
||||
}
|
||||
|
||||
return this.jwtConfigurer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(H http) throws Exception {
|
||||
registerDefaultAccessDeniedHandler(http);
|
||||
registerDefaultEntryPoint(http);
|
||||
registerDefaultCsrfOverride(http);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(H http) throws Exception {
|
||||
BearerTokenResolver bearerTokenResolver = getBearerTokenResolver();
|
||||
this.requestMatcher.setBearerTokenResolver(bearerTokenResolver);
|
||||
|
||||
AuthenticationManager manager = http.getSharedObject(AuthenticationManager.class);
|
||||
|
||||
BearerTokenAuthenticationFilter filter =
|
||||
new BearerTokenAuthenticationFilter(manager);
|
||||
filter.setBearerTokenResolver(bearerTokenResolver);
|
||||
filter.setAuthenticationEntryPoint(this.authenticationEntryPoint);
|
||||
filter = postProcess(filter);
|
||||
|
||||
http.addFilter(filter);
|
||||
|
||||
if ( this.jwtConfigurer == null ) {
|
||||
throw new IllegalStateException("Jwt is the only supported format for bearer tokens " +
|
||||
"in Spring Security and no Jwt configuration was found. Make sure to specify " +
|
||||
"a jwk set uri by doing http.oauth2ResourceServer().jwt().jwkSetUri(uri), or wire a " +
|
||||
"JwtDecoder instance by doing http.oauth2ResourceServer().jwt().decoder(decoder), or " +
|
||||
"expose a JwtDecoder instance as a bean and do http.oauth2ResourceServer().jwt().");
|
||||
}
|
||||
|
||||
JwtDecoder decoder = this.jwtConfigurer.getJwtDecoder();
|
||||
Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter =
|
||||
this.jwtConfigurer.getJwtAuthenticationConverter();
|
||||
|
||||
JwtAuthenticationProvider provider =
|
||||
new JwtAuthenticationProvider(decoder);
|
||||
provider.setJwtAuthenticationConverter(jwtAuthenticationConverter);
|
||||
provider = postProcess(provider);
|
||||
|
||||
http.authenticationProvider(provider);
|
||||
}
|
||||
|
||||
public class JwtConfigurer {
|
||||
private final ApplicationContext context;
|
||||
|
||||
private JwtDecoder decoder;
|
||||
|
||||
private Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter =
|
||||
new JwtAuthenticationConverter();
|
||||
|
||||
JwtConfigurer(ApplicationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public JwtConfigurer decoder(JwtDecoder decoder) {
|
||||
this.decoder = decoder;
|
||||
return this;
|
||||
}
|
||||
|
||||
public JwtConfigurer jwkSetUri(String uri) {
|
||||
this.decoder = new NimbusJwtDecoderJwkSupport(uri);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JwtConfigurer jwtAuthenticationConverter
|
||||
(Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter) {
|
||||
|
||||
this.jwtAuthenticationConverter = jwtAuthenticationConverter;
|
||||
return this;
|
||||
}
|
||||
|
||||
public OAuth2ResourceServerConfigurer<H> and() {
|
||||
return OAuth2ResourceServerConfigurer.this;
|
||||
}
|
||||
|
||||
Converter<Jwt, ? extends AbstractAuthenticationToken> getJwtAuthenticationConverter() {
|
||||
return this.jwtAuthenticationConverter;
|
||||
}
|
||||
|
||||
JwtDecoder getJwtDecoder() {
|
||||
if ( this.decoder == null ) {
|
||||
return this.context.getBean(JwtDecoder.class);
|
||||
}
|
||||
|
||||
return this.decoder;
|
||||
}
|
||||
}
|
||||
|
||||
private void registerDefaultAccessDeniedHandler(H http) {
|
||||
ExceptionHandlingConfigurer<H> exceptionHandling = http
|
||||
.getConfigurer(ExceptionHandlingConfigurer.class);
|
||||
if (exceptionHandling == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
exceptionHandling.defaultAccessDeniedHandlerFor(
|
||||
this.accessDeniedHandler,
|
||||
this.requestMatcher);
|
||||
}
|
||||
|
||||
private void registerDefaultEntryPoint(H http) {
|
||||
ExceptionHandlingConfigurer<H> exceptionHandling = http
|
||||
.getConfigurer(ExceptionHandlingConfigurer.class);
|
||||
if (exceptionHandling == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
exceptionHandling.defaultAuthenticationEntryPointFor(
|
||||
this.authenticationEntryPoint,
|
||||
this.requestMatcher);
|
||||
}
|
||||
|
||||
private void registerDefaultCsrfOverride(H http) {
|
||||
CsrfConfigurer<H> csrf = http
|
||||
.getConfigurer(CsrfConfigurer.class);
|
||||
if (csrf == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
csrf.ignoringRequestMatchers(this.requestMatcher);
|
||||
}
|
||||
|
||||
BearerTokenResolver getBearerTokenResolver() {
|
||||
if ( this.bearerTokenResolver == null ) {
|
||||
if ( this.context.getBeanNamesForType(BearerTokenResolver.class).length > 0 ) {
|
||||
this.bearerTokenResolver = this.context.getBean(BearerTokenResolver.class);
|
||||
} else {
|
||||
this.bearerTokenResolver = new DefaultBearerTokenResolver();
|
||||
}
|
||||
}
|
||||
|
||||
return this.bearerTokenResolver;
|
||||
}
|
||||
|
||||
private static final class BearerTokenRequestMatcher implements RequestMatcher {
|
||||
private BearerTokenResolver bearerTokenResolver;
|
||||
|
||||
@Override
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
try {
|
||||
return this.bearerTokenResolver.resolve(request) != null;
|
||||
} catch ( OAuth2AuthenticationException e ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void setBearerTokenResolver(BearerTokenResolver tokenResolver) {
|
||||
Assert.notNull(tokenResolver, "resolver cannot be null");
|
||||
this.bearerTokenResolver = tokenResolver;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -479,7 +479,7 @@ public final class OpenIDLoginConfigurer<H extends HttpSecurityBuilder<H>> exten
|
||||
/**
|
||||
* The OpenID attribute type.
|
||||
* @param type
|
||||
* @return the {@link AttributeConfigurer} for further customizations
|
||||
* @return
|
||||
*/
|
||||
public AttributeConfigurer type(String type) {
|
||||
this.type = type;
|
||||
|
||||
+1
-6
@@ -54,7 +54,6 @@ import java.lang.annotation.Target;
|
||||
* <pre class="code">
|
||||
* @EnableWebFluxSecurity
|
||||
* public class MyExplicitSecurityConfiguration {
|
||||
* // @formatter:off
|
||||
* @Bean
|
||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
* http
|
||||
@@ -65,9 +64,7 @@ import java.lang.annotation.Target;
|
||||
* .formLogin();
|
||||
* return http.build();
|
||||
* }
|
||||
* // @formatter:on
|
||||
*
|
||||
* // @formatter:off
|
||||
* @Bean
|
||||
* public MapReactiveUserDetailsService userDetailsService() {
|
||||
* UserDetails user = User.withDefaultPasswordEncoder()
|
||||
@@ -77,7 +74,6 @@ import java.lang.annotation.Target;
|
||||
* .build();
|
||||
* return new MapReactiveUserDetailsService(user);
|
||||
* }
|
||||
* // @formatter:on
|
||||
* }
|
||||
*
|
||||
* @author Rob Winch
|
||||
@@ -86,8 +82,7 @@ import java.lang.annotation.Target;
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
@Documented
|
||||
@Import({ServerHttpSecurityConfiguration.class, WebFluxSecurityConfiguration.class,
|
||||
ReactiveOAuth2ClientImportSelector.class})
|
||||
@Import({ServerHttpSecurityConfiguration.class, WebFluxSecurityConfiguration.class})
|
||||
@Configuration
|
||||
public @interface EnableWebFluxSecurity {
|
||||
}
|
||||
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.config.annotation.web.reactive;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.ImportSelector;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.web.server.AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository;
|
||||
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
|
||||
import org.springframework.security.oauth2.client.web.reactive.result.method.annotation.OAuth2AuthorizedClientArgumentResolver;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.web.reactive.config.WebFluxConfigurer;
|
||||
import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* {@link Configuration} for OAuth 2.0 Client support.
|
||||
*
|
||||
* <p>
|
||||
* This {@code Configuration} is imported by {@link EnableWebFluxSecurity}
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 5.1
|
||||
*/
|
||||
final class ReactiveOAuth2ClientImportSelector implements ImportSelector {
|
||||
|
||||
@Override
|
||||
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
|
||||
boolean oauth2ClientPresent = ClassUtils.isPresent(
|
||||
"org.springframework.security.oauth2.client.registration.ClientRegistration", getClass().getClassLoader());
|
||||
|
||||
return oauth2ClientPresent ?
|
||||
new String[] { "org.springframework.security.config.annotation.web.reactive.ReactiveOAuth2ClientImportSelector$OAuth2ClientWebFluxSecurityConfiguration" } :
|
||||
new String[] {};
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class OAuth2ClientWebFluxSecurityConfiguration implements WebFluxConfigurer {
|
||||
private ReactiveClientRegistrationRepository clientRegistrationRepository;
|
||||
|
||||
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
|
||||
|
||||
private ReactiveOAuth2AuthorizedClientService authorizedClientService;
|
||||
|
||||
@Override
|
||||
public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
|
||||
if (this.authorizedClientRepository != null && this.clientRegistrationRepository != null) {
|
||||
configurer.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver(this.clientRegistrationRepository, getAuthorizedClientRepository()));
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setClientRegistrationRepository(
|
||||
ReactiveClientRegistrationRepository clientRegistrationRepository) {
|
||||
this.clientRegistrationRepository = clientRegistrationRepository;
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setAuthorizedClientRepository(ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
|
||||
this.authorizedClientRepository = authorizedClientRepository;
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setAuthorizedClientService(List<ReactiveOAuth2AuthorizedClientService> authorizedClientService) {
|
||||
if (authorizedClientService.size() == 1) {
|
||||
this.authorizedClientService = authorizedClientService.get(0);
|
||||
}
|
||||
}
|
||||
|
||||
private ServerOAuth2AuthorizedClientRepository getAuthorizedClientRepository() {
|
||||
if (this.authorizedClientRepository != null) {
|
||||
return this.authorizedClientRepository;
|
||||
}
|
||||
if (this.authorizedClientService != null) {
|
||||
return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(this.authorizedClientService);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-34
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -16,26 +16,22 @@
|
||||
|
||||
package org.springframework.security.config.annotation.web.reactive;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.context.expression.BeanFactoryResolver;
|
||||
import org.springframework.core.ReactiveAdapterRegistry;
|
||||
import org.springframework.security.authentication.ReactiveAuthenticationManager;
|
||||
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager;
|
||||
import org.springframework.security.config.web.server.ServerHttpSecurity;
|
||||
import org.springframework.security.core.userdetails.ReactiveUserDetailsPasswordService;
|
||||
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.reactive.result.method.annotation.AuthenticationPrincipalArgumentResolver;
|
||||
import org.springframework.web.reactive.config.WebFluxConfigurer;
|
||||
import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer;
|
||||
|
||||
import static org.springframework.security.config.web.server.ServerHttpSecurity.http;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
@@ -57,12 +53,6 @@ class ServerHttpSecurityConfiguration implements WebFluxConfigurer {
|
||||
@Autowired(required = false)
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Autowired(required = false)
|
||||
private ReactiveUserDetailsPasswordService userDetailsPasswordService;
|
||||
|
||||
@Autowired(required = false)
|
||||
private BeanFactory beanFactory;
|
||||
|
||||
@Override
|
||||
public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
|
||||
configurer.addCustomResolver(authenticationPrincipalArgumentResolver());
|
||||
@@ -70,46 +60,30 @@ class ServerHttpSecurityConfiguration implements WebFluxConfigurer {
|
||||
|
||||
@Bean
|
||||
public AuthenticationPrincipalArgumentResolver authenticationPrincipalArgumentResolver() {
|
||||
AuthenticationPrincipalArgumentResolver resolver = new AuthenticationPrincipalArgumentResolver(
|
||||
this.adapterRegistry);
|
||||
if (this.beanFactory != null) {
|
||||
resolver.setBeanResolver(new BeanFactoryResolver(this.beanFactory));
|
||||
}
|
||||
return resolver;
|
||||
return new AuthenticationPrincipalArgumentResolver(this.adapterRegistry);
|
||||
}
|
||||
|
||||
@Bean(HTTPSECURITY_BEAN_NAME)
|
||||
@Scope("prototype")
|
||||
public ServerHttpSecurity httpSecurity() {
|
||||
ContextAwareServerHttpSecurity http = new ContextAwareServerHttpSecurity();
|
||||
return http
|
||||
return http()
|
||||
.authenticationManager(authenticationManager())
|
||||
.headers().and()
|
||||
.logout().and();
|
||||
}
|
||||
|
||||
private ReactiveAuthenticationManager authenticationManager() {
|
||||
if (this.authenticationManager != null) {
|
||||
if(this.authenticationManager != null) {
|
||||
return this.authenticationManager;
|
||||
}
|
||||
if (this.reactiveUserDetailsService != null) {
|
||||
if(this.reactiveUserDetailsService != null) {
|
||||
UserDetailsRepositoryReactiveAuthenticationManager manager =
|
||||
new UserDetailsRepositoryReactiveAuthenticationManager(this.reactiveUserDetailsService);
|
||||
if (this.passwordEncoder != null) {
|
||||
if(this.passwordEncoder != null) {
|
||||
manager.setPasswordEncoder(this.passwordEncoder);
|
||||
}
|
||||
manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
|
||||
return manager;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static class ContextAwareServerHttpSecurity extends ServerHttpSecurity implements
|
||||
ApplicationContextAware {
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
super.setApplicationContext(applicationContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+10
-35
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -16,9 +16,6 @@
|
||||
|
||||
package org.springframework.security.config.annotation.web.reactive;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@@ -28,10 +25,12 @@ import org.springframework.security.config.web.server.ServerHttpSecurity;
|
||||
import org.springframework.security.web.reactive.result.view.CsrfRequestDataValueProcessor;
|
||||
import org.springframework.security.web.server.SecurityWebFilterChain;
|
||||
import org.springframework.security.web.server.WebFilterChainProxy;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
import org.springframework.web.reactive.result.view.AbstractView;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @since 5.0
|
||||
@@ -44,11 +43,6 @@ class WebFluxSecurityConfiguration {
|
||||
|
||||
private static final String SPRING_SECURITY_WEBFILTERCHAINFILTER_BEAN_NAME = BEAN_NAME_PREFIX + "WebFilterChainFilter";
|
||||
|
||||
public static final String REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME = "org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository";
|
||||
|
||||
private static final boolean isOAuth2Present = ClassUtils.isPresent(
|
||||
REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, WebFluxSecurityConfiguration.class.getClassLoader());
|
||||
|
||||
@Autowired(required = false)
|
||||
private List<SecurityWebFilterChain> securityWebFilterChains;
|
||||
|
||||
@@ -68,7 +62,7 @@ class WebFluxSecurityConfiguration {
|
||||
|
||||
private List<SecurityWebFilterChain> getSecurityWebFilterChains() {
|
||||
List<SecurityWebFilterChain> result = this.securityWebFilterChains;
|
||||
if (ObjectUtils.isEmpty(result)) {
|
||||
if(ObjectUtils.isEmpty(result)) {
|
||||
return Arrays.asList(springSecurityFilterChain());
|
||||
}
|
||||
return result;
|
||||
@@ -87,29 +81,10 @@ class WebFluxSecurityConfiguration {
|
||||
private SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
http
|
||||
.authorizeExchange()
|
||||
.anyExchange().authenticated();
|
||||
|
||||
if (isOAuth2Present && OAuth2ClasspathGuard.shouldConfigure(this.context)) {
|
||||
OAuth2ClasspathGuard.configure(this.context, http);
|
||||
} else {
|
||||
http
|
||||
.httpBasic().and()
|
||||
.formLogin();
|
||||
}
|
||||
|
||||
SecurityWebFilterChain result = http.build();
|
||||
return result;
|
||||
}
|
||||
|
||||
private static class OAuth2ClasspathGuard {
|
||||
static void configure(ApplicationContext context, ServerHttpSecurity http) {
|
||||
http.oauth2Login();
|
||||
}
|
||||
|
||||
static boolean shouldConfigure(ApplicationContext context) {
|
||||
ClassLoader loader = context.getClassLoader();
|
||||
Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils.resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader);
|
||||
return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1;
|
||||
}
|
||||
.anyExchange().authenticated()
|
||||
.and()
|
||||
.httpBasic().and()
|
||||
.formLogin();
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -216,7 +216,7 @@ public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setMessageExpressionHandler(List<SecurityExpressionHandler<Message<Object>>> expressionHandlers) {
|
||||
if (expressionHandlers.size() == 1) {
|
||||
if(expressionHandlers.size() == 1) {
|
||||
this.expressionHandler = expressionHandlers.get(0);
|
||||
}
|
||||
}
|
||||
@@ -227,7 +227,7 @@ public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends
|
||||
}
|
||||
|
||||
private SecurityExpressionHandler<Message<Object>> getMessageExpressionHandler() {
|
||||
if (expressionHandler == null) {
|
||||
if(expressionHandler == null) {
|
||||
return defaultExpressionHandler;
|
||||
}
|
||||
return expressionHandler;
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -103,7 +103,7 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition
|
||||
else {
|
||||
BeanDefinition provider = resolver.resolve(
|
||||
providerElt.getNamespaceURI()).parse(providerElt, pc);
|
||||
Assert.notNull(provider, () -> "Parser for " + providerElt.getNodeName()
|
||||
Assert.notNull(provider, "Parser for " + providerElt.getNodeName()
|
||||
+ " returned a null bean definition");
|
||||
String providerId = pc.getReaderContext().generateBeanName(provider);
|
||||
pc.registerBeanComponent(new BeanComponentDefinition(provider,
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -55,7 +55,7 @@ public class AuthenticationManagerFactoryBean implements
|
||||
}
|
||||
|
||||
UserDetailsService uds = getBeanOrNull(UserDetailsService.class);
|
||||
if (uds == null) {
|
||||
if(uds == null) {
|
||||
throw new NoSuchBeanDefinitionException(BeanIds.AUTHENTICATION_MANAGER,
|
||||
MISSING_BEAN_ERROR_MESSAGE);
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -49,7 +49,7 @@ public class CachingUserDetailsService implements UserDetailsService {
|
||||
user = delegate.loadUserByUsername(username);
|
||||
}
|
||||
|
||||
Assert.notNull(user, () -> "UserDetailsService " + delegate
|
||||
Assert.notNull(user, "UserDetailsService " + delegate
|
||||
+ " returned null for username " + username + ". "
|
||||
+ "This is an interface contract violation");
|
||||
|
||||
|
||||
+1
@@ -57,6 +57,7 @@ public class ReactiveUserDetailsServiceResourceFactoryBean
|
||||
* Sets the location of a Resource that is a Properties file in the format defined in {@link UserDetailsResourceFactoryBean}.
|
||||
*
|
||||
* @param resourceLocation the location of the properties file that contains the users (i.e. "classpath:users.properties")
|
||||
* @return the UserDetailsResourceFactoryBean
|
||||
*/
|
||||
public void setResourceLocation(String resourceLocation) {
|
||||
this.userDetails.setResourceLocation(resourceLocation);
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -96,7 +96,7 @@ public class UserDetailsResourceFactoryBean implements ResourceLoaderAware, Fact
|
||||
|
||||
private Resource getPropertiesResource() {
|
||||
Resource result = resource;
|
||||
if (result == null && resourceLocation != null) {
|
||||
if(result == null && resourceLocation != null) {
|
||||
result = resourceLoader.getResource(resourceLocation);
|
||||
}
|
||||
Assert.notNull(result, "resource cannot be null if resourceLocation is null");
|
||||
|
||||
+2
-10
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -48,7 +48,6 @@ import org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthe
|
||||
import org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor;
|
||||
import org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
import org.springframework.security.web.csrf.CsrfToken;
|
||||
@@ -124,7 +123,6 @@ final class AuthenticationConfigBuilder {
|
||||
@SuppressWarnings("rawtypes")
|
||||
private ManagedList logoutHandlers;
|
||||
private BeanDefinition loginPageGenerationFilter;
|
||||
private BeanDefinition logoutPageGenerationFilter;
|
||||
private BeanDefinition etf;
|
||||
private final BeanReference requestCache;
|
||||
private final BeanReference portMapper;
|
||||
@@ -546,10 +544,6 @@ final class AuthenticationConfigBuilder {
|
||||
.rootBeanDefinition(DefaultLoginPageGeneratingFilter.class);
|
||||
loginPageFilter.addPropertyValue("resolveHiddenInputs", new CsrfTokenHiddenInputFunction());
|
||||
|
||||
BeanDefinitionBuilder logoutPageFilter = BeanDefinitionBuilder
|
||||
.rootBeanDefinition(DefaultLogoutPageGeneratingFilter.class);
|
||||
logoutPageFilter.addPropertyValue("resolveHiddenInputs", new CsrfTokenHiddenInputFunction());
|
||||
|
||||
if (formFilterId != null) {
|
||||
loginPageFilter.addConstructorArgReference(formFilterId);
|
||||
loginPageFilter.addPropertyValue("authenticationUrl", loginProcessingUrl);
|
||||
@@ -562,7 +556,6 @@ final class AuthenticationConfigBuilder {
|
||||
}
|
||||
|
||||
loginPageGenerationFilter = loginPageFilter.getBeanDefinition();
|
||||
this.logoutPageGenerationFilter = logoutPageFilter.getBeanDefinition();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -805,7 +798,6 @@ final class AuthenticationConfigBuilder {
|
||||
|
||||
if (loginPageGenerationFilter != null) {
|
||||
filters.add(new OrderDecorator(loginPageGenerationFilter, LOGIN_PAGE_FILTER));
|
||||
filters.add(new OrderDecorator(this.logoutPageGenerationFilter, LOGOUT_PAGE_FILTER));
|
||||
}
|
||||
|
||||
if (basicFilter != null) {
|
||||
@@ -849,7 +841,7 @@ final class AuthenticationConfigBuilder {
|
||||
@Override
|
||||
public Map<String, String> apply(HttpServletRequest request) {
|
||||
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
||||
if (token == null) {
|
||||
if(token == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return Collections.singletonMap(token.getParameterName(), token.getToken());
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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.
|
||||
@@ -39,17 +39,17 @@ public class CorsBeanDefinitionParser {
|
||||
private static final String ATT_REF = "ref";
|
||||
|
||||
public BeanMetadataElement parse(Element element, ParserContext parserContext) {
|
||||
if (element == null) {
|
||||
if(element == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String filterRef = element.getAttribute(ATT_REF);
|
||||
if (StringUtils.hasText(filterRef)) {
|
||||
if(StringUtils.hasText(filterRef)) {
|
||||
return new RuntimeBeanReference(filterRef);
|
||||
}
|
||||
|
||||
BeanMetadataElement configurationSource = getSource(element, parserContext);
|
||||
if (configurationSource == null) {
|
||||
if(configurationSource == null) {
|
||||
throw new BeanCreationException("Could not create CorsFilter");
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ public class CorsBeanDefinitionParser {
|
||||
|
||||
boolean mvcPresent = ClassUtils.isPresent(HANDLER_MAPPING_INTROSPECTOR,
|
||||
getClass().getClassLoader());
|
||||
if (!mvcPresent) {
|
||||
if(!mvcPresent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -183,7 +183,7 @@ public class FormLoginBeanDefinitionParser {
|
||||
if (StringUtils.hasText(successHandlerRef)) {
|
||||
filterBuilder.addPropertyReference("authenticationSuccessHandler",
|
||||
successHandlerRef);
|
||||
} else if (StringUtils.hasText(authenticationSuccessForwardUrl)) {
|
||||
} else if(StringUtils.hasText(authenticationSuccessForwardUrl)) {
|
||||
BeanDefinitionBuilder forwardSuccessHandler = BeanDefinitionBuilder
|
||||
.rootBeanDefinition(ForwardAuthenticationSuccessHandler.class);
|
||||
forwardSuccessHandler.addConstructorArgValue(authenticationSuccessForwardUrl);
|
||||
@@ -216,7 +216,7 @@ public class FormLoginBeanDefinitionParser {
|
||||
if (StringUtils.hasText(failureHandlerRef)) {
|
||||
filterBuilder.addPropertyReference("authenticationFailureHandler",
|
||||
failureHandlerRef);
|
||||
} else if (StringUtils.hasText(authenticationFailureForwardUrl)) {
|
||||
} else if(StringUtils.hasText(authenticationFailureForwardUrl)) {
|
||||
BeanDefinitionBuilder forwardFailureHandler = BeanDefinitionBuilder
|
||||
.rootBeanDefinition(ForwardAuthenticationFailureHandler.class);
|
||||
forwardFailureHandler.addConstructorArgValue(authenticationFailureForwardUrl);
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -48,7 +48,7 @@ class GrantedAuthorityDefaultsParserUtils {
|
||||
public final void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
String[] grantedAuthorityDefaultsBeanNames = applicationContext.getBeanNamesForType(GrantedAuthorityDefaults.class);
|
||||
if (grantedAuthorityDefaultsBeanNames.length == 1) {
|
||||
if(grantedAuthorityDefaultsBeanNames.length == 1) {
|
||||
GrantedAuthorityDefaults grantedAuthorityDefaults = applicationContext.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
|
||||
this.rolePrefix = grantedAuthorityDefaults.getRolePrefix();
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -37,7 +37,7 @@ class HandlerMappingIntrospectorFactoryBean implements FactoryBean<HandlerMappin
|
||||
private ApplicationContext context;
|
||||
|
||||
public HandlerMappingIntrospector getObject() {
|
||||
if (!this.context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) {
|
||||
if(!this.context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) {
|
||||
throw new NoSuchBeanDefinitionException(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, "A Bean named " + HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME +" of type " + HandlerMappingIntrospector.class.getName()
|
||||
+ " is required to use MvcRequestMatcher. Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext.");
|
||||
}
|
||||
|
||||
+1
-32
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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,6 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.config.http;
|
||||
|
||||
import java.net.URI;
|
||||
@@ -48,7 +47,6 @@ import org.w3c.dom.Node;
|
||||
* @author Marten Deinum
|
||||
* @author Tim Ysewyn
|
||||
* @author Eddú Meléndez
|
||||
* @author Vedran Pavic
|
||||
* @since 3.2
|
||||
*/
|
||||
public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
|
||||
@@ -87,7 +85,6 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
|
||||
|
||||
private static final String CONTENT_SECURITY_POLICY_ELEMENT = "content-security-policy";
|
||||
private static final String REFERRER_POLICY_ELEMENT = "referrer-policy";
|
||||
private static final String FEATURE_POLICY_ELEMENT = "feature-policy";
|
||||
|
||||
private static final String ALLOW_FROM = "ALLOW-FROM";
|
||||
|
||||
@@ -117,8 +114,6 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
|
||||
|
||||
parseReferrerPolicyElement(element, parserContext);
|
||||
|
||||
parseFeaturePolicyElement(element, parserContext);
|
||||
|
||||
parseHeaderElements(element);
|
||||
|
||||
boolean noWriters = headerWriters.isEmpty();
|
||||
@@ -318,32 +313,6 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
|
||||
headerWriters.add(headersWriter.getBeanDefinition());
|
||||
}
|
||||
|
||||
private void parseFeaturePolicyElement(Element element, ParserContext context) {
|
||||
Element featurePolicyElement = (element == null) ? null
|
||||
: DomUtils.getChildElementByTagName(element, FEATURE_POLICY_ELEMENT);
|
||||
if (featurePolicyElement != null) {
|
||||
addFeaturePolicy(featurePolicyElement, context);
|
||||
}
|
||||
}
|
||||
|
||||
private void addFeaturePolicy(Element featurePolicyElement, ParserContext context) {
|
||||
BeanDefinitionBuilder headersWriter = BeanDefinitionBuilder
|
||||
.genericBeanDefinition(FeaturePolicyHeaderWriter.class);
|
||||
|
||||
String policyDirectives = featurePolicyElement
|
||||
.getAttribute(ATT_POLICY_DIRECTIVES);
|
||||
if (!StringUtils.hasText(policyDirectives)) {
|
||||
context.getReaderContext().error(
|
||||
ATT_POLICY_DIRECTIVES + " requires a 'value' to be set.",
|
||||
featurePolicyElement);
|
||||
}
|
||||
else {
|
||||
headersWriter.addConstructorArgValue(policyDirectives);
|
||||
}
|
||||
|
||||
headerWriters.add(headersWriter.getBeanDefinition());
|
||||
}
|
||||
|
||||
private void attrNotAllowed(ParserContext context, String attrName,
|
||||
String otherAttrName, Element element) {
|
||||
context.getReaderContext().error(
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -252,7 +252,7 @@ class HttpConfigurationBuilder {
|
||||
|
||||
String repoRef = httpElt.getAttribute(ATT_SECURITY_CONTEXT_REPOSITORY);
|
||||
String disableUrlRewriting = httpElt.getAttribute(ATT_DISABLE_URL_REWRITING);
|
||||
if (!StringUtils.hasText(disableUrlRewriting)) {
|
||||
if(!StringUtils.hasText(disableUrlRewriting)) {
|
||||
disableUrlRewriting = "true";
|
||||
}
|
||||
|
||||
|
||||
@@ -40,9 +40,7 @@ enum SecurityFilters {
|
||||
FORM_LOGIN_FILTER,
|
||||
OPENID_FILTER,
|
||||
LOGIN_PAGE_FILTER,
|
||||
LOGOUT_PAGE_FILTER,
|
||||
DIGEST_AUTH_FILTER,
|
||||
BEARER_TOKEN_AUTH_FILTER,
|
||||
BASIC_AUTH_FILTER,
|
||||
REQUEST_CACHE_FILTER,
|
||||
SERVLET_API_SUPPORT_FILTER,
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -512,7 +512,7 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
|
||||
synchronized (delegateMonitor) {
|
||||
if (delegate == null) {
|
||||
Assert.state(beanFactory != null,
|
||||
() -> "BeanFactory must be set to resolve " + authMgrBean);
|
||||
"BeanFactory must be set to resolve " + authMgrBean);
|
||||
try {
|
||||
delegate = beanFactory.getBean(authMgrBean,
|
||||
AuthenticationManager.class);
|
||||
@@ -561,7 +561,7 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
|
||||
public final void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
String[] grantedAuthorityDefaultsBeanNames = applicationContext.getBeanNamesForType(GrantedAuthorityDefaults.class);
|
||||
if (grantedAuthorityDefaultsBeanNames.length == 1) {
|
||||
if(grantedAuthorityDefaultsBeanNames.length == 1) {
|
||||
GrantedAuthorityDefaults grantedAuthorityDefaults = applicationContext.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
|
||||
this.rolePrefix = grantedAuthorityDefaults.getRolePrefix();
|
||||
}
|
||||
|
||||
+8
-8
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -36,7 +36,7 @@ public enum CommonOAuth2Provider {
|
||||
@Override
|
||||
public Builder getBuilder(String registrationId) {
|
||||
ClientRegistration.Builder builder = getBuilder(registrationId,
|
||||
ClientAuthenticationMethod.BASIC, DEFAULT_REDIRECT_URL);
|
||||
ClientAuthenticationMethod.BASIC, DEFAULT_LOGIN_REDIRECT_URL);
|
||||
builder.scope("openid", "profile", "email");
|
||||
builder.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
|
||||
builder.tokenUri("https://www.googleapis.com/oauth2/v4/token");
|
||||
@@ -53,7 +53,7 @@ public enum CommonOAuth2Provider {
|
||||
@Override
|
||||
public Builder getBuilder(String registrationId) {
|
||||
ClientRegistration.Builder builder = getBuilder(registrationId,
|
||||
ClientAuthenticationMethod.BASIC, DEFAULT_REDIRECT_URL);
|
||||
ClientAuthenticationMethod.BASIC, DEFAULT_LOGIN_REDIRECT_URL);
|
||||
builder.scope("read:user");
|
||||
builder.authorizationUri("https://github.com/login/oauth/authorize");
|
||||
builder.tokenUri("https://github.com/login/oauth/access_token");
|
||||
@@ -69,11 +69,11 @@ public enum CommonOAuth2Provider {
|
||||
@Override
|
||||
public Builder getBuilder(String registrationId) {
|
||||
ClientRegistration.Builder builder = getBuilder(registrationId,
|
||||
ClientAuthenticationMethod.POST, DEFAULT_REDIRECT_URL);
|
||||
ClientAuthenticationMethod.POST, DEFAULT_LOGIN_REDIRECT_URL);
|
||||
builder.scope("public_profile", "email");
|
||||
builder.authorizationUri("https://www.facebook.com/v2.8/dialog/oauth");
|
||||
builder.tokenUri("https://graph.facebook.com/v2.8/oauth/access_token");
|
||||
builder.userInfoUri("https://graph.facebook.com/me?fields=id,name,email");
|
||||
builder.userInfoUri("https://graph.facebook.com/me");
|
||||
builder.userNameAttributeName("id");
|
||||
builder.clientName("Facebook");
|
||||
return builder;
|
||||
@@ -85,15 +85,15 @@ public enum CommonOAuth2Provider {
|
||||
@Override
|
||||
public Builder getBuilder(String registrationId) {
|
||||
ClientRegistration.Builder builder = getBuilder(registrationId,
|
||||
ClientAuthenticationMethod.BASIC, DEFAULT_REDIRECT_URL);
|
||||
builder.scope("openid", "profile", "email");
|
||||
ClientAuthenticationMethod.BASIC, DEFAULT_LOGIN_REDIRECT_URL);
|
||||
builder.scope("openid", "profile", "email", "address", "phone");
|
||||
builder.userNameAttributeName(IdTokenClaimNames.SUB);
|
||||
builder.clientName("Okta");
|
||||
return builder;
|
||||
}
|
||||
};
|
||||
|
||||
private static final String DEFAULT_REDIRECT_URL = "{baseUrl}/{action}/oauth2/code/{registrationId}";
|
||||
private static final String DEFAULT_LOGIN_REDIRECT_URL = "{baseUrl}/login/oauth2/code/{registrationId}";
|
||||
|
||||
protected final ClientRegistration.Builder getBuilder(String registrationId,
|
||||
ClientAuthenticationMethod method, String redirectUri) {
|
||||
|
||||
-9
@@ -23,14 +23,6 @@ package org.springframework.security.config.web.server;
|
||||
public enum SecurityWebFiltersOrder {
|
||||
FIRST(Integer.MIN_VALUE),
|
||||
HTTP_HEADERS_WRITER,
|
||||
/**
|
||||
* {@link org.springframework.security.web.server.transport.HttpsRedirectWebFilter}
|
||||
*/
|
||||
HTTPS_REDIRECT,
|
||||
/**
|
||||
* {@link org.springframework.web.cors.reactive.CorsWebFilter}
|
||||
*/
|
||||
CORS,
|
||||
/**
|
||||
* {@link org.springframework.security.web.server.csrf.CsrfWebFilter}
|
||||
*/
|
||||
@@ -48,7 +40,6 @@ public enum SecurityWebFiltersOrder {
|
||||
*/
|
||||
FORM_LOGIN,
|
||||
AUTHENTICATION,
|
||||
OAUTH2_AUTHORIZATION_CODE,
|
||||
LOGIN_PAGE_GENERATING,
|
||||
LOGOUT_PAGE_GENERATING,
|
||||
/**
|
||||
|
||||
+57
-1150
File diff suppressed because it is too large
Load Diff
+8
-8
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2014 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -110,7 +110,7 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
|
||||
/**
|
||||
* @param element
|
||||
* @param parserContext
|
||||
* @return the {@link BeanDefinition}
|
||||
* @return
|
||||
*/
|
||||
public BeanDefinition parse(Element element, ParserContext parserContext) {
|
||||
BeanDefinitionRegistry registry = parserContext.getRegistry();
|
||||
@@ -143,7 +143,7 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
|
||||
.rootBeanDefinition(ExpressionBasedMessageSecurityMetadataSourceFactory.class);
|
||||
mds.setFactoryMethod("createExpressionMessageMetadataSource");
|
||||
mds.addConstructorArgValue(matcherToExpression);
|
||||
if (expressionHandlerDefined) {
|
||||
if(expressionHandlerDefined) {
|
||||
mds.addConstructorArgReference(expressionHandlerRef);
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
|
||||
|
||||
ManagedList<BeanDefinition> voters = new ManagedList<>();
|
||||
BeanDefinitionBuilder messageExpressionVoterBldr = BeanDefinitionBuilder.rootBeanDefinition(MessageExpressionVoter.class);
|
||||
if (expressionHandlerDefined) {
|
||||
if(expressionHandlerDefined) {
|
||||
messageExpressionVoterBldr.addPropertyReference("expressionHandler", expressionHandlerRef);
|
||||
}
|
||||
voters.add(messageExpressionVoterBldr.getBeanDefinition());
|
||||
@@ -172,7 +172,7 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
|
||||
if (StringUtils.hasText(id)) {
|
||||
registry.registerAlias(inSecurityInterceptorName, id);
|
||||
|
||||
if (!registry.containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) {
|
||||
if(!registry.containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) {
|
||||
registry.registerBeanDefinition(PATH_MATCHER_BEAN_NAME, new RootBeanDefinition(AntPathMatcher.class));
|
||||
}
|
||||
}
|
||||
@@ -267,10 +267,10 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
|
||||
AuthenticationPrincipalArgumentResolver.class));
|
||||
bd.getPropertyValues().add(CUSTOM_ARG_RESOLVERS_PROP, argResolvers);
|
||||
|
||||
if (!registry.containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) {
|
||||
if(!registry.containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) {
|
||||
PropertyValue pathMatcherProp = bd.getPropertyValues().getPropertyValue("pathMatcher");
|
||||
Object pathMatcher = pathMatcherProp == null ? null : pathMatcherProp.getValue();
|
||||
if (pathMatcher instanceof BeanReference) {
|
||||
if(pathMatcher instanceof BeanReference) {
|
||||
registry.registerAlias(((BeanReference) pathMatcher).getBeanName(), PATH_MATCHER_BEAN_NAME);
|
||||
}
|
||||
}
|
||||
@@ -312,7 +312,7 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
|
||||
|
||||
inboundChannel.getPropertyValues().add(INTERCEPTORS_PROP, interceptors);
|
||||
|
||||
if (!registry.containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) {
|
||||
if(!registry.containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) {
|
||||
registry.registerBeanDefinition(PATH_MATCHER_BEAN_NAME, new RootBeanDefinition(AntPathMatcher.class));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
http\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-5.1.xsd
|
||||
http\://www.springframework.org/schema/security/spring-security-5.1.xsd=org/springframework/security/config/spring-security-5.1.xsd
|
||||
http\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-5.0.xsd
|
||||
http\://www.springframework.org/schema/security/spring-security-5.0.xsd=org/springframework/security/config/spring-security-5.0.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
|
||||
|
||||
+1
-1
@@ -748,7 +748,7 @@ csrf-options.attlist &=
|
||||
## The RequestMatcher instance to be used to determine if CSRF should be applied. Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS"
|
||||
attribute request-matcher-ref { xsd:token }?
|
||||
csrf-options.attlist &=
|
||||
## The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository wrapped by LazyCsrfTokenRepository.
|
||||
## The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository
|
||||
attribute token-repository-ref { xsd:token }?
|
||||
|
||||
headers =
|
||||
|
||||
+1
-2
@@ -2337,8 +2337,7 @@
|
||||
</xs:attribute>
|
||||
<xs:attribute name="token-repository-ref" type="xs:token">
|
||||
<xs:annotation>
|
||||
<xs:documentation>The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository wrapped by
|
||||
LazyCsrfTokenRepository.
|
||||
<xs:documentation>The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository
|
||||
</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
|
||||
+1
-1
@@ -738,7 +738,7 @@ csrf-options.attlist &=
|
||||
## The RequestMatcher instance to be used to determine if CSRF should be applied. Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS"
|
||||
attribute request-matcher-ref { xsd:token }?
|
||||
csrf-options.attlist &=
|
||||
## The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository wrapped by LazyCsrfTokenRepository.
|
||||
## The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository
|
||||
attribute token-repository-ref { xsd:token }?
|
||||
|
||||
headers =
|
||||
|
||||
+1
-2
@@ -2232,8 +2232,7 @@
|
||||
</xs:attribute>
|
||||
<xs:attribute name="token-repository-ref" type="xs:token">
|
||||
<xs:annotation>
|
||||
<xs:documentation>The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository wrapped by
|
||||
LazyCsrfTokenRepository.
|
||||
<xs:documentation>The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository
|
||||
</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
|
||||
-916
@@ -1,916 +0,0 @@
|
||||
namespace a = "http://relaxng.org/ns/compatibility/annotations/1.0"
|
||||
datatypes xsd = "http://www.w3.org/2001/XMLSchema-datatypes"
|
||||
|
||||
default namespace = "http://www.springframework.org/schema/security"
|
||||
|
||||
start = http | ldap-server | authentication-provider | ldap-authentication-provider | any-user-service | ldap-server | ldap-authentication-provider
|
||||
|
||||
hash =
|
||||
## Defines the hashing algorithm used on user passwords. Bcrypt is recommended.
|
||||
attribute hash {"bcrypt"}
|
||||
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}
|
||||
password-encoder.attlist &=
|
||||
ref | (hash)
|
||||
|
||||
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 wrapped by LazyCsrfTokenRepository.
|
||||
attribute token-repository-ref { xsd:token }?
|
||||
|
||||
headers =
|
||||
## Element for configuration of the HeaderWritersFilter. Enables easy setting for the X-Frame-Options, X-XSS-Protection and X-Content-Type-Options headers.
|
||||
element headers { headers-options.attlist, (cache-control? & xss-protection? & hsts? & frame-options? & content-type-options? & hpkp? & content-security-policy? & referrer-policy? & feature-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"}?
|
||||
|
||||
feature-policy =
|
||||
## Adds support for Feature Policy
|
||||
element feature-policy {feature-options.attlist}
|
||||
feature-options.attlist &=
|
||||
## The security policy directive(s) for the Feature-Policy header.
|
||||
attribute policy-directives {xsd:token}?
|
||||
|
||||
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" |"LOGOUT_PAGE_FILTER" | "DIGEST_AUTH_FILTER" | "BEARER_TOKEN_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"
|
||||
-2741
File diff suppressed because it is too large
Load Diff
+92
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.method.configuration
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat
|
||||
import static org.junit.Assert.fail
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.context.ConfigurableApplicationContext
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.security.access.AccessDeniedException
|
||||
import org.springframework.security.access.PermissionEvaluator;
|
||||
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler
|
||||
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken
|
||||
import org.springframework.security.config.annotation.BaseSpringSpec
|
||||
import org.springframework.security.config.annotation.method.configuration.NamespaceGlobalMethodSecurityTests.BaseMethodConfig;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class NamespaceGlobalMethodSecurityExpressionHandlerTests extends BaseSpringSpec {
|
||||
def setup() {
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new TestingAuthenticationToken("user", "password","ROLE_USER"))
|
||||
}
|
||||
|
||||
def "global-method-security/expression-handler @PreAuthorize"() {
|
||||
setup:
|
||||
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomAccessDecisionManagerConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
when:
|
||||
service.hasPermission("granted")
|
||||
then:
|
||||
noExceptionThrown()
|
||||
when:
|
||||
service.hasPermission("denied")
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
}
|
||||
|
||||
def "global-method-security/expression-handler @PostAuthorize"() {
|
||||
setup:
|
||||
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomAccessDecisionManagerConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
when:
|
||||
service.postHasPermission("granted")
|
||||
then:
|
||||
noExceptionThrown()
|
||||
when:
|
||||
service.postHasPermission("denied")
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public static class CustomAccessDecisionManagerConfig extends GlobalMethodSecurityConfiguration {
|
||||
@Override
|
||||
protected MethodSecurityExpressionHandler createExpressionHandler() {
|
||||
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler()
|
||||
expressionHandler.permissionEvaluator = new PermissionEvaluator() {
|
||||
boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
|
||||
"granted" == targetDomainObject
|
||||
}
|
||||
boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
|
||||
throw new UnsupportedOperationException()
|
||||
}
|
||||
}
|
||||
return expressionHandler
|
||||
}
|
||||
}
|
||||
}
|
||||
+444
@@ -0,0 +1,444 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.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
|
||||
import static org.junit.Assert.fail
|
||||
|
||||
import java.lang.reflect.Method
|
||||
|
||||
import org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect
|
||||
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
|
||||
import org.springframework.beans.factory.BeanCreationException
|
||||
import org.springframework.context.ConfigurableApplicationContext
|
||||
import org.springframework.context.annotation.AdviceMode
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.context.annotation.Import
|
||||
import org.springframework.core.Ordered
|
||||
import org.springframework.security.access.AccessDecisionManager
|
||||
import org.springframework.security.access.AccessDeniedException
|
||||
import org.springframework.security.access.ConfigAttribute
|
||||
import org.springframework.security.access.SecurityConfig
|
||||
import org.springframework.security.access.intercept.AfterInvocationManager
|
||||
import org.springframework.security.access.intercept.RunAsManager
|
||||
import org.springframework.security.access.intercept.RunAsManagerImpl
|
||||
import org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor
|
||||
import org.springframework.security.access.intercept.aopalliance.MethodSecurityMetadataSourceAdvisor
|
||||
import org.springframework.security.access.method.AbstractMethodSecurityMetadataSource
|
||||
import org.springframework.security.access.method.MethodSecurityMetadataSource
|
||||
import org.springframework.security.authentication.AuthenticationManager
|
||||
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.core.Authentication
|
||||
import org.springframework.security.core.context.SecurityContextHolder
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class NamespaceGlobalMethodSecurityTests extends BaseSpringSpec {
|
||||
def setup() {
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new TestingAuthenticationToken("user", "password","ROLE_USER"))
|
||||
}
|
||||
|
||||
// --- access-decision-manager-ref ---
|
||||
|
||||
def "custom AccessDecisionManager can be used"() {
|
||||
setup: "Create an instance with an AccessDecisionManager that always denies access"
|
||||
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomAccessDecisionManagerConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
when:
|
||||
service.preAuthorize()
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
when:
|
||||
service.secured()
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
|
||||
public static class CustomAccessDecisionManagerConfig extends GlobalMethodSecurityConfiguration {
|
||||
@Override
|
||||
protected AccessDecisionManager accessDecisionManager() {
|
||||
return new DenyAllAccessDecisionManager()
|
||||
}
|
||||
|
||||
public static class DenyAllAccessDecisionManager implements AccessDecisionManager {
|
||||
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {
|
||||
throw new AccessDeniedException("Always Denied")
|
||||
}
|
||||
public boolean supports(ConfigAttribute attribute) {
|
||||
return true
|
||||
}
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- authentication-manager-ref ---
|
||||
|
||||
def "custom AuthenticationManager can be used"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(CustomAuthenticationConfig)
|
||||
MethodSecurityInterceptor interceptor = context.getBean(MethodSecurityInterceptor)
|
||||
interceptor.authenticationManager.authenticate(SecurityContextHolder.context.authentication)
|
||||
then:
|
||||
thrown(UnsupportedOperationException)
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity
|
||||
public static class CustomAuthenticationConfig extends GlobalMethodSecurityConfiguration {
|
||||
@Override
|
||||
protected AuthenticationManager authenticationManager() {
|
||||
return new AuthenticationManager() {
|
||||
Authentication authenticate(Authentication authentication) {
|
||||
throw new UnsupportedOperationException()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- jsr250-annotations ---
|
||||
|
||||
def "enable jsr250"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(Jsr250Config)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
then: "@Secured and @PreAuthorize are ignored"
|
||||
service.secured() == null
|
||||
service.preAuthorize() == null
|
||||
|
||||
when: "@DenyAll method invoked"
|
||||
service.jsr250()
|
||||
then: "access is denied"
|
||||
thrown(AccessDeniedException)
|
||||
when: "@PermitAll method invoked"
|
||||
String jsr250PermitAll = service.jsr250PermitAll()
|
||||
then: "access is allowed"
|
||||
jsr250PermitAll == null
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(jsr250Enabled = true)
|
||||
@Configuration
|
||||
public static class Jsr250Config extends BaseMethodConfig {
|
||||
}
|
||||
|
||||
// --- metadata-source-ref ---
|
||||
|
||||
def "custom MethodSecurityMetadataSource can be used with higher priority than other sources"() {
|
||||
setup:
|
||||
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomMethodSecurityMetadataSourceConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
when:
|
||||
service.preAuthorize()
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
when:
|
||||
service.secured()
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
when:
|
||||
service.jsr250()
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity
|
||||
public static class CustomMethodSecurityMetadataSourceConfig extends GlobalMethodSecurityConfiguration {
|
||||
@Override
|
||||
protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
|
||||
return new AbstractMethodSecurityMetadataSource() {
|
||||
public Collection<ConfigAttribute> getAttributes(Method method, Class<?> targetClass) {
|
||||
// require ROLE_NOBODY for any method on MethodSecurityService class
|
||||
return MethodSecurityService.isAssignableFrom(targetClass) ? [new SecurityConfig("ROLE_NOBODY")] : []
|
||||
}
|
||||
public Collection<ConfigAttribute> getAllConfigAttributes() {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- mode ---
|
||||
|
||||
def "aspectj mode works"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(AspectJModeConfig)
|
||||
then:
|
||||
context.getBean(AnnotationSecurityAspect)
|
||||
context.getBean(AspectJMethodSecurityInterceptor)
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(mode = AdviceMode.ASPECTJ, proxyTargetClass = true)
|
||||
public static class AspectJModeConfig extends BaseMethodConfig {
|
||||
}
|
||||
|
||||
def "aspectj mode works extending GlobalMethodSecurityConfiguration"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(BaseMethodConfig,AspectJModeExtendsGMSCConfig)
|
||||
then:
|
||||
context.getBean(AnnotationSecurityAspect)
|
||||
context.getBean(AspectJMethodSecurityInterceptor)
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(mode = AdviceMode.ASPECTJ)
|
||||
public static class AspectJModeExtendsGMSCConfig extends GlobalMethodSecurityConfiguration {
|
||||
}
|
||||
|
||||
// --- order ---
|
||||
|
||||
def order() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(CustomOrderConfig)
|
||||
MethodSecurityMetadataSourceAdvisor advisor = context.getBean(MethodSecurityMetadataSourceAdvisor)
|
||||
then:
|
||||
advisor.order == 135
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(order = 135)
|
||||
public static class CustomOrderConfig extends BaseMethodConfig {
|
||||
}
|
||||
|
||||
def "order is defaulted to Ordered.LOWEST_PRECEDENCE when using @EnableGlobalMethodSecurity"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(DefaultOrderConfig)
|
||||
MethodSecurityMetadataSourceAdvisor advisor = context.getBean(MethodSecurityMetadataSourceAdvisor)
|
||||
then:
|
||||
advisor.order == Ordered.LOWEST_PRECEDENCE
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity
|
||||
public static class DefaultOrderConfig extends BaseMethodConfig {
|
||||
}
|
||||
|
||||
def "order is defaulted to Ordered.LOWEST_PRECEDENCE when extending GlobalMethodSecurityConfiguration"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(BaseMethodConfig,DefaultOrderExtendsMethodSecurityConfig)
|
||||
MethodSecurityMetadataSourceAdvisor advisor = context.getBean(MethodSecurityMetadataSourceAdvisor)
|
||||
then:
|
||||
advisor.order == Ordered.LOWEST_PRECEDENCE
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity
|
||||
public static class DefaultOrderExtendsMethodSecurityConfig extends GlobalMethodSecurityConfiguration {
|
||||
}
|
||||
|
||||
// --- pre-post-annotations ---
|
||||
|
||||
def preAuthorize() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(PreAuthorizeConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
then:
|
||||
service.secured() == null
|
||||
service.jsr250() == null
|
||||
|
||||
when:
|
||||
service.preAuthorize()
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
@Configuration
|
||||
public static class PreAuthorizeConfig extends BaseMethodConfig {
|
||||
}
|
||||
|
||||
def "prePostEnabled extends GlobalMethodSecurityConfiguration"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(BaseMethodConfig,PreAuthorizeExtendsGMSCConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
then:
|
||||
service.secured() == null
|
||||
service.jsr250() == null
|
||||
|
||||
when:
|
||||
service.preAuthorize()
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
@Configuration
|
||||
public static class PreAuthorizeExtendsGMSCConfig extends GlobalMethodSecurityConfiguration {
|
||||
}
|
||||
|
||||
// --- proxy-target-class ---
|
||||
|
||||
def "proxying classes works"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(ProxyTargetClass)
|
||||
MethodSecurityServiceImpl service = context.getBean(MethodSecurityServiceImpl)
|
||||
then:
|
||||
noExceptionThrown()
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(proxyTargetClass = true)
|
||||
@Configuration
|
||||
public static class ProxyTargetClass extends BaseMethodConfig {
|
||||
}
|
||||
|
||||
def "proxying interfaces works"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(PreAuthorizeConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
then: "we get an instance of the interface"
|
||||
noExceptionThrown()
|
||||
when: "try to cast to the class"
|
||||
MethodSecurityServiceImpl serviceImpl = service
|
||||
then: "we get a class cast exception"
|
||||
thrown(ClassCastException)
|
||||
}
|
||||
|
||||
// --- run-as-manager-ref ---
|
||||
|
||||
def "custom RunAsManager"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomRunAsManagerConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
then:
|
||||
service.runAs().authorities.find { it.authority == "ROLE_RUN_AS_SUPER"}
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(securedEnabled = true)
|
||||
public static class CustomRunAsManagerConfig extends GlobalMethodSecurityConfiguration {
|
||||
@Override
|
||||
protected RunAsManager runAsManager() {
|
||||
RunAsManagerImpl runAsManager = new RunAsManagerImpl()
|
||||
runAsManager.setKey("some key")
|
||||
return runAsManager
|
||||
}
|
||||
}
|
||||
|
||||
// --- secured-annotation ---
|
||||
|
||||
def "secured enabled"() {
|
||||
setup:
|
||||
context = new AnnotationConfigApplicationContext(SecuredConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
when:
|
||||
service.secured()
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
and: "service with ROLE_USER allowed"
|
||||
service.securedUser() == null
|
||||
and:
|
||||
service.preAuthorize() == null
|
||||
service.jsr250() == null
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(securedEnabled = true)
|
||||
@Configuration
|
||||
public static class SecuredConfig extends BaseMethodConfig {
|
||||
}
|
||||
|
||||
// --- after-invocation-provider
|
||||
|
||||
def "custom AfterInvocationManager"() {
|
||||
setup:
|
||||
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomAfterInvocationManagerConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
when:
|
||||
service.preAuthorizePermitAll()
|
||||
then:
|
||||
AccessDeniedException e = thrown()
|
||||
e.message == "custom AfterInvocationManager"
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public static class CustomAfterInvocationManagerConfig extends GlobalMethodSecurityConfiguration {
|
||||
@Override
|
||||
protected AfterInvocationManager afterInvocationManager() {
|
||||
return new AfterInvocationManagerStub()
|
||||
}
|
||||
|
||||
public static class AfterInvocationManagerStub implements AfterInvocationManager {
|
||||
Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> attributes,
|
||||
Object returnedObject) throws AccessDeniedException {
|
||||
throw new AccessDeniedException("custom AfterInvocationManager")
|
||||
}
|
||||
|
||||
boolean supports(ConfigAttribute attribute) {
|
||||
return true
|
||||
}
|
||||
boolean supports(Class<?> clazz) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- misc ---
|
||||
|
||||
def "good error message when no Enable annotation"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(ExtendsNoEnableAnntotationConfig)
|
||||
MethodSecurityInterceptor interceptor = context.getBean(MethodSecurityInterceptor)
|
||||
interceptor.authenticationManager.authenticate(SecurityContextHolder.context.authentication)
|
||||
then:
|
||||
BeanCreationException e = thrown()
|
||||
e.message.contains(EnableGlobalMethodSecurity.class.getName() + " is required")
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class ExtendsNoEnableAnntotationConfig extends GlobalMethodSecurityConfiguration {
|
||||
@Override
|
||||
protected AuthenticationManager authenticationManager() {
|
||||
return new AuthenticationManager() {
|
||||
Authentication authenticate(Authentication authentication) {
|
||||
throw new UnsupportedOperationException()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def "import subclass of GlobalMethodSecurityConfiguration"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(ImportSubclassGMSCConfig)
|
||||
MethodSecurityService service = context.getBean(MethodSecurityService)
|
||||
then:
|
||||
service.secured() == null
|
||||
service.jsr250() == null
|
||||
|
||||
when:
|
||||
service.preAuthorize()
|
||||
then:
|
||||
thrown(AccessDeniedException)
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@Import(PreAuthorizeExtendsGMSCConfig)
|
||||
public static class ImportSubclassGMSCConfig extends BaseMethodConfig {
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class BaseMethodConfig extends BaseAuthenticationConfig {
|
||||
@Bean
|
||||
public MethodSecurityService methodSecurityService() {
|
||||
return new MethodSecurityServiceImpl()
|
||||
}
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.sec2758;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.PriorityOrdered;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.access.annotation.Jsr250MethodSecurityMetadataSource;
|
||||
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken
|
||||
import org.springframework.security.config.annotation.BaseSpringSpec
|
||||
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.config.annotation.web.configuration.sec2377.a.*
|
||||
import org.springframework.security.config.annotation.web.configuration.sec2377.b.*
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
|
||||
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext
|
||||
|
||||
public class Sec2758Tests extends BaseSpringSpec {
|
||||
|
||||
def cleanup() {
|
||||
SecurityContextHolder.clearContext()
|
||||
}
|
||||
|
||||
def "SEC-2758: Verify Passivity Restored with Advice from JIRA"() {
|
||||
setup:
|
||||
SecurityContextHolder.context.authentication = new TestingAuthenticationToken("user", "pass", "USER")
|
||||
loadConfig(SecurityConfig)
|
||||
Service service = context.getBean(Service)
|
||||
|
||||
when:
|
||||
findFilter(FilterSecurityInterceptor).doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain())
|
||||
then:
|
||||
noExceptionThrown()
|
||||
|
||||
when:
|
||||
service.doPreAuthorize()
|
||||
then:
|
||||
noExceptionThrown()
|
||||
|
||||
when:
|
||||
service.doJsr250()
|
||||
then:
|
||||
noExceptionThrown()
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled=true)
|
||||
static class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.anyRequest().hasAnyAuthority("USER");
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) {
|
||||
auth
|
||||
.inMemoryAuthentication()
|
||||
.withUser("user").password("password").authorities("USER")
|
||||
}
|
||||
|
||||
@Bean
|
||||
Service service() {
|
||||
return new ServiceImpl()
|
||||
}
|
||||
|
||||
@Bean
|
||||
static DefaultRolesPrefixPostProcessor defaultRolesPrefixPostProcessor() {
|
||||
new DefaultRolesPrefixPostProcessor()
|
||||
}
|
||||
}
|
||||
|
||||
interface Service {
|
||||
void doPreAuthorize()
|
||||
void doJsr250()
|
||||
}
|
||||
|
||||
static class ServiceImpl implements Service {
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
void doPreAuthorize() {}
|
||||
|
||||
@RolesAllowed("USER")
|
||||
void doJsr250() {}
|
||||
}
|
||||
|
||||
static class DefaultRolesPrefixPostProcessor implements BeanPostProcessor, PriorityOrdered {
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
if(bean instanceof Jsr250MethodSecurityMetadataSource) {
|
||||
((Jsr250MethodSecurityMetadataSource) bean).setDefaultRolePrefix(null);
|
||||
}
|
||||
if(bean instanceof DefaultMethodSecurityExpressionHandler) {
|
||||
((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
|
||||
}
|
||||
if(bean instanceof DefaultWebSecurityExpressionHandler) {
|
||||
((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return PriorityOrdered.HIGHEST_PRECEDENCE;
|
||||
}
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configuration
|
||||
|
||||
import org.springframework.mock.web.MockServletContext
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal
|
||||
import org.springframework.security.core.context.SecurityContext
|
||||
import org.springframework.security.core.context.SecurityContextImpl
|
||||
import org.springframework.security.core.userdetails.PasswordEncodedUser
|
||||
import org.springframework.security.core.userdetails.User
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository
|
||||
import org.springframework.test.context.web.WebAppConfiguration
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.mock.web.MockHttpServletRequest
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken
|
||||
import org.springframework.security.authentication.AuthenticationManager
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
|
||||
import org.springframework.security.config.annotation.BaseSpringSpec
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity
|
||||
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter
|
||||
import org.springframework.security.web.debug.DebugFilter
|
||||
import org.springframework.test.web.servlet.MockMvc
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
class EnableWebSecurityTests extends BaseSpringSpec {
|
||||
|
||||
def "@Bean(BeanIds.AUTHENTICATION_MANAGER) includes HttpSecurity's AuthenticationManagerBuilder"() {
|
||||
when:
|
||||
loadConfig(SecurityConfig)
|
||||
AuthenticationManager authenticationManager = context.getBean(AuthenticationManager)
|
||||
AnonymousAuthenticationToken anonymousAuthToken = findFilter(AnonymousAuthenticationFilter).createAuthentication(new MockHttpServletRequest())
|
||||
then:
|
||||
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"))
|
||||
authenticationManager.authenticate(anonymousAuthToken)
|
||||
|
||||
}
|
||||
|
||||
|
||||
@EnableWebSecurity
|
||||
static class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth
|
||||
.inMemoryAuthentication()
|
||||
.withUser(PasswordEncodedUser.user());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
public AuthenticationManager authenticationManagerBean()
|
||||
throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers("/*").hasRole("USER")
|
||||
.and()
|
||||
.formLogin();
|
||||
}
|
||||
}
|
||||
|
||||
def "@EnableWebSecurity on superclass"() {
|
||||
when:
|
||||
loadConfig(ChildSecurityConfig)
|
||||
then:
|
||||
context.getBean("springSecurityFilterChain", DebugFilter)
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class ChildSecurityConfig extends DebugSecurityConfig {
|
||||
}
|
||||
|
||||
@EnableWebSecurity(debug=true)
|
||||
static class DebugSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
}
|
||||
|
||||
def "SEC-2942: EnableWebSecurity adds AuthenticationPrincipalArgumentResolver"() {
|
||||
setup:
|
||||
def username = "test"
|
||||
context = new AnnotationConfigWebApplicationContext()
|
||||
context.servletContext = new MockServletContext()
|
||||
context.register(AuthenticationPrincipalConfig)
|
||||
context.refresh()
|
||||
SecurityContext securityContext = new SecurityContextImpl(authentication: new TestingAuthenticationToken(username, "pass", "ROLE_USER"))
|
||||
MockMvc mockMvc = MockMvcBuilders
|
||||
.webAppContextSetup(context)
|
||||
.addFilters(springSecurityFilterChain)
|
||||
.build()
|
||||
when:
|
||||
String body = mockMvc
|
||||
.perform(get("/").sessionAttr(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext))
|
||||
.andReturn().response.contentAsString
|
||||
then:
|
||||
body == username
|
||||
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@EnableWebMvc
|
||||
@Configuration
|
||||
static class AuthenticationPrincipalConfig {
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) {
|
||||
auth.inMemoryAuthentication()
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class AuthController {
|
||||
|
||||
@RequestMapping("/")
|
||||
String principal(@AuthenticationPrincipal String principal) {
|
||||
principal
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configuration;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.beans.FatalBeanException;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.security.authentication.AuthenticationManager
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
|
||||
import org.springframework.security.config.annotation.BaseSpringSpec
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
|
||||
public class Sec2515Tests extends BaseSpringSpec {
|
||||
|
||||
def "SEC-2515: Prevent StackOverflow with bean graph cycle"() {
|
||||
when:
|
||||
loadConfig(StackOverflowSecurityConfig)
|
||||
then:
|
||||
thrown(FatalBeanException)
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class StackOverflowSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManagerBean()
|
||||
throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
}
|
||||
|
||||
def "Custom Name Prevent StackOverflow with bean graph cycle"() {
|
||||
when:
|
||||
loadConfig(StackOverflowSecurityConfig)
|
||||
then:
|
||||
thrown(FatalBeanException)
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class CustomBeanNameStackOverflowSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
@Bean(name="custom")
|
||||
public AuthenticationManager authenticationManagerBean()
|
||||
throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
}
|
||||
|
||||
def "SEC-2549: Can load with child classloader"() {
|
||||
setup:
|
||||
CanLoadWithChildConfig.AM = Mock(AuthenticationManager)
|
||||
context = new AnnotationConfigApplicationContext()
|
||||
context.classLoader = new URLClassLoader(new URL[0], context.classLoader)
|
||||
context.register(CanLoadWithChildConfig)
|
||||
context.refresh()
|
||||
when:
|
||||
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"))
|
||||
then:
|
||||
noExceptionThrown()
|
||||
1 * CanLoadWithChildConfig.AM.authenticate(_) >> new TestingAuthenticationToken("user","password","ROLE_USER")
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class CanLoadWithChildConfig extends WebSecurityConfigurerAdapter {
|
||||
static AuthenticationManager AM
|
||||
@Bean
|
||||
public AuthenticationManager am() {
|
||||
AM
|
||||
}
|
||||
}
|
||||
|
||||
def "SEC-2515: @Bean still works when configure(AuthenticationManagerBuilder) used"() {
|
||||
when:
|
||||
loadConfig(SecurityConfig)
|
||||
then:
|
||||
noExceptionThrown();
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManagerBean()
|
||||
throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth)
|
||||
throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-15
@@ -15,10 +15,7 @@
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers
|
||||
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.security.core.userdetails.PasswordEncodedUser
|
||||
import org.springframework.security.web.firewall.StrictHttpFirewall
|
||||
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
@@ -47,7 +44,7 @@ class CsrfConfigurerTests extends BaseSpringSpec {
|
||||
@Unroll
|
||||
def "csrf applied by default"() {
|
||||
setup:
|
||||
loadConfig(CsrfAppliedDefaultConfig, AllowHttpMethodsFirewallConfig)
|
||||
loadConfig(CsrfAppliedDefaultConfig)
|
||||
request.method = httpMethod
|
||||
clearCsrfToken()
|
||||
when:
|
||||
@@ -69,21 +66,11 @@ class CsrfConfigurerTests extends BaseSpringSpec {
|
||||
|
||||
def "csrf default creates CsrfRequestDataValueProcessor"() {
|
||||
when:
|
||||
loadConfig(CsrfAppliedDefaultConfig, AllowHttpMethodsFirewallConfig)
|
||||
loadConfig(CsrfAppliedDefaultConfig)
|
||||
then:
|
||||
context.getBean(RequestDataValueProcessor)
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class AllowHttpMethodsFirewallConfig {
|
||||
@Bean
|
||||
StrictHttpFirewall strictHttpFirewall() {
|
||||
StrictHttpFirewall result = new StrictHttpFirewall();
|
||||
result.setAllowedHttpMethods(StrictHttpFirewall.ALLOW_ANY_HTTP_METHOD);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class CsrfAppliedDefaultConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
|
||||
+61
-170
@@ -53,33 +53,15 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
request.requestURI = "/login"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.getContentAsString() == """<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
<title>Please sign in</title>
|
||||
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
|
||||
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin" method="post" action="/login">
|
||||
<h2 class="form-signin-heading">Please sign in</h2>
|
||||
<p>
|
||||
<label for="username" class="sr-only">Username</label>
|
||||
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
|
||||
</p>
|
||||
<p>
|
||||
<label for="password" class="sr-only">Password</label>
|
||||
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
|
||||
</p>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
|
||||
</form>
|
||||
</body></html>"""
|
||||
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
|
||||
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
|
||||
<table>
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form></body></html>"""
|
||||
when: "fail to log in"
|
||||
super.setup()
|
||||
request.servletPath = "/login"
|
||||
@@ -95,33 +77,15 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
request.queryString = "error"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.getContentAsString() == """<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
<title>Please sign in</title>
|
||||
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
|
||||
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin" method="post" action="/login">
|
||||
<h2 class="form-signin-heading">Please sign in</h2>
|
||||
<div class="alert alert-danger" role="alert">Bad credentials</div> <p>
|
||||
<label for="username" class="sr-only">Username</label>
|
||||
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
|
||||
</p>
|
||||
<p>
|
||||
<label for="password" class="sr-only">Password</label>
|
||||
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
|
||||
</p>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
|
||||
</form>
|
||||
</body></html>"""
|
||||
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
|
||||
<p style='color:red;'>Your login attempt was not successful, try again.<br/><br/>Reason: Bad credentials</p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
|
||||
<table>
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form></body></html>"""
|
||||
when: "login success"
|
||||
super.setup()
|
||||
request.servletPath = "/login"
|
||||
@@ -142,33 +106,15 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
request.method = "GET"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "sent to default success page"
|
||||
response.getContentAsString() == """<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
<title>Please sign in</title>
|
||||
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
|
||||
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin" method="post" action="/login">
|
||||
<h2 class="form-signin-heading">Please sign in</h2>
|
||||
<div class="alert alert-success" role="alert">You have been signed out</div> <p>
|
||||
<label for="username" class="sr-only">Username</label>
|
||||
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
|
||||
</p>
|
||||
<p>
|
||||
<label for="password" class="sr-only">Password</label>
|
||||
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
|
||||
</p>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
|
||||
</form>
|
||||
</body></html>"""
|
||||
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
|
||||
<p style='color:green;'>You have been logged out</p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
|
||||
<table>
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form></body></html>"""
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -245,34 +191,16 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
request.requestURI = "/login"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.getContentAsString() == """<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
<title>Please sign in</title>
|
||||
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
|
||||
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin" method="post" action="/login">
|
||||
<h2 class="form-signin-heading">Please sign in</h2>
|
||||
<p>
|
||||
<label for="username" class="sr-only">Username</label>
|
||||
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
|
||||
</p>
|
||||
<p>
|
||||
<label for="password" class="sr-only">Password</label>
|
||||
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
|
||||
</p>
|
||||
<p><input type='checkbox' name='remember-me'/> Remember me on this computer.</p>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
|
||||
</form>
|
||||
</body></html>"""
|
||||
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
|
||||
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
|
||||
<table>
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td><input type='checkbox' name='remember-me'/></td><td>Remember me on this computer.</td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form></body></html>"""
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -296,29 +224,13 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
request.requestURI = "/login"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.getContentAsString() == """<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
<title>Please sign in</title>
|
||||
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
|
||||
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form name="oidf" class="form-signin" method="post" action="/login/openid">
|
||||
<h2 class="form-signin-heading">Login with OpenID Identity</h2>
|
||||
<p>
|
||||
<label for="username" class="sr-only">Identity</label>
|
||||
<input type="text" id="username" name="openid_identifier" class="form-control" placeholder="Username" required autofocus>
|
||||
</p>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
|
||||
</form>
|
||||
</body></html>"""
|
||||
response.getContentAsString() == """<html><head><title>Login Page</title></head><h3>Login with OpenID Identity</h3><form name='oidf' action='/login/openid' method='POST'>
|
||||
<table>
|
||||
<tr><td>Identity:</td><td><input type='text' size='30' name='openid_identifier'/></td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
</table>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</form></body></html>"""
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -340,44 +252,23 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
request.requestURI = "/login"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.getContentAsString() == """<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
<title>Please sign in</title>
|
||||
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
|
||||
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin" method="post" action="/login">
|
||||
<h2 class="form-signin-heading">Please sign in</h2>
|
||||
<p>
|
||||
<label for="username" class="sr-only">Username</label>
|
||||
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
|
||||
</p>
|
||||
<p>
|
||||
<label for="password" class="sr-only">Password</label>
|
||||
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
|
||||
</p>
|
||||
<p><input type='checkbox' name='remember-me'/> Remember me on this computer.</p>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
|
||||
</form>
|
||||
<form name="oidf" class="form-signin" method="post" action="/login/openid">
|
||||
<h2 class="form-signin-heading">Login with OpenID Identity</h2>
|
||||
<p>
|
||||
<label for="username" class="sr-only">Identity</label>
|
||||
<input type="text" id="username" name="openid_identifier" class="form-control" placeholder="Username" required autofocus>
|
||||
</p>
|
||||
<p><input type='checkbox' name='remember-me'/> Remember me on this computer.</p>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
|
||||
</form>
|
||||
</body></html>"""
|
||||
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
|
||||
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
|
||||
<table>
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td><input type='checkbox' name='remember-me'/></td><td>Remember me on this computer.</td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form><h3>Login with OpenID Identity</h3><form name='oidf' action='/login/openid' method='POST'>
|
||||
<table>
|
||||
<tr><td>Identity:</td><td><input type='text' size='30' name='openid_identifier'/></td></tr>
|
||||
<tr><td><input type='checkbox' name='remember-me'></td><td>Remember me on this computer.</td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
</table>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</form></body></html>"""
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ import spock.lang.Unroll
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
class FormLoginConfigurerSpec extends BaseSpringSpec {
|
||||
class FormLoginConfigurerTests extends BaseSpringSpec {
|
||||
def "Form Login"() {
|
||||
when: "load formLogin()"
|
||||
context = new AnnotationConfigApplicationContext(FormLoginConfig)
|
||||
+1
-46
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 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,6 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.config.annotation.web.configurers
|
||||
|
||||
import org.springframework.beans.factory.BeanCreationException
|
||||
@@ -21,17 +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
|
||||
|
||||
/**
|
||||
* Tests for {@link HeadersConfigurer}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @author Tim Ysewyn
|
||||
* @author Joe Grandja
|
||||
* @author Eddú Meléndez
|
||||
* @author Vedran Pavic
|
||||
*/
|
||||
class HeadersConfigurerTests extends BaseSpringSpec {
|
||||
|
||||
@@ -501,45 +497,4 @@ class HeadersConfigurerTests extends BaseSpringSpec {
|
||||
}
|
||||
}
|
||||
|
||||
def "headers.featurePolicy default header"() {
|
||||
setup:
|
||||
loadConfig(FeaturePolicyDefaultConfig)
|
||||
request.secure = true
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request, response, chain)
|
||||
then:
|
||||
responseHeaders == ['Feature-Policy': 'geolocation \'self\'']
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class FeaturePolicyDefaultConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.headers()
|
||||
.defaultsDisabled()
|
||||
.featurePolicy("geolocation 'self'");
|
||||
}
|
||||
}
|
||||
|
||||
def "headers.featurePolicy empty policyDirectives"() {
|
||||
when:
|
||||
loadConfig(FeaturePolicyInvalidConfig)
|
||||
then:
|
||||
thrown(BeanCreationException)
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
static class FeaturePolicyInvalidConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.headers()
|
||||
.defaultsDisabled()
|
||||
.featurePolicy("");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ public class NamespaceHttpFirewallTests extends BaseSpringSpec {
|
||||
MockFilterChain chain
|
||||
|
||||
def setup() {
|
||||
request = new MockHttpServletRequest("GET", "")
|
||||
request = new MockHttpServletRequest()
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
}
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ public class NamespaceHttpPortMappingsTests extends BaseSpringSpec {
|
||||
MockFilterChain chain
|
||||
|
||||
def setup() {
|
||||
request = new MockHttpServletRequest("GET", "")
|
||||
request = new MockHttpServletRequest()
|
||||
request.setMethod("GET")
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
|
||||
+1
-35
@@ -13,9 +13,7 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers
|
||||
|
||||
import sun.security.x509.X500Name
|
||||
package org.springframework.security.config.annotation.web.configurers;
|
||||
|
||||
import java.security.cert.CertificateFactory
|
||||
import java.security.cert.X509Certificate
|
||||
@@ -164,38 +162,6 @@ public class NamespaceHttpX509Tests extends BaseSpringSpec {
|
||||
}
|
||||
}
|
||||
|
||||
def "http/x509@custom-principal-extractor"() {
|
||||
setup:
|
||||
X509Certificate certificate = loadCert("rodatexampledotcom.cer")
|
||||
loadConfig(CustomPrincipalExtractorConfig)
|
||||
when:
|
||||
request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
|
||||
springSecurityFilterChain.doFilter(request, response, chain)
|
||||
then:
|
||||
response.status == 200
|
||||
authentication().name == 'rod@example.com'
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
public static class CustomPrincipalExtractorConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.
|
||||
inMemoryAuthentication()
|
||||
.withUser("rod@example.com").password("password").roles("USER","ADMIN");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.anyRequest().hasRole("USER")
|
||||
.and()
|
||||
.x509()
|
||||
.x509PrincipalExtractor{ (it.subjectDN as X500Name).commonName }
|
||||
}
|
||||
}
|
||||
|
||||
def "http/x509@user-service-ref"() {
|
||||
setup:
|
||||
X509Certificate certificate = loadCert("rodatexampledotcom.cer")
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user