diff --git a/.github/actions/algolia-config.json b/.github/actions/algolia-config.json new file mode 100644 index 00000000000..09d30d486ea --- /dev/null +++ b/.github/actions/algolia-config.json @@ -0,0 +1,20 @@ +{ + "index_name": "security-docs", + "start_urls": [ + "https://docs.spring.io/spring-security/reference/" + ], + "selectors": { + "lvl0": { + "selector": "//nav[@class='crumbs']//li[@class='crumb'][last()-1]", + "type": "xpath", + "global": true, + "default_value": "Home" + }, + "lvl1": ".doc h1", + "lvl2": ".doc h2", + "lvl3": ".doc h3", + "lvl4": ".doc h4", + "text": ".doc p, .doc td.content, .doc th.tableblock" + } +} + diff --git a/.github/actions/algolia-deploy.sh b/.github/actions/algolia-deploy.sh new file mode 100755 index 00000000000..994dfee9ac9 --- /dev/null +++ b/.github/actions/algolia-deploy.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +HOST="$1" +HOST_PATH="$2" +SSH_PRIVATE_KEY="$3" +SSH_KNOWN_HOST="$4" + + +if [ "$#" -ne 4 ]; then + echo -e "not enough arguments USAGE:\n\n$0 \$HOST \$HOST_PATH \$SSH_PRIVATE_KEY \$SSH_KNOWN_HOSTS \n\n" >&2 + exit 1 +fi + +# Use a non-default path to avoid overriding when testing locally +SSH_PRIVATE_KEY_PATH=~/.ssh/github-actions-docs +install -m 600 -D /dev/null "$SSH_PRIVATE_KEY_PATH" +echo "$SSH_PRIVATE_KEY" > "$SSH_PRIVATE_KEY_PATH" +echo "$SSH_KNOWN_HOST" > ~/.ssh/known_hosts +rsync --delete -avze "ssh -i $SSH_PRIVATE_KEY_PATH" docs/build/site/ "$HOST:$HOST_PATH" +rm -f "$SSH_PRIVATE_KEY_PATH" diff --git a/.github/actions/algolia-docsearch-scraper.sh b/.github/actions/algolia-docsearch-scraper.sh new file mode 100755 index 00000000000..2bb9ce178ac --- /dev/null +++ b/.github/actions/algolia-docsearch-scraper.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +### +# Docs +# config.json https://docsearch.algolia.com/docs/config-file +# Run the crawler https://docsearch.algolia.com/docs/run-your-own/#run-the-crawl-from-the-docker-image + +### USAGE +if [ "$#" -ne 3 ]; then + echo -e "not enough arguments USAGE:\n\n$0 \$ALGOLIA_APPLICATION_ID \$ALGOLIA_API_KEY \$CONFIG_FILE\n\n" >&2 + exit 1 +fi + +# Script Parameters +APPLICATION_ID=$1 +API_KEY=$2 +CONFIG_FILE=$3 + +#### Script +script_dir=$(dirname $0) +docker run -e "APPLICATION_ID=$APPLICATION_ID" -e "API_KEY=$API_KEY" -e "CONFIG=$(cat $CONFIG_FILE | jq -r tostring)" algolia/docsearch-scraper diff --git a/.github/actions/dispatch.sh b/.github/actions/dispatch.sh index d6c2a37794e..955e9cbbeef 100755 --- a/.github/actions/dispatch.sh +++ b/.github/actions/dispatch.sh @@ -1,5 +1,5 @@ REPOSITORY_REF="$1" TOKEN="$2" -curl -H "Accept: application/vnd.github.everest-preview+json" -H "Authorization: token ${TOKEN}" --request POST --data '{"event_type": "request-build"}' https://api.github.com/repos/${REPOSITORY_REF}/dispatches -echo "Requested Build for $REPOSITORY_REF" \ No newline at end of file +curl -H "Accept: application/vnd.github.everest-preview+json" -H "Authorization: token ${TOKEN}" --request POST --data '{"event_type": "request-build-reference"}' https://api.github.com/repos/${REPOSITORY_REF}/dispatches +echo "Requested Build for $REPOSITORY_REF" diff --git a/.github/workflows/algolia-index.yml b/.github/workflows/algolia-index.yml new file mode 100644 index 00000000000..dfc2295af33 --- /dev/null +++ b/.github/workflows/algolia-index.yml @@ -0,0 +1,16 @@ +name: Update Algolia Index + +on: + schedule: + - cron: '0 10 * * *' # Once per day at 10am UTC + workflow_dispatch: # Manual trigger + +jobs: + update: + name: Update Algolia Index + runs-on: ubuntu-latest + steps: + - name: Checkout Source + uses: actions/checkout@v2 + - name: Update Index + run: ${GITHUB_WORKSPACE}/.github/actions/algolia-docsearch-scraper.sh "${{ secrets.ALGOLIA_APPLICATION_ID }}" "${{ secrets.ALGOLIA_WRITE_API_KEY }}" "${GITHUB_WORKSPACE}/.github/actions/algolia-config.json" diff --git a/.github/workflows/build-reference.yml b/.github/workflows/antora-generate.yml similarity index 91% rename from .github/workflows/build-reference.yml rename to .github/workflows/antora-generate.yml index 7387f4a0407..f5cd25cfbf9 100644 --- a/.github/workflows/build-reference.yml +++ b/.github/workflows/antora-generate.yml @@ -1,4 +1,4 @@ -name: reference +name: Generate Antora Files and Request Build on: push: @@ -27,4 +27,4 @@ jobs: repository-name: "spring-io/spring-generated-docs" token: ${{ secrets.GH_ACTIONS_REPO_TOKEN }} - name: Dispatch Build Request - run: ${GITHUB_WORKSPACE}/.github/actions/dispatch.sh 'spring-io/spring-reference' "$GH_ACTIONS_REPO_TOKEN" + run: ${GITHUB_WORKSPACE}/.github/actions/dispatch.sh 'spring-projects/spring-security' "$GH_ACTIONS_REPO_TOKEN" diff --git a/.github/workflows/continuous-integration-workflow.yml b/.github/workflows/continuous-integration-workflow.yml index d3679cc30fa..f9868aab190 100644 --- a/.github/workflows/continuous-integration-workflow.yml +++ b/.github/workflows/continuous-integration-workflow.yml @@ -29,8 +29,8 @@ jobs: name: Determine if should continue if: env.RUN_JOBS == 'true' run: echo "::set-output name=runjobs::true" - build_jdk_11: - name: Build JDK 11 + build_jdk_17: + name: Build JDK 17 needs: [prerequisites] strategy: matrix: @@ -39,10 +39,10 @@ jobs: if: needs.prerequisites.outputs.runjobs steps: - uses: actions/checkout@v2 - - name: Set up JDK 11 + - name: Set up JDK 17 uses: actions/setup-java@v1 with: - java-version: '11' + java-version: '17' - name: Setup gradle user name run: | mkdir -p ~/.gradle @@ -68,7 +68,7 @@ jobs: - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: '11' + java-version: '17' - name: Setup gradle user name run: | mkdir -p ~/.gradle @@ -89,7 +89,7 @@ jobs: - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: '11' + java-version: '17' - name: Setup gradle user name run: | mkdir -p ~/.gradle @@ -110,7 +110,7 @@ jobs: - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: '11' + java-version: '17' - name: Setup gradle user name run: | mkdir -p ~/.gradle @@ -123,14 +123,14 @@ jobs: ./gradlew check s101 -Ps101.licenseId="$STRUCTURE101_LICENSEID" --stacktrace deploy_artifacts: name: Deploy Artifacts - needs: [build_jdk_11, snapshot_tests, check_samples, check_tangles] + needs: [build_jdk_17, snapshot_tests, check_samples, check_tangles] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: '11' + java-version: '17' - name: Setup gradle user name run: | mkdir -p ~/.gradle @@ -150,14 +150,14 @@ jobs: ARTIFACTORY_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} deploy_docs: name: Deploy Docs - needs: [build_jdk_11, snapshot_tests, check_samples, check_tangles] + needs: [build_jdk_17, snapshot_tests, check_samples, check_tangles] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: '11' + java-version: '17' - name: Setup gradle user name run: | mkdir -p ~/.gradle @@ -174,14 +174,14 @@ jobs: DOCS_HOST: ${{ secrets.DOCS_HOST }} deploy_schema: name: Deploy Schema - needs: [build_jdk_11, snapshot_tests, check_samples, check_tangles] + needs: [build_jdk_17, snapshot_tests, check_samples, check_tangles] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: '11' + java-version: '17' - name: Setup gradle user name run: | mkdir -p ~/.gradle @@ -198,7 +198,7 @@ jobs: DOCS_HOST: ${{ secrets.DOCS_HOST }} notify_result: name: Check for failures - needs: [build_jdk_11, snapshot_tests, check_samples, check_tangles, deploy_artifacts, deploy_docs, deploy_schema] + needs: [build_jdk_17, snapshot_tests, check_samples, check_tangles, deploy_artifacts, deploy_docs, deploy_schema] if: failure() runs-on: ubuntu-latest steps: diff --git a/.github/workflows/deploy-reference.yml b/.github/workflows/deploy-reference.yml new file mode 100644 index 00000000000..a0033b926b0 --- /dev/null +++ b/.github/workflows/deploy-reference.yml @@ -0,0 +1,33 @@ +name: Build & Deploy Reference + +on: + repository_dispatch: + types: request-build-reference + schedule: + - cron: '0 10 * * *' # Once per day at 10am UTC + workflow_dispatch: # Manual trigger + +jobs: + deploy: + name: deploy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + java-version: '11' + distribution: 'adopt' + cache: gradle + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b + - name: Build with Gradle + run: ./gradlew :spring-security-docs:antora --stacktrace + - name: Cleanup Gradle Cache + # Remove some files from the Gradle cache, so they aren't cached by GitHub Actions. + # Restoring these files from a GitHub Actions cache might cause problems for future builds. + run: | + rm -f ~/.gradle/caches/modules-2/modules-2.lock + rm -f ~/.gradle/caches/modules-2/gc.properties + - name: Deploy + run: ${GITHUB_WORKSPACE}/.github/actions/algolia-deploy.sh "${{ secrets.DOCS_USERNAME }}@${{ secrets.DOCS_HOST }}" "/opt/www/domains/spring.io/docs/htdocs/spring-security/reference/" "${{ secrets.DOCS_SSH_KEY }}" "${{ secrets.DOCS_SSH_HOST_KEY }}" diff --git a/.github/workflows/pr-build-workflow.yml b/.github/workflows/pr-build-workflow.yml index 0e7d5e7fdf0..d9a5c571343 100644 --- a/.github/workflows/pr-build-workflow.yml +++ b/.github/workflows/pr-build-workflow.yml @@ -16,7 +16,7 @@ jobs: if: env.RUN_JOBS == 'true' uses: actions/setup-java@v1 with: - java-version: '11' + java-version: '17' - name: Cache Gradle packages if: env.RUN_JOBS == 'true' uses: actions/cache@v2 diff --git a/README.adoc b/README.adoc index 80d2f102e55..272b99ff6d0 100644 --- a/README.adoc +++ b/README.adoc @@ -6,8 +6,8 @@ image:https://img.shields.io/badge/Revved%20up%20by-Gradle%20Enterprise-06A0CE?l = Spring Security -Spring Security provides security services for the https://docs.spring.io[Spring IO Platform]. Spring Security 5.0 requires Spring 5.0 as -a minimum and also requires Java 8. +Spring Security provides security services for the https://docs.spring.io[Spring IO Platform]. Spring Security 6.0 requires Spring 6.0 as +a minimum and also requires Java 17. For a detailed list of features and access to the latest release, please visit https://spring.io/projects[Spring projects]. @@ -30,9 +30,9 @@ In the instructions below, https://vimeo.com/34436402[`./gradlew`] is invoked fr a cross-platform, self-contained bootstrap mechanism for the build. === Prerequisites -https://help.github.com/set-up-git-redirect[Git] and the https://www.oracle.com/technetwork/java/javase/downloads[JDK11 build]. +https://help.github.com/set-up-git-redirect[Git] and the https://www.oracle.com/technetwork/java/javase/downloads[JDK17 build]. -Be sure that your `JAVA_HOME` environment variable points to the `jdk-11` folder extracted from the JDK download. +Be sure that your `JAVA_HOME` environment variable points to the `jdk-17` folder extracted from the JDK download. === Check out sources [indent=0] diff --git a/acl/spring-security-acl.gradle b/acl/spring-security-acl.gradle index 8de65558b88..976d8d42dbc 100644 --- a/acl/spring-security-acl.gradle +++ b/acl/spring-security-acl.gradle @@ -9,8 +9,6 @@ dependencies { api 'org.springframework:spring-jdbc' api 'org.springframework:spring-tx' - optional 'net.sf.ehcache:ehcache' - testImplementation "org.assertj:assertj-core" testImplementation "org.junit.jupiter:junit-jupiter-api" testImplementation "org.junit.jupiter:junit-jupiter-params" diff --git a/acl/src/main/java/org/springframework/security/acls/domain/EhCacheBasedAclCache.java b/acl/src/main/java/org/springframework/security/acls/domain/EhCacheBasedAclCache.java deleted file mode 100644 index 9ad106d7afe..00000000000 --- a/acl/src/main/java/org/springframework/security/acls/domain/EhCacheBasedAclCache.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.acls.domain; - -import java.io.Serializable; - -import net.sf.ehcache.CacheException; -import net.sf.ehcache.Ehcache; -import net.sf.ehcache.Element; - -import org.springframework.security.acls.model.AclCache; -import org.springframework.security.acls.model.MutableAcl; -import org.springframework.security.acls.model.ObjectIdentity; -import org.springframework.security.acls.model.PermissionGrantingStrategy; -import org.springframework.security.util.FieldUtils; -import org.springframework.util.Assert; - -/** - * Simple implementation of {@link AclCache} that delegates to EH-CACHE. - *

- * Designed to handle the transient fields in {@link AclImpl}. Note that this - * implementation assumes all {@link AclImpl} instances share the same - * {@link PermissionGrantingStrategy} and {@link AclAuthorizationStrategy} instances. - * - * @author Ben Alex - * @deprecated since 5.6. In favor of JCache based implementations - */ -@Deprecated -public class EhCacheBasedAclCache implements AclCache { - - private final Ehcache cache; - - private PermissionGrantingStrategy permissionGrantingStrategy; - - private AclAuthorizationStrategy aclAuthorizationStrategy; - - public EhCacheBasedAclCache(Ehcache cache, PermissionGrantingStrategy permissionGrantingStrategy, - AclAuthorizationStrategy aclAuthorizationStrategy) { - Assert.notNull(cache, "Cache required"); - Assert.notNull(permissionGrantingStrategy, "PermissionGrantingStrategy required"); - Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required"); - this.cache = cache; - this.permissionGrantingStrategy = permissionGrantingStrategy; - this.aclAuthorizationStrategy = aclAuthorizationStrategy; - } - - @Override - public void evictFromCache(Serializable pk) { - Assert.notNull(pk, "Primary key (identifier) required"); - MutableAcl acl = getFromCache(pk); - if (acl != null) { - this.cache.remove(acl.getId()); - this.cache.remove(acl.getObjectIdentity()); - } - } - - @Override - public void evictFromCache(ObjectIdentity objectIdentity) { - Assert.notNull(objectIdentity, "ObjectIdentity required"); - MutableAcl acl = getFromCache(objectIdentity); - if (acl != null) { - this.cache.remove(acl.getId()); - this.cache.remove(acl.getObjectIdentity()); - } - } - - @Override - public MutableAcl getFromCache(ObjectIdentity objectIdentity) { - Assert.notNull(objectIdentity, "ObjectIdentity required"); - try { - Element element = this.cache.get(objectIdentity); - return (element != null) ? initializeTransientFields((MutableAcl) element.getValue()) : null; - } - catch (CacheException ex) { - return null; - } - } - - @Override - public MutableAcl getFromCache(Serializable pk) { - Assert.notNull(pk, "Primary key (identifier) required"); - try { - Element element = this.cache.get(pk); - return (element != null) ? initializeTransientFields((MutableAcl) element.getValue()) : null; - } - catch (CacheException ex) { - return null; - } - } - - @Override - public void putInCache(MutableAcl acl) { - Assert.notNull(acl, "Acl required"); - Assert.notNull(acl.getObjectIdentity(), "ObjectIdentity required"); - Assert.notNull(acl.getId(), "ID required"); - if (this.aclAuthorizationStrategy == null) { - if (acl instanceof AclImpl) { - this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils - .getProtectedFieldValue("aclAuthorizationStrategy", acl); - this.permissionGrantingStrategy = (PermissionGrantingStrategy) FieldUtils - .getProtectedFieldValue("permissionGrantingStrategy", acl); - } - } - if ((acl.getParentAcl() != null) && (acl.getParentAcl() instanceof MutableAcl)) { - putInCache((MutableAcl) acl.getParentAcl()); - } - this.cache.put(new Element(acl.getObjectIdentity(), acl)); - this.cache.put(new Element(acl.getId(), acl)); - } - - private MutableAcl initializeTransientFields(MutableAcl value) { - if (value instanceof AclImpl) { - FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy); - FieldUtils.setProtectedFieldValue("permissionGrantingStrategy", value, this.permissionGrantingStrategy); - } - if (value.getParentAcl() != null) { - initializeTransientFields((MutableAcl) value.getParentAcl()); - } - return value; - } - - @Override - public void clearCache() { - this.cache.removeAll(); - } - -} diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java index 9d4d099b257..5f8db850e52 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java @@ -42,7 +42,7 @@ import org.springframework.security.acls.domain.DefaultPermissionFactory; import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; import org.springframework.security.acls.domain.GrantedAuthoritySid; -import org.springframework.security.acls.domain.ObjectIdentityImpl; +import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.domain.PermissionFactory; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.AccessControlEntry; @@ -51,6 +51,7 @@ import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; +import org.springframework.security.acls.model.ObjectIdentityGenerator; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.PermissionGrantingStrategy; import org.springframework.security.acls.model.Sid; @@ -109,6 +110,8 @@ public class BasicLookupStrategy implements LookupStrategy { private final AclAuthorizationStrategy aclAuthorizationStrategy; + private ObjectIdentityGenerator objectIdentityGenerator; + private PermissionFactory permissionFactory = new DefaultPermissionFactory(); private final AclCache aclCache; @@ -162,6 +165,7 @@ public BasicLookupStrategy(DataSource dataSource, AclCache aclCache, this.aclCache = aclCache; this.aclAuthorizationStrategy = aclAuthorizationStrategy; this.grantingStrategy = grantingStrategy; + this.objectIdentityGenerator = new ObjectIdentityRetrievalStrategyImpl(); this.aclClassIdUtils = new AclClassIdUtils(); this.fieldAces.setAccessible(true); this.fieldAcl.setAccessible(true); @@ -488,6 +492,11 @@ public final void setAclClassIdSupported(boolean aclClassIdSupported) { } } + public final void setObjectIdentityGenerator(ObjectIdentityGenerator objectIdentityGenerator) { + Assert.notNull(objectIdentityGenerator, "objectIdentityGenerator cannot be null"); + this.objectIdentityGenerator = objectIdentityGenerator; + } + public final void setConversionService(ConversionService conversionService) { this.aclClassIdUtils = new AclClassIdUtils(conversionService); } @@ -569,7 +578,8 @@ private void convertCurrentResultIntoObject(Map acls, ResultS // target id type, e.g. UUID. Serializable identifier = (Serializable) rs.getObject("object_id_identity"); identifier = BasicLookupStrategy.this.aclClassIdUtils.identifierFrom(identifier, rs); - ObjectIdentity objectIdentity = new ObjectIdentityImpl(rs.getString("class"), identifier); + ObjectIdentity objectIdentity = BasicLookupStrategy.this.objectIdentityGenerator + .createObjectIdentity(identifier, rs.getString("class")); Acl parentAcl = null; long parentAclId = rs.getLong("parent_object"); diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java b/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java index 935466f5d1d..e499577388c 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java @@ -31,11 +31,12 @@ import org.springframework.core.convert.ConversionService; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.security.acls.domain.ObjectIdentityImpl; +import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; +import org.springframework.security.acls.model.ObjectIdentityGenerator; import org.springframework.security.acls.model.Sid; import org.springframework.util.Assert; @@ -81,6 +82,8 @@ public class JdbcAclService implements AclService { private AclClassIdUtils aclClassIdUtils; + private ObjectIdentityGenerator objectIdentityGenerator; + public JdbcAclService(DataSource dataSource, LookupStrategy lookupStrategy) { this(new JdbcTemplate(dataSource), lookupStrategy); } @@ -91,6 +94,7 @@ public JdbcAclService(JdbcOperations jdbcOperations, LookupStrategy lookupStrate this.jdbcOperations = jdbcOperations; this.lookupStrategy = lookupStrategy; this.aclClassIdUtils = new AclClassIdUtils(); + this.objectIdentityGenerator = new ObjectIdentityRetrievalStrategyImpl(); } @Override @@ -105,7 +109,7 @@ private ObjectIdentity mapObjectIdentityRow(ResultSet rs) throws SQLException { String javaType = rs.getString("class"); Serializable identifier = (Serializable) rs.getObject("obj_id"); identifier = this.aclClassIdUtils.identifierFrom(identifier, rs); - return new ObjectIdentityImpl(javaType, identifier); + return this.objectIdentityGenerator.createObjectIdentity(identifier, javaType); } @Override @@ -165,6 +169,11 @@ public void setConversionService(ConversionService conversionService) { this.aclClassIdUtils = new AclClassIdUtils(conversionService); } + public void setObjectIdentityGenerator(ObjectIdentityGenerator objectIdentityGenerator) { + Assert.notNull(objectIdentityGenerator, "objectIdentityGenerator cannot be null"); + this.objectIdentityGenerator = objectIdentityGenerator; + } + protected boolean isAclClassIdSupported() { return this.aclClassIdSupported; } diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java index 4a6b1d695f6..4ad369dc4be 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java @@ -16,6 +16,7 @@ package org.springframework.security.acls.jdbc; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -23,15 +24,15 @@ import javax.sql.DataSource; -import net.sf.ehcache.Cache; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Ehcache; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.acls.TargetObject; import org.springframework.security.acls.TargetObjectWithUUID; @@ -41,10 +42,10 @@ import org.springframework.security.acls.domain.ConsoleAuditLogger; import org.springframework.security.acls.domain.DefaultPermissionFactory; import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; -import org.springframework.security.acls.domain.EhCacheBasedAclCache; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.PrincipalSid; +import org.springframework.security.acls.domain.SpringCacheBasedAclCache; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AuditableAccessControlEntry; import org.springframework.security.acls.model.MutableAcl; @@ -55,6 +56,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; /** * Tests {@link BasicLookupStrategy} @@ -75,7 +78,7 @@ public abstract class AbstractBasicLookupStrategyTests { private BasicLookupStrategy strategy; - private static CacheManager cacheManager; + private static CacheManagerMock cacheManager; public abstract JdbcTemplate getJdbcTemplate(); @@ -83,14 +86,13 @@ public abstract class AbstractBasicLookupStrategyTests { @BeforeAll public static void initCacheManaer() { - cacheManager = CacheManager.create(); - cacheManager.addCache(new Cache("basiclookuptestcache", 500, false, false, 30, 30)); + cacheManager = new CacheManagerMock(); + cacheManager.addCache("basiclookuptestcache"); } @AfterAll public static void shutdownCacheManager() { - cacheManager.removalAll(); - cacheManager.shutdown(); + cacheManager.clear(); } @BeforeEach @@ -118,11 +120,17 @@ protected AclAuthorizationStrategy aclAuthStrategy() { return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMINISTRATOR")); } - protected EhCacheBasedAclCache aclCache() { - return new EhCacheBasedAclCache(getCache(), new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), + protected SpringCacheBasedAclCache aclCache() { + return new SpringCacheBasedAclCache(getCache(), new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))); } + protected Cache getCache() { + Cache cache = cacheManager.getCacheManager().getCache("basiclookuptestcache"); + cache.clear(); + return cache; + } + @AfterEach public void emptyDatabase() { String query = "DELETE FROM acl_entry;" + "DELETE FROM acl_object_identity WHERE ID = 9;" @@ -134,12 +142,6 @@ public void emptyDatabase() { getJdbcTemplate().execute(query); } - protected Ehcache getCache() { - Ehcache cache = cacheManager.getCache("basiclookuptestcache"); - cache.removeAll(); - return cache; - } - @Test public void testAclsRetrievalWithDefaultBatchSize() throws Exception { ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100L); @@ -318,4 +320,41 @@ public void testCreateGrantedAuthority() { assertThat(((GrantedAuthoritySid) result).getGrantedAuthority()).isEqualTo("sid"); } + @Test + public void setObjectIdentityGeneratorWhenNullThenThrowsIllegalArgumentException() { + // @formatter:off + assertThatIllegalArgumentException() + .isThrownBy(() -> this.strategy.setObjectIdentityGenerator(null)) + .withMessage("objectIdentityGenerator cannot be null"); + // @formatter:on + } + + private static final class CacheManagerMock { + + private final List cacheNames; + + private final CacheManager cacheManager; + + private CacheManagerMock() { + this.cacheNames = new ArrayList<>(); + this.cacheManager = mock(CacheManager.class); + given(this.cacheManager.getCacheNames()).willReturn(this.cacheNames); + } + + private CacheManager getCacheManager() { + return this.cacheManager; + } + + private void addCache(String name) { + this.cacheNames.add(name); + Cache cache = new ConcurrentMapCache(name); + given(this.cacheManager.getCache(name)).willReturn(cache); + } + + private void clear() { + this.cacheNames.clear(); + } + + } + } diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java deleted file mode 100644 index 35545abae26..00000000000 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.acls.jdbc; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.List; - -import net.sf.ehcache.Ehcache; -import net.sf.ehcache.Element; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import org.springframework.security.acls.domain.AclAuthorizationStrategy; -import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl; -import org.springframework.security.acls.domain.AclImpl; -import org.springframework.security.acls.domain.ConsoleAuditLogger; -import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; -import org.springframework.security.acls.domain.EhCacheBasedAclCache; -import org.springframework.security.acls.domain.ObjectIdentityImpl; -import org.springframework.security.acls.model.MutableAcl; -import org.springframework.security.acls.model.ObjectIdentity; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.util.FieldUtils; -import org.springframework.test.util.ReflectionTestUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * Tests {@link EhCacheBasedAclCache} - * - * @author Andrei Stefan - */ -@ExtendWith(MockitoExtension.class) -public class EhCacheBasedAclCacheTests { - - private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject"; - - @Mock - private Ehcache cache; - - @Captor - private ArgumentCaptor element; - - private EhCacheBasedAclCache myCache; - - private MutableAcl acl; - - @BeforeEach - public void setup() { - this.myCache = new EhCacheBasedAclCache(this.cache, - new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), - new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))); - ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L); - AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( - new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), - new SimpleGrantedAuthority("ROLE_GENERAL")); - this.acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); - } - - @AfterEach - public void cleanup() { - SecurityContextHolder.clearContext(); - } - - @Test - public void constructorRejectsNullParameters() { - assertThatIllegalArgumentException().isThrownBy( - () -> new EhCacheBasedAclCache(null, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), - new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER")))); - } - - @Test - public void methodsRejectNullParameters() { - assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.evictFromCache((Serializable) null)); - assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.evictFromCache((ObjectIdentity) null)); - assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.getFromCache((Serializable) null)); - assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.getFromCache((ObjectIdentity) null)); - assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.putInCache(null)); - } - - // SEC-527 - @Test - public void testDiskSerializationOfMutableAclObjectInstance() throws Exception { - // Serialization test - File file = File.createTempFile("SEC_TEST", ".object"); - FileOutputStream fos = new FileOutputStream(file); - ObjectOutputStream oos = new ObjectOutputStream(fos); - oos.writeObject(this.acl); - oos.close(); - FileInputStream fis = new FileInputStream(file); - ObjectInputStream ois = new ObjectInputStream(fis); - MutableAcl retrieved = (MutableAcl) ois.readObject(); - ois.close(); - assertThat(retrieved).isEqualTo(this.acl); - Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", retrieved); - assertThat(retrieved1).isNull(); - Object retrieved2 = FieldUtils.getProtectedFieldValue("permissionGrantingStrategy", retrieved); - assertThat(retrieved2).isNull(); - } - - @Test - public void clearCache() { - this.myCache.clearCache(); - verify(this.cache).removeAll(); - } - - @Test - public void putInCache() { - this.myCache.putInCache(this.acl); - verify(this.cache, times(2)).put(this.element.capture()); - assertThat(this.element.getValue().getKey()).isEqualTo(this.acl.getId()); - assertThat(this.element.getValue().getObjectValue()).isEqualTo(this.acl); - assertThat(this.element.getAllValues().get(0).getKey()).isEqualTo(this.acl.getObjectIdentity()); - assertThat(this.element.getAllValues().get(0).getObjectValue()).isEqualTo(this.acl); - } - - @Test - public void putInCacheAclWithParent() { - Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL"); - auth.setAuthenticated(true); - SecurityContextHolder.getContext().setAuthentication(auth); - ObjectIdentity identityParent = new ObjectIdentityImpl(TARGET_CLASS, 2L); - AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( - new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), - new SimpleGrantedAuthority("ROLE_GENERAL")); - MutableAcl parentAcl = new AclImpl(identityParent, 2L, aclAuthorizationStrategy, new ConsoleAuditLogger()); - this.acl.setParent(parentAcl); - this.myCache.putInCache(this.acl); - verify(this.cache, times(4)).put(this.element.capture()); - List allValues = this.element.getAllValues(); - assertThat(allValues.get(0).getKey()).isEqualTo(parentAcl.getObjectIdentity()); - assertThat(allValues.get(0).getObjectValue()).isEqualTo(parentAcl); - assertThat(allValues.get(1).getKey()).isEqualTo(parentAcl.getId()); - assertThat(allValues.get(1).getObjectValue()).isEqualTo(parentAcl); - assertThat(allValues.get(2).getKey()).isEqualTo(this.acl.getObjectIdentity()); - assertThat(allValues.get(2).getObjectValue()).isEqualTo(this.acl); - assertThat(allValues.get(3).getKey()).isEqualTo(this.acl.getId()); - assertThat(allValues.get(3).getObjectValue()).isEqualTo(this.acl); - } - - @Test - public void getFromCacheSerializable() { - given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl)); - assertThat(this.myCache.getFromCache(this.acl.getId())).isEqualTo(this.acl); - } - - @Test - public void getFromCacheSerializablePopulatesTransient() { - given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl)); - this.myCache.putInCache(this.acl); - ReflectionTestUtils.setField(this.acl, "permissionGrantingStrategy", null); - ReflectionTestUtils.setField(this.acl, "aclAuthorizationStrategy", null); - MutableAcl fromCache = this.myCache.getFromCache(this.acl.getId()); - assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull(); - assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull(); - } - - @Test - public void getFromCacheObjectIdentity() { - given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl)); - assertThat(this.myCache.getFromCache(this.acl.getId())).isEqualTo(this.acl); - } - - @Test - public void getFromCacheObjectIdentityPopulatesTransient() { - given(this.cache.get(this.acl.getObjectIdentity())).willReturn(new Element(this.acl.getId(), this.acl)); - this.myCache.putInCache(this.acl); - ReflectionTestUtils.setField(this.acl, "permissionGrantingStrategy", null); - ReflectionTestUtils.setField(this.acl, "aclAuthorizationStrategy", null); - MutableAcl fromCache = this.myCache.getFromCache(this.acl.getObjectIdentity()); - assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull(); - assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull(); - } - - @Test - public void evictCacheSerializable() { - given(this.cache.get(this.acl.getObjectIdentity())).willReturn(new Element(this.acl.getId(), this.acl)); - this.myCache.evictFromCache(this.acl.getObjectIdentity()); - verify(this.cache).remove(this.acl.getId()); - verify(this.cache).remove(this.acl.getObjectIdentity()); - } - - @Test - public void evictCacheObjectIdentity() { - given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl)); - this.myCache.evictFromCache(this.acl.getId()); - verify(this.cache).remove(this.acl.getId()); - verify(this.cache).remove(this.acl.getObjectIdentity()); - } - -} diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java index 903fd3264ce..cd91ae17453 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java @@ -45,6 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; @@ -170,6 +171,26 @@ public void findChildrenOfIdTypeUUID() { .isEqualTo(UUID.fromString("25d93b3f-c3aa-4814-9d5e-c7c96ced7762")); } + @Test + public void setObjectIdentityGeneratorWhenNullThenThrowsIllegalArgumentException() { + assertThatIllegalArgumentException() + .isThrownBy(() -> this.aclServiceIntegration.setObjectIdentityGenerator(null)) + .withMessage("objectIdentityGenerator cannot be null"); + } + + @Test + public void findChildrenWhenObjectIdentityGeneratorSetThenUsed() { + this.aclServiceIntegration + .setObjectIdentityGenerator((id, type) -> new ObjectIdentityImpl(type, "prefix:" + id)); + + ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US"); + this.aclServiceIntegration.setAclClassIdSupported(true); + List objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); + assertThat(objectIdentities.size()).isEqualTo(1); + assertThat(objectIdentities.get(0).getType()).isEqualTo("location"); + assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("prefix:US-PAL"); + } + class MockLongIdDomainObject { private Object id; diff --git a/acl/src/test/resources/jdbcMutableAclServiceTests-context.xml b/acl/src/test/resources/jdbcMutableAclServiceTests-context.xml index 457c183d569..d23a727141c 100644 --- a/acl/src/test/resources/jdbcMutableAclServiceTests-context.xml +++ b/acl/src/test/resources/jdbcMutableAclServiceTests-context.xml @@ -13,16 +13,10 @@ - + - - - - - - - - + + diff --git a/aspects/spring-security-aspects.gradle b/aspects/spring-security-aspects.gradle index 3a58595619f..eb43bb87576 100644 --- a/aspects/spring-security-aspects.gradle +++ b/aspects/spring-security-aspects.gradle @@ -1,6 +1,15 @@ apply plugin: 'io.spring.convention.spring-module' apply plugin: 'io.freefair.aspectj' +compileAspectj { + sourceCompatibility "17" + targetCompatibility "17" +} +compileTestAspectj { + sourceCompatibility "17" + targetCompatibility "17" +} + dependencies { management platform(project(":spring-security-dependencies")) api "org.aspectj:aspectjrt" @@ -27,7 +36,3 @@ sourceSets.test.aspectj.srcDir "src/test/java" sourceSets.test.java.srcDirs = files() compileAspectj.ajcOptions.outxmlfile = "META-INF/aop.xml" - -aspectj { - version = aspectjVersion -} diff --git a/build.gradle b/build.gradle index 20f17eab4f7..17d42b1b817 100644 --- a/build.gradle +++ b/build.gradle @@ -2,7 +2,7 @@ buildscript { dependencies { classpath "io.spring.javaformat:spring-javaformat-gradle-plugin:$springJavaformatVersion" classpath 'io.spring.nohttp:nohttp-gradle:0.0.10' - classpath "io.freefair.gradle:aspectj-plugin:6.2.0" + classpath "io.freefair.gradle:aspectj-plugin:6.3.0" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" classpath "com.netflix.nebula:nebula-project-plugin:8.2.0" } @@ -22,6 +22,7 @@ apply plugin: 'org.springframework.security.update-dependencies' apply plugin: 'org.springframework.security.sagan' apply plugin: 'org.springframework.github.milestone' apply plugin: 'org.springframework.github.changelog' +apply plugin: 'org.springframework.github.release' group = 'org.springframework.security' description = 'Spring Security' @@ -46,6 +47,13 @@ tasks.named("gitHubCheckMilestoneHasNoOpenIssues") { } } +tasks.named("createGitHubRelease") { + repository { + owner = "spring-projects" + name = "spring-security" + } +} + tasks.named("updateDependencies") { // we aren't Gradle 7 compatible yet checkForGradleUpdate = false @@ -100,7 +108,7 @@ updateDependenciesSettings { subprojects { plugins.withType(JavaPlugin) { - project.sourceCompatibility='1.8' + project.sourceCompatibility=JavaVersion.VERSION_17 } tasks.withType(JavaCompile) { options.encoding = "UTF-8" diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index 18001d9e6a3..bd715609a60 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -5,11 +5,9 @@ plugins { id 'com.apollographql.apollo' version '2.4.5' } - -sourceCompatibility = 1.8 +sourceCompatibility = JavaVersion.VERSION_11 repositories { - jcenter() gradlePluginPortal() mavenCentral() maven { url 'https://repo.spring.io/plugins-release/' } @@ -56,6 +54,10 @@ gradlePlugin { id = "org.springframework.github.changelog" implementationClass = "org.springframework.gradle.github.changelog.GitHubChangelogPlugin" } + githubRelease { + id = "org.springframework.github.release" + implementationClass = "org.springframework.gradle.github.release.GitHubReleasePlugin" + } s101 { id = "s101" implementationClass = "s101.S101Plugin" diff --git a/buildSrc/gradle/wrapper/gradle-wrapper.jar b/buildSrc/gradle/wrapper/gradle-wrapper.jar index e708b1c023e..7454180f2ae 100644 Binary files a/buildSrc/gradle/wrapper/gradle-wrapper.jar and b/buildSrc/gradle/wrapper/gradle-wrapper.jar differ diff --git a/buildSrc/gradle/wrapper/gradle-wrapper.properties b/buildSrc/gradle/wrapper/gradle-wrapper.properties index ffed3a254e9..e750102e092 100644 --- a/buildSrc/gradle/wrapper/gradle-wrapper.properties +++ b/buildSrc/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/buildSrc/src/main/groovy/io/spring/gradle/convention/DocsPlugin.groovy b/buildSrc/src/main/groovy/io/spring/gradle/convention/DocsPlugin.groovy index d0a64ab85bb..c62fef79b1c 100644 --- a/buildSrc/src/main/groovy/io/spring/gradle/convention/DocsPlugin.groovy +++ b/buildSrc/src/main/groovy/io/spring/gradle/convention/DocsPlugin.groovy @@ -25,7 +25,7 @@ public class DocsPlugin implements Plugin { group = 'Distribution' archiveBaseName = project.rootProject.name archiveClassifier = 'docs' - description = "Builds -${classifier} archive containing all " + + description = "Builds -${archiveClassifier.get()} archive containing all " + "Docs for deployment at docs.spring.io" from(project.tasks.api.outputs) { diff --git a/buildSrc/src/main/groovy/io/spring/gradle/convention/JacocoPlugin.groovy b/buildSrc/src/main/groovy/io/spring/gradle/convention/JacocoPlugin.groovy index 900cf9f1442..8f558eabbe3 100644 --- a/buildSrc/src/main/groovy/io/spring/gradle/convention/JacocoPlugin.groovy +++ b/buildSrc/src/main/groovy/io/spring/gradle/convention/JacocoPlugin.groovy @@ -34,7 +34,7 @@ class JacocoPlugin implements Plugin { project.tasks.check.dependsOn project.tasks.jacocoTestReport project.jacoco { - toolVersion = '0.8.2' + toolVersion = '0.8.7' } } } diff --git a/buildSrc/src/main/groovy/io/spring/gradle/convention/RepositoryConventionPlugin.groovy b/buildSrc/src/main/groovy/io/spring/gradle/convention/RepositoryConventionPlugin.groovy index c2420814290..407163d82a0 100644 --- a/buildSrc/src/main/groovy/io/spring/gradle/convention/RepositoryConventionPlugin.groovy +++ b/buildSrc/src/main/groovy/io/spring/gradle/convention/RepositoryConventionPlugin.groovy @@ -35,11 +35,6 @@ class RepositoryConventionPlugin implements Plugin { mavenLocal() } mavenCentral() - jcenter() { - content { - includeGroup "org.gretty" - } - } if (isSnapshot) { maven { name = 'artifactory-snapshot' diff --git a/buildSrc/src/main/java/org/springframework/gradle/github/milestones/RepositoryRef.java b/buildSrc/src/main/java/org/springframework/gradle/github/RepositoryRef.java similarity index 93% rename from buildSrc/src/main/java/org/springframework/gradle/github/milestones/RepositoryRef.java rename to buildSrc/src/main/java/org/springframework/gradle/github/RepositoryRef.java index 70eec3b1505..e570a47e902 100644 --- a/buildSrc/src/main/java/org/springframework/gradle/github/milestones/RepositoryRef.java +++ b/buildSrc/src/main/java/org/springframework/gradle/github/RepositoryRef.java @@ -1,10 +1,11 @@ -package org.springframework.gradle.github.milestones; +package org.springframework.gradle.github; + public class RepositoryRef { private String owner; private String name; - RepositoryRef() { + public RepositoryRef() { } public RepositoryRef(String owner, String name) { @@ -62,4 +63,3 @@ public RepositoryRef build() { } } } - diff --git a/buildSrc/src/main/java/org/springframework/gradle/github/changelog/GitHubChangelogPlugin.java b/buildSrc/src/main/java/org/springframework/gradle/github/changelog/GitHubChangelogPlugin.java index 2000e1a378c..0eab3d80068 100644 --- a/buildSrc/src/main/java/org/springframework/gradle/github/changelog/GitHubChangelogPlugin.java +++ b/buildSrc/src/main/java/org/springframework/gradle/github/changelog/GitHubChangelogPlugin.java @@ -16,6 +16,9 @@ package org.springframework.gradle.github.changelog; +import java.io.File; +import java.nio.file.Paths; + import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; @@ -28,12 +31,10 @@ import org.gradle.api.artifacts.repositories.IvyPatternRepositoryLayout; import org.gradle.api.tasks.JavaExec; -import java.io.File; -import java.nio.file.Paths; - public class GitHubChangelogPlugin implements Plugin { public static final String CHANGELOG_GENERATOR_CONFIGURATION_NAME = "changelogGenerator"; + public static final String RELEASE_NOTES_PATH = "changelog/release-notes.md"; @Override public void apply(Project project) { @@ -42,7 +43,7 @@ public void apply(Project project) { project.getTasks().register("generateChangelog", JavaExec.class, new Action() { @Override public void execute(JavaExec generateChangelog) { - File outputFile = project.file(Paths.get(project.getBuildDir().getPath(), "changelog/release-notes.md")); + File outputFile = project.file(Paths.get(project.getBuildDir().getPath(), RELEASE_NOTES_PATH)); outputFile.getParentFile().mkdirs(); generateChangelog.setGroup("Release"); generateChangelog.setDescription("Generates the changelog"); diff --git a/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneApi.java b/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneApi.java index 31f1274adb4..fd3c0d817bb 100644 --- a/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneApi.java +++ b/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneApi.java @@ -16,6 +16,9 @@ package org.springframework.gradle.github.milestones; +import java.io.IOException; +import java.util.List; + import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import okhttp3.Interceptor; @@ -23,8 +26,7 @@ import okhttp3.Request; import okhttp3.Response; -import java.io.IOException; -import java.util.List; +import org.springframework.gradle.github.RepositoryRef; public class GitHubMilestoneApi { private String baseUrl = "https://api.github.com"; diff --git a/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneHasNoOpenIssuesTask.java b/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneHasNoOpenIssuesTask.java index de846378f7a..40b026c8045 100644 --- a/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneHasNoOpenIssuesTask.java +++ b/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestoneHasNoOpenIssuesTask.java @@ -21,6 +21,8 @@ import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.TaskAction; +import org.springframework.gradle.github.RepositoryRef; + public class GitHubMilestoneHasNoOpenIssuesTask extends DefaultTask { @Input private RepositoryRef repository = new RepositoryRef(); diff --git a/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestonePlugin.java b/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestonePlugin.java index 527b7676133..81663f25611 100644 --- a/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestonePlugin.java +++ b/buildSrc/src/main/java/org/springframework/gradle/github/milestones/GitHubMilestonePlugin.java @@ -29,7 +29,7 @@ public void execute(GitHubMilestoneHasNoOpenIssuesTask githubCheckMilestoneHasNo githubCheckMilestoneHasNoOpenIssues.setGroup("Release"); githubCheckMilestoneHasNoOpenIssues.setDescription("Checks if there are any open issues for the specified repository and milestone"); githubCheckMilestoneHasNoOpenIssues.setMilestoneTitle((String) project.findProperty("nextVersion")); - if (project.hasProperty("githubAccessToken")) { + if (project.hasProperty("gitHubAccessToken")) { githubCheckMilestoneHasNoOpenIssues.setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); } } diff --git a/buildSrc/src/main/java/org/springframework/gradle/github/release/CreateGitHubReleaseTask.java b/buildSrc/src/main/java/org/springframework/gradle/github/release/CreateGitHubReleaseTask.java new file mode 100644 index 00000000000..65c8b687be0 --- /dev/null +++ b/buildSrc/src/main/java/org/springframework/gradle/github/release/CreateGitHubReleaseTask.java @@ -0,0 +1,130 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.gradle.github.release; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.gradle.api.Action; +import org.gradle.api.DefaultTask; +import org.gradle.api.Project; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.Optional; +import org.gradle.api.tasks.TaskAction; + +import org.springframework.gradle.github.RepositoryRef; +import org.springframework.gradle.github.changelog.GitHubChangelogPlugin; + +/** + * @author Steve Riesenberg + */ +public class CreateGitHubReleaseTask extends DefaultTask { + @Input + private RepositoryRef repository = new RepositoryRef(); + + @Input @Optional + private String gitHubAccessToken; + + @Input + private String version; + + @Input @Optional + private String branch = "main"; + + @Input + private boolean createRelease = false; + + @TaskAction + public void createGitHubRelease() { + String body = readReleaseNotes(); + Release release = Release.tag(this.version) + .commit(this.branch) + .name(this.version) + .body(body) + .preRelease(this.version.contains("-")) + .build(); + + System.out.printf("%sCreating GitHub release for %s/%s@%s\n", + this.createRelease ? "" : "[DRY RUN] ", + this.repository.getOwner(), + this.repository.getName(), + this.version + ); + System.out.printf(" Release Notes:\n\n----\n%s\n----\n\n", body.trim()); + + if (this.createRelease) { + GitHubReleaseApi github = new GitHubReleaseApi(this.gitHubAccessToken); + github.publishRelease(this.repository, release); + } + } + + private String readReleaseNotes() { + Project project = getProject(); + File inputFile = project.file(Paths.get(project.getBuildDir().getPath(), GitHubChangelogPlugin.RELEASE_NOTES_PATH)); + try { + return Files.readString(inputFile.toPath()); + } catch (IOException ex) { + throw new RuntimeException("Unable to read release notes from " + inputFile, ex); + } + } + + public RepositoryRef getRepository() { + return repository; + } + + public void repository(Action repository) { + repository.execute(this.repository); + } + + public void setRepository(RepositoryRef repository) { + this.repository = repository; + } + + public String getGitHubAccessToken() { + return gitHubAccessToken; + } + + public void setGitHubAccessToken(String gitHubAccessToken) { + this.gitHubAccessToken = gitHubAccessToken; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getBranch() { + return branch; + } + + public void setBranch(String branch) { + this.branch = branch; + } + + public boolean isCreateRelease() { + return createRelease; + } + + public void setCreateRelease(boolean createRelease) { + this.createRelease = createRelease; + } +} diff --git a/buildSrc/src/main/java/org/springframework/gradle/github/release/GitHubReleaseApi.java b/buildSrc/src/main/java/org/springframework/gradle/github/release/GitHubReleaseApi.java new file mode 100644 index 00000000000..65238d0b821 --- /dev/null +++ b/buildSrc/src/main/java/org/springframework/gradle/github/release/GitHubReleaseApi.java @@ -0,0 +1,91 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.gradle.github.release; + +import java.io.IOException; + +import com.google.gson.Gson; +import okhttp3.Interceptor; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +import org.springframework.gradle.github.RepositoryRef; + +/** + * Manage GitHub releases. + * + * @author Steve Riesenberg + */ +public class GitHubReleaseApi { + private String baseUrl = "https://api.github.com"; + + private final OkHttpClient httpClient; + private Gson gson = new Gson(); + + public GitHubReleaseApi(String gitHubAccessToken) { + this.httpClient = new OkHttpClient.Builder() + .addInterceptor(new AuthorizationInterceptor(gitHubAccessToken)) + .build(); + } + + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + } + + /** + * Publish a release with no binary attachments. + * + * @param repository The repository owner/name + * @param release The contents of the release + */ + public void publishRelease(RepositoryRef repository, Release release) { + String url = this.baseUrl + "/repos/" + repository.getOwner() + "/" + repository.getName() + "/releases"; + String json = this.gson.toJson(release); + RequestBody body = RequestBody.create(MediaType.parse("application/json"), json); + Request request = new Request.Builder().url(url).post(body).build(); + try { + Response response = this.httpClient.newCall(request).execute(); + if (!response.isSuccessful()) { + throw new RuntimeException(String.format("Could not create release %s for repository %s/%s. Got response %s", + release.getName(), repository.getOwner(), repository.getName(), response)); + } + } catch (IOException ex) { + throw new RuntimeException(String.format("Could not create release %s for repository %s/%s", + release.getName(), repository.getOwner(), repository.getName()), ex); + } + } + + private static class AuthorizationInterceptor implements Interceptor { + private final String token; + + public AuthorizationInterceptor(String token) { + this.token = token; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request().newBuilder() + .addHeader("Authorization", "Bearer " + this.token) + .build(); + + return chain.proceed(request); + } + } +} diff --git a/buildSrc/src/main/java/org/springframework/gradle/github/release/GitHubReleasePlugin.java b/buildSrc/src/main/java/org/springframework/gradle/github/release/GitHubReleasePlugin.java new file mode 100644 index 00000000000..ae2c44a7694 --- /dev/null +++ b/buildSrc/src/main/java/org/springframework/gradle/github/release/GitHubReleasePlugin.java @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.gradle.github.release; + +import groovy.lang.MissingPropertyException; +import org.gradle.api.Action; +import org.gradle.api.Plugin; +import org.gradle.api.Project; + +/** + * @author Steve Riesenberg + */ +public class GitHubReleasePlugin implements Plugin { + @Override + public void apply(Project project) { + project.getTasks().register("createGitHubRelease", CreateGitHubReleaseTask.class, new Action() { + @Override + public void execute(CreateGitHubReleaseTask createGitHubRelease) { + createGitHubRelease.setGroup("Release"); + createGitHubRelease.setDescription("Create a github release"); + createGitHubRelease.dependsOn("generateChangelog"); + + createGitHubRelease.setCreateRelease("true".equals(project.findProperty("createRelease"))); + createGitHubRelease.setVersion((String) project.findProperty("nextVersion")); + if (project.hasProperty("branch")) { + createGitHubRelease.setBranch((String) project.findProperty("branch")); + } + createGitHubRelease.setGitHubAccessToken((String) project.findProperty("gitHubAccessToken")); + if (createGitHubRelease.isCreateRelease() && createGitHubRelease.getGitHubAccessToken() == null) { + throw new MissingPropertyException("Please provide an access token with -PgitHubAccessToken=..."); + } + } + }); + } +} diff --git a/buildSrc/src/main/java/org/springframework/gradle/github/release/Release.java b/buildSrc/src/main/java/org/springframework/gradle/github/release/Release.java new file mode 100644 index 00000000000..6dec2ceb796 --- /dev/null +++ b/buildSrc/src/main/java/org/springframework/gradle/github/release/Release.java @@ -0,0 +1,156 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.gradle.github.release; + +import com.google.gson.annotations.SerializedName; + +/** + * @author Steve Riesenberg + */ +public class Release { + @SerializedName("tag_name") + private final String tag; + + @SerializedName("target_commitish") + private final String commit; + + @SerializedName("name") + private final String name; + + @SerializedName("body") + private final String body; + + @SerializedName("draft") + private final boolean draft; + + @SerializedName("prerelease") + private final boolean preRelease; + + @SerializedName("generate_release_notes") + private final boolean generateReleaseNotes; + + private Release(String tag, String commit, String name, String body, boolean draft, boolean preRelease, boolean generateReleaseNotes) { + this.tag = tag; + this.commit = commit; + this.name = name; + this.body = body; + this.draft = draft; + this.preRelease = preRelease; + this.generateReleaseNotes = generateReleaseNotes; + } + + public String getTag() { + return tag; + } + + public String getCommit() { + return commit; + } + + public String getName() { + return name; + } + + public String getBody() { + return body; + } + + public boolean isDraft() { + return draft; + } + + public boolean isPreRelease() { + return preRelease; + } + + public boolean isGenerateReleaseNotes() { + return generateReleaseNotes; + } + + @Override + public String toString() { + return "Release{" + + "tag='" + tag + '\'' + + ", commit='" + commit + '\'' + + ", name='" + name + '\'' + + ", body='" + body + '\'' + + ", draft=" + draft + + ", preRelease=" + preRelease + + ", generateReleaseNotes=" + generateReleaseNotes + + '}'; + } + + public static Builder tag(String tag) { + return new Builder().tag(tag); + } + + public static Builder commit(String commit) { + return new Builder().commit(commit); + } + + public static final class Builder { + private String tag; + private String commit; + private String name; + private String body; + private boolean draft; + private boolean preRelease; + private boolean generateReleaseNotes; + + private Builder() { + } + + public Builder tag(String tag) { + this.tag = tag; + return this; + } + + public Builder commit(String commit) { + this.commit = commit; + return this; + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder body(String body) { + this.body = body; + return this; + } + + public Builder draft(boolean draft) { + this.draft = draft; + return this; + } + + public Builder preRelease(boolean preRelease) { + this.preRelease = preRelease; + return this; + } + + public Builder generateReleaseNotes(boolean generateReleaseNotes) { + this.generateReleaseNotes = generateReleaseNotes; + return this; + } + + public Release build() { + return new Release(tag, commit, name, body, draft, preRelease, generateReleaseNotes); + } + } +} diff --git a/buildSrc/src/main/java/s101/S101Configurer.java b/buildSrc/src/main/java/s101/S101Configurer.java index 414e4885358..b3b74391366 100644 --- a/buildSrc/src/main/java/s101/S101Configurer.java +++ b/buildSrc/src/main/java/s101/S101Configurer.java @@ -161,7 +161,7 @@ private boolean deleteDirectory(File directoryToBeDeleted) { } private String installBuildTool(File installationDirectory, File configurationDirectory) { - String source = "https://structure101.com/binaries/v6"; + String source = "https://structure101.com/binaries/19159"; try (final WebClient webClient = new WebClient()) { HtmlPage page = webClient.getPage(source); for (HtmlAnchor anchor : page.getAnchors()) { diff --git a/buildSrc/src/test/java/io/spring/gradle/convention/JavadocApiPluginITest.java b/buildSrc/src/test/java/io/spring/gradle/convention/JavadocApiPluginITest.java index 681d5c49831..e77f341786a 100644 --- a/buildSrc/src/test/java/io/spring/gradle/convention/JavadocApiPluginITest.java +++ b/buildSrc/src/test/java/io/spring/gradle/convention/JavadocApiPluginITest.java @@ -5,6 +5,7 @@ import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.TaskOutcome; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -28,7 +29,7 @@ public void multiModuleApi() throws Exception { .build(); assertThat(result.task(":api").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); File allClasses = new File(testKit.getRootDir(), "build/api/allclasses-noframe.html"); - File index = new File(testKit.getRootDir(), "build/api/allclasses.html"); + File index = new File(testKit.getRootDir(), "build/api/allclasses-index.html"); File listing = allClasses.exists() ? allClasses : index; String listingText = FileUtils.readFileToString(listing); assertThat(listingText).contains("sample/Api.html"); diff --git a/buildSrc/src/test/java/io/spring/gradle/convention/RepositoryConventionPluginTests.java b/buildSrc/src/test/java/io/spring/gradle/convention/RepositoryConventionPluginTests.java index 2bad49c8a3a..f1048dbbab6 100644 --- a/buildSrc/src/test/java/io/spring/gradle/convention/RepositoryConventionPluginTests.java +++ b/buildSrc/src/test/java/io/spring/gradle/convention/RepositoryConventionPluginTests.java @@ -107,7 +107,7 @@ public void applyWhenIsReleaseWithForceLocalThenShouldIncludeReleaseAndLocalRepo this.project.getPluginManager().apply(RepositoryConventionPlugin.class); RepositoryHandler repositories = this.project.getRepositories(); - assertThat(repositories).hasSize(5); + assertThat(repositories).hasSize(4); assertThat((repositories.get(0)).getName()).isEqualTo("MavenLocal"); } @@ -119,39 +119,33 @@ public void applyWhenIsReleaseWithForceMilestoneAndLocalThenShouldIncludeMilesto this.project.getPluginManager().apply(RepositoryConventionPlugin.class); RepositoryHandler repositories = this.project.getRepositories(); - assertThat(repositories).hasSize(6); + assertThat(repositories).hasSize(5); assertThat((repositories.get(0)).getName()).isEqualTo("MavenLocal"); } private void assertSnapshotRepository(RepositoryHandler repositories) { - assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(6); + assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(5); assertThat(((MavenArtifactRepository) repositories.get(0)).getUrl().toString()) .isEqualTo("https://repo.maven.apache.org/maven2/"); assertThat(((MavenArtifactRepository) repositories.get(1)).getUrl().toString()) - .isEqualTo("https://jcenter.bintray.com/"); - assertThat(((MavenArtifactRepository) repositories.get(2)).getUrl().toString()) .isEqualTo("https://repo.spring.io/snapshot/"); - assertThat(((MavenArtifactRepository) repositories.get(3)).getUrl().toString()) + assertThat(((MavenArtifactRepository) repositories.get(2)).getUrl().toString()) .isEqualTo("https://repo.spring.io/milestone/"); } private void assertMilestoneRepository(RepositoryHandler repositories) { - assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(5); + assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(4); assertThat(((MavenArtifactRepository) repositories.get(0)).getUrl().toString()) .isEqualTo("https://repo.maven.apache.org/maven2/"); assertThat(((MavenArtifactRepository) repositories.get(1)).getUrl().toString()) - .isEqualTo("https://jcenter.bintray.com/"); - assertThat(((MavenArtifactRepository) repositories.get(2)).getUrl().toString()) .isEqualTo("https://repo.spring.io/milestone/"); } private void assertReleaseRepository(RepositoryHandler repositories) { - assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(4); + assertThat(repositories).extracting(ArtifactRepository::getName).hasSize(3); assertThat(((MavenArtifactRepository) repositories.get(0)).getUrl().toString()) .isEqualTo("https://repo.maven.apache.org/maven2/"); assertThat(((MavenArtifactRepository) repositories.get(1)).getUrl().toString()) - .isEqualTo("https://jcenter.bintray.com/"); - assertThat(((MavenArtifactRepository) repositories.get(2)).getUrl().toString()) .isEqualTo("https://repo.spring.io/release/"); } diff --git a/buildSrc/src/test/java/io/spring/gradle/github/milestones/GitHubMilestoneApiTests.java b/buildSrc/src/test/java/io/spring/gradle/github/milestones/GitHubMilestoneApiTests.java index 183cf09d5ab..b9b0764ee53 100644 --- a/buildSrc/src/test/java/io/spring/gradle/github/milestones/GitHubMilestoneApiTests.java +++ b/buildSrc/src/test/java/io/spring/gradle/github/milestones/GitHubMilestoneApiTests.java @@ -1,15 +1,16 @@ package io.spring.gradle.github.milestones; +import java.util.concurrent.TimeUnit; + import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.gradle.github.milestones.GitHubMilestoneApi; -import org.springframework.gradle.github.milestones.RepositoryRef; -import java.util.concurrent.TimeUnit; +import org.springframework.gradle.github.RepositoryRef; +import org.springframework.gradle.github.milestones.GitHubMilestoneApi; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; diff --git a/buildSrc/src/test/java/org/springframework/gradle/github/milestones/GitHubMilestoneApiTests.java b/buildSrc/src/test/java/org/springframework/gradle/github/milestones/GitHubMilestoneApiTests.java index b4072c079eb..0a1a293ab04 100644 --- a/buildSrc/src/test/java/org/springframework/gradle/github/milestones/GitHubMilestoneApiTests.java +++ b/buildSrc/src/test/java/org/springframework/gradle/github/milestones/GitHubMilestoneApiTests.java @@ -1,5 +1,7 @@ package org.springframework.gradle.github.milestones; +import java.util.concurrent.TimeUnit; + import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; @@ -7,7 +9,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.TimeUnit; +import org.springframework.gradle.github.RepositoryRef; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; diff --git a/buildSrc/src/test/java/org/springframework/gradle/github/release/GitHubReleaseApiTests.java b/buildSrc/src/test/java/org/springframework/gradle/github/release/GitHubReleaseApiTests.java new file mode 100644 index 00000000000..6ac79557222 --- /dev/null +++ b/buildSrc/src/test/java/org/springframework/gradle/github/release/GitHubReleaseApiTests.java @@ -0,0 +1,151 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.gradle.github.release; + +import java.util.concurrent.TimeUnit; + +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +import org.springframework.gradle.github.RepositoryRef; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +/** + * @author Steve Riesenberg + */ +public class GitHubReleaseApiTests { + private GitHubReleaseApi github; + + private RepositoryRef repository = new RepositoryRef("spring-projects", "spring-security"); + + private MockWebServer server; + + private String baseUrl; + + @BeforeEach + public void setup() throws Exception { + this.server = new MockWebServer(); + this.server.start(); + this.github = new GitHubReleaseApi("mock-oauth-token"); + this.baseUrl = this.server.url("/api").toString(); + this.github.setBaseUrl(this.baseUrl); + } + + @AfterEach + public void cleanup() throws Exception { + this.server.shutdown(); + } + + @Test + public void publishReleaseWhenValidParametersThenSuccess() throws Exception { + String responseJson = "{\n" + + " \"url\": \"https://api.github.com/spring-projects/spring-security/releases/1\",\n" + + " \"html_url\": \"https://github.com/spring-projects/spring-security/releases/tags/v1.0.0\",\n" + + " \"assets_url\": \"https://api.github.com/spring-projects/spring-security/releases/1/assets\",\n" + + " \"upload_url\": \"https://uploads.github.com/spring-projects/spring-security/releases/1/assets{?name,label}\",\n" + + " \"tarball_url\": \"https://api.github.com/spring-projects/spring-security/tarball/v1.0.0\",\n" + + " \"zipball_url\": \"https://api.github.com/spring-projects/spring-security/zipball/v1.0.0\",\n" + + " \"discussion_url\": \"https://github.com/spring-projects/spring-security/discussions/90\",\n" + + " \"id\": 1,\n" + + " \"node_id\": \"MDc6UmVsZWFzZTE=\",\n" + + " \"tag_name\": \"v1.0.0\",\n" + + " \"target_commitish\": \"main\",\n" + + " \"name\": \"v1.0.0\",\n" + + " \"body\": \"Description of the release\",\n" + + " \"draft\": false,\n" + + " \"prerelease\": false,\n" + + " \"created_at\": \"2013-02-27T19:35:32Z\",\n" + + " \"published_at\": \"2013-02-27T19:35:32Z\",\n" + + " \"author\": {\n" + + " \"login\": \"sjohnr\",\n" + + " \"id\": 1,\n" + + " \"node_id\": \"MDQ6VXNlcjE=\",\n" + + " \"avatar_url\": \"https://github.com/images/avatar.gif\",\n" + + " \"gravatar_id\": \"\",\n" + + " \"url\": \"https://api.github.com/users/sjohnr\",\n" + + " \"html_url\": \"https://github.com/sjohnr\",\n" + + " \"followers_url\": \"https://api.github.com/users/sjohnr/followers\",\n" + + " \"following_url\": \"https://api.github.com/users/sjohnr/following{/other_user}\",\n" + + " \"gists_url\": \"https://api.github.com/users/sjohnr/gists{/gist_id}\",\n" + + " \"starred_url\": \"https://api.github.com/users/sjohnr/starred{/owner}{/repo}\",\n" + + " \"subscriptions_url\": \"https://api.github.com/users/sjohnr/subscriptions\",\n" + + " \"organizations_url\": \"https://api.github.com/users/sjohnr/orgs\",\n" + + " \"repos_url\": \"https://api.github.com/users/sjohnr/repos\",\n" + + " \"events_url\": \"https://api.github.com/users/sjohnr/events{/privacy}\",\n" + + " \"received_events_url\": \"https://api.github.com/users/sjohnr/received_events\",\n" + + " \"type\": \"User\",\n" + + " \"site_admin\": false\n" + + " },\n" + + " \"assets\": [\n" + + " {\n" + + " \"url\": \"https://api.github.com/spring-projects/spring-security/releases/assets/1\",\n" + + " \"browser_download_url\": \"https://github.com/spring-projects/spring-security/releases/download/v1.0.0/example.zip\",\n" + + " \"id\": 1,\n" + + " \"node_id\": \"MDEyOlJlbGVhc2VBc3NldDE=\",\n" + + " \"name\": \"example.zip\",\n" + + " \"label\": \"short description\",\n" + + " \"state\": \"uploaded\",\n" + + " \"content_type\": \"application/zip\",\n" + + " \"size\": 1024,\n" + + " \"download_count\": 42,\n" + + " \"created_at\": \"2013-02-27T19:35:32Z\",\n" + + " \"updated_at\": \"2013-02-27T19:35:32Z\",\n" + + " \"uploader\": {\n" + + " \"login\": \"sjohnr\",\n" + + " \"id\": 1,\n" + + " \"node_id\": \"MDQ6VXNlcjE=\",\n" + + " \"avatar_url\": \"https://github.com/images/avatar.gif\",\n" + + " \"gravatar_id\": \"\",\n" + + " \"url\": \"https://api.github.com/users/sjohnr\",\n" + + " \"html_url\": \"https://github.com/sjohnr\",\n" + + " \"followers_url\": \"https://api.github.com/users/sjohnr/followers\",\n" + + " \"following_url\": \"https://api.github.com/users/sjohnr/following{/other_user}\",\n" + + " \"gists_url\": \"https://api.github.com/users/sjohnr/gists{/gist_id}\",\n" + + " \"starred_url\": \"https://api.github.com/users/sjohnr/starred{/owner}{/repo}\",\n" + + " \"subscriptions_url\": \"https://api.github.com/users/sjohnr/subscriptions\",\n" + + " \"organizations_url\": \"https://api.github.com/users/sjohnr/orgs\",\n" + + " \"repos_url\": \"https://api.github.com/users/sjohnr/repos\",\n" + + " \"events_url\": \"https://api.github.com/users/sjohnr/events{/privacy}\",\n" + + " \"received_events_url\": \"https://api.github.com/users/sjohnr/received_events\",\n" + + " \"type\": \"User\",\n" + + " \"site_admin\": false\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; + this.server.enqueue(new MockResponse().setBody(responseJson)); + this.github.publishRelease(this.repository, Release.tag("1.0.0").build()); + + RecordedRequest recordedRequest = this.server.takeRequest(1, TimeUnit.SECONDS); + assertThat(recordedRequest.getMethod()).isEqualToIgnoringCase("post"); + assertThat(recordedRequest.getRequestUrl().toString()).isEqualTo(this.baseUrl + "/repos/spring-projects/spring-security/releases"); + assertThat(recordedRequest.getBody().toString()).isEqualTo("{\"tag_name\":\"1.0.0\"}"); + } + + @Test + public void publishReleaseWhenErrorResponseThenException() throws Exception { + this.server.enqueue(new MockResponse().setResponseCode(400)); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.github.publishRelease(this.repository, Release.tag("1.0.0").build())); + } +} diff --git a/buildSrc/src/test/resources/samples/integrationtest/withpropdeps/build.gradle b/buildSrc/src/test/resources/samples/integrationtest/withpropdeps/build.gradle index 732278d03b5..48a9859419e 100644 --- a/buildSrc/src/test/resources/samples/integrationtest/withpropdeps/build.gradle +++ b/buildSrc/src/test/resources/samples/integrationtest/withpropdeps/build.gradle @@ -9,6 +9,6 @@ repositories { } dependencies { - optional 'javax.servlet:javax.servlet-api:3.1.0' + optional 'jakarta.servlet:jakarta.servlet-api:5.0.0' testCompile 'junit:junit:4.12' } \ No newline at end of file diff --git a/buildSrc/src/test/resources/samples/integrationtest/withpropdeps/src/integration-test/java/sample/TheTest.java b/buildSrc/src/test/resources/samples/integrationtest/withpropdeps/src/integration-test/java/sample/TheTest.java index de492ca0e67..8bd9ea43927 100644 --- a/buildSrc/src/test/resources/samples/integrationtest/withpropdeps/src/integration-test/java/sample/TheTest.java +++ b/buildSrc/src/test/resources/samples/integrationtest/withpropdeps/src/integration-test/java/sample/TheTest.java @@ -1,7 +1,7 @@ package sample; import org.junit.Test; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; public class TheTest { @Test diff --git a/cas/spring-security-cas.gradle b/cas/spring-security-cas.gradle deleted file mode 100644 index 8b3d4630f75..00000000000 --- a/cas/spring-security-cas.gradle +++ /dev/null @@ -1,26 +0,0 @@ -apply plugin: 'io.spring.convention.spring-module' - -dependencies { - management platform(project(":spring-security-dependencies")) - api project(':spring-security-core') - api project(':spring-security-web') - api 'org.jasig.cas.client:cas-client-core' - api 'org.springframework:spring-beans' - api 'org.springframework:spring-context' - api 'org.springframework:spring-core' - api 'org.springframework:spring-web' - - optional 'com.fasterxml.jackson.core:jackson-databind' - optional 'net.sf.ehcache:ehcache' - - provided 'javax.servlet:javax.servlet-api' - - testImplementation "org.assertj:assertj-core" - testImplementation "org.junit.jupiter:junit-jupiter-api" - testImplementation "org.junit.jupiter:junit-jupiter-params" - testImplementation "org.junit.jupiter:junit-jupiter-engine" - testImplementation "org.mockito:mockito-core" - testImplementation "org.mockito:mockito-junit-jupiter" - testImplementation "org.springframework:spring-test" - testImplementation 'org.skyscreamer:jsonassert' -} diff --git a/cas/src/main/java/org/springframework/security/cas/SamlServiceProperties.java b/cas/src/main/java/org/springframework/security/cas/SamlServiceProperties.java deleted file mode 100644 index 8e300f8f8ed..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/SamlServiceProperties.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas; - -/** - * Sets the appropriate parameters for CAS's implementation of SAML (which is not - * guaranteed to be actually SAML compliant). - * - * @author Scott Battaglia - * @since 3.0 - */ -public final class SamlServiceProperties extends ServiceProperties { - - public static final String DEFAULT_SAML_ARTIFACT_PARAMETER = "SAMLart"; - - public static final String DEFAULT_SAML_SERVICE_PARAMETER = "TARGET"; - - public SamlServiceProperties() { - super.setArtifactParameter(DEFAULT_SAML_ARTIFACT_PARAMETER); - super.setServiceParameter(DEFAULT_SAML_SERVICE_PARAMETER); - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/ServiceProperties.java b/cas/src/main/java/org/springframework/security/cas/ServiceProperties.java deleted file mode 100644 index caf03dd62a1..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/ServiceProperties.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.util.Assert; - -/** - * Stores properties related to this CAS service. - *

- * Each web application capable of processing CAS tickets is known as a service. This - * class stores the properties that are relevant to the local CAS service, being the - * application that is being secured by Spring Security. - * - * @author Ben Alex - */ -public class ServiceProperties implements InitializingBean { - - public static final String DEFAULT_CAS_ARTIFACT_PARAMETER = "ticket"; - - public static final String DEFAULT_CAS_SERVICE_PARAMETER = "service"; - - private String service; - - private boolean authenticateAllArtifacts; - - private boolean sendRenew = false; - - private String artifactParameter = DEFAULT_CAS_ARTIFACT_PARAMETER; - - private String serviceParameter = DEFAULT_CAS_SERVICE_PARAMETER; - - @Override - public void afterPropertiesSet() { - Assert.hasLength(this.service, "service cannot be empty."); - Assert.hasLength(this.artifactParameter, "artifactParameter cannot be empty."); - Assert.hasLength(this.serviceParameter, "serviceParameter cannot be empty."); - } - - /** - * Represents the service the user is authenticating to. - *

- * This service is the callback URL belonging to the local Spring Security System for - * Spring secured application. For example, - * - *

-	 * https://www.mycompany.com/application/login/cas
-	 * 
- * @return the URL of the service the user is authenticating to - */ - public final String getService() { - return this.service; - } - - /** - * Indicates whether the renew parameter should be sent to the CAS login - * URL and CAS validation URL. - *

- * If true, it will force CAS to authenticate the user again (even if the - * user has previously authenticated). During ticket validation it will require the - * ticket was generated as a consequence of an explicit login. High security - * applications would probably set this to true. Defaults to - * false, providing automated single sign on. - * @return whether to send the renew parameter to CAS - */ - public final boolean isSendRenew() { - return this.sendRenew; - } - - public final void setSendRenew(final boolean sendRenew) { - this.sendRenew = sendRenew; - } - - public final void setService(final String service) { - this.service = service; - } - - public final String getArtifactParameter() { - return this.artifactParameter; - } - - /** - * Configures the Request Parameter to look for when attempting to see if a CAS ticket - * was sent from the server. - * @param artifactParameter the id to use. Default is "ticket". - */ - public final void setArtifactParameter(final String artifactParameter) { - this.artifactParameter = artifactParameter; - } - - /** - * Configures the Request parameter to look for when attempting to send a request to - * CAS. - * @return the service parameter to use. Default is "service". - */ - public final String getServiceParameter() { - return this.serviceParameter; - } - - public final void setServiceParameter(final String serviceParameter) { - this.serviceParameter = serviceParameter; - } - - public final boolean isAuthenticateAllArtifacts() { - return this.authenticateAllArtifacts; - } - - /** - * If true, then any non-null artifact (ticket) should be authenticated. Additionally, - * the service will be determined dynamically in order to ensure the service matches - * the expected value for this artifact. - * @param authenticateAllArtifacts - */ - public final void setAuthenticateAllArtifacts(final boolean authenticateAllArtifacts) { - this.authenticateAllArtifacts = authenticateAllArtifacts; - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/CasAssertionAuthenticationToken.java b/cas/src/main/java/org/springframework/security/cas/authentication/CasAssertionAuthenticationToken.java deleted file mode 100644 index d04d30d1545..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/authentication/CasAssertionAuthenticationToken.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import java.util.ArrayList; - -import org.jasig.cas.client.validation.Assertion; - -import org.springframework.security.authentication.AbstractAuthenticationToken; -import org.springframework.security.core.SpringSecurityCoreVersion; - -/** - * Temporary authentication object needed to load the user details service. - * - * @author Scott Battaglia - * @since 3.0 - */ -public final class CasAssertionAuthenticationToken extends AbstractAuthenticationToken { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - private final Assertion assertion; - - private final String ticket; - - public CasAssertionAuthenticationToken(final Assertion assertion, final String ticket) { - super(new ArrayList<>()); - this.assertion = assertion; - this.ticket = ticket; - } - - @Override - public Object getPrincipal() { - return this.assertion.getPrincipal().getName(); - } - - @Override - public Object getCredentials() { - return this.ticket; - } - - public Assertion getAssertion() { - return this.assertion; - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java deleted file mode 100644 index 3a84c2109ae..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jasig.cas.client.validation.Assertion; -import org.jasig.cas.client.validation.TicketValidationException; -import org.jasig.cas.client.validation.TicketValidator; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.MessageSource; -import org.springframework.context.MessageSourceAware; -import org.springframework.context.support.MessageSourceAccessor; -import org.springframework.core.log.LogMessage; -import org.springframework.security.authentication.AccountStatusUserDetailsChecker; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.web.CasAuthenticationFilter; -import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.SpringSecurityMessageSource; -import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; -import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper; -import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper; -import org.springframework.security.core.userdetails.UserDetailsChecker; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.util.Assert; - -/** - * An {@link AuthenticationProvider} implementation that integrates with JA-SIG Central - * Authentication Service (CAS). - *

- * This AuthenticationProvider is capable of validating - * {@link UsernamePasswordAuthenticationToken} requests which contain a - * principal name equal to either - * {@link CasAuthenticationFilter#CAS_STATEFUL_IDENTIFIER} or - * {@link CasAuthenticationFilter#CAS_STATELESS_IDENTIFIER}. It can also validate a - * previously created {@link CasAuthenticationToken}. - * - * @author Ben Alex - * @author Scott Battaglia - */ -public class CasAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware { - - private static final Log logger = LogFactory.getLog(CasAuthenticationProvider.class); - - private AuthenticationUserDetailsService authenticationUserDetailsService; - - private final UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker(); - - protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); - - private StatelessTicketCache statelessTicketCache = new NullStatelessTicketCache(); - - private String key; - - private TicketValidator ticketValidator; - - private ServiceProperties serviceProperties; - - private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper(); - - @Override - public void afterPropertiesSet() { - Assert.notNull(this.authenticationUserDetailsService, "An authenticationUserDetailsService must be set"); - Assert.notNull(this.ticketValidator, "A ticketValidator must be set"); - Assert.notNull(this.statelessTicketCache, "A statelessTicketCache must be set"); - Assert.hasText(this.key, - "A Key is required so CasAuthenticationProvider can identify tokens it previously authenticated"); - Assert.notNull(this.messages, "A message source must be set"); - } - - @Override - public Authentication authenticate(Authentication authentication) throws AuthenticationException { - if (!supports(authentication.getClass())) { - return null; - } - if (authentication instanceof UsernamePasswordAuthenticationToken - && (!CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER.equals(authentication.getPrincipal().toString()) - && !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER - .equals(authentication.getPrincipal().toString()))) { - // UsernamePasswordAuthenticationToken not CAS related - return null; - } - // If an existing CasAuthenticationToken, just check we created it - if (authentication instanceof CasAuthenticationToken) { - if (this.key.hashCode() != ((CasAuthenticationToken) authentication).getKeyHash()) { - throw new BadCredentialsException(this.messages.getMessage("CasAuthenticationProvider.incorrectKey", - "The presented CasAuthenticationToken does not contain the expected key")); - } - return authentication; - } - - // Ensure credentials are presented - if ((authentication.getCredentials() == null) || "".equals(authentication.getCredentials())) { - throw new BadCredentialsException(this.messages.getMessage("CasAuthenticationProvider.noServiceTicket", - "Failed to provide a CAS service ticket to validate")); - } - - boolean stateless = (authentication instanceof UsernamePasswordAuthenticationToken - && CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER.equals(authentication.getPrincipal())); - CasAuthenticationToken result = null; - - if (stateless) { - // Try to obtain from cache - result = this.statelessTicketCache.getByTicketId(authentication.getCredentials().toString()); - } - if (result == null) { - result = this.authenticateNow(authentication); - result.setDetails(authentication.getDetails()); - } - if (stateless) { - // Add to cache - this.statelessTicketCache.putTicketInCache(result); - } - return result; - } - - private CasAuthenticationToken authenticateNow(final Authentication authentication) throws AuthenticationException { - try { - Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), - getServiceUrl(authentication)); - UserDetails userDetails = loadUserByAssertion(assertion); - this.userDetailsChecker.check(userDetails); - return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(), - this.authoritiesMapper.mapAuthorities(userDetails.getAuthorities()), userDetails, assertion); - } - catch (TicketValidationException ex) { - throw new BadCredentialsException(ex.getMessage(), ex); - } - } - - /** - * Gets the serviceUrl. If the {@link Authentication#getDetails()} is an instance of - * {@link ServiceAuthenticationDetails}, then - * {@link ServiceAuthenticationDetails#getServiceUrl()} is used. Otherwise, the - * {@link ServiceProperties#getService()} is used. - * @param authentication - * @return - */ - private String getServiceUrl(Authentication authentication) { - String serviceUrl; - if (authentication.getDetails() instanceof ServiceAuthenticationDetails) { - return ((ServiceAuthenticationDetails) authentication.getDetails()).getServiceUrl(); - } - Assert.state(this.serviceProperties != null, - "serviceProperties cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails."); - Assert.state(this.serviceProperties.getService() != null, - "serviceProperties.getService() cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails."); - serviceUrl = this.serviceProperties.getService(); - logger.debug(LogMessage.format("serviceUrl = %s", serviceUrl)); - return serviceUrl; - } - - /** - * Template method for retrieving the UserDetails based on the assertion. Default is - * to call configured userDetailsService and pass the username. Deployers can override - * this method and retrieve the user based on any criteria they desire. - * @param assertion The CAS Assertion. - * @return the UserDetails. - */ - protected UserDetails loadUserByAssertion(final Assertion assertion) { - final CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(assertion, ""); - return this.authenticationUserDetailsService.loadUserDetails(token); - } - - @SuppressWarnings("unchecked") - /** - * Sets the UserDetailsService to use. This is a convenience method to invoke - */ - public void setUserDetailsService(final UserDetailsService userDetailsService) { - this.authenticationUserDetailsService = new UserDetailsByNameServiceWrapper(userDetailsService); - } - - public void setAuthenticationUserDetailsService( - final AuthenticationUserDetailsService authenticationUserDetailsService) { - this.authenticationUserDetailsService = authenticationUserDetailsService; - } - - public void setServiceProperties(final ServiceProperties serviceProperties) { - this.serviceProperties = serviceProperties; - } - - protected String getKey() { - return this.key; - } - - public void setKey(String key) { - this.key = key; - } - - public StatelessTicketCache getStatelessTicketCache() { - return this.statelessTicketCache; - } - - protected TicketValidator getTicketValidator() { - return this.ticketValidator; - } - - @Override - public void setMessageSource(final MessageSource messageSource) { - this.messages = new MessageSourceAccessor(messageSource); - } - - public void setStatelessTicketCache(final StatelessTicketCache statelessTicketCache) { - this.statelessTicketCache = statelessTicketCache; - } - - public void setTicketValidator(final TicketValidator ticketValidator) { - this.ticketValidator = ticketValidator; - } - - public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { - this.authoritiesMapper = authoritiesMapper; - } - - @Override - public boolean supports(final Class authentication) { - return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)) - || (CasAuthenticationToken.class.isAssignableFrom(authentication)) - || (CasAssertionAuthenticationToken.class.isAssignableFrom(authentication)); - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java deleted file mode 100644 index 8020da0400a..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import java.io.Serializable; -import java.util.Collection; - -import org.jasig.cas.client.validation.Assertion; - -import org.springframework.security.authentication.AbstractAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.SpringSecurityCoreVersion; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.util.Assert; -import org.springframework.util.ObjectUtils; - -/** - * Represents a successful CAS Authentication. - * - * @author Ben Alex - * @author Scott Battaglia - */ -public class CasAuthenticationToken extends AbstractAuthenticationToken implements Serializable { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - private final Object credentials; - - private final Object principal; - - private final UserDetails userDetails; - - private final int keyHash; - - private final Assertion assertion; - - /** - * Constructor. - * @param key to identify if this object made by a given - * {@link CasAuthenticationProvider} - * @param principal typically the UserDetails object (cannot be null) - * @param credentials the service/proxy ticket ID from CAS (cannot be - * null) - * @param authorities the authorities granted to the user (from the - * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot - * be null) - * @param userDetails the user details (from the - * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot - * be null) - * @param assertion the assertion returned from the CAS servers. It contains the - * principal and how to obtain a proxy ticket for the user. - * @throws IllegalArgumentException if a null was passed - */ - public CasAuthenticationToken(final String key, final Object principal, final Object credentials, - final Collection authorities, final UserDetails userDetails, - final Assertion assertion) { - this(extractKeyHash(key), principal, credentials, authorities, userDetails, assertion); - } - - /** - * Private constructor for Jackson Deserialization support - * @param keyHash hashCode of provided key to identify if this object made by a given - * {@link CasAuthenticationProvider} - * @param principal typically the UserDetails object (cannot be null) - * @param credentials the service/proxy ticket ID from CAS (cannot be - * null) - * @param authorities the authorities granted to the user (from the - * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot - * be null) - * @param userDetails the user details (from the - * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot - * be null) - * @param assertion the assertion returned from the CAS servers. It contains the - * principal and how to obtain a proxy ticket for the user. - * @throws IllegalArgumentException if a null was passed - * @since 4.2 - */ - private CasAuthenticationToken(final Integer keyHash, final Object principal, final Object credentials, - final Collection authorities, final UserDetails userDetails, - final Assertion assertion) { - super(authorities); - if ((principal == null) || "".equals(principal) || (credentials == null) || "".equals(credentials) - || (authorities == null) || (userDetails == null) || (assertion == null)) { - throw new IllegalArgumentException("Cannot pass null or empty values to constructor"); - } - this.keyHash = keyHash; - this.principal = principal; - this.credentials = credentials; - this.userDetails = userDetails; - this.assertion = assertion; - setAuthenticated(true); - } - - private static Integer extractKeyHash(String key) { - Assert.hasLength(key, "key cannot be null or empty"); - return key.hashCode(); - } - - @Override - public boolean equals(final Object obj) { - if (!super.equals(obj)) { - return false; - } - if (obj instanceof CasAuthenticationToken) { - CasAuthenticationToken test = (CasAuthenticationToken) obj; - if (!this.assertion.equals(test.getAssertion())) { - return false; - } - if (this.getKeyHash() != test.getKeyHash()) { - return false; - } - return true; - } - return false; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + this.credentials.hashCode(); - result = 31 * result + this.principal.hashCode(); - result = 31 * result + this.userDetails.hashCode(); - result = 31 * result + this.keyHash; - result = 31 * result + ObjectUtils.nullSafeHashCode(this.assertion); - return result; - } - - @Override - public Object getCredentials() { - return this.credentials; - } - - public int getKeyHash() { - return this.keyHash; - } - - @Override - public Object getPrincipal() { - return this.principal; - } - - public Assertion getAssertion() { - return this.assertion; - } - - public UserDetails getUserDetails() { - return this.userDetails; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(super.toString()); - sb.append(" Assertion: ").append(this.assertion); - sb.append(" Credentials (Service/Proxy Ticket): ").append(this.credentials); - return (sb.toString()); - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java deleted file mode 100644 index 595c0d23f2e..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import net.sf.ehcache.Ehcache; -import net.sf.ehcache.Element; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.core.log.LogMessage; -import org.springframework.util.Assert; - -/** - * Caches tickets using a Spring IoC defined - * EHCACHE. - * - * @author Ben Alex - * @deprecated since 5.6. In favor of JCache based implementations - */ -@Deprecated -public class EhCacheBasedTicketCache implements StatelessTicketCache, InitializingBean { - - private static final Log logger = LogFactory.getLog(EhCacheBasedTicketCache.class); - - private Ehcache cache; - - @Override - public void afterPropertiesSet() { - Assert.notNull(this.cache, "cache mandatory"); - } - - @Override - public CasAuthenticationToken getByTicketId(final String serviceTicket) { - final Element element = this.cache.get(serviceTicket); - logger.debug(LogMessage.of(() -> "Cache hit: " + (element != null) + "; service ticket: " + serviceTicket)); - return (element != null) ? (CasAuthenticationToken) element.getValue() : null; - } - - public Ehcache getCache() { - return this.cache; - } - - @Override - public void putTicketInCache(final CasAuthenticationToken token) { - final Element element = new Element(token.getCredentials().toString(), token); - logger.debug(LogMessage.of(() -> "Cache put: " + element.getKey())); - this.cache.put(element); - } - - @Override - public void removeTicketFromCache(final CasAuthenticationToken token) { - logger.debug(LogMessage.of(() -> "Cache remove: " + token.getCredentials().toString())); - this.removeTicketFromCache(token.getCredentials().toString()); - } - - @Override - public void removeTicketFromCache(final String serviceTicket) { - this.cache.remove(serviceTicket); - } - - public void setCache(final Ehcache cache) { - this.cache = cache; - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/NullStatelessTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/NullStatelessTicketCache.java deleted file mode 100644 index 4284161a39a..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/authentication/NullStatelessTicketCache.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -/** - * Implementation of @link {@link StatelessTicketCache} that has no backing cache. Useful - * in instances where storing of tickets for stateless session management is not required. - *

- * This is the default StatelessTicketCache of the @link {@link CasAuthenticationProvider} - * to eliminate the unnecessary dependency on EhCache that applications have even if they - * are not using the stateless session management. - * - * @author Scott Battaglia - * @see CasAuthenticationProvider - */ -public final class NullStatelessTicketCache implements StatelessTicketCache { - - /** - * @return null since we are not storing any tickets. - */ - @Override - public CasAuthenticationToken getByTicketId(final String serviceTicket) { - return null; - } - - /** - * This is a no-op since we are not storing tickets. - */ - @Override - public void putTicketInCache(final CasAuthenticationToken token) { - // nothing to do - } - - /** - * This is a no-op since we are not storing tickets. - */ - @Override - public void removeTicketFromCache(final CasAuthenticationToken token) { - // nothing to do - } - - /** - * This is a no-op since we are not storing tickets. - */ - @Override - public void removeTicketFromCache(final String serviceTicket) { - // nothing to do - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java deleted file mode 100644 index b72e824c75f..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.cache.Cache; -import org.springframework.core.log.LogMessage; -import org.springframework.util.Assert; - -/** - * Caches tickets using a Spring IoC defined {@link Cache}. - * - * @author Marten Deinum - * @since 3.2 - * - */ -public class SpringCacheBasedTicketCache implements StatelessTicketCache { - - private static final Log logger = LogFactory.getLog(SpringCacheBasedTicketCache.class); - - private final Cache cache; - - public SpringCacheBasedTicketCache(Cache cache) { - Assert.notNull(cache, "cache mandatory"); - this.cache = cache; - } - - @Override - public CasAuthenticationToken getByTicketId(final String serviceTicket) { - final Cache.ValueWrapper element = (serviceTicket != null) ? this.cache.get(serviceTicket) : null; - logger.debug(LogMessage.of(() -> "Cache hit: " + (element != null) + "; service ticket: " + serviceTicket)); - return (element != null) ? (CasAuthenticationToken) element.get() : null; - } - - @Override - public void putTicketInCache(final CasAuthenticationToken token) { - String key = token.getCredentials().toString(); - logger.debug(LogMessage.of(() -> "Cache put: " + key)); - this.cache.put(key, token); - } - - @Override - public void removeTicketFromCache(final CasAuthenticationToken token) { - logger.debug(LogMessage.of(() -> "Cache remove: " + token.getCredentials().toString())); - this.removeTicketFromCache(token.getCredentials().toString()); - } - - @Override - public void removeTicketFromCache(final String serviceTicket) { - this.cache.evict(serviceTicket); - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/StatelessTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/StatelessTicketCache.java deleted file mode 100644 index 74df6bb9df4..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/authentication/StatelessTicketCache.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2004 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -/** - * Caches CAS service tickets and CAS proxy tickets for stateless connections. - * - *

- * When a service ticket or proxy ticket is validated against the CAS server, it is unable - * to be used again. Most types of callers are stateful and are associated with a given - * HttpSession. This allows the affirmative CAS validation outcome to be - * stored in the HttpSession, meaning the removal of the ticket from the CAS - * server is not an issue. - *

- * - *

- * Stateless callers, such as remoting protocols, cannot take advantage of - * HttpSession. If the stateless caller is located a significant network - * distance from the CAS server, acquiring a fresh service ticket or proxy ticket for each - * invocation would be expensive. - *

- * - *

- * To avoid this issue with stateless callers, it is expected stateless callers will - * obtain a single service ticket or proxy ticket, and then present this same ticket to - * the Spring Security secured application on each occasion. As no - * HttpSession is available for such callers, the affirmative CAS validation - * outcome cannot be stored in this location. - *

- * - *

- * The StatelessTicketCache enables the service tickets and proxy tickets - * belonging to stateless callers to be placed in a cache. This in-memory cache stores the - * CasAuthenticationToken, effectively providing the same capability as a - * HttpSession with the ticket identifier being the key rather than a session - * identifier. - *

- * - *

- * Implementations should provide a reasonable timeout on stored entries, such that the - * stateless caller are not required to unnecessarily acquire fresh CAS service tickets or - * proxy tickets. - *

- * - * @author Ben Alex - */ -public interface StatelessTicketCache { - - /** - * Retrieves the CasAuthenticationToken associated with the specified - * ticket. - * - *

- * If not found, returns a nullCasAuthenticationToken. - *

- * @return the fully populated authentication token - */ - CasAuthenticationToken getByTicketId(String serviceTicket); - - /** - * Adds the specified CasAuthenticationToken to the cache. - * - *

- * The {@link CasAuthenticationToken#getCredentials()} method is used to retrieve the - * service ticket number. - *

- * @param token to be added to the cache - */ - void putTicketInCache(CasAuthenticationToken token); - - /** - * Removes the specified ticket from the cache, as per - * {@link #removeTicketFromCache(String)}. - * - *

- * Implementations should use {@link CasAuthenticationToken#getCredentials()} to - * obtain the ticket and then delegate to the {@link #removeTicketFromCache(String)} - * method. - *

- * @param token to be removed - */ - void removeTicketFromCache(CasAuthenticationToken token); - - /** - * Removes the specified ticket from the cache, meaning that future calls will require - * a new service ticket. - * - *

- * This is in case applications wish to provide a session termination capability for - * their stateless clients. - *

- * @param serviceTicket to be removed - */ - void removeTicketFromCache(String serviceTicket); - -} diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/package-info.java b/cas/src/main/java/org/springframework/security/cas/authentication/package-info.java deleted file mode 100644 index 8803500a0a2..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/authentication/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * An {@code AuthenticationProvider} that can process CAS service tickets and proxy - * tickets. - */ -package org.springframework.security.cas.authentication; diff --git a/cas/src/main/java/org/springframework/security/cas/jackson2/AssertionImplMixin.java b/cas/src/main/java/org/springframework/security/cas/jackson2/AssertionImplMixin.java deleted file mode 100644 index f3d7de8c025..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/jackson2/AssertionImplMixin.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2015-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.jackson2; - -import java.util.Date; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import org.jasig.cas.client.authentication.AttributePrincipal; - -/** - * Helps in jackson deserialization of class - * {@link org.jasig.cas.client.validation.AssertionImpl}, which is used with - * {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. To use - * this class we need to register with - * {@link com.fasterxml.jackson.databind.ObjectMapper}. Type information will be stored - * in @class property. - *

- *

- *     ObjectMapper mapper = new ObjectMapper();
- *     mapper.registerModule(new CasJackson2Module());
- * 
- * - * @author Jitendra Singh - * @since 4.2 - * @see CasJackson2Module - * @see org.springframework.security.jackson2.SecurityJackson2Modules - */ -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) -@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, - isGetterVisibility = JsonAutoDetect.Visibility.NONE) -@JsonIgnoreProperties(ignoreUnknown = true) -class AssertionImplMixin { - - /** - * Mixin Constructor helps in deserialize - * {@link org.jasig.cas.client.validation.AssertionImpl} - * @param principal the Principal to associate with the Assertion. - * @param validFromDate when the assertion is valid from. - * @param validUntilDate when the assertion is valid to. - * @param authenticationDate when the assertion is authenticated. - * @param attributes the key/value pairs for this attribute. - */ - @JsonCreator - AssertionImplMixin(@JsonProperty("principal") AttributePrincipal principal, - @JsonProperty("validFromDate") Date validFromDate, @JsonProperty("validUntilDate") Date validUntilDate, - @JsonProperty("authenticationDate") Date authenticationDate, - @JsonProperty("attributes") Map attributes) { - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/jackson2/AttributePrincipalImplMixin.java b/cas/src/main/java/org/springframework/security/cas/jackson2/AttributePrincipalImplMixin.java deleted file mode 100644 index 0ec671fb557..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/jackson2/AttributePrincipalImplMixin.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2015-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.jackson2; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import org.jasig.cas.client.proxy.ProxyRetriever; - -/** - * Helps in deserialize {@link org.jasig.cas.client.authentication.AttributePrincipalImpl} - * which is used with - * {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. Type - * information will be stored in property named @class. - *

- *

- *     ObjectMapper mapper = new ObjectMapper();
- *     mapper.registerModule(new CasJackson2Module());
- * 
- * - * @author Jitendra Singh - * @since 4.2 - * @see CasJackson2Module - * @see org.springframework.security.jackson2.SecurityJackson2Modules - */ -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) -@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, - isGetterVisibility = JsonAutoDetect.Visibility.NONE) -@JsonIgnoreProperties(ignoreUnknown = true) -class AttributePrincipalImplMixin { - - /** - * Mixin Constructor helps in deserialize - * {@link org.jasig.cas.client.authentication.AttributePrincipalImpl} - * @param name the unique identifier for the principal. - * @param attributes the key/value pairs for this principal. - * @param proxyGrantingTicket the ticket associated with this principal. - * @param proxyRetriever the ProxyRetriever implementation to call back to the CAS - * server. - */ - @JsonCreator - AttributePrincipalImplMixin(@JsonProperty("name") String name, - @JsonProperty("attributes") Map attributes, - @JsonProperty("proxyGrantingTicket") String proxyGrantingTicket, - @JsonProperty("proxyRetriever") ProxyRetriever proxyRetriever) { - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixin.java b/cas/src/main/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixin.java deleted file mode 100644 index 80e40a0dcaf..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixin.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.jackson2; - -import java.util.Collection; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import org.jasig.cas.client.validation.Assertion; - -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.authentication.CasAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -/** - * Mixin class which helps in deserialize - * {@link org.springframework.security.cas.authentication.CasAuthenticationToken} using - * jackson. Two more dependent classes needs to register along with this mixin class. - *
    - *
  1. {@link org.springframework.security.cas.jackson2.AssertionImplMixin}
  2. - *
  3. {@link org.springframework.security.cas.jackson2.AttributePrincipalImplMixin}
  4. - *
- * - *

- * - *

- *     ObjectMapper mapper = new ObjectMapper();
- *     mapper.registerModule(new CasJackson2Module());
- * 
- * - * @author Jitendra Singh - * @since 4.2 - * @see CasJackson2Module - * @see org.springframework.security.jackson2.SecurityJackson2Modules - */ -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) -@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, isGetterVisibility = JsonAutoDetect.Visibility.NONE, - getterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.ANY) -@JsonIgnoreProperties(ignoreUnknown = true) -class CasAuthenticationTokenMixin { - - /** - * Mixin Constructor helps in deserialize {@link CasAuthenticationToken} - * @param keyHash hashCode of provided key to identify if this object made by a given - * {@link CasAuthenticationProvider} - * @param principal typically the UserDetails object (cannot be null) - * @param credentials the service/proxy ticket ID from CAS (cannot be - * null) - * @param authorities the authorities granted to the user (from the - * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot - * be null) - * @param userDetails the user details (from the - * {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot - * be null) - * @param assertion the assertion returned from the CAS servers. It contains the - * principal and how to obtain a proxy ticket for the user. - */ - @JsonCreator - CasAuthenticationTokenMixin(@JsonProperty("keyHash") Integer keyHash, @JsonProperty("principal") Object principal, - @JsonProperty("credentials") Object credentials, - @JsonProperty("authorities") Collection authorities, - @JsonProperty("userDetails") UserDetails userDetails, @JsonProperty("assertion") Assertion assertion) { - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/jackson2/CasJackson2Module.java b/cas/src/main/java/org/springframework/security/cas/jackson2/CasJackson2Module.java deleted file mode 100644 index 34f19ca10af..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/jackson2/CasJackson2Module.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2015-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.jackson2; - -import com.fasterxml.jackson.core.Version; -import com.fasterxml.jackson.databind.module.SimpleModule; -import org.jasig.cas.client.authentication.AttributePrincipalImpl; -import org.jasig.cas.client.validation.AssertionImpl; - -import org.springframework.security.cas.authentication.CasAuthenticationToken; -import org.springframework.security.jackson2.SecurityJackson2Modules; - -/** - * Jackson module for spring-security-cas. This module register - * {@link AssertionImplMixin}, {@link AttributePrincipalImplMixin} and - * {@link CasAuthenticationTokenMixin}. If no default typing enabled by default then it'll - * enable it because typing info is needed to properly serialize/deserialize objects. In - * order to use this module just add this module into your ObjectMapper configuration. - * - *
- *     ObjectMapper mapper = new ObjectMapper();
- *     mapper.registerModule(new CasJackson2Module());
- * 
Note: use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get list - * of all security modules on the classpath. - * - * @author Jitendra Singh. - * @since 4.2 - * @see org.springframework.security.jackson2.SecurityJackson2Modules - */ -public class CasJackson2Module extends SimpleModule { - - public CasJackson2Module() { - super(CasJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null)); - } - - @Override - public void setupModule(SetupContext context) { - SecurityJackson2Modules.enableDefaultTyping(context.getOwner()); - context.setMixInAnnotations(AssertionImpl.class, AssertionImplMixin.class); - context.setMixInAnnotations(AttributePrincipalImpl.class, AttributePrincipalImplMixin.class); - context.setMixInAnnotations(CasAuthenticationToken.class, CasAuthenticationTokenMixin.class); - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/package-info.java b/cas/src/main/java/org/springframework/security/cas/package-info.java deleted file mode 100644 index 13fae9057d0..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Spring Security support for Jasig's Central Authentication Service - * (CAS). - */ -package org.springframework.security.cas; diff --git a/cas/src/main/java/org/springframework/security/cas/userdetails/AbstractCasAssertionUserDetailsService.java b/cas/src/main/java/org/springframework/security/cas/userdetails/AbstractCasAssertionUserDetailsService.java deleted file mode 100644 index 3d8cd9e412a..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/userdetails/AbstractCasAssertionUserDetailsService.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.userdetails; - -import org.jasig.cas.client.validation.Assertion; - -import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken; -import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; -import org.springframework.security.core.userdetails.UserDetails; - -/** - * Abstract class for using the provided CAS assertion to construct a new User object. - * This generally is most useful when combined with a SAML-based response from the CAS - * Server/client. - * - * @author Scott Battaglia - * @since 3.0 - */ -public abstract class AbstractCasAssertionUserDetailsService - implements AuthenticationUserDetailsService { - - @Override - public final UserDetails loadUserDetails(final CasAssertionAuthenticationToken token) { - return loadUserDetails(token.getAssertion()); - } - - /** - * Protected template method for construct a - * {@link org.springframework.security.core.userdetails.UserDetails} via the supplied - * CAS assertion. - * @param assertion the assertion to use to construct the new UserDetails. CANNOT be - * NULL. - * @return the newly constructed UserDetails. - */ - protected abstract UserDetails loadUserDetails(Assertion assertion); - -} diff --git a/cas/src/main/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsService.java b/cas/src/main/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsService.java deleted file mode 100644 index 0e47d1c57f8..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsService.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.userdetails; - -import java.util.ArrayList; -import java.util.List; - -import org.jasig.cas.client.validation.Assertion; - -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.util.Assert; - -/** - * Populates the {@link org.springframework.security.core.GrantedAuthority}s for a user by - * reading a list of attributes that were returned as part of the CAS response. Each - * attribute is read and each value of the attribute is turned into a GrantedAuthority. If - * the attribute has no value then its not added. - * - * @author Scott Battaglia - * @since 3.0 - */ -public final class GrantedAuthorityFromAssertionAttributesUserDetailsService - extends AbstractCasAssertionUserDetailsService { - - private static final String NON_EXISTENT_PASSWORD_VALUE = "NO_PASSWORD"; - - private final String[] attributes; - - private boolean convertToUpperCase = true; - - public GrantedAuthorityFromAssertionAttributesUserDetailsService(final String[] attributes) { - Assert.notNull(attributes, "attributes cannot be null."); - Assert.isTrue(attributes.length > 0, "At least one attribute is required to retrieve roles from."); - this.attributes = attributes; - } - - @SuppressWarnings("unchecked") - @Override - protected UserDetails loadUserDetails(final Assertion assertion) { - List grantedAuthorities = new ArrayList<>(); - for (String attribute : this.attributes) { - Object value = assertion.getPrincipal().getAttributes().get(attribute); - if (value != null) { - if (value instanceof List) { - for (Object o : (List) value) { - grantedAuthorities.add(createSimpleGrantedAuthority(o)); - } - } - else { - grantedAuthorities.add(createSimpleGrantedAuthority(value)); - } - } - } - return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true, - grantedAuthorities); - } - - private SimpleGrantedAuthority createSimpleGrantedAuthority(Object o) { - return new SimpleGrantedAuthority(this.convertToUpperCase ? o.toString().toUpperCase() : o.toString()); - } - - /** - * Converts the returned attribute values to uppercase values. - * @param convertToUpperCase true if it should convert, false otherwise. - */ - public void setConvertToUpperCase(final boolean convertToUpperCase) { - this.convertToUpperCase = convertToUpperCase; - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java deleted file mode 100644 index 25221addf8c..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.web; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.jasig.cas.client.util.CommonUtils; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.util.Assert; - -/** - * Used by the ExceptionTranslationFilter to commence authentication via the - * JA-SIG Central Authentication Service (CAS). - *

- * The user's browser will be redirected to the JA-SIG CAS enterprise-wide login page. - * This page is specified by the loginUrl property. Once login is complete, - * the CAS login page will redirect to the page indicated by the service - * property. The service is a HTTP URL belonging to the current application. - * The service URL is monitored by the {@link CasAuthenticationFilter}, which - * will validate the CAS login was successful. - * - * @author Ben Alex - * @author Scott Battaglia - */ -public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean { - - private ServiceProperties serviceProperties; - - private String loginUrl; - - /** - * Determines whether the Service URL should include the session id for the specific - * user. As of CAS 3.0.5, the session id will automatically be stripped. However, - * older versions of CAS (i.e. CAS 2), do not automatically strip the session - * identifier (this is a bug on the part of the older server implementations), so an - * option to disable the session encoding is provided for backwards compatibility. - * - * By default, encoding is enabled. - */ - private boolean encodeServiceUrlWithSessionId = true; - - @Override - public void afterPropertiesSet() { - Assert.hasLength(this.loginUrl, "loginUrl must be specified"); - Assert.notNull(this.serviceProperties, "serviceProperties must be specified"); - Assert.notNull(this.serviceProperties.getService(), "serviceProperties.getService() cannot be null."); - } - - @Override - public final void commence(final HttpServletRequest servletRequest, HttpServletResponse response, - AuthenticationException authenticationException) throws IOException { - String urlEncodedService = createServiceUrl(servletRequest, response); - String redirectUrl = createRedirectUrl(urlEncodedService); - preCommence(servletRequest, response); - response.sendRedirect(redirectUrl); - } - - /** - * Constructs a new Service Url. The default implementation relies on the CAS client - * to do the bulk of the work. - * @param request the HttpServletRequest - * @param response the HttpServlet Response - * @return the constructed service url. CANNOT be NULL. - */ - protected String createServiceUrl(HttpServletRequest request, HttpServletResponse response) { - return CommonUtils.constructServiceUrl(null, response, this.serviceProperties.getService(), null, - this.serviceProperties.getArtifactParameter(), this.encodeServiceUrlWithSessionId); - } - - /** - * Constructs the Url for Redirection to the CAS server. Default implementation relies - * on the CAS client to do the bulk of the work. - * @param serviceUrl the service url that should be included. - * @return the redirect url. CANNOT be NULL. - */ - protected String createRedirectUrl(String serviceUrl) { - return CommonUtils.constructRedirectUrl(this.loginUrl, this.serviceProperties.getServiceParameter(), serviceUrl, - this.serviceProperties.isSendRenew(), false); - } - - /** - * Template method for you to do your own pre-processing before the redirect occurs. - * @param request the HttpServletRequest - * @param response the HttpServletResponse - */ - protected void preCommence(HttpServletRequest request, HttpServletResponse response) { - - } - - /** - * The enterprise-wide CAS login URL. Usually something like - * https://www.mycompany.com/cas/login. - * @return the enterprise-wide CAS login URL - */ - public final String getLoginUrl() { - return this.loginUrl; - } - - public final ServiceProperties getServiceProperties() { - return this.serviceProperties; - } - - public final void setLoginUrl(String loginUrl) { - this.loginUrl = loginUrl; - } - - public final void setServiceProperties(ServiceProperties serviceProperties) { - this.serviceProperties = serviceProperties; - } - - /** - * Sets whether to encode the service url with the session id or not. - * @param encodeServiceUrlWithSessionId whether to encode the service url with the - * session id or not. - */ - public final void setEncodeServiceUrlWithSessionId(boolean encodeServiceUrlWithSessionId) { - this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId; - } - - /** - * Sets whether to encode the service url with the session id or not. - * @return whether to encode the service url with the session id or not. - * - */ - protected boolean getEncodeServiceUrlWithSessionId() { - return this.encodeServiceUrlWithSessionId; - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java deleted file mode 100644 index 2352887b1f7..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.web; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage; -import org.jasig.cas.client.util.CommonUtils; -import org.jasig.cas.client.validation.TicketValidator; - -import org.springframework.core.log.LogMessage; -import org.springframework.security.authentication.AnonymousAuthenticationToken; -import org.springframework.security.authentication.AuthenticationDetailsSource; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails; -import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; -import org.springframework.security.web.authentication.AuthenticationFailureHandler; -import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; -import org.springframework.security.web.util.matcher.RequestMatcher; -import org.springframework.util.Assert; - -/** - * Processes a CAS service ticket, obtains proxy granting tickets, and processes proxy - * tickets. - *

Service Tickets

- *

- * A service ticket consists of an opaque ticket string. It arrives at this filter by the - * user's browser successfully authenticating using CAS, and then receiving a HTTP - * redirect to a service. The opaque ticket string is presented in the - * ticket request parameter. - *

- * This filter monitors the service URL so it can receive the service ticket - * and process it. By default this filter processes the URL /login/cas. When - * processing this URL, the value of {@link ServiceProperties#getService()} is used as the - * service when validating the ticket. This means that it is - * important that {@link ServiceProperties#getService()} specifies the same value as the - * filterProcessesUrl. - *

- * Processing the service ticket involves creating a - * UsernamePasswordAuthenticationToken which uses - * {@link #CAS_STATEFUL_IDENTIFIER} for the principal and the opaque ticket - * string as the credentials. - *

Obtaining Proxy Granting Tickets

- *

- * If specified, the filter can also monitor the proxyReceptorUrl. The filter - * will respond to requests matching this url so that the CAS Server can provide a PGT to - * the filter. Note that in addition to the proxyReceptorUrl a non-null - * proxyGrantingTicketStorage must be provided in order for the filter to - * respond to proxy receptor requests. By configuring a shared - * {@link ProxyGrantingTicketStorage} between the {@link TicketValidator} and the - * CasAuthenticationFilter one can have the CasAuthenticationFilter handle the proxying - * requirements for CAS. - *

Proxy Tickets

- *

- * The filter can process tickets present on any url. This is useful when wanting to - * process proxy tickets. In order for proxy tickets to get processed - * {@link ServiceProperties#isAuthenticateAllArtifacts()} must return true. - * Additionally, if the request is already authenticated, authentication will not - * occur. Last, {@link AuthenticationDetailsSource#buildDetails(Object)} must return a - * {@link ServiceAuthenticationDetails}. This can be accomplished using the - * {@link ServiceAuthenticationDetailsSource}. In this case - * {@link ServiceAuthenticationDetails#getServiceUrl()} will be used for the service url. - *

- * Processing the proxy ticket involves creating a - * UsernamePasswordAuthenticationToken which uses - * {@link #CAS_STATELESS_IDENTIFIER} for the principal and the opaque ticket - * string as the credentials. When a proxy ticket is successfully - * authenticated, the FilterChain continues and the - * authenticationSuccessHandler is not used. - *

Notes about the AuthenticationManager

- *

- * The configured AuthenticationManager is expected to provide a provider - * that can recognise UsernamePasswordAuthenticationTokens containing this - * special principal name, and process them accordingly by validation with - * the CAS server. Additionally, it should be capable of using the result of - * {@link ServiceAuthenticationDetails#getServiceUrl()} as the service when validating the - * ticket. - *

Example Configuration

- *

- * An example configuration that supports service tickets, obtaining proxy granting - * tickets, and proxy tickets is illustrated below: - * - *

- * <b:bean id="serviceProperties"
- *     class="org.springframework.security.cas.ServiceProperties"
- *     p:service="https://service.example.com/cas-sample/login/cas"
- *     p:authenticateAllArtifacts="true"/>
- * <b:bean id="casEntryPoint"
- *     class="org.springframework.security.cas.web.CasAuthenticationEntryPoint"
- *     p:serviceProperties-ref="serviceProperties" p:loginUrl="https://login.example.org/cas/login" />
- * <b:bean id="casFilter"
- *     class="org.springframework.security.cas.web.CasAuthenticationFilter"
- *     p:authenticationManager-ref="authManager"
- *     p:serviceProperties-ref="serviceProperties"
- *     p:proxyGrantingTicketStorage-ref="pgtStorage"
- *     p:proxyReceptorUrl="/login/cas/proxyreceptor">
- *     <b:property name="authenticationDetailsSource">
- *         <b:bean class="org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource"/>
- *     </b:property>
- *     <b:property name="authenticationFailureHandler">
- *         <b:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
- *             p:defaultFailureUrl="/casfailed.jsp"/>
- *     </b:property>
- * </b:bean>
- * <!--
- *     NOTE: In a real application you should not use an in memory implementation. You will also want
- *           to ensure to clean up expired tickets by calling ProxyGrantingTicketStorage.cleanup()
- *  -->
- * <b:bean id="pgtStorage" class="org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl"/>
- * <b:bean id="casAuthProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider"
- *     p:serviceProperties-ref="serviceProperties"
- *     p:key="casAuthProviderKey">
- *     <b:property name="authenticationUserDetailsService">
- *         <b:bean
- *             class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
- *             <b:constructor-arg ref="userService" />
- *         </b:bean>
- *     </b:property>
- *     <b:property name="ticketValidator">
- *         <b:bean
- *             class="org.jasig.cas.client.validation.Cas20ProxyTicketValidator"
- *             p:acceptAnyProxy="true"
- *             p:proxyCallbackUrl="https://service.example.com/cas-sample/login/cas/proxyreceptor"
- *             p:proxyGrantingTicketStorage-ref="pgtStorage">
- *             <b:constructor-arg value="https://login.example.org/cas" />
- *         </b:bean>
- *     </b:property>
- *     <b:property name="statelessTicketCache">
- *         <b:bean class="org.springframework.security.cas.authentication.EhCacheBasedTicketCache">
- *             <b:property name="cache">
- *                 <b:bean class="net.sf.ehcache.Cache"
- *                   init-method="initialise"
- *                   destroy-method="dispose">
- *                     <b:constructor-arg value="casTickets"/>
- *                     <b:constructor-arg value="50"/>
- *                     <b:constructor-arg value="true"/>
- *                     <b:constructor-arg value="false"/>
- *                     <b:constructor-arg value="3600"/>
- *                     <b:constructor-arg value="900"/>
- *                 </b:bean>
- *             </b:property>
- *         </b:bean>
- *     </b:property>
- * </b:bean>
- * 
- * - * @author Ben Alex - * @author Rob Winch - */ -public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFilter { - - /** - * Used to identify a CAS request for a stateful user agent, such as a web browser. - */ - public static final String CAS_STATEFUL_IDENTIFIER = "_cas_stateful_"; - - /** - * Used to identify a CAS request for a stateless user agent, such as a remoting - * protocol client (e.g. Hessian, Burlap, SOAP etc). Results in a more aggressive - * caching strategy being used, as the absence of a HttpSession will - * result in a new authentication attempt on every request. - */ - public static final String CAS_STATELESS_IDENTIFIER = "_cas_stateless_"; - - /** - * The last portion of the receptor url, i.e. /proxy/receptor - */ - private RequestMatcher proxyReceptorMatcher; - - /** - * The backing storage to store ProxyGrantingTicket requests. - */ - private ProxyGrantingTicketStorage proxyGrantingTicketStorage; - - private String artifactParameter = ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER; - - private boolean authenticateAllArtifacts; - - private AuthenticationFailureHandler proxyFailureHandler = new SimpleUrlAuthenticationFailureHandler(); - - public CasAuthenticationFilter() { - super("/login/cas"); - setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler()); - } - - @Override - protected final void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, - FilterChain chain, Authentication authResult) throws IOException, ServletException { - boolean continueFilterChain = proxyTicketRequest(serviceTicketRequest(request, response), request); - if (!continueFilterChain) { - super.successfulAuthentication(request, response, chain, authResult); - return; - } - this.logger.debug( - LogMessage.format("Authentication success. Updating SecurityContextHolder to contain: %s", authResult)); - SecurityContext context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(authResult); - SecurityContextHolder.setContext(context); - if (this.eventPublisher != null) { - this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); - } - chain.doFilter(request, response); - } - - @Override - public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) - throws AuthenticationException, IOException { - // if the request is a proxy request process it and return null to indicate the - // request has been processed - if (proxyReceptorRequest(request)) { - this.logger.debug("Responding to proxy receptor request"); - CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage); - return null; - } - boolean serviceTicketRequest = serviceTicketRequest(request, response); - String username = serviceTicketRequest ? CAS_STATEFUL_IDENTIFIER : CAS_STATELESS_IDENTIFIER; - String password = obtainArtifact(request); - if (password == null) { - this.logger.debug("Failed to obtain an artifact (cas ticket)"); - password = ""; - } - UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); - authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); - return this.getAuthenticationManager().authenticate(authRequest); - } - - /** - * If present, gets the artifact (CAS ticket) from the {@link HttpServletRequest}. - * @param request - * @return if present the artifact from the {@link HttpServletRequest}, else null - */ - protected String obtainArtifact(HttpServletRequest request) { - return request.getParameter(this.artifactParameter); - } - - /** - * Overridden to provide proxying capabilities. - */ - @Override - protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { - final boolean serviceTicketRequest = serviceTicketRequest(request, response); - final boolean result = serviceTicketRequest || proxyReceptorRequest(request) - || (proxyTicketRequest(serviceTicketRequest, request)); - if (this.logger.isDebugEnabled()) { - this.logger.debug("requiresAuthentication = " + result); - } - return result; - } - - /** - * Sets the {@link AuthenticationFailureHandler} for proxy requests. - * @param proxyFailureHandler - */ - public final void setProxyAuthenticationFailureHandler(AuthenticationFailureHandler proxyFailureHandler) { - Assert.notNull(proxyFailureHandler, "proxyFailureHandler cannot be null"); - this.proxyFailureHandler = proxyFailureHandler; - } - - /** - * Wraps the {@link AuthenticationFailureHandler} to distinguish between handling - * proxy ticket authentication failures and service ticket failures. - */ - @Override - public final void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) { - super.setAuthenticationFailureHandler(new CasAuthenticationFailureHandler(failureHandler)); - } - - public final void setProxyReceptorUrl(final String proxyReceptorUrl) { - this.proxyReceptorMatcher = new AntPathRequestMatcher("/**" + proxyReceptorUrl); - } - - public final void setProxyGrantingTicketStorage(final ProxyGrantingTicketStorage proxyGrantingTicketStorage) { - this.proxyGrantingTicketStorage = proxyGrantingTicketStorage; - } - - public final void setServiceProperties(final ServiceProperties serviceProperties) { - this.artifactParameter = serviceProperties.getArtifactParameter(); - this.authenticateAllArtifacts = serviceProperties.isAuthenticateAllArtifacts(); - } - - /** - * Indicates if the request is elgible to process a service ticket. This method exists - * for readability. - * @param request - * @param response - * @return - */ - private boolean serviceTicketRequest(HttpServletRequest request, HttpServletResponse response) { - boolean result = super.requiresAuthentication(request, response); - this.logger.debug(LogMessage.format("serviceTicketRequest = %s", result)); - return result; - } - - /** - * Indicates if the request is elgible to process a proxy ticket. - * @param request - * @return - */ - private boolean proxyTicketRequest(boolean serviceTicketRequest, HttpServletRequest request) { - if (serviceTicketRequest) { - return false; - } - boolean result = this.authenticateAllArtifacts && obtainArtifact(request) != null && !authenticated(); - this.logger.debug(LogMessage.format("proxyTicketRequest = %s", result)); - return result; - } - - /** - * Determines if a user is already authenticated. - * @return - */ - private boolean authenticated() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - return authentication != null && authentication.isAuthenticated() - && !(authentication instanceof AnonymousAuthenticationToken); - } - - /** - * Indicates if the request is elgible to be processed as the proxy receptor. - * @param request - * @return - */ - private boolean proxyReceptorRequest(HttpServletRequest request) { - final boolean result = proxyReceptorConfigured() && this.proxyReceptorMatcher.matches(request); - this.logger.debug(LogMessage.format("proxyReceptorRequest = %s", result)); - return result; - } - - /** - * Determines if the {@link CasAuthenticationFilter} is configured to handle the proxy - * receptor requests. - * @return - */ - private boolean proxyReceptorConfigured() { - final boolean result = this.proxyGrantingTicketStorage != null && this.proxyReceptorMatcher != null; - this.logger.debug(LogMessage.format("proxyReceptorConfigured = %s", result)); - return result; - } - - /** - * A wrapper for the AuthenticationFailureHandler that will flex the - * {@link AuthenticationFailureHandler} that is used. The value - * {@link CasAuthenticationFilter#setProxyAuthenticationFailureHandler(AuthenticationFailureHandler)} - * will be used for proxy requests that fail. The value - * {@link CasAuthenticationFilter#setAuthenticationFailureHandler(AuthenticationFailureHandler)} - * will be used for service tickets that fail. - */ - private class CasAuthenticationFailureHandler implements AuthenticationFailureHandler { - - private final AuthenticationFailureHandler serviceTicketFailureHandler; - - CasAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) { - Assert.notNull(failureHandler, "failureHandler"); - this.serviceTicketFailureHandler = failureHandler; - } - - @Override - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, - AuthenticationException exception) throws IOException, ServletException { - if (serviceTicketRequest(request, response)) { - this.serviceTicketFailureHandler.onAuthenticationFailure(request, response, exception); - } - else { - CasAuthenticationFilter.this.proxyFailureHandler.onAuthenticationFailure(request, response, exception); - } - } - - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetails.java b/cas/src/main/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetails.java deleted file mode 100644 index 2171df6cfcb..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetails.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2011-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.web.authentication; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.regex.Pattern; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.security.web.authentication.WebAuthenticationDetails; -import org.springframework.security.web.util.UrlUtils; -import org.springframework.util.Assert; - -/** - * A default implementation of {@link ServiceAuthenticationDetails} that figures out the - * value for {@link #getServiceUrl()} by inspecting the current {@link HttpServletRequest} - * and using the current URL minus the artifact and the corresponding value. - * - * @author Rob Winch - */ -final class DefaultServiceAuthenticationDetails extends WebAuthenticationDetails - implements ServiceAuthenticationDetails { - - private static final long serialVersionUID = 6192409090610517700L; - - private final String serviceUrl; - - /** - * Creates a new instance - * @param request the current {@link HttpServletRequest} to obtain the - * {@link #getServiceUrl()} from. - * @param artifactPattern the {@link Pattern} that will be used to clean up the query - * string from containing the artifact name and value. This can be created using - * {@link #createArtifactPattern(String)}. - */ - DefaultServiceAuthenticationDetails(String casService, HttpServletRequest request, Pattern artifactPattern) - throws MalformedURLException { - super(request); - URL casServiceUrl = new URL(casService); - int port = getServicePort(casServiceUrl); - final String query = getQueryString(request, artifactPattern); - this.serviceUrl = UrlUtils.buildFullRequestUrl(casServiceUrl.getProtocol(), casServiceUrl.getHost(), port, - request.getRequestURI(), query); - } - - /** - * Returns the current URL minus the artifact parameter and its value, if present. - * @see org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails#getServiceUrl() - */ - @Override - public String getServiceUrl() { - return this.serviceUrl; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj) || !(obj instanceof DefaultServiceAuthenticationDetails)) { - return false; - } - ServiceAuthenticationDetails that = (ServiceAuthenticationDetails) obj; - return this.serviceUrl.equals(that.getServiceUrl()); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + this.serviceUrl.hashCode(); - return result; - } - - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - result.append(super.toString()); - result.append("ServiceUrl: "); - result.append(this.serviceUrl); - return result.toString(); - } - - /** - * If present, removes the artifactParameterName and the corresponding value from the - * query String. - * @param request - * @return the query String minus the artifactParameterName and the corresponding - * value. - */ - private String getQueryString(final HttpServletRequest request, final Pattern artifactPattern) { - final String query = request.getQueryString(); - if (query == null) { - return null; - } - String result = artifactPattern.matcher(query).replaceFirst(""); - if (result.length() == 0) { - return null; - } - // strip off the trailing & only if the artifact was the first query param - return result.startsWith("&") ? result.substring(1) : result; - } - - /** - * Creates a {@link Pattern} that can be passed into the constructor. This allows the - * {@link Pattern} to be reused for every instance of - * {@link DefaultServiceAuthenticationDetails}. - * @param artifactParameterName - * @return - */ - static Pattern createArtifactPattern(String artifactParameterName) { - Assert.hasLength(artifactParameterName, "artifactParameterName is expected to have a length"); - return Pattern.compile("&?" + Pattern.quote(artifactParameterName) + "=[^&]*"); - } - - /** - * Gets the port from the casServiceURL ensuring to return the proper value if the - * default port is being used. - * @param casServiceUrl the casServerUrl to be used (i.e. - * "https://example.com/context/login/cas") - * @return the port that is configured for the casServerUrl - */ - private static int getServicePort(URL casServiceUrl) { - int port = casServiceUrl.getPort(); - if (port == -1) { - port = casServiceUrl.getDefaultPort(); - } - return port; - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetails.java b/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetails.java deleted file mode 100644 index e14da3d70e6..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetails.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2011-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.web.authentication; - -import java.io.Serializable; - -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.core.Authentication; - -/** - * In order for the {@link CasAuthenticationProvider} to provide the correct service url - * to authenticate the ticket, the returned value of {@link Authentication#getDetails()} - * should implement this interface when tickets can be sent to any URL rather than only - * {@link ServiceProperties#getService()}. - * - * @author Rob Winch - * @see ServiceAuthenticationDetailsSource - */ -public interface ServiceAuthenticationDetails extends Serializable { - - /** - * Gets the absolute service url (i.e. https://example.com/service/). - * @return the service url. Cannot be null. - */ - String getServiceUrl(); - -} diff --git a/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetailsSource.java b/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetailsSource.java deleted file mode 100644 index 375952373f5..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetailsSource.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2011-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.web.authentication; - -import java.net.MalformedURLException; -import java.util.regex.Pattern; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.security.authentication.AuthenticationDetailsSource; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.util.Assert; - -/** - * The {@code AuthenticationDetailsSource} that is set on the - * {@code CasAuthenticationFilter} should return a value that implements - * {@code ServiceAuthenticationDetails} if the application needs to authenticate dynamic - * service urls. The - * {@code ServiceAuthenticationDetailsSource#buildDetails(HttpServletRequest)} creates a - * default {@code ServiceAuthenticationDetails}. - * - * @author Rob Winch - */ -public class ServiceAuthenticationDetailsSource - implements AuthenticationDetailsSource { - - private final Pattern artifactPattern; - - private ServiceProperties serviceProperties; - - /** - * Creates an implementation that uses the specified ServiceProperties and the default - * CAS artifactParameterName. - * @param serviceProperties The ServiceProperties to use to construct the serviceUrl. - */ - public ServiceAuthenticationDetailsSource(ServiceProperties serviceProperties) { - this(serviceProperties, ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER); - } - - /** - * Creates an implementation that uses the specified artifactParameterName - * @param serviceProperties The ServiceProperties to use to construct the serviceUrl. - * @param artifactParameterName the artifactParameterName that is removed from the - * current URL. The result becomes the service url. Cannot be null and cannot be an - * empty String. - */ - public ServiceAuthenticationDetailsSource(ServiceProperties serviceProperties, String artifactParameterName) { - Assert.notNull(serviceProperties, "serviceProperties cannot be null"); - this.serviceProperties = serviceProperties; - this.artifactPattern = DefaultServiceAuthenticationDetails.createArtifactPattern(artifactParameterName); - } - - /** - * @param context the {@code HttpServletRequest} object. - * @return the {@code ServiceAuthenticationDetails} containing information about the - * current request - */ - @Override - public ServiceAuthenticationDetails buildDetails(HttpServletRequest context) { - try { - return new DefaultServiceAuthenticationDetails(this.serviceProperties.getService(), context, - this.artifactPattern); - } - catch (MalformedURLException ex) { - throw new RuntimeException(ex); - } - } - -} diff --git a/cas/src/main/java/org/springframework/security/cas/web/authentication/package-info.java b/cas/src/main/java/org/springframework/security/cas/web/authentication/package-info.java deleted file mode 100644 index ecd447dbac6..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/web/authentication/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Authentication processing mechanisms which respond to the submission of authentication - * credentials using CAS. - */ -package org.springframework.security.cas.web.authentication; diff --git a/cas/src/main/java/org/springframework/security/cas/web/package-info.java b/cas/src/main/java/org/springframework/security/cas/web/package-info.java deleted file mode 100644 index 903fdb8d4c0..00000000000 --- a/cas/src/main/java/org/springframework/security/cas/web/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Authenticates standard web browser users via CAS. - */ -package org.springframework.security.cas.web; diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/AbstractStatelessTicketCacheTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/AbstractStatelessTicketCacheTests.java deleted file mode 100644 index 7f1233b7d5f..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/authentication/AbstractStatelessTicketCacheTests.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import java.util.ArrayList; -import java.util.List; - -import org.jasig.cas.client.validation.Assertion; -import org.jasig.cas.client.validation.AssertionImpl; - -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.User; - -/** - * @author Scott Battaglia - * @since 2.0 - * - */ -public abstract class AbstractStatelessTicketCacheTests { - - protected CasAuthenticationToken getToken() { - List proxyList = new ArrayList<>(); - proxyList.add("https://localhost/newPortal/login/cas"); - User user = new User("rod", "password", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); - final Assertion assertion = new AssertionImpl("rod"); - return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ", - AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), user, assertion); - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java deleted file mode 100644 index 242d32a730d..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java +++ /dev/null @@ -1,382 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import java.util.HashMap; -import java.util.Map; - -import org.jasig.cas.client.validation.Assertion; -import org.jasig.cas.client.validation.AssertionImpl; -import org.jasig.cas.client.validation.TicketValidator; -import org.junit.jupiter.api.Test; - -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.web.CasAuthenticationFilter; -import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.web.authentication.WebAuthenticationDetails; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * Tests {@link CasAuthenticationProvider}. - * - * @author Ben Alex - * @author Scott Battaglia - */ -@SuppressWarnings("unchecked") -public class CasAuthenticationProviderTests { - - private UserDetails makeUserDetails() { - return new User("user", "password", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); - } - - private UserDetails makeUserDetailsFromAuthoritiesPopulator() { - return new User("user", "password", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B")); - } - - private ServiceProperties makeServiceProperties() { - final ServiceProperties serviceProperties = new ServiceProperties(); - serviceProperties.setSendRenew(false); - serviceProperties.setService("http://test.com"); - return serviceProperties; - } - - @Test - public void statefulAuthenticationIsSuccessful() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - StatelessTicketCache cache = new MockStatelessTicketCache(); - cap.setStatelessTicketCache(cache); - cap.setServiceProperties(makeServiceProperties()); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.afterPropertiesSet(); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( - CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, "ST-123"); - token.setDetails("details"); - Authentication result = cap.authenticate(token); - // Confirm ST-123 was NOT added to the cache - assertThat(cache.getByTicketId("ST-456") == null).isTrue(); - if (!(result instanceof CasAuthenticationToken)) { - fail("Should have returned a CasAuthenticationToken"); - } - CasAuthenticationToken casResult = (CasAuthenticationToken) result; - assertThat(casResult.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator()); - assertThat(casResult.getCredentials()).isEqualTo("ST-123"); - assertThat(casResult.getAuthorities()).contains(new SimpleGrantedAuthority("ROLE_A")); - assertThat(casResult.getAuthorities()).contains(new SimpleGrantedAuthority("ROLE_B")); - assertThat(casResult.getKeyHash()).isEqualTo(cap.getKey().hashCode()); - assertThat(casResult.getDetails()).isEqualTo("details"); - // Now confirm the CasAuthenticationToken is automatically re-accepted. - // To ensure TicketValidator not called again, set it to deliver an exception... - cap.setTicketValidator(new MockTicketValidator(false)); - Authentication laterResult = cap.authenticate(result); - assertThat(laterResult).isEqualTo(result); - } - - @Test - public void statelessAuthenticationIsSuccessful() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - StatelessTicketCache cache = new MockStatelessTicketCache(); - cap.setStatelessTicketCache(cache); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.setServiceProperties(makeServiceProperties()); - cap.afterPropertiesSet(); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( - CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, "ST-456"); - token.setDetails("details"); - Authentication result = cap.authenticate(token); - // Confirm ST-456 was added to the cache - assertThat(cache.getByTicketId("ST-456") != null).isTrue(); - if (!(result instanceof CasAuthenticationToken)) { - fail("Should have returned a CasAuthenticationToken"); - } - assertThat(result.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator()); - assertThat(result.getCredentials()).isEqualTo("ST-456"); - assertThat(result.getDetails()).isEqualTo("details"); - // Now try to authenticate again. To ensure TicketValidator not - // called again, set it to deliver an exception... - cap.setTicketValidator(new MockTicketValidator(false)); - // Previously created UsernamePasswordAuthenticationToken is OK - Authentication newResult = cap.authenticate(token); - assertThat(newResult.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator()); - assertThat(newResult.getCredentials()).isEqualTo("ST-456"); - } - - @Test - public void authenticateAllNullService() throws Exception { - String serviceUrl = "https://service/context"; - ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class); - given(details.getServiceUrl()).willReturn(serviceUrl); - TicketValidator validator = mock(TicketValidator.class); - given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod")); - ServiceProperties serviceProperties = makeServiceProperties(); - serviceProperties.setAuthenticateAllArtifacts(true); - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - cap.setTicketValidator(validator); - cap.setServiceProperties(serviceProperties); - cap.afterPropertiesSet(); - String ticket = "ST-456"; - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( - CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, ticket); - Authentication result = cap.authenticate(token); - } - - @Test - public void authenticateAllAuthenticationIsSuccessful() throws Exception { - String serviceUrl = "https://service/context"; - ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class); - given(details.getServiceUrl()).willReturn(serviceUrl); - TicketValidator validator = mock(TicketValidator.class); - given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod")); - ServiceProperties serviceProperties = makeServiceProperties(); - serviceProperties.setAuthenticateAllArtifacts(true); - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - cap.setTicketValidator(validator); - cap.setServiceProperties(serviceProperties); - cap.afterPropertiesSet(); - String ticket = "ST-456"; - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( - CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, ticket); - Authentication result = cap.authenticate(token); - verify(validator).validate(ticket, serviceProperties.getService()); - serviceProperties.setAuthenticateAllArtifacts(true); - result = cap.authenticate(token); - verify(validator, times(2)).validate(ticket, serviceProperties.getService()); - token.setDetails(details); - result = cap.authenticate(token); - verify(validator).validate(ticket, serviceUrl); - serviceProperties.setAuthenticateAllArtifacts(false); - serviceProperties.setService(null); - cap.setServiceProperties(serviceProperties); - cap.afterPropertiesSet(); - result = cap.authenticate(token); - verify(validator, times(2)).validate(ticket, serviceUrl); - token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); - assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token)); - cap.setServiceProperties(null); - cap.afterPropertiesSet(); - assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token)); - } - - @Test - public void missingTicketIdIsDetected() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - StatelessTicketCache cache = new MockStatelessTicketCache(); - cap.setStatelessTicketCache(cache); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.setServiceProperties(makeServiceProperties()); - cap.afterPropertiesSet(); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( - CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, ""); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token)); - } - - @Test - public void invalidKeyIsDetected() throws Exception { - final Assertion assertion = new AssertionImpl("test"); - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - StatelessTicketCache cache = new MockStatelessTicketCache(); - cap.setStatelessTicketCache(cache); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.setServiceProperties(makeServiceProperties()); - cap.afterPropertiesSet(); - CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials", - AuthorityUtils.createAuthorityList("XX"), makeUserDetails(), assertion); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token)); - } - - @Test - public void detectsMissingAuthoritiesPopulator() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setKey("qwerty"); - cap.setStatelessTicketCache(new MockStatelessTicketCache()); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.setServiceProperties(makeServiceProperties()); - assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet()); - } - - @Test - public void detectsMissingKey() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setStatelessTicketCache(new MockStatelessTicketCache()); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.setServiceProperties(makeServiceProperties()); - assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet()); - } - - @Test - public void detectsMissingStatelessTicketCache() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - // set this explicitly to null to test failure - cap.setStatelessTicketCache(null); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.setServiceProperties(makeServiceProperties()); - assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet()); - } - - @Test - public void detectsMissingTicketValidator() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - cap.setStatelessTicketCache(new MockStatelessTicketCache()); - cap.setServiceProperties(makeServiceProperties()); - assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet()); - } - - @Test - public void gettersAndSettersMatch() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - cap.setStatelessTicketCache(new MockStatelessTicketCache()); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.setServiceProperties(makeServiceProperties()); - cap.afterPropertiesSet(); - // TODO disabled because why do we need to expose this? - // assertThat(cap.getUserDetailsService() != null).isTrue(); - assertThat(cap.getKey()).isEqualTo("qwerty"); - assertThat(cap.getStatelessTicketCache() != null).isTrue(); - assertThat(cap.getTicketValidator() != null).isTrue(); - } - - @Test - public void ignoresClassesItDoesNotSupport() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - cap.setStatelessTicketCache(new MockStatelessTicketCache()); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.setServiceProperties(makeServiceProperties()); - cap.afterPropertiesSet(); - TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password", "ROLE_A"); - assertThat(cap.supports(TestingAuthenticationToken.class)).isFalse(); - // Try it anyway - assertThat(cap.authenticate(token)).isNull(); - } - - @Test - public void ignoresUsernamePasswordAuthenticationTokensWithoutCasIdentifiersAsPrincipal() throws Exception { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); - cap.setKey("qwerty"); - cap.setStatelessTicketCache(new MockStatelessTicketCache()); - cap.setTicketValidator(new MockTicketValidator(true)); - cap.setServiceProperties(makeServiceProperties()); - cap.afterPropertiesSet(); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user", - "password", AuthorityUtils.createAuthorityList("ROLE_A")); - assertThat(cap.authenticate(token)).isNull(); - } - - @Test - public void supportsRequiredTokens() { - CasAuthenticationProvider cap = new CasAuthenticationProvider(); - assertThat(cap.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); - assertThat(cap.supports(CasAuthenticationToken.class)).isTrue(); - } - - private class MockAuthoritiesPopulator implements AuthenticationUserDetailsService { - - @Override - public UserDetails loadUserDetails(final Authentication token) throws UsernameNotFoundException { - return makeUserDetailsFromAuthoritiesPopulator(); - } - - } - - private class MockStatelessTicketCache implements StatelessTicketCache { - - private Map cache = new HashMap<>(); - - @Override - public CasAuthenticationToken getByTicketId(String serviceTicket) { - return this.cache.get(serviceTicket); - } - - @Override - public void putTicketInCache(CasAuthenticationToken token) { - this.cache.put(token.getCredentials().toString(), token); - } - - @Override - public void removeTicketFromCache(CasAuthenticationToken token) { - throw new UnsupportedOperationException("mock method not implemented"); - } - - @Override - public void removeTicketFromCache(String serviceTicket) { - throw new UnsupportedOperationException("mock method not implemented"); - } - - } - - private class MockTicketValidator implements TicketValidator { - - private boolean returnTicket; - - MockTicketValidator(boolean returnTicket) { - this.returnTicket = returnTicket; - } - - @Override - public Assertion validate(final String ticket, final String service) { - if (this.returnTicket) { - return new AssertionImpl("rod"); - } - throw new BadCredentialsException("As requested from mock"); - } - - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java deleted file mode 100644 index 8ac076830be..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import java.util.Collections; -import java.util.List; - -import org.jasig.cas.client.validation.Assertion; -import org.jasig.cas.client.validation.AssertionImpl; -import org.junit.jupiter.api.Test; - -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests {@link CasAuthenticationToken}. - * - * @author Ben Alex - */ -public class CasAuthenticationTokenTests { - - private final List ROLES = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"); - - private UserDetails makeUserDetails() { - return makeUserDetails("user"); - } - - private UserDetails makeUserDetails(final String name) { - return new User(name, "password", true, true, true, true, this.ROLES); - } - - @Test - public void testConstructorRejectsNulls() { - Assertion assertion = new AssertionImpl("test"); - assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken(null, makeUserDetails(), - "Password", this.ROLES, makeUserDetails(), assertion)); - assertThatIllegalArgumentException().isThrownBy( - () -> new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion)); - assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), null, - this.ROLES, makeUserDetails(), assertion)); - assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), - "Password", this.ROLES, makeUserDetails(), null)); - assertThatIllegalArgumentException().isThrownBy( - () -> new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion)); - assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), - "Password", AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion)); - } - - @Test - public void constructorWhenEmptyKeyThenThrowsException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new CasAuthenticationToken("", "user", "password", Collections.emptyList(), - new User("user", "password", Collections.emptyList()), null)); - } - - @Test - public void testEqualsWhenEqual() { - final Assertion assertion = new AssertionImpl("test"); - CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion); - CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion); - assertThat(token2).isEqualTo(token1); - } - - @Test - public void testGetters() { - // Build the proxy list returned in the ticket from CAS - final Assertion assertion = new AssertionImpl("test"); - CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion); - assertThat(token.getKeyHash()).isEqualTo("key".hashCode()); - assertThat(token.getPrincipal()).isEqualTo(makeUserDetails()); - assertThat(token.getCredentials()).isEqualTo("Password"); - assertThat(token.getAuthorities()).contains(new SimpleGrantedAuthority("ROLE_ONE")); - assertThat(token.getAuthorities()).contains(new SimpleGrantedAuthority("ROLE_TWO")); - assertThat(token.getAssertion()).isEqualTo(assertion); - assertThat(token.getUserDetails().getUsername()).isEqualTo(makeUserDetails().getUsername()); - } - - @Test - public void testNoArgConstructorDoesntExist() { - assertThatExceptionOfType(NoSuchMethodException.class) - .isThrownBy(() -> CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null)); - } - - @Test - public void testNotEqualsDueToAbstractParentEqualsCheck() { - final Assertion assertion = new AssertionImpl("test"); - CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion); - CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails("OTHER_NAME"), "Password", - this.ROLES, makeUserDetails(), assertion); - assertThat(!token1.equals(token2)).isTrue(); - } - - @Test - public void testNotEqualsDueToDifferentAuthenticationClass() { - final Assertion assertion = new AssertionImpl("test"); - CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion); - UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password", - this.ROLES); - assertThat(!token1.equals(token2)).isTrue(); - } - - @Test - public void testNotEqualsDueToKey() { - final Assertion assertion = new AssertionImpl("test"); - CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion); - CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY", makeUserDetails(), "Password", - this.ROLES, makeUserDetails(), assertion); - assertThat(!token1.equals(token2)).isTrue(); - } - - @Test - public void testNotEqualsDueToAssertion() { - final Assertion assertion = new AssertionImpl("test"); - final Assertion assertion2 = new AssertionImpl("test"); - CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion); - CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion2); - assertThat(!token1.equals(token2)).isTrue(); - } - - @Test - public void testSetAuthenticated() { - final Assertion assertion = new AssertionImpl("test"); - CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion); - assertThat(token.isAuthenticated()).isTrue(); - token.setAuthenticated(false); - assertThat(!token.isAuthenticated()).isTrue(); - } - - @Test - public void testToString() { - final Assertion assertion = new AssertionImpl("test"); - CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, - makeUserDetails(), assertion); - String result = token.toString(); - assertThat(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1).isTrue(); - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCacheTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCacheTests.java deleted file mode 100644 index c824eef4bc6..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCacheTests.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import net.sf.ehcache.Cache; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Ehcache; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests {@link EhCacheBasedTicketCache}. - * - * @author Ben Alex - */ -public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTests { - - private static CacheManager cacheManager; - - @BeforeAll - public static void initCacheManaer() { - cacheManager = CacheManager.create(); - cacheManager.addCache(new Cache("castickets", 500, false, false, 30, 30)); - } - - @AfterAll - public static void shutdownCacheManager() { - cacheManager.removalAll(); - cacheManager.shutdown(); - } - - @Test - public void testCacheOperation() throws Exception { - EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache(); - cache.setCache(cacheManager.getCache("castickets")); - cache.afterPropertiesSet(); - final CasAuthenticationToken token = getToken(); - // Check it gets stored in the cache - cache.putTicketInCache(token); - assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isEqualTo(token); - // Check it gets removed from the cache - cache.removeTicketFromCache(getToken()); - assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isNull(); - // Check it doesn't return values for null or unknown service tickets - assertThat(cache.getByTicketId(null)).isNull(); - assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull(); - } - - @Test - public void testStartupDetectsMissingCache() throws Exception { - EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache(); - assertThatIllegalArgumentException().isThrownBy(cache::afterPropertiesSet); - Ehcache myCache = cacheManager.getCache("castickets"); - cache.setCache(myCache); - assertThat(cache.getCache()).isEqualTo(myCache); - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/NullStatelessTicketCacheTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/NullStatelessTicketCacheTests.java deleted file mode 100644 index f5a87e5c4e9..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/authentication/NullStatelessTicketCacheTests.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Test cases for the @link {@link NullStatelessTicketCache} - * - * @author Scott Battaglia - * - */ -public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheTests { - - private StatelessTicketCache cache = new NullStatelessTicketCache(); - - @Test - public void testGetter() { - assertThat(this.cache.getByTicketId(null)).isNull(); - assertThat(this.cache.getByTicketId("test")).isNull(); - } - - @Test - public void testInsertAndGet() { - final CasAuthenticationToken token = getToken(); - this.cache.putTicketInCache(token); - assertThat(this.cache.getByTicketId((String) token.getCredentials())).isNull(); - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCacheTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCacheTests.java deleted file mode 100644 index e27344a9ce6..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCacheTests.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.authentication; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import org.springframework.cache.CacheManager; -import org.springframework.cache.concurrent.ConcurrentMapCacheManager; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests - * {@link org.springframework.security.cas.authentication.SpringCacheBasedTicketCache}. - * - * @author Marten Deinum - * @since 3.2 - */ -public class SpringCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTests { - - private static CacheManager cacheManager; - - @BeforeAll - public static void initCacheManaer() { - cacheManager = new ConcurrentMapCacheManager(); - cacheManager.getCache("castickets"); - } - - @Test - public void testCacheOperation() throws Exception { - SpringCacheBasedTicketCache cache = new SpringCacheBasedTicketCache(cacheManager.getCache("castickets")); - final CasAuthenticationToken token = getToken(); - // Check it gets stored in the cache - cache.putTicketInCache(token); - assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isEqualTo(token); - // Check it gets removed from the cache - cache.removeTicketFromCache(getToken()); - assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isNull(); - // Check it doesn't return values for null or unknown service tickets - assertThat(cache.getByTicketId(null)).isNull(); - assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull(); - } - - @Test - public void testStartupDetectsMissingCache() throws Exception { - assertThatIllegalArgumentException().isThrownBy(() -> new SpringCacheBasedTicketCache(null)); - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixinTests.java b/cas/src/test/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixinTests.java deleted file mode 100644 index ce333d4d83f..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixinTests.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright 2015-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.jackson2; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.jasig.cas.client.authentication.AttributePrincipalImpl; -import org.jasig.cas.client.validation.Assertion; -import org.jasig.cas.client.validation.AssertionImpl; -import org.json.JSONException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; - -import org.springframework.security.cas.authentication.CasAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.jackson2.SecurityJackson2Modules; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Jitendra Singh - * @since 4.2 - */ -public class CasAuthenticationTokenMixinTests { - - private static final String KEY = "casKey"; - - private static final String PASSWORD = "\"1234\""; - - private static final Date START_DATE = new Date(); - - private static final Date END_DATE = new Date(); - - public static final String AUTHORITY_JSON = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"authority\": \"ROLE_USER\"}"; - - public static final String AUTHORITIES_SET_JSON = "[\"java.util.Collections$UnmodifiableSet\", [" + AUTHORITY_JSON - + "]]"; - - public static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", [" - + AUTHORITY_JSON + "]]"; - - // @formatter:off - public static final String USER_JSON = "{" - + "\"@class\": \"org.springframework.security.core.userdetails.User\", " - + "\"username\": \"admin\"," - + " \"password\": " + PASSWORD + ", " - + "\"accountNonExpired\": true, " - + "\"accountNonLocked\": true, " - + "\"credentialsNonExpired\": true, " - + "\"enabled\": true, " - + "\"authorities\": " + AUTHORITIES_SET_JSON - + "}"; - // @formatter:on - private static final String CAS_TOKEN_JSON = "{" - + "\"@class\": \"org.springframework.security.cas.authentication.CasAuthenticationToken\", " - + "\"keyHash\": " + KEY.hashCode() + "," + "\"principal\": " + USER_JSON + ", " + "\"credentials\": " - + PASSWORD + ", " + "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + "," + "\"userDetails\": " + USER_JSON - + "," + "\"authenticated\": true, " + "\"details\": null," + "\"assertion\": {" - + "\"@class\": \"org.jasig.cas.client.validation.AssertionImpl\", " + "\"principal\": {" - + "\"@class\": \"org.jasig.cas.client.authentication.AttributePrincipalImpl\", " - + "\"name\": \"assertName\", " + "\"attributes\": {\"@class\": \"java.util.Collections$EmptyMap\"}, " - + "\"proxyGrantingTicket\": null, " + "\"proxyRetriever\": null" + "}, " - + "\"validFromDate\": [\"java.util.Date\", " + START_DATE.getTime() + "], " - + "\"validUntilDate\": [\"java.util.Date\", " + END_DATE.getTime() + "]," - + "\"authenticationDate\": [\"java.util.Date\", " + START_DATE.getTime() + "], " - + "\"attributes\": {\"@class\": \"java.util.Collections$EmptyMap\"}" + "}" + "}"; - - private static final String CAS_TOKEN_CLEARED_JSON = CAS_TOKEN_JSON.replaceFirst(PASSWORD, "null"); - - protected ObjectMapper mapper; - - @BeforeEach - public void setup() { - this.mapper = new ObjectMapper(); - ClassLoader loader = getClass().getClassLoader(); - this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); - } - - @Test - public void serializeCasAuthenticationTest() throws JsonProcessingException, JSONException { - CasAuthenticationToken token = createCasAuthenticationToken(); - String actualJson = this.mapper.writeValueAsString(token); - JSONAssert.assertEquals(CAS_TOKEN_JSON, actualJson, true); - } - - @Test - public void serializeCasAuthenticationTestAfterEraseCredentialInvoked() - throws JsonProcessingException, JSONException { - CasAuthenticationToken token = createCasAuthenticationToken(); - token.eraseCredentials(); - String actualJson = this.mapper.writeValueAsString(token); - JSONAssert.assertEquals(CAS_TOKEN_CLEARED_JSON, actualJson, true); - } - - @Test - public void deserializeCasAuthenticationTestAfterEraseCredentialInvoked() throws Exception { - CasAuthenticationToken token = this.mapper.readValue(CAS_TOKEN_CLEARED_JSON, CasAuthenticationToken.class); - assertThat(((UserDetails) token.getPrincipal()).getPassword()).isNull(); - } - - @Test - public void deserializeCasAuthenticationTest() throws IOException { - CasAuthenticationToken token = this.mapper.readValue(CAS_TOKEN_JSON, CasAuthenticationToken.class); - assertThat(token).isNotNull(); - assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class); - assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin"); - assertThat(((User) token.getPrincipal()).getPassword()).isEqualTo("1234"); - assertThat(token.getUserDetails()).isNotNull().isInstanceOf(User.class); - assertThat(token.getAssertion()).isNotNull().isInstanceOf(AssertionImpl.class); - assertThat(token.getKeyHash()).isEqualTo(KEY.hashCode()); - assertThat(token.getUserDetails().getAuthorities()).extracting(GrantedAuthority::getAuthority) - .containsOnly("ROLE_USER"); - assertThat(token.getAssertion().getAuthenticationDate()).isEqualTo(START_DATE); - assertThat(token.getAssertion().getValidFromDate()).isEqualTo(START_DATE); - assertThat(token.getAssertion().getValidUntilDate()).isEqualTo(END_DATE); - assertThat(token.getAssertion().getPrincipal().getName()).isEqualTo("assertName"); - assertThat(token.getAssertion().getAttributes()).hasSize(0); - } - - private CasAuthenticationToken createCasAuthenticationToken() { - User principal = new User("admin", "1234", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); - Collection authorities = Collections - .singletonList(new SimpleGrantedAuthority("ROLE_USER")); - Assertion assertion = new AssertionImpl(new AttributePrincipalImpl("assertName"), START_DATE, END_DATE, - START_DATE, Collections.emptyMap()); - return new CasAuthenticationToken(KEY, principal, principal.getPassword(), authorities, - new User("admin", "1234", authorities), assertion); - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests.java b/cas/src/test/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests.java deleted file mode 100644 index 3db719dcc28..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2002-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.userdetails; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import org.jasig.cas.client.authentication.AttributePrincipal; -import org.jasig.cas.client.validation.Assertion; -import org.junit.jupiter.api.Test; - -import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.UserDetails; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * @author Luke Taylor - */ -public class GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests { - - @Test - public void correctlyExtractsNamedAttributesFromAssertionAndConvertsThemToAuthorities() { - GrantedAuthorityFromAssertionAttributesUserDetailsService uds = new GrantedAuthorityFromAssertionAttributesUserDetailsService( - new String[] { "a", "b", "c", "d" }); - uds.setConvertToUpperCase(false); - Assertion assertion = mock(Assertion.class); - AttributePrincipal principal = mock(AttributePrincipal.class); - Map attributes = new HashMap<>(); - attributes.put("a", Arrays.asList("role_a1", "role_a2")); - attributes.put("b", "role_b"); - attributes.put("c", "role_c"); - attributes.put("d", null); - attributes.put("someother", "unused"); - given(assertion.getPrincipal()).willReturn(principal); - given(principal.getAttributes()).willReturn(attributes); - given(principal.getName()).willReturn("somebody"); - CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(assertion, "ticket"); - UserDetails user = uds.loadUserDetails(token); - Set roles = AuthorityUtils.authorityListToSet(user.getAuthorities()); - assertThat(roles).containsExactlyInAnyOrder("role_a1", "role_a2", "role_b", "role_c"); - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java deleted file mode 100644 index 5fb0e7c7f8c..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.web; - -import java.net.URLEncoder; - -import org.junit.jupiter.api.Test; - -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.security.cas.ServiceProperties; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests {@link CasAuthenticationEntryPoint}. - * - * @author Ben Alex - */ -public class CasAuthenticationEntryPointTests { - - @Test - public void testDetectsMissingLoginFormUrl() throws Exception { - CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); - ep.setServiceProperties(new ServiceProperties()); - assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) - .withMessage("loginUrl must be specified"); - } - - @Test - public void testDetectsMissingServiceProperties() throws Exception { - CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); - ep.setLoginUrl("https://cas/login"); - assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) - .withMessage("serviceProperties must be specified"); - } - - @Test - public void testGettersSetters() { - CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); - ep.setLoginUrl("https://cas/login"); - assertThat(ep.getLoginUrl()).isEqualTo("https://cas/login"); - ep.setServiceProperties(new ServiceProperties()); - assertThat(ep.getServiceProperties() != null).isTrue(); - } - - @Test - public void testNormalOperationWithRenewFalse() throws Exception { - ServiceProperties sp = new ServiceProperties(); - sp.setSendRenew(false); - sp.setService("https://mycompany.com/bigWebApp/login/cas"); - CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); - ep.setLoginUrl("https://cas/login"); - ep.setServiceProperties(sp); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/some_path"); - MockHttpServletResponse response = new MockHttpServletResponse(); - ep.afterPropertiesSet(); - ep.commence(request, response, null); - assertThat( - "https://cas/login?service=" + URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", "UTF-8")) - .isEqualTo(response.getRedirectedUrl()); - } - - @Test - public void testNormalOperationWithRenewTrue() throws Exception { - ServiceProperties sp = new ServiceProperties(); - sp.setSendRenew(true); - sp.setService("https://mycompany.com/bigWebApp/login/cas"); - CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); - ep.setLoginUrl("https://cas/login"); - ep.setServiceProperties(sp); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/some_path"); - MockHttpServletResponse response = new MockHttpServletResponse(); - ep.afterPropertiesSet(); - ep.commence(request, response, null); - assertThat("https://cas/login?service=" - + URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", "UTF-8") + "&renew=true") - .isEqualTo(response.getRedirectedUrl()); - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java deleted file mode 100644 index fab4d2ed1d9..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.web; - -import javax.servlet.FilterChain; - -import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.security.authentication.AnonymousAuthenticationToken; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.AuthenticationSuccessHandler; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; - -/** - * Tests {@link CasAuthenticationFilter}. - * - * @author Ben Alex - * @author Rob Winch - */ -public class CasAuthenticationFilterTests { - - @AfterEach - public void tearDown() { - SecurityContextHolder.clearContext(); - } - - @Test - public void testGettersSetters() { - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); - filter.setProxyReceptorUrl("/someurl"); - filter.setServiceProperties(new ServiceProperties()); - } - - @Test - public void testNormalOperation() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setServletPath("/login/cas"); - request.addParameter("ticket", "ST-0-ER94xMJmn6pha35CQRoZ"); - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setAuthenticationManager((a) -> a); - assertThat(filter.requiresAuthentication(request, new MockHttpServletResponse())).isTrue(); - Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); - assertThat(result != null).isTrue(); - } - - @Test - public void testNullServiceTicketHandledGracefully() throws Exception { - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setAuthenticationManager((a) -> { - throw new BadCredentialsException("Rejected"); - }); - assertThatExceptionOfType(AuthenticationException.class).isThrownBy( - () -> filter.attemptAuthentication(new MockHttpServletRequest(), new MockHttpServletResponse())); - } - - @Test - public void testRequiresAuthenticationFilterProcessUrl() { - String url = "/login/cas"; - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setFilterProcessesUrl(url); - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - request.setServletPath(url); - assertThat(filter.requiresAuthentication(request, response)).isTrue(); - } - - @Test - public void testRequiresAuthenticationProxyRequest() { - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - request.setServletPath("/pgtCallback"); - assertThat(filter.requiresAuthentication(request, response)).isFalse(); - filter.setProxyReceptorUrl(request.getServletPath()); - assertThat(filter.requiresAuthentication(request, response)).isFalse(); - filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); - assertThat(filter.requiresAuthentication(request, response)).isTrue(); - request.setServletPath("/other"); - assertThat(filter.requiresAuthentication(request, response)).isFalse(); - } - - @Test - public void testRequiresAuthenticationAuthAll() { - ServiceProperties properties = new ServiceProperties(); - properties.setAuthenticateAllArtifacts(true); - String url = "/login/cas"; - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setFilterProcessesUrl(url); - filter.setServiceProperties(properties); - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - request.setServletPath(url); - assertThat(filter.requiresAuthentication(request, response)).isTrue(); - request.setServletPath("/other"); - assertThat(filter.requiresAuthentication(request, response)).isFalse(); - request.setParameter(properties.getArtifactParameter(), "value"); - assertThat(filter.requiresAuthentication(request, response)).isTrue(); - SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key", "principal", - AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); - assertThat(filter.requiresAuthentication(request, response)).isTrue(); - SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("un", "principal")); - assertThat(filter.requiresAuthentication(request, response)).isTrue(); - SecurityContextHolder.getContext() - .setAuthentication(new TestingAuthenticationToken("un", "principal", "ROLE_ANONYMOUS")); - assertThat(filter.requiresAuthentication(request, response)).isFalse(); - } - - @Test - public void testAuthenticateProxyUrl() throws Exception { - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - request.setServletPath("/pgtCallback"); - filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); - filter.setProxyReceptorUrl(request.getServletPath()); - assertThat(filter.attemptAuthentication(request, response)).isNull(); - } - - @Test - public void testDoFilterAuthenticateAll() throws Exception { - AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class); - AuthenticationManager manager = mock(AuthenticationManager.class); - Authentication authentication = new TestingAuthenticationToken("un", "pwd", "ROLE_USER"); - given(manager.authenticate(any(Authentication.class))).willReturn(authentication); - ServiceProperties serviceProperties = new ServiceProperties(); - serviceProperties.setAuthenticateAllArtifacts(true); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setParameter("ticket", "ST-1-123"); - request.setServletPath("/authenticate"); - MockHttpServletResponse response = new MockHttpServletResponse(); - FilterChain chain = mock(FilterChain.class); - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setServiceProperties(serviceProperties); - filter.setAuthenticationSuccessHandler(successHandler); - filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); - filter.setAuthenticationManager(manager); - filter.afterPropertiesSet(); - filter.doFilter(request, response, chain); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull() - .withFailMessage("Authentication should not be null"); - verify(chain).doFilter(request, response); - verifyZeroInteractions(successHandler); - // validate for when the filterProcessUrl matches - filter.setFilterProcessesUrl(request.getServletPath()); - SecurityContextHolder.clearContext(); - filter.doFilter(request, response, chain); - verifyNoMoreInteractions(chain); - verify(successHandler).onAuthenticationSuccess(request, response, authentication); - } - - // SEC-1592 - @Test - public void testChainNotInvokedForProxyReceptor() throws Exception { - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - FilterChain chain = mock(FilterChain.class); - request.setServletPath("/pgtCallback"); - filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); - filter.setProxyReceptorUrl(request.getServletPath()); - filter.doFilter(request, response, chain); - verifyZeroInteractions(chain); - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/web/ServicePropertiesTests.java b/cas/src/test/java/org/springframework/security/cas/web/ServicePropertiesTests.java deleted file mode 100644 index fc52e1d6a54..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/web/ServicePropertiesTests.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.web; - -import org.junit.jupiter.api.Test; - -import org.springframework.security.cas.SamlServiceProperties; -import org.springframework.security.cas.ServiceProperties; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests {@link ServiceProperties}. - * - * @author Ben Alex - */ -public class ServicePropertiesTests { - - @Test - public void detectsMissingService() throws Exception { - ServiceProperties sp = new ServiceProperties(); - assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet); - } - - @Test - public void nullServiceWhenAuthenticateAllTokens() throws Exception { - ServiceProperties sp = new ServiceProperties(); - sp.setAuthenticateAllArtifacts(true); - assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet); - sp.setAuthenticateAllArtifacts(false); - assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet); - } - - @Test - public void testGettersSetters() throws Exception { - ServiceProperties[] sps = { new ServiceProperties(), new SamlServiceProperties() }; - for (ServiceProperties sp : sps) { - sp.setSendRenew(false); - assertThat(sp.isSendRenew()).isFalse(); - sp.setSendRenew(true); - assertThat(sp.isSendRenew()).isTrue(); - sp.setArtifactParameter("notticket"); - assertThat(sp.getArtifactParameter()).isEqualTo("notticket"); - sp.setServiceParameter("notservice"); - assertThat(sp.getServiceParameter()).isEqualTo("notservice"); - sp.setService("https://mycompany.com/service"); - assertThat(sp.getService()).isEqualTo("https://mycompany.com/service"); - sp.afterPropertiesSet(); - } - } - -} diff --git a/cas/src/test/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetailsTests.java b/cas/src/test/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetailsTests.java deleted file mode 100644 index 893d2567751..00000000000 --- a/cas/src/test/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetailsTests.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2011-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.cas.web.authentication; - -import java.util.regex.Pattern; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.GenericXmlApplicationContext; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.web.util.UrlUtils; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Rob Winch - */ -public class DefaultServiceAuthenticationDetailsTests { - - private DefaultServiceAuthenticationDetails details; - - private MockHttpServletRequest request; - - private Pattern artifactPattern; - - private String casServiceUrl; - - private ConfigurableApplicationContext context; - - @BeforeEach - public void setUp() { - this.casServiceUrl = "https://localhost:8443/j_spring_security_cas"; - this.request = new MockHttpServletRequest(); - this.request.setScheme("https"); - this.request.setServerName("localhost"); - this.request.setServerPort(8443); - this.request.setRequestURI("/cas-sample/secure/"); - this.artifactPattern = DefaultServiceAuthenticationDetails - .createArtifactPattern(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER); - } - - @AfterEach - public void cleanup() { - if (this.context != null) { - this.context.close(); - } - } - - @Test - public void getServiceUrlNullQuery() throws Exception { - this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); - assertThat(this.details.getServiceUrl()).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); - } - - @Test - public void getServiceUrlTicketOnlyParam() throws Exception { - this.request.setQueryString("ticket=123"); - this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); - String serviceUrl = this.details.getServiceUrl(); - this.request.setQueryString(null); - assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); - } - - @Test - public void getServiceUrlTicketFirstMultiParam() throws Exception { - this.request.setQueryString("ticket=123&other=value"); - this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); - String serviceUrl = this.details.getServiceUrl(); - this.request.setQueryString("other=value"); - assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); - } - - @Test - public void getServiceUrlTicketLastMultiParam() throws Exception { - this.request.setQueryString("other=value&ticket=123"); - this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); - String serviceUrl = this.details.getServiceUrl(); - this.request.setQueryString("other=value"); - assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); - } - - @Test - public void getServiceUrlTicketMiddleMultiParam() throws Exception { - this.request.setQueryString("other=value&ticket=123&last=this"); - this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); - String serviceUrl = this.details.getServiceUrl(); - this.request.setQueryString("other=value&last=this"); - assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); - } - - @Test - public void getServiceUrlDoesNotUseHostHeader() throws Exception { - this.casServiceUrl = "https://example.com/j_spring_security_cas"; - this.request.setServerName("evil.com"); - this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); - assertThat(this.details.getServiceUrl()).isEqualTo("https://example.com/cas-sample/secure/"); - } - - @Test - public void getServiceUrlDoesNotUseHostHeaderExplicit() { - this.casServiceUrl = "https://example.com/j_spring_security_cas"; - this.request.setServerName("evil.com"); - ServiceAuthenticationDetails details = loadServiceAuthenticationDetails( - "defaultserviceauthenticationdetails-explicit.xml"); - assertThat(details.getServiceUrl()).isEqualTo("https://example.com/cas-sample/secure/"); - } - - private ServiceAuthenticationDetails loadServiceAuthenticationDetails(String resourceName) { - this.context = new GenericXmlApplicationContext(getClass(), resourceName); - ServiceAuthenticationDetailsSource source = this.context.getBean(ServiceAuthenticationDetailsSource.class); - return source.buildDetails(this.request); - } - -} diff --git a/cas/src/test/resources/logback-test.xml b/cas/src/test/resources/logback-test.xml deleted file mode 100644 index 2d51ba4180a..00000000000 --- a/cas/src/test/resources/logback-test.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - diff --git a/cas/src/test/resources/org/springframework/security/cas/web/authentication/defaultserviceauthenticationdetails-explicit.xml b/cas/src/test/resources/org/springframework/security/cas/web/authentication/defaultserviceauthenticationdetails-explicit.xml deleted file mode 100644 index c7d5346179a..00000000000 --- a/cas/src/test/resources/org/springframework/security/cas/web/authentication/defaultserviceauthenticationdetails-explicit.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/cas/src/test/resources/org/springframework/security/cas/web/authentication/defaultserviceauthenticationdetails-passivity.xml b/cas/src/test/resources/org/springframework/security/cas/web/authentication/defaultserviceauthenticationdetails-passivity.xml deleted file mode 100644 index 0fe950ff2b9..00000000000 --- a/cas/src/test/resources/org/springframework/security/cas/web/authentication/defaultserviceauthenticationdetails-passivity.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/config/spring-security-config.gradle b/config/spring-security-config.gradle index a54edbd15c8..fa04b5286dc 100644 --- a/config/spring-security-config.gradle +++ b/config/spring-security-config.gradle @@ -37,12 +37,11 @@ dependencies { optional'org.springframework:spring-websocket' optional 'org.jetbrains.kotlin:kotlin-reflect' optional 'org.jetbrains.kotlin:kotlin-stdlib-jdk8' - optional 'javax.annotation:jsr250-api' + optional 'jakarta.annotation:jakarta.annotation-api' - provided 'javax.servlet:javax.servlet-api' + provided 'jakarta.servlet:jakarta.servlet-api' testImplementation project(':spring-security-aspects') - testImplementation project(':spring-security-cas') testImplementation project(':spring-security-test') testImplementation project(path : ':spring-security-core', configuration : 'tests') testImplementation project(path : ':spring-security-ldap', configuration : 'tests') @@ -62,8 +61,8 @@ dependencies { testImplementation 'ch.qos.logback:logback-classic' testImplementation 'io.projectreactor.netty:reactor-netty' testImplementation 'io.rsocket:rsocket-transport-netty' - testImplementation 'javax.annotation:jsr250-api:1.0' - testImplementation 'javax.xml.bind:jaxb-api' + testImplementation 'jakarta.annotation:jakarta.annotation-api' + testImplementation 'jakarta.xml.bind:jakarta.xml.bind-api' testImplementation 'ldapsdk:ldapsdk:4.1' testImplementation('net.sourceforge.htmlunit:htmlunit') { exclude group: 'commons-logging', module: 'commons-logging' @@ -74,8 +73,8 @@ dependencies { testImplementation "org.apache.directory.server:apacheds-protocol-ldap" testImplementation "org.apache.directory.server:apacheds-server-jndi" testImplementation 'org.apache.directory.shared:shared-ldap' - testImplementation 'org.eclipse.persistence:javax.persistence' - testImplementation 'org.hibernate:hibernate-entitymanager' + testImplementation 'jakarta.persistence:jakarta.persistence-api' + testImplementation 'org.hibernate:hibernate-core-jakarta' testImplementation 'org.hsqldb:hsqldb' testImplementation 'org.mockito:mockito-core' testImplementation "org.mockito:mockito-inline" @@ -117,7 +116,7 @@ tasks.withType(KotlinCompile).configureEach { languageVersion = "1.3" apiVersion = "1.3" freeCompilerArgs = ["-Xjsr305=strict", "-Xsuppress-version-warnings"] - jvmTarget = "1.8" + jvmTarget = "11" } } diff --git a/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java b/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java index d3dd04a7d9c..9e56d238fe5 100644 --- a/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java +++ b/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java @@ -94,7 +94,7 @@ public BeanDefinition parse(Element element, ParserContext pc) { if (!namespaceMatchesVersion(element)) { pc.getReaderContext().fatal("You cannot use a spring-security-2.0.xsd or spring-security-3.0.xsd or " + "spring-security-3.1.xsd schema or spring-security-3.2.xsd schema or spring-security-4.0.xsd schema " - + "with Spring Security 5.6. Please update your schema declarations to the 5.6 schema.", element); + + "with Spring Security 6.0. Please update your schema declarations to the 6.0 schema.", element); } String name = pc.getDelegate().getLocalName(element); BeanDefinitionParser parser = this.parsers.get(name); @@ -215,7 +215,7 @@ private boolean namespaceMatchesVersion(Element element) { private boolean matchesVersionInternal(Element element) { String schemaLocation = element.getAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation"); - return schemaLocation.matches("(?m).*spring-security-5\\.6.*.xsd.*") + return schemaLocation.matches("(?m).*spring-security-6\\.0.*.xsd.*") || schemaLocation.matches("(?m).*spring-security.xsd.*") || !schemaLocation.matches("(?m).*spring-security.*"); } diff --git a/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurer.java index 07605a3fead..873936a4924 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -141,7 +141,7 @@ private LdapAuthoritiesPopulator getLdapAuthoritiesPopulator() { defaultAuthoritiesPopulator.setGroupSearchFilter(this.groupSearchFilter); defaultAuthoritiesPopulator.setSearchSubtree(this.groupSearchSubtree); defaultAuthoritiesPopulator.setRolePrefix(this.rolePrefix); - this.ldapAuthoritiesPopulator = defaultAuthoritiesPopulator; + this.ldapAuthoritiesPopulator = postProcess(defaultAuthoritiesPopulator); return defaultAuthoritiesPopulator; } diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.java b/config/src/main/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.java index d2cea903a43..c99587681bf 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.java @@ -20,7 +20,7 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.DispatcherType; +import jakarta.servlet.DispatcherType; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java b/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java index 475f2de2f50..c3da8890e37 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/HttpSecurityBuilder.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.annotation.SecurityBuilder; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/WebSecurityConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/WebSecurityConfigurer.java index c7bc0578d5f..981fdd3742f 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/WebSecurityConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/WebSecurityConfigurer.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.SecurityBuilder; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java index 13248b7e679..2026e7d8557 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java @@ -20,7 +20,7 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.springframework.security.web.access.ExceptionTranslationFilter; import org.springframework.security.web.access.channel.ChannelProcessingFilter; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java index 14d32ecd76c..7f04681042d 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java @@ -21,12 +21,12 @@ import java.util.List; import java.util.Map; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.context.ApplicationContext; import org.springframework.core.OrderComparator; @@ -1048,7 +1048,7 @@ public HttpSecurity x509(Customizer> x509Customizer * The following configuration demonstrates how to allow token based remember me * authentication. Upon authenticating if the HTTP parameter named "remember-me" * exists, then the user will be remembered even after their - * {@link javax.servlet.http.HttpSession} expires. + * {@link jakarta.servlet.http.HttpSession} expires. * *
 	 * @Configuration
@@ -1084,7 +1084,7 @@ public RememberMeConfigurer rememberMe() throws Exception {
 	 * The following configuration demonstrates how to allow token based remember me
 	 * authentication. Upon authenticating if the HTTP parameter named "remember-me"
 	 * exists, then the user will be remembered even after their
-	 * {@link javax.servlet.http.HttpSession} expires.
+	 * {@link jakarta.servlet.http.HttpSession} expires.
 	 *
 	 * 
 	 * @Configuration
@@ -2889,8 +2889,15 @@ protected void beforeConfigure() throws Exception {
 		}
 	}
 
+	@SuppressWarnings("unchecked")
 	@Override
 	protected DefaultSecurityFilterChain performBuild() {
+		ExpressionUrlAuthorizationConfigurer expressionConfigurer = getConfigurer(
+				ExpressionUrlAuthorizationConfigurer.class);
+		AuthorizeHttpRequestsConfigurer httpConfigurer = getConfigurer(AuthorizeHttpRequestsConfigurer.class);
+		boolean oneConfigurerPresent = expressionConfigurer == null ^ httpConfigurer == null;
+		Assert.state((expressionConfigurer == null && httpConfigurer == null) || oneConfigurerPresent,
+				"authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one.");
 		this.filters.sort(OrderComparator.INSTANCE);
 		List sortedFilters = new ArrayList<>(this.filters.size());
 		for (Filter filter : this.filters) {
@@ -3234,7 +3241,9 @@ public HttpSecurity antMatcher(String antPattern) {
 	 * @see MvcRequestMatcher
 	 */
 	public HttpSecurity mvcMatcher(String mvcPattern) {
-		HandlerMappingIntrospector introspector = new HandlerMappingIntrospector(getContext());
+		HandlerMappingIntrospector introspector = new HandlerMappingIntrospector();
+		introspector.setApplicationContext(getContext());
+		introspector.afterPropertiesSet();
 		return requestMatcher(new MvcRequestMatcher(introspector, mvcPattern));
 	}
 
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java
index f0395b840ea..8bd1c67d83a 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java
@@ -19,8 +19,9 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import javax.servlet.Filter;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.Filter;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.HttpServletRequest;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -33,6 +34,7 @@
 import org.springframework.security.access.PermissionEvaluator;
 import org.springframework.security.access.expression.SecurityExpressionHandler;
 import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
+import org.springframework.security.authorization.AuthorizationManager;
 import org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder;
 import org.springframework.security.config.annotation.ObjectPostProcessor;
 import org.springframework.security.config.annotation.SecurityBuilder;
@@ -47,9 +49,12 @@
 import org.springframework.security.web.FilterChainProxy;
 import org.springframework.security.web.FilterInvocation;
 import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.security.web.access.AuthorizationManagerWebInvocationPrivilegeEvaluator;
 import org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator;
+import org.springframework.security.web.access.RequestMatcherDelegatingWebInvocationPrivilegeEvaluator;
 import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
 import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
+import org.springframework.security.web.access.intercept.AuthorizationFilter;
 import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
 import org.springframework.security.web.debug.DebugFilter;
 import org.springframework.security.web.firewall.HttpFirewall;
@@ -57,7 +62,9 @@
 import org.springframework.security.web.firewall.StrictHttpFirewall;
 import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
 import org.springframework.security.web.util.matcher.RequestMatcher;
+import org.springframework.security.web.util.matcher.RequestMatcherEntry;
 import org.springframework.util.Assert;
+import org.springframework.web.context.ServletContextAware;
 import org.springframework.web.filter.DelegatingFilterProxy;
 
 /**
@@ -81,7 +88,7 @@
  * @see WebSecurityConfiguration
  */
 public final class WebSecurity extends AbstractConfiguredSecurityBuilder
-		implements SecurityBuilder, ApplicationContextAware {
+		implements SecurityBuilder, ApplicationContextAware, ServletContextAware {
 
 	private final Log logger = LogFactory.getLog(getClass());
 
@@ -108,6 +115,8 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder {
 	};
 
+	private ServletContext servletContext;
+
 	/**
 	 * Creates a new instance
 	 * @param objectPostProcessor the {@link ObjectPostProcessor} to use
@@ -252,6 +261,8 @@ public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() {
 	 * {@link WebSecurityConfigurerAdapter}.
 	 * @param securityInterceptor the {@link FilterSecurityInterceptor} to use
 	 * @return the {@link WebSecurity} for further customizations
+	 * @deprecated Use {@link #privilegeEvaluator(WebInvocationPrivilegeEvaluator)}
+	 * instead
 	 */
 	public WebSecurity securityInterceptor(FilterSecurityInterceptor securityInterceptor) {
 		this.filterSecurityInterceptor = securityInterceptor;
@@ -278,11 +289,22 @@ protected Filter performBuild() throws Exception {
 						+ ".addSecurityFilterChainBuilder directly");
 		int chainSize = this.ignoredRequests.size() + this.securityFilterChainBuilders.size();
 		List securityFilterChains = new ArrayList<>(chainSize);
+		List>> requestMatcherPrivilegeEvaluatorsEntries = new ArrayList<>();
 		for (RequestMatcher ignoredRequest : this.ignoredRequests) {
-			securityFilterChains.add(new DefaultSecurityFilterChain(ignoredRequest));
+			SecurityFilterChain securityFilterChain = new DefaultSecurityFilterChain(ignoredRequest);
+			securityFilterChains.add(securityFilterChain);
+			requestMatcherPrivilegeEvaluatorsEntries
+					.add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain));
 		}
 		for (SecurityBuilder securityFilterChainBuilder : this.securityFilterChainBuilders) {
-			securityFilterChains.add(securityFilterChainBuilder.build());
+			SecurityFilterChain securityFilterChain = securityFilterChainBuilder.build();
+			securityFilterChains.add(securityFilterChain);
+			requestMatcherPrivilegeEvaluatorsEntries
+					.add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain));
+		}
+		if (this.privilegeEvaluator == null) {
+			this.privilegeEvaluator = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(
+					requestMatcherPrivilegeEvaluatorsEntries);
 		}
 		FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains);
 		if (this.httpFirewall != null) {
@@ -306,6 +328,26 @@ protected Filter performBuild() throws Exception {
 		return result;
 	}
 
+	private RequestMatcherEntry> getRequestMatcherPrivilegeEvaluatorsEntry(
+			SecurityFilterChain securityFilterChain) {
+		List privilegeEvaluators = new ArrayList<>();
+		for (Filter filter : securityFilterChain.getFilters()) {
+			if (filter instanceof FilterSecurityInterceptor) {
+				DefaultWebInvocationPrivilegeEvaluator defaultWebInvocationPrivilegeEvaluator = new DefaultWebInvocationPrivilegeEvaluator(
+						(FilterSecurityInterceptor) filter);
+				defaultWebInvocationPrivilegeEvaluator.setServletContext(this.servletContext);
+				privilegeEvaluators.add(defaultWebInvocationPrivilegeEvaluator);
+				continue;
+			}
+			if (filter instanceof AuthorizationFilter) {
+				AuthorizationManager authorizationManager = ((AuthorizationFilter) filter)
+						.getAuthorizationManager();
+				privilegeEvaluators.add(new AuthorizationManagerWebInvocationPrivilegeEvaluator(authorizationManager));
+			}
+		}
+		return new RequestMatcherEntry<>(securityFilterChain::matches, privilegeEvaluators);
+	}
+
 	@Override
 	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
 		this.defaultWebSecurityExpressionHandler.setApplicationContext(applicationContext);
@@ -333,6 +375,11 @@ public void setApplicationContext(ApplicationContext applicationContext) throws
 		}
 	}
 
+	@Override
+	public void setServletContext(ServletContext servletContext) {
+		this.servletContext = servletContext;
+	}
+
 	/**
 	 * An {@link IgnoredRequestConfigurer} that allows optionally configuring the
 	 * {@link MvcRequestMatcher#setMethod(HttpMethod)}
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/AutowiredWebSecurityConfigurersIgnoreParents.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/AutowiredWebSecurityConfigurersIgnoreParents.java
index dec674d3054..5ac1033e911 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/AutowiredWebSecurityConfigurersIgnoreParents.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/AutowiredWebSecurityConfigurersIgnoreParents.java
@@ -21,7 +21,7 @@
 import java.util.Map;
 import java.util.Map.Entry;
 
-import javax.servlet.Filter;
+import jakarta.servlet.Filter;
 
 import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
 import org.springframework.context.ApplicationContext;
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java
index 2783cb358bc..6695e855b73 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2020 the original author or authors.
+ * Copyright 2002-2021 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,13 +16,17 @@
 
 package org.springframework.security.config.annotation.web.configuration;
 
+import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.function.Function;
+import java.util.function.Supplier;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
 
 import org.reactivestreams.Publisher;
 import org.reactivestreams.Subscription;
@@ -67,17 +71,22 @@ static class SecurityReactorContextSubscriberRegistrar implements InitializingBe
 
 		private static final String SECURITY_REACTOR_CONTEXT_OPERATOR_KEY = "org.springframework.security.SECURITY_REACTOR_CONTEXT_OPERATOR";
 
+		private static final Map> CONTEXT_ATTRIBUTE_VALUE_LOADERS = new HashMap<>();
+
+		static {
+			CONTEXT_ATTRIBUTE_VALUE_LOADERS.put(HttpServletRequest.class,
+					SecurityReactorContextSubscriberRegistrar::getRequest);
+			CONTEXT_ATTRIBUTE_VALUE_LOADERS.put(HttpServletResponse.class,
+					SecurityReactorContextSubscriberRegistrar::getResponse);
+			CONTEXT_ATTRIBUTE_VALUE_LOADERS.put(Authentication.class,
+					SecurityReactorContextSubscriberRegistrar::getAuthentication);
+		}
+
 		@Override
 		public void afterPropertiesSet() throws Exception {
 			Function, ? extends Publisher> lifter = Operators
 					.liftPublisher((pub, sub) -> createSubscriberIfNecessary(sub));
-			Hooks.onLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY, (pub) -> {
-				if (!contextAttributesAvailable()) {
-					// No need to decorate so return original Publisher
-					return pub;
-				}
-				return lifter.apply(pub);
-			});
+			Hooks.onLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY, lifter::apply);
 		}
 
 		@Override
@@ -93,36 +102,30 @@  CoreSubscriber createSubscriberIfNecessary(CoreSubscriber delegate) {
 			return new SecurityReactorContextSubscriber<>(delegate, getContextAttributes());
 		}
 
-		private static boolean contextAttributesAvailable() {
-			return SecurityContextHolder.getContext().getAuthentication() != null
-					|| RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes;
+		private static Map getContextAttributes() {
+			return new LoadingMap<>(CONTEXT_ATTRIBUTE_VALUE_LOADERS);
 		}
 
-		private static Map getContextAttributes() {
-			HttpServletRequest servletRequest = null;
-			HttpServletResponse servletResponse = null;
+		private static HttpServletRequest getRequest() {
 			RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
 			if (requestAttributes instanceof ServletRequestAttributes) {
 				ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
-				servletRequest = servletRequestAttributes.getRequest();
-				servletResponse = servletRequestAttributes.getResponse(); // possible null
+				return servletRequestAttributes.getRequest();
 			}
-			Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
-			if (authentication == null && servletRequest == null) {
-				return Collections.emptyMap();
-			}
-			Map contextAttributes = new HashMap<>();
-			if (servletRequest != null) {
-				contextAttributes.put(HttpServletRequest.class, servletRequest);
-			}
-			if (servletResponse != null) {
-				contextAttributes.put(HttpServletResponse.class, servletResponse);
-			}
-			if (authentication != null) {
-				contextAttributes.put(Authentication.class, authentication);
+			return null;
+		}
+
+		private static HttpServletResponse getResponse() {
+			RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
+			if (requestAttributes instanceof ServletRequestAttributes) {
+				ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
+				return servletRequestAttributes.getResponse(); // possible null
 			}
+			return null;
+		}
 
-			return contextAttributes;
+		private static Authentication getAuthentication() {
+			return SecurityContextHolder.getContext().getAuthentication();
 		}
 
 	}
@@ -175,4 +178,112 @@ public void onComplete() {
 
 	}
 
+	/**
+	 * A map that computes each value when {@link #get} is invoked
+	 */
+	static class LoadingMap implements Map {
+
+		private final Map loaded = new ConcurrentHashMap<>();
+
+		private final Map> loaders;
+
+		LoadingMap(Map> loaders) {
+			this.loaders = Collections.unmodifiableMap(new HashMap<>(loaders));
+		}
+
+		@Override
+		public int size() {
+			return this.loaders.size();
+		}
+
+		@Override
+		public boolean isEmpty() {
+			return this.loaders.isEmpty();
+		}
+
+		@Override
+		public boolean containsKey(Object key) {
+			return this.loaders.containsKey(key);
+		}
+
+		@Override
+		public Set keySet() {
+			return this.loaders.keySet();
+		}
+
+		@Override
+		public V get(Object key) {
+			if (!this.loaders.containsKey(key)) {
+				throw new IllegalArgumentException(
+						"This map only supports the following keys: " + this.loaders.keySet());
+			}
+			return this.loaded.computeIfAbsent((K) key, (k) -> this.loaders.get(k).get());
+		}
+
+		@Override
+		public V put(K key, V value) {
+			if (!this.loaders.containsKey(key)) {
+				throw new IllegalArgumentException(
+						"This map only supports the following keys: " + this.loaders.keySet());
+			}
+			return this.loaded.put(key, value);
+		}
+
+		@Override
+		public V remove(Object key) {
+			if (!this.loaders.containsKey(key)) {
+				throw new IllegalArgumentException(
+						"This map only supports the following keys: " + this.loaders.keySet());
+			}
+			return this.loaded.remove(key);
+		}
+
+		@Override
+		public void putAll(Map m) {
+			for (Map.Entry entry : m.entrySet()) {
+				put(entry.getKey(), entry.getValue());
+			}
+		}
+
+		@Override
+		public void clear() {
+			this.loaded.clear();
+		}
+
+		@Override
+		public boolean containsValue(Object value) {
+			return this.loaded.containsValue(value);
+		}
+
+		@Override
+		public Collection values() {
+			return this.loaded.values();
+		}
+
+		@Override
+		public Set> entrySet() {
+			return this.loaded.entrySet();
+		}
+
+		@Override
+		public boolean equals(Object o) {
+			if (this == o) {
+				return true;
+			}
+			if (o == null || getClass() != o.getClass()) {
+				return false;
+			}
+
+			LoadingMap that = (LoadingMap) o;
+
+			return this.loaded.equals(that.loaded);
+		}
+
+		@Override
+		public int hashCode() {
+			return this.loaded.hashCode();
+		}
+
+	}
+
 }
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.java
index 45bf5e5f1e7..1bd9857bbff 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2020 the original author or authors.
+ * Copyright 2002-2021 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.
@@ -20,11 +20,10 @@
 import java.util.List;
 import java.util.Map;
 
-import javax.servlet.Filter;
+import jakarta.servlet.Filter;
 
 import org.springframework.beans.factory.BeanClassLoaderAware;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
 import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
 import org.springframework.context.annotation.Bean;
@@ -128,8 +127,8 @@ public Filter springSecurityFilterChain() throws Exception {
 	}
 
 	/**
-	 * Creates the {@link WebInvocationPrivilegeEvaluator} that is necessary for the JSP
-	 * tag support.
+	 * Creates the {@link WebInvocationPrivilegeEvaluator} that is necessary to evaluate
+	 * privileges for a given web URI
 	 * @return the {@link WebInvocationPrivilegeEvaluator}
 	 */
 	@Bean
@@ -143,19 +142,20 @@ public WebInvocationPrivilegeEvaluator privilegeEvaluator() {
 	 * instances used to create the web configuration.
 	 * @param objectPostProcessor the {@link ObjectPostProcessor} used to create a
 	 * {@link WebSecurity} instance
-	 * @param webSecurityConfigurers the
+	 * @param beanFactory the bean factory to use to retrieve the relevant
 	 * {@code } instances used to
 	 * create the web configuration
 	 * @throws Exception
 	 */
 	@Autowired(required = false)
 	public void setFilterChainProxySecurityConfigurer(ObjectPostProcessor objectPostProcessor,
-			@Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List> webSecurityConfigurers)
-			throws Exception {
+			ConfigurableListableBeanFactory beanFactory) throws Exception {
 		this.webSecurity = objectPostProcessor.postProcess(new WebSecurity(objectPostProcessor));
 		if (this.debugEnabled != null) {
 			this.webSecurity.debug(this.debugEnabled);
 		}
+		List> webSecurityConfigurers = new AutowiredWebSecurityConfigurersIgnoreParents(
+				beanFactory).getWebSecurityConfigurers();
 		webSecurityConfigurers.sort(AnnotationAwareOrderComparator.INSTANCE);
 		Integer previousOrder = null;
 		Object previousConfig = null;
@@ -189,12 +189,6 @@ public static BeanFactoryPostProcessor conversionServicePostProcessor() {
 		return new RsaKeyConversionServicePostProcessor();
 	}
 
-	@Bean
-	public static AutowiredWebSecurityConfigurersIgnoreParents autowiredWebSecurityConfigurersIgnoreParents(
-			ConfigurableListableBeanFactory beanFactory) {
-		return new AutowiredWebSecurityConfigurersIgnoreParents(beanFactory);
-	}
-
 	@Override
 	public void setImportMetadata(AnnotationMetadata importMetadata) {
 		Map enableWebSecurityAttrMap = importMetadata
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java
index 0837de2a7f8..f38ca4c76c5 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java
@@ -19,7 +19,7 @@
 import java.util.Arrays;
 import java.util.Collections;
 
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
 
 import org.springframework.http.MediaType;
 import org.springframework.security.authentication.AuthenticationDetailsSource;
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurer.java
index 44d2416cd58..c2e02ecb177 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2020 the original author or authors.
+ * Copyright 2002-2021 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,10 @@
 
 package org.springframework.security.config.annotation.web.configurers;
 
+import java.util.LinkedHashMap;
 import java.util.List;
 
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
 
 import org.springframework.context.ApplicationContext;
 import org.springframework.http.HttpMethod;
@@ -46,6 +47,9 @@
 public final class AuthorizeHttpRequestsConfigurer>
 		extends AbstractHttpConfigurer, H> {
 
+	static final AuthorizationManager permitAllAuthorizationManager = (a,
+			o) -> new AuthorizationDecision(true);
+
 	private final AuthorizationManagerRequestMatcherRegistry registry;
 
 	/**
@@ -81,6 +85,12 @@ private AuthorizationManagerRequestMatcherRegistry addMapping(List manager) {
+		this.registry.addFirst(matcher, manager);
+		return this.registry;
+	}
+
 	/**
 	 * Registry for mapping a {@link RequestMatcher} to an {@link AuthorizationManager}.
 	 *
@@ -106,6 +116,19 @@ private void addMapping(RequestMatcher matcher, AuthorizationManager manager) {
+			this.unmappedMatchers = null;
+			this.managerBuilder.mappings((m) -> {
+				LinkedHashMap> reorderedMap = new LinkedHashMap<>(
+						m.size() + 1);
+				reorderedMap.put(matcher, manager);
+				reorderedMap.putAll(m);
+				m.clear();
+				m.putAll(reorderedMap);
+			});
+			this.mappingCount++;
+		}
+
 		private AuthorizationManager createAuthorizationManager() {
 			Assert.state(this.unmappedMatchers == null,
 					() -> "An incomplete mapping was found for " + this.unmappedMatchers
@@ -209,7 +232,7 @@ protected List getMatchers() {
 		 * customizations
 		 */
 		public AuthorizationManagerRequestMatcherRegistry permitAll() {
-			return access((a, o) -> new AuthorizationDecision(true));
+			return access(permitAllAuthorizationManager);
 		}
 
 		/**
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ChannelSecurityConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ChannelSecurityConfigurer.java
index 19fc8ae0ca8..979084ce8c9 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ChannelSecurityConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ChannelSecurityConfigurer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2013 the original author or authors.
+ * Copyright 2002-2021 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.
@@ -30,7 +30,9 @@
 import org.springframework.security.config.annotation.SecurityConfigurer;
 import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.web.DefaultRedirectStrategy;
 import org.springframework.security.web.PortMapper;
+import org.springframework.security.web.RedirectStrategy;
 import org.springframework.security.web.access.channel.ChannelDecisionManagerImpl;
 import org.springframework.security.web.access.channel.ChannelProcessingFilter;
 import org.springframework.security.web.access.channel.ChannelProcessor;
@@ -75,6 +77,7 @@
  *
  * @param  the type of {@link HttpSecurityBuilder} that is being configured
  * @author Rob Winch
+ * @author Onur Kagan Ozcan
  * @since 3.2
  */
 public final class ChannelSecurityConfigurer>
@@ -86,6 +89,8 @@ public final class ChannelSecurityConfigurer>
 
 	private List channelProcessors;
 
+	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
+
 	private final ChannelRequestMatcherRegistry REGISTRY;
 
 	/**
@@ -123,9 +128,11 @@ private List getChannelProcessors(H http) {
 		if (portMapper != null) {
 			RetryWithHttpEntryPoint httpEntryPoint = new RetryWithHttpEntryPoint();
 			httpEntryPoint.setPortMapper(portMapper);
+			httpEntryPoint.setRedirectStrategy(this.redirectStrategy);
 			insecureChannelProcessor.setEntryPoint(httpEntryPoint);
 			RetryWithHttpsEntryPoint httpsEntryPoint = new RetryWithHttpsEntryPoint();
 			httpsEntryPoint.setPortMapper(portMapper);
+			httpsEntryPoint.setRedirectStrategy(this.redirectStrategy);
 			secureChannelProcessor.setEntryPoint(httpsEntryPoint);
 		}
 		insecureChannelProcessor = postProcess(insecureChannelProcessor);
@@ -185,6 +192,17 @@ public ChannelRequestMatcherRegistry channelProcessors(List ch
 			return this;
 		}
 
+		/**
+		 * Sets the {@link RedirectStrategy} instances to use in
+		 * {@link RetryWithHttpEntryPoint} and {@link RetryWithHttpsEntryPoint}
+		 * @param redirectStrategy
+		 * @return the {@link ChannelSecurityConfigurer} for further customizations
+		 */
+		public ChannelRequestMatcherRegistry redirectStrategy(RedirectStrategy redirectStrategy) {
+			ChannelSecurityConfigurer.this.redirectStrategy = redirectStrategy;
+			return this;
+		}
+
 		/**
 		 * Return the {@link SecurityBuilder} when done using the
 		 * {@link SecurityConfigurer}. This is useful for method chaining.
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurer.java
index c0a3cd62ee6..38daaec214d 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurer.java
@@ -20,7 +20,7 @@
 import java.util.LinkedHashMap;
 import java.util.List;
 
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
 
 import org.springframework.context.ApplicationContext;
 import org.springframework.http.HttpMethod;
@@ -237,8 +237,8 @@ private RequestMatcher getRequireCsrfProtectionMatcher() {
 
 	/**
 	 * Gets the default {@link AccessDeniedHandler} from the
-	 * {@link ExceptionHandlingConfigurer#getAccessDeniedHandler()} or create a
-	 * {@link AccessDeniedHandlerImpl} if not available.
+	 * {@link ExceptionHandlingConfigurer#getAccessDeniedHandler(HttpSecurityBuilder)} or
+	 * create a {@link AccessDeniedHandlerImpl} if not available.
 	 * @param http the {@link HttpSecurityBuilder}
 	 * @return the {@link AccessDeniedHandler}
 	 */
@@ -247,7 +247,7 @@ private AccessDeniedHandler getDefaultAccessDeniedHandler(H http) {
 		ExceptionHandlingConfigurer exceptionConfig = http.getConfigurer(ExceptionHandlingConfigurer.class);
 		AccessDeniedHandler handler = null;
 		if (exceptionConfig != null) {
-			handler = exceptionConfig.getAccessDeniedHandler();
+			handler = exceptionConfig.getAccessDeniedHandler(http);
 		}
 		if (handler == null) {
 			handler = new AccessDeniedHandlerImpl();
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurer.java
index 95bea02fcf5..557fd1ee398 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurer.java
@@ -19,7 +19,7 @@
 import java.util.Collections;
 import java.util.Map;
 
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
 
 import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurer.java
index cd177581b91..0ad06d2274f 100644
--- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurer.java
+++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2019 the original author or authors.
+ * Copyright 2002-2021 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.
@@ -21,7 +21,7 @@
 import java.util.List;
 import java.util.Map;
 
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
 
 import org.springframework.security.config.Customizer;
 import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
@@ -31,6 +31,9 @@
 import org.springframework.security.web.header.HeaderWriterFilter;
 import org.springframework.security.web.header.writers.CacheControlHeadersWriter;
 import org.springframework.security.web.header.writers.ContentSecurityPolicyHeaderWriter;
+import org.springframework.security.web.header.writers.CrossOriginEmbedderPolicyHeaderWriter;
+import org.springframework.security.web.header.writers.CrossOriginOpenerPolicyHeaderWriter;
+import org.springframework.security.web.header.writers.CrossOriginResourcePolicyHeaderWriter;
 import org.springframework.security.web.header.writers.FeaturePolicyHeaderWriter;
 import org.springframework.security.web.header.writers.HpkpHeaderWriter;
 import org.springframework.security.web.header.writers.HstsHeaderWriter;
@@ -97,6 +100,12 @@ public class HeadersConfigurer>
 
 	private final PermissionsPolicyConfig permissionsPolicy = new PermissionsPolicyConfig();
 
+	private final CrossOriginOpenerPolicyConfig crossOriginOpenerPolicy = new CrossOriginOpenerPolicyConfig();
+
+	private final CrossOriginEmbedderPolicyConfig crossOriginEmbedderPolicy = new CrossOriginEmbedderPolicyConfig();
+
+	private final CrossOriginResourcePolicyConfig crossOriginResourcePolicy = new CrossOriginResourcePolicyConfig();
+
 	/**
 	 * Creates a new instance
 	 *
@@ -392,6 +401,9 @@ private List getHeaderWriters() {
 		addIfNotNull(writers, this.referrerPolicy.writer);
 		addIfNotNull(writers, this.featurePolicy.writer);
 		addIfNotNull(writers, this.permissionsPolicy.writer);
+		addIfNotNull(writers, this.crossOriginOpenerPolicy.writer);
+		addIfNotNull(writers, this.crossOriginEmbedderPolicy.writer);
+		addIfNotNull(writers, this.crossOriginResourcePolicy.writer);
 		writers.addAll(this.headerWriters);
 		return writers;
 	}
@@ -544,6 +556,129 @@ public PermissionsPolicyConfig permissionsPolicy(Customizer
+	 * Cross-Origin-Opener-Policy header.
+	 * 

+ * Configuration is provided to the {@link CrossOriginOpenerPolicyHeaderWriter} which + * responsible for writing the header. + *

+ * @return the {@link CrossOriginOpenerPolicyConfig} for additional confniguration + * @since 5.7 + * @see CrossOriginOpenerPolicyHeaderWriter + */ + public CrossOriginOpenerPolicyConfig crossOriginOpenerPolicy() { + this.crossOriginOpenerPolicy.writer = new CrossOriginOpenerPolicyHeaderWriter(); + return this.crossOriginOpenerPolicy; + } + + /** + * Allows configuration for + * Cross-Origin-Opener-Policy header. + *

+ * Calling this method automatically enables (includes) the + * {@code Cross-Origin-Opener-Policy} header in the response using the supplied + * policy. + *

+ *

+ * Configuration is provided to the {@link CrossOriginOpenerPolicyHeaderWriter} which + * responsible for writing the header. + *

+ * @return the {@link HeadersConfigurer} for additional customizations + * @since 5.7 + * @see CrossOriginOpenerPolicyHeaderWriter + */ + public HeadersConfigurer crossOriginOpenerPolicy( + Customizer crossOriginOpenerPolicyCustomizer) { + this.crossOriginOpenerPolicy.writer = new CrossOriginOpenerPolicyHeaderWriter(); + crossOriginOpenerPolicyCustomizer.customize(this.crossOriginOpenerPolicy); + return HeadersConfigurer.this; + } + + /** + * Allows configuration for + * Cross-Origin-Embedder-Policy header. + *

+ * Configuration is provided to the {@link CrossOriginEmbedderPolicyHeaderWriter} + * which is responsible for writing the header. + *

+ * @return the {@link CrossOriginEmbedderPolicyConfig} for additional customizations + * @since 5.7 + * @see CrossOriginEmbedderPolicyHeaderWriter + */ + public CrossOriginEmbedderPolicyConfig crossOriginEmbedderPolicy() { + this.crossOriginEmbedderPolicy.writer = new CrossOriginEmbedderPolicyHeaderWriter(); + return this.crossOriginEmbedderPolicy; + } + + /** + * Allows configuration for + * Cross-Origin-Embedder-Policy header. + *

+ * Calling this method automatically enables (includes) the + * {@code Cross-Origin-Embedder-Policy} header in the response using the supplied + * policy. + *

+ *

+ * Configuration is provided to the {@link CrossOriginEmbedderPolicyHeaderWriter} + * which is responsible for writing the header. + *

+ * @return the {@link HeadersConfigurer} for additional customizations + * @since 5.7 + * @see CrossOriginEmbedderPolicyHeaderWriter + */ + public HeadersConfigurer crossOriginEmbedderPolicy( + Customizer crossOriginEmbedderPolicyCustomizer) { + this.crossOriginEmbedderPolicy.writer = new CrossOriginEmbedderPolicyHeaderWriter(); + crossOriginEmbedderPolicyCustomizer.customize(this.crossOriginEmbedderPolicy); + return HeadersConfigurer.this; + } + + /** + * Allows configuration for + * Cross-Origin-Resource-Policy header. + *

+ * Configuration is provided to the {@link CrossOriginResourcePolicyHeaderWriter} + * which is responsible for writing the header: + *

+ * @return the {@link HeadersConfigurer} for additional customizations + * @since 5.7 + * @see CrossOriginResourcePolicyHeaderWriter + */ + public CrossOriginResourcePolicyConfig crossOriginResourcePolicy() { + this.crossOriginResourcePolicy.writer = new CrossOriginResourcePolicyHeaderWriter(); + return this.crossOriginResourcePolicy; + } + + /** + * Allows configuration for + * Cross-Origin-Resource-Policy header. + *

+ * Calling this method automatically enables (includes) the + * {@code Cross-Origin-Resource-Policy} header in the response using the supplied + * policy. + *

+ *

+ * Configuration is provided to the {@link CrossOriginResourcePolicyHeaderWriter} + * which is responsible for writing the header: + *

+ * @return the {@link HeadersConfigurer} for additional customizations + * @since 5.7 + * @see CrossOriginResourcePolicyHeaderWriter + */ + public HeadersConfigurer crossOriginResourcePolicy( + Customizer crossOriginResourcePolicyCustomizer) { + this.crossOriginResourcePolicy.writer = new CrossOriginResourcePolicyHeaderWriter(); + crossOriginResourcePolicyCustomizer.customize(this.crossOriginResourcePolicy); + return HeadersConfigurer.this; + } + public final class ContentTypeOptionsConfig { private XContentTypeOptionsHeaderWriter writer; @@ -1142,4 +1277,96 @@ public HeadersConfigurer and() { } + public final class CrossOriginOpenerPolicyConfig { + + private CrossOriginOpenerPolicyHeaderWriter writer; + + public CrossOriginOpenerPolicyConfig() { + } + + /** + * Sets the policy to be used in the {@code Cross-Origin-Opener-Policy} header + * @param openerPolicy a {@code Cross-Origin-Opener-Policy} + * @return the {@link CrossOriginOpenerPolicyConfig} for additional configuration + * @throws IllegalArgumentException if openerPolicy is null + */ + public CrossOriginOpenerPolicyConfig policy( + CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy openerPolicy) { + this.writer.setPolicy(openerPolicy); + return this; + } + + /** + * Allows completing configuration of Cross Origin Opener Policy and continuing + * configuration of headers. + * @return the {@link HeadersConfigurer} for additional configuration + */ + public HeadersConfigurer and() { + return HeadersConfigurer.this; + } + + } + + public final class CrossOriginEmbedderPolicyConfig { + + private CrossOriginEmbedderPolicyHeaderWriter writer; + + public CrossOriginEmbedderPolicyConfig() { + } + + /** + * Sets the policy to be used in the {@code Cross-Origin-Embedder-Policy} header + * @param embedderPolicy a {@code Cross-Origin-Embedder-Policy} + * @return the {@link CrossOriginEmbedderPolicyConfig} for additional + * configuration + * @throws IllegalArgumentException if embedderPolicy is null + */ + public CrossOriginEmbedderPolicyConfig policy( + CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy embedderPolicy) { + this.writer.setPolicy(embedderPolicy); + return this; + } + + /** + * Allows completing configuration of Cross-Origin-Embedder-Policy and continuing + * configuration of headers. + * @return the {@link HeadersConfigurer} for additional configuration + */ + public HeadersConfigurer and() { + return HeadersConfigurer.this; + } + + } + + public final class CrossOriginResourcePolicyConfig { + + private CrossOriginResourcePolicyHeaderWriter writer; + + public CrossOriginResourcePolicyConfig() { + } + + /** + * Sets the policy to be used in the {@code Cross-Origin-Resource-Policy} header + * @param resourcePolicy a {@code Cross-Origin-Resource-Policy} + * @return the {@link CrossOriginResourcePolicyConfig} for additional + * configuration + * @throws IllegalArgumentException if resourcePolicy is null + */ + public CrossOriginResourcePolicyConfig policy( + CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy resourcePolicy) { + this.writer.setPolicy(resourcePolicy); + return this; + } + + /** + * Allows completing configuration of Cross-Origin-Resource-Policy and continuing + * configuration of headers. + * @return the {@link HeadersConfigurer} for additional configuration + */ + public HeadersConfigurer and() { + return HeadersConfigurer.this; + } + + } + } diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurer.java index e45bb31a060..6fbf4cafec8 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurer.java @@ -20,7 +20,7 @@ import java.util.Collections; import java.util.LinkedHashMap; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurer.java index bbd91f045c2..6a16498975e 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurer.java @@ -19,7 +19,7 @@ import java.util.HashSet; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.HttpSecurityBuilder; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.java index be651793021..1c1be56203e 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.java @@ -20,7 +20,7 @@ import java.util.LinkedHashMap; import java.util.List; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.springframework.security.config.annotation.SecurityConfigurer; import org.springframework.security.config.annotation.web.HttpSecurityBuilder; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupport.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupport.java index 3af0eba1720..ea0eb21b0fc 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupport.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2021 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,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.access.SecurityConfig; import org.springframework.security.config.annotation.web.HttpSecurityBuilder; @@ -48,11 +48,22 @@ static void permitAll(HttpSecurityBuilder> http RequestMatcher... requestMatchers) { ExpressionUrlAuthorizationConfigurer configurer = http .getConfigurer(ExpressionUrlAuthorizationConfigurer.class); - Assert.state(configurer != null, "permitAll only works with HttpSecurity.authorizeRequests()"); + AuthorizeHttpRequestsConfigurer httpConfigurer = http.getConfigurer(AuthorizeHttpRequestsConfigurer.class); + + boolean oneConfigurerPresent = configurer == null ^ httpConfigurer == null; + Assert.state(oneConfigurerPresent, + "permitAll only works with either HttpSecurity.authorizeRequests() or HttpSecurity.authorizeHttpRequests(). " + + "Please define one or the other but not both."); + for (RequestMatcher matcher : requestMatchers) { if (matcher != null) { - configurer.getRegistry().addMapping(0, new UrlMapping(matcher, - SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll))); + if (configurer != null) { + configurer.getRegistry().addMapping(0, new UrlMapping(matcher, + SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll))); + } + else { + httpConfigurer.addFirst(matcher, AuthorizeHttpRequestsConfigurer.permitAllAuthorizationManager); + } } } } diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurer.java index 5959d9d08e8..e41d3230423 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurer.java @@ -18,7 +18,7 @@ import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.context.ApplicationContext; import org.springframework.security.authentication.AuthenticationManager; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java index 86b9cc0275a..d9d69f7ceaa 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java @@ -20,8 +20,8 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; @@ -201,6 +201,12 @@ public SessionManagementConfigurer sessionAuthenticationFailureHandler( * {@link HttpServletResponse#encodeRedirectURL(String)} or * {@link HttpServletResponse#encodeURL(String)}, otherwise disallows HTTP sessions to * be included in the URL. This prevents leaking information to external domains. + *

+ * This is achieved by guarding {@link HttpServletResponse#encodeURL} and + * {@link HttpServletResponse#encodeRedirectURL} invocations. Any code that also + * overrides either of these two methods, like + * {@link org.springframework.web.servlet.resource.ResourceUrlEncodingFilter}, needs + * to come after the security filter chain or risk being skipped. * @param enableSessionUrlRewriting true if should allow the JSESSIONID to be * rewritten into the URLs, else false (default) * @return the {@link SessionManagementConfigurer} for further customization diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/X509Configurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/X509Configurer.java index 93e1b092506..8691b614200 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/X509Configurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/X509Configurer.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.AuthenticationManager; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurer.java index 02a99fdb2a4..0abfb199020 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurer.java @@ -18,9 +18,11 @@ import java.util.Arrays; import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.function.Supplier; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.context.ApplicationContext; import org.springframework.core.convert.converter.Converter; @@ -51,6 +53,9 @@ 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.access.AccessDeniedHandlerImpl; +import org.springframework.security.web.access.DelegatingAccessDeniedHandler; +import org.springframework.security.web.csrf.CsrfException; import org.springframework.security.web.util.matcher.AndRequestMatcher; import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher; import org.springframework.security.web.util.matcher.NegatedRequestMatcher; @@ -153,7 +158,9 @@ public final class OAuth2ResourceServerConfigurer(Map.of(CsrfException.class, new AccessDeniedHandlerImpl())), + new BearerTokenAccessDeniedHandler()); private AuthenticationEntryPoint authenticationEntryPoint = new BearerTokenAuthenticationEntryPoint(); diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurer.java index 0d618ce01e8..db042047798 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurer.java @@ -21,7 +21,7 @@ import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.openid4java.consumer.ConsumerException; import org.openid4java.consumer.ConsumerManager; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurer.java index aa1ddb29af6..d6cf80068dc 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurer.java @@ -19,7 +19,7 @@ import java.util.LinkedHashMap; import java.util.Map; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.opensaml.core.Version; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LogoutConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LogoutConfigurer.java index 45bd549c01c..cd9aca8d168 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LogoutConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LogoutConfigurer.java @@ -21,8 +21,8 @@ import java.util.Objects; import java.util.function.Predicate; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.opensaml.core.Version; diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.java index 60139cd59aa..6c29525dde8 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.java @@ -50,8 +50,8 @@ import org.springframework.util.Assert; import org.springframework.util.PathMatcher; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; -import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.server.HandshakeInterceptor; import org.springframework.web.socket.server.support.WebSocketHttpRequestHandler; import org.springframework.web.socket.sockjs.SockJsService; @@ -84,8 +84,8 @@ */ @Order(Ordered.HIGHEST_PRECEDENCE + 100) @Import(ObjectPostProcessorConfiguration.class) -public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends AbstractWebSocketMessageBrokerConfigurer - implements SmartInitializingSingleton { +public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer + implements WebSocketMessageBrokerConfigurer, SmartInitializingSingleton { private final WebSocketMessageSecurityMetadataSourceRegistry inboundRegistry = new WebSocketMessageSecurityMetadataSourceRegistry(); @@ -107,12 +107,12 @@ public void addArgumentResolvers(List argumentRes @Override public final void configureClientInboundChannel(ChannelRegistration registration) { ChannelSecurityInterceptor inboundChannelSecurity = this.context.getBean(ChannelSecurityInterceptor.class); - registration.setInterceptors(this.context.getBean(SecurityContextChannelInterceptor.class)); + registration.interceptors(this.context.getBean(SecurityContextChannelInterceptor.class)); if (!sameOriginDisabled()) { - registration.setInterceptors(this.context.getBean(CsrfChannelInterceptor.class)); + registration.interceptors(this.context.getBean(CsrfChannelInterceptor.class)); } if (this.inboundRegistry.containsMapping()) { - registration.setInterceptors(inboundChannelSecurity); + registration.interceptors(inboundChannelSecurity); } customizeClientInboundChannel(registration); } diff --git a/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java b/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java index d3c0ce32f4b..7b1d57076fa 100644 --- a/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java +++ b/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java @@ -23,7 +23,7 @@ import java.util.Map; import java.util.function.Function; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/config/src/main/java/org/springframework/security/config/http/CsrfBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/CsrfBeanDefinitionParser.java index 58dcd468a80..0e21437183d 100644 --- a/config/src/main/java/org/springframework/security/config/http/CsrfBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/CsrfBeanDefinitionParser.java @@ -20,7 +20,7 @@ import java.util.HashSet; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.w3c.dom.Element; diff --git a/config/src/main/java/org/springframework/security/config/http/DefaultFilterChainValidator.java b/config/src/main/java/org/springframework/security/config/http/DefaultFilterChainValidator.java index 423ae18de64..932d647fd6b 100644 --- a/config/src/main/java/org/springframework/security/config/http/DefaultFilterChainValidator.java +++ b/config/src/main/java/org/springframework/security/config/http/DefaultFilterChainValidator.java @@ -21,7 +21,7 @@ import java.util.Iterator; import java.util.List; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/config/src/main/java/org/springframework/security/config/http/HeadersBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/HeadersBeanDefinitionParser.java index 7f42ff724e2..b980f635a73 100644 --- a/config/src/main/java/org/springframework/security/config/http/HeadersBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/HeadersBeanDefinitionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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,6 +36,9 @@ import org.springframework.security.web.header.HeaderWriterFilter; import org.springframework.security.web.header.writers.CacheControlHeadersWriter; import org.springframework.security.web.header.writers.ContentSecurityPolicyHeaderWriter; +import org.springframework.security.web.header.writers.CrossOriginEmbedderPolicyHeaderWriter; +import org.springframework.security.web.header.writers.CrossOriginOpenerPolicyHeaderWriter; +import org.springframework.security.web.header.writers.CrossOriginResourcePolicyHeaderWriter; import org.springframework.security.web.header.writers.FeaturePolicyHeaderWriter; import org.springframework.security.web.header.writers.HpkpHeaderWriter; import org.springframework.security.web.header.writers.HstsHeaderWriter; @@ -122,6 +125,12 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser { private static final String PERMISSIONS_POLICY_ELEMENT = "permissions-policy"; + private static final String CROSS_ORIGIN_OPENER_POLICY_ELEMENT = "cross-origin-opener-policy"; + + private static final String CROSS_ORIGIN_EMBEDDER_POLICY_ELEMENT = "cross-origin-embedder-policy"; + + private static final String CROSS_ORIGIN_RESOURCE_POLICY_ELEMENT = "cross-origin-resource-policy"; + private static final String ALLOW_FROM = "ALLOW-FROM"; private ManagedList headerWriters; @@ -144,6 +153,9 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { parseReferrerPolicyElement(element, parserContext); parseFeaturePolicyElement(element, parserContext); parsePermissionsPolicyElement(element, parserContext); + parseCrossOriginOpenerPolicy(disabled, element); + parseCrossOriginEmbedderPolicy(disabled, element); + parseCrossOriginResourcePolicy(disabled, element); parseHeaderElements(element); boolean noWriters = this.headerWriters.isEmpty(); if (disabled && !noWriters) { @@ -376,6 +388,75 @@ private void addPermissionsPolicy(Element permissionsPolicyElement, ParserContex this.headerWriters.add(headersWriter.getBeanDefinition()); } + private void parseCrossOriginOpenerPolicy(boolean elementDisabled, Element element) { + if (elementDisabled || element == null) { + return; + } + CrossOriginOpenerPolicyHeaderWriter writer = new CrossOriginOpenerPolicyHeaderWriter(); + Element crossOriginOpenerPolicyElement = DomUtils.getChildElementByTagName(element, + CROSS_ORIGIN_OPENER_POLICY_ELEMENT); + if (crossOriginOpenerPolicyElement != null) { + addCrossOriginOpenerPolicy(crossOriginOpenerPolicyElement, writer); + } + BeanDefinitionBuilder builder = BeanDefinitionBuilder + .genericBeanDefinition(CrossOriginOpenerPolicyHeaderWriter.class, () -> writer); + this.headerWriters.add(builder.getBeanDefinition()); + } + + private void parseCrossOriginEmbedderPolicy(boolean elementDisabled, Element element) { + if (elementDisabled || element == null) { + return; + } + CrossOriginEmbedderPolicyHeaderWriter writer = new CrossOriginEmbedderPolicyHeaderWriter(); + Element crossOriginEmbedderPolicyElement = DomUtils.getChildElementByTagName(element, + CROSS_ORIGIN_EMBEDDER_POLICY_ELEMENT); + if (crossOriginEmbedderPolicyElement != null) { + addCrossOriginEmbedderPolicy(crossOriginEmbedderPolicyElement, writer); + } + BeanDefinitionBuilder builder = BeanDefinitionBuilder + .genericBeanDefinition(CrossOriginEmbedderPolicyHeaderWriter.class, () -> writer); + this.headerWriters.add(builder.getBeanDefinition()); + } + + private void parseCrossOriginResourcePolicy(boolean elementDisabled, Element element) { + if (elementDisabled || element == null) { + return; + } + CrossOriginResourcePolicyHeaderWriter writer = new CrossOriginResourcePolicyHeaderWriter(); + Element crossOriginResourcePolicyElement = DomUtils.getChildElementByTagName(element, + CROSS_ORIGIN_RESOURCE_POLICY_ELEMENT); + if (crossOriginResourcePolicyElement != null) { + addCrossOriginResourcePolicy(crossOriginResourcePolicyElement, writer); + } + BeanDefinitionBuilder builder = BeanDefinitionBuilder + .genericBeanDefinition(CrossOriginResourcePolicyHeaderWriter.class, () -> writer); + this.headerWriters.add(builder.getBeanDefinition()); + } + + private void addCrossOriginResourcePolicy(Element crossOriginResourcePolicyElement, + CrossOriginResourcePolicyHeaderWriter writer) { + String policy = crossOriginResourcePolicyElement.getAttribute(ATT_POLICY); + if (StringUtils.hasText(policy)) { + writer.setPolicy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.from(policy)); + } + } + + private void addCrossOriginEmbedderPolicy(Element crossOriginEmbedderPolicyElement, + CrossOriginEmbedderPolicyHeaderWriter writer) { + String policy = crossOriginEmbedderPolicyElement.getAttribute(ATT_POLICY); + if (StringUtils.hasText(policy)) { + writer.setPolicy(CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.from(policy)); + } + } + + private void addCrossOriginOpenerPolicy(Element crossOriginOpenerPolicyElement, + CrossOriginOpenerPolicyHeaderWriter writer) { + String policy = crossOriginOpenerPolicyElement.getAttribute(ATT_POLICY); + if (StringUtils.hasText(policy)) { + writer.setPolicy(CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy.from(policy)); + } + } + private void attrNotAllowed(ParserContext context, String attrName, String otherAttrName, Element element) { context.getReaderContext().error("Only one of '" + attrName + "' or '" + otherAttrName + "' can be set.", element); diff --git a/config/src/main/java/org/springframework/security/config/http/HttpConfigurationBuilder.java b/config/src/main/java/org/springframework/security/config/http/HttpConfigurationBuilder.java index e3339b3b136..88e8d3001d1 100644 --- a/config/src/main/java/org/springframework/security/config/http/HttpConfigurationBuilder.java +++ b/config/src/main/java/org/springframework/security/config/http/HttpConfigurationBuilder.java @@ -19,7 +19,7 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.ServletRequest; +import jakarta.servlet.ServletRequest; import org.w3c.dom.Element; diff --git a/config/src/main/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParser.java index 2be6d13796c..ec959feb2ad 100644 --- a/config/src/main/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParser.java @@ -19,7 +19,7 @@ import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.w3c.dom.Element; diff --git a/config/src/main/java/org/springframework/security/config/http/SessionCreationPolicy.java b/config/src/main/java/org/springframework/security/config/http/SessionCreationPolicy.java index 74beef711d6..d4ee52926cc 100644 --- a/config/src/main/java/org/springframework/security/config/http/SessionCreationPolicy.java +++ b/config/src/main/java/org/springframework/security/config/http/SessionCreationPolicy.java @@ -16,7 +16,7 @@ package org.springframework.security.config.http; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.springframework.security.core.context.SecurityContext; diff --git a/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java b/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java index 282896dd836..5c0094f079a 100644 --- a/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java +++ b/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java @@ -133,6 +133,7 @@ import org.springframework.security.web.server.authorization.AuthorizationWebFilter; import org.springframework.security.web.server.authorization.DelegatingReactiveAuthorizationManager; import org.springframework.security.web.server.authorization.ExceptionTranslationWebFilter; +import org.springframework.security.web.server.authorization.IpAddressReactiveAuthorizationManager; import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler; import org.springframework.security.web.server.authorization.ServerWebExchangeDelegatingServerAccessDeniedHandler; import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository; @@ -148,6 +149,12 @@ import org.springframework.security.web.server.header.CompositeServerHttpHeadersWriter; import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter; import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter; +import org.springframework.security.web.server.header.CrossOriginEmbedderPolicyServerHttpHeadersWriter; +import org.springframework.security.web.server.header.CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy; +import org.springframework.security.web.server.header.CrossOriginOpenerPolicyServerHttpHeadersWriter; +import org.springframework.security.web.server.header.CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy; +import org.springframework.security.web.server.header.CrossOriginResourcePolicyServerHttpHeadersWriter; +import org.springframework.security.web.server.header.CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy; import org.springframework.security.web.server.header.FeaturePolicyServerHttpHeadersWriter; import org.springframework.security.web.server.header.HttpHeaderWriterWebFilter; import org.springframework.security.web.server.header.PermissionsPolicyServerHttpHeadersWriter; @@ -1682,6 +1689,18 @@ public AuthorizeExchangeSpec authenticated() { return access(AuthenticatedReactiveAuthorizationManager.authenticated()); } + /** + * Require a specific IP address or range using an IP/Netmask (e.g. + * 192.168.1.0/24). + * @param ipAddress the address or range of addresses from which the request + * must come. + * @return the {@link AuthorizeExchangeSpec} to configure + * @since 5.7 + */ + public AuthorizeExchangeSpec hasIpAddress(String ipAddress) { + return access(IpAddressReactiveAuthorizationManager.hasIpAddress(ipAddress)); + } + /** * Allows plugging in a custom authorization strategy * @param manager the authorization manager to use @@ -2367,10 +2386,17 @@ public final class HeaderSpec { private ReferrerPolicyServerHttpHeadersWriter referrerPolicy = new ReferrerPolicyServerHttpHeadersWriter(); + private CrossOriginOpenerPolicyServerHttpHeadersWriter crossOriginOpenerPolicy = new CrossOriginOpenerPolicyServerHttpHeadersWriter(); + + private CrossOriginEmbedderPolicyServerHttpHeadersWriter crossOriginEmbedderPolicy = new CrossOriginEmbedderPolicyServerHttpHeadersWriter(); + + private CrossOriginResourcePolicyServerHttpHeadersWriter crossOriginResourcePolicy = new CrossOriginResourcePolicyServerHttpHeadersWriter(); + private HeaderSpec() { this.writers = new ArrayList<>(Arrays.asList(this.cacheControl, this.contentTypeOptions, this.hsts, this.frameOptions, this.xss, this.featurePolicy, this.permissionsPolicy, this.contentSecurityPolicy, - this.referrerPolicy)); + this.referrerPolicy, this.crossOriginOpenerPolicy, this.crossOriginEmbedderPolicy, + this.crossOriginResourcePolicy)); } /** @@ -2582,6 +2608,84 @@ public HeaderSpec referrerPolicy(Customizer referrerPolicyCu return this; } + /** + * Configures the + * Cross-Origin-Opener-Policy header. + * @return the {@link CrossOriginOpenerPolicySpec} to configure + * @since 5.7 + * @see CrossOriginOpenerPolicyServerHttpHeadersWriter + */ + public CrossOriginOpenerPolicySpec crossOriginOpenerPolicy() { + return new CrossOriginOpenerPolicySpec(); + } + + /** + * Configures the + * Cross-Origin-Opener-Policy header. + * @return the {@link HeaderSpec} to customize + * @since 5.7 + * @see CrossOriginOpenerPolicyServerHttpHeadersWriter + */ + public HeaderSpec crossOriginOpenerPolicy( + Customizer crossOriginOpenerPolicyCustomizer) { + crossOriginOpenerPolicyCustomizer.customize(new CrossOriginOpenerPolicySpec()); + return this; + } + + /** + * Configures the + * Cross-Origin-Embedder-Policy header. + * @return the {@link CrossOriginEmbedderPolicySpec} to configure + * @since 5.7 + * @see CrossOriginEmbedderPolicyServerHttpHeadersWriter + */ + public CrossOriginEmbedderPolicySpec crossOriginEmbedderPolicy() { + return new CrossOriginEmbedderPolicySpec(); + } + + /** + * Configures the + * Cross-Origin-Embedder-Policy header. + * @return the {@link HeaderSpec} to customize + * @since 5.7 + * @see CrossOriginEmbedderPolicyServerHttpHeadersWriter + */ + public HeaderSpec crossOriginEmbedderPolicy( + Customizer crossOriginEmbedderPolicyCustomizer) { + crossOriginEmbedderPolicyCustomizer.customize(new CrossOriginEmbedderPolicySpec()); + return this; + } + + /** + * Configures the + * Cross-Origin-Resource-Policy header. + * @return the {@link CrossOriginResourcePolicySpec} to configure + * @since 5.7 + * @see CrossOriginResourcePolicyServerHttpHeadersWriter + */ + public CrossOriginResourcePolicySpec crossOriginResourcePolicy() { + return new CrossOriginResourcePolicySpec(); + } + + /** + * Configures the + * Cross-Origin-Resource-Policy header. + * @return the {@link HeaderSpec} to customize + * @since 5.7 + * @see CrossOriginResourcePolicyServerHttpHeadersWriter + */ + public HeaderSpec crossOriginResourcePolicy( + Customizer crossOriginResourcePolicyCustomizer) { + crossOriginResourcePolicyCustomizer.customize(new CrossOriginResourcePolicySpec()); + return this; + } + /** * Configures cache control headers * @@ -2897,6 +3001,99 @@ public HeaderSpec and() { } + /** + * Configures the Cross-Origin-Opener-Policy header + * + * @since 5.7 + */ + public final class CrossOriginOpenerPolicySpec { + + private CrossOriginOpenerPolicySpec() { + } + + /** + * Sets the value to be used in the `Cross-Origin-Opener-Policy` header + * @param openerPolicy a opener policy + * @return the {@link CrossOriginOpenerPolicySpec} to continue configuring + */ + public CrossOriginOpenerPolicySpec policy(CrossOriginOpenerPolicy openerPolicy) { + HeaderSpec.this.crossOriginOpenerPolicy.setPolicy(openerPolicy); + return this; + } + + /** + * Allows method chaining to continue configuring the + * {@link ServerHttpSecurity}. + * @return the {@link HeaderSpec} to continue configuring + */ + public HeaderSpec and() { + return HeaderSpec.this; + } + + } + + /** + * Configures the Cross-Origin-Embedder-Policy header + * + * @since 5.7 + */ + public final class CrossOriginEmbedderPolicySpec { + + private CrossOriginEmbedderPolicySpec() { + } + + /** + * Sets the value to be used in the `Cross-Origin-Embedder-Policy` header + * @param embedderPolicy a opener policy + * @return the {@link CrossOriginEmbedderPolicySpec} to continue configuring + */ + public CrossOriginEmbedderPolicySpec policy(CrossOriginEmbedderPolicy embedderPolicy) { + HeaderSpec.this.crossOriginEmbedderPolicy.setPolicy(embedderPolicy); + return this; + } + + /** + * Allows method chaining to continue configuring the + * {@link ServerHttpSecurity}. + * @return the {@link HeaderSpec} to continue configuring + */ + public HeaderSpec and() { + return HeaderSpec.this; + } + + } + + /** + * Configures the Cross-Origin-Resource-Policy header + * + * @since 5.7 + */ + public final class CrossOriginResourcePolicySpec { + + private CrossOriginResourcePolicySpec() { + } + + /** + * Sets the value to be used in the `Cross-Origin-Resource-Policy` header + * @param resourcePolicy a opener policy + * @return the {@link CrossOriginResourcePolicySpec} to continue configuring + */ + public CrossOriginResourcePolicySpec policy(CrossOriginResourcePolicy resourcePolicy) { + HeaderSpec.this.crossOriginResourcePolicy.setPolicy(resourcePolicy); + return this; + } + + /** + * Allows method chaining to continue configuring the + * {@link ServerHttpSecurity}. + * @return the {@link HeaderSpec} to continue configuring + */ + public HeaderSpec and() { + return HeaderSpec.this; + } + + } + } /** diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/AbstractRequestMatcherDsl.kt similarity index 96% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/AbstractRequestMatcherDsl.kt index 9e35287b5f5..0a4720341e8 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/AbstractRequestMatcherDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.http.HttpMethod import org.springframework.security.web.util.matcher.AnyRequestMatcher diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/AnonymousDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/AnonymousDsl.kt similarity index 97% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/AnonymousDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/AnonymousDsl.kt index 89055ed025a..8fca7646b47 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/AnonymousDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/AnonymousDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.authentication.AuthenticationProvider import org.springframework.security.config.annotation.web.builders.HttpSecurity diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/AuthorizeRequestsDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/AuthorizeRequestsDsl.kt similarity index 99% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/AuthorizeRequestsDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/AuthorizeRequestsDsl.kt index 663287a1184..693966ace78 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/AuthorizeRequestsDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/AuthorizeRequestsDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.http.HttpMethod import org.springframework.security.config.annotation.web.builders.HttpSecurity diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/CorsDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/CorsDsl.kt similarity index 96% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/CorsDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/CorsDsl.kt index a4b0d0ba68a..38363bf5883 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/CorsDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/CorsDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.CorsConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/CsrfDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/CsrfDsl.kt similarity index 96% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/CsrfDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/CsrfDsl.kt index f0120e369dc..0ed411416cc 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/CsrfDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/CsrfDsl.kt @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy import org.springframework.security.web.csrf.CsrfTokenRepository import org.springframework.security.web.util.matcher.RequestMatcher -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest /** * A Kotlin DSL to configure [HttpSecurity] CSRF protection diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/ExceptionHandlingDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/ExceptionHandlingDsl.kt similarity index 98% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/ExceptionHandlingDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/ExceptionHandlingDsl.kt index cba38265c76..7acd172cb7c 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/ExceptionHandlingDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/ExceptionHandlingDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/FormLoginDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/FormLoginDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/FormLoginDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/FormLoginDsl.kt index afa40f2281b..4f15900b3e4 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/FormLoginDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/FormLoginDsl.kt @@ -14,15 +14,14 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.authentication.AuthenticationDetailsSource -import org.springframework.security.config.annotation.web.HttpSecurityBuilder import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer import org.springframework.security.web.authentication.AuthenticationFailureHandler import org.springframework.security.web.authentication.AuthenticationSuccessHandler -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest /** * A Kotlin DSL to configure [HttpSecurity] form login using idiomatic Kotlin code. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/HeadersDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/HeadersDsl.kt similarity index 75% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/HeadersDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/HeadersDsl.kt index 3079dd11ff3..a468be3b23e 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/HeadersDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/HeadersDsl.kt @@ -14,11 +14,11 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer -import org.springframework.security.config.web.servlet.headers.* +import org.springframework.security.config.annotation.web.headers.* import org.springframework.security.web.header.HeaderWriter import org.springframework.security.web.header.writers.* import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter @@ -42,6 +42,9 @@ class HeadersDsl { private var referrerPolicy: ((HeadersConfigurer.ReferrerPolicyConfig) -> Unit)? = null private var featurePolicyDirectives: String? = null private var permissionsPolicy: ((HeadersConfigurer.PermissionsPolicyConfig) -> Unit)? = null + private var crossOriginOpenerPolicy: ((HeadersConfigurer.CrossOriginOpenerPolicyConfig) -> Unit)? = null + private var crossOriginEmbedderPolicy: ((HeadersConfigurer.CrossOriginEmbedderPolicyConfig) -> Unit)? = null + private var crossOriginResourcePolicy: ((HeadersConfigurer.CrossOriginResourcePolicyConfig) -> Unit)? = null private var disabled = false private var headerWriters = mutableListOf() @@ -181,6 +184,54 @@ class HeadersDsl { this.permissionsPolicy = PermissionsPolicyDsl().apply(permissionsPolicyConfig).get() } + /** + * Allows configuration for + * Cross-Origin-Opener-Policy header. + * + *

+ * Calling this method automatically enables (includes) the Cross-Origin-Opener-Policy + * header in the response using the supplied policy. + *

+ * + * @since 5.7 + * @param crossOriginOpenerPolicyConfig the customization to apply to the header + */ + fun crossOriginOpenerPolicy(crossOriginOpenerPolicyConfig: CrossOriginOpenerPolicyDsl.() -> Unit) { + this.crossOriginOpenerPolicy = CrossOriginOpenerPolicyDsl().apply(crossOriginOpenerPolicyConfig).get() + } + + /** + * Allows configuration for + * Cross-Origin-Embedder-Policy header. + * + *

+ * Calling this method automatically enables (includes) the Cross-Origin-Embedder-Policy + * header in the response using the supplied policy. + *

+ * + * @since 5.7 + * @param crossOriginEmbedderPolicyConfig the customization to apply to the header + */ + fun crossOriginEmbedderPolicy(crossOriginEmbedderPolicyConfig: CrossOriginEmbedderPolicyDsl.() -> Unit) { + this.crossOriginEmbedderPolicy = CrossOriginEmbedderPolicyDsl().apply(crossOriginEmbedderPolicyConfig).get() + } + + /** + * Configures the + * Cross-Origin-Resource-Policy header. + * + *

+ * Calling this method automatically enables (includes) the Cross-Origin-Resource-Policy + * header in the response using the supplied policy. + *

+ * + * @since 5.7 + * @param crossOriginResourcePolicyConfig the customization to apply to the header + */ + fun crossOriginResourcePolicy(crossOriginResourcePolicyConfig: CrossOriginResourcePolicyDsl.() -> Unit) { + this.crossOriginResourcePolicy = CrossOriginResourcePolicyDsl().apply(crossOriginResourcePolicyConfig).get() + } + /** * Adds a [HeaderWriter] instance. * @@ -238,6 +289,15 @@ class HeadersDsl { permissionsPolicy?.also { headers.permissionsPolicy(permissionsPolicy) } + crossOriginOpenerPolicy?.also { + headers.crossOriginOpenerPolicy(crossOriginOpenerPolicy) + } + crossOriginEmbedderPolicy?.also { + headers.crossOriginEmbedderPolicy(crossOriginEmbedderPolicy) + } + crossOriginResourcePolicy?.also { + headers.crossOriginResourcePolicy(crossOriginResourcePolicy) + } headerWriters.forEach { headerWriter -> headers.addHeaderWriter(headerWriter) } diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/HttpBasicDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/HttpBasicDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/HttpBasicDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/HttpBasicDsl.kt index 7a1a1155dd6..53235664e92 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/HttpBasicDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/HttpBasicDsl.kt @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.authentication.AuthenticationDetailsSource import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HttpBasicConfigurer import org.springframework.security.web.AuthenticationEntryPoint import org.springframework.security.web.authentication.www.BasicAuthenticationFilter -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest /** * A Kotlin DSL to configure [HttpSecurity] basic authentication using idiomatic Kotlin code. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/HttpSecurityDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/HttpSecurityDsl.kt similarity index 99% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/HttpSecurityDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/HttpSecurityDsl.kt index d7a17f72af6..ef35967ffda 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/HttpSecurityDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/HttpSecurityDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.context.ApplicationContext import org.springframework.security.authentication.AuthenticationManager @@ -23,8 +23,8 @@ import org.springframework.security.oauth2.client.registration.ClientRegistratio import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository import org.springframework.security.web.util.matcher.RequestMatcher import org.springframework.util.ClassUtils -import javax.servlet.Filter -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.Filter +import jakarta.servlet.http.HttpServletRequest /** * Configures [HttpSecurity] using a [HttpSecurity Kotlin DSL][HttpSecurityDsl]. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/LogoutDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/LogoutDsl.kt similarity index 98% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/LogoutDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/LogoutDsl.kt index 133e45955ac..476f571967f 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/LogoutDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/LogoutDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer @@ -25,7 +25,7 @@ import org.springframework.security.web.authentication.logout.LogoutSuccessHandl import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler import org.springframework.security.web.util.matcher.RequestMatcher import java.util.* -import javax.servlet.http.HttpSession +import jakarta.servlet.http.HttpSession /** * A Kotlin DSL to configure [HttpSecurity] logout support diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/OAuth2ClientDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/OAuth2ClientDsl.kt similarity index 94% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/OAuth2ClientDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/OAuth2ClientDsl.kt index 2681ed4e192..f0df1b281ba 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/OAuth2ClientDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/OAuth2ClientDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web /* * Copyright 2002-2020 the original author or authors. @@ -33,8 +33,8 @@ package org.springframework.security.config.web.servlet */ import org.springframework.security.config.annotation.web.builders.HttpSecurity -import org.springframework.security.config.web.servlet.oauth2.client.AuthorizationCodeGrantDsl -import org.springframework.security.config.web.servlet.oauth2.login.AuthorizationEndpointDsl +import org.springframework.security.config.annotation.web.oauth2.client.AuthorizationCodeGrantDsl +import org.springframework.security.config.annotation.web.oauth2.login.AuthorizationEndpointDsl import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2ClientConfigurer import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/OAuth2LoginDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/OAuth2LoginDsl.kt similarity index 94% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/OAuth2LoginDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/OAuth2LoginDsl.kt index 09668dcaa20..9a69b448fd1 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/OAuth2LoginDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/OAuth2LoginDsl.kt @@ -14,22 +14,21 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.authentication.AuthenticationDetailsSource -import org.springframework.security.config.annotation.web.HttpSecurityBuilder import org.springframework.security.config.annotation.web.builders.HttpSecurity -import org.springframework.security.config.web.servlet.oauth2.login.AuthorizationEndpointDsl -import org.springframework.security.config.web.servlet.oauth2.login.RedirectionEndpointDsl -import org.springframework.security.config.web.servlet.oauth2.login.TokenEndpointDsl -import org.springframework.security.config.web.servlet.oauth2.login.UserInfoEndpointDsl +import org.springframework.security.config.annotation.web.oauth2.login.AuthorizationEndpointDsl +import org.springframework.security.config.annotation.web.oauth2.login.RedirectionEndpointDsl +import org.springframework.security.config.annotation.web.oauth2.login.TokenEndpointDsl +import org.springframework.security.config.annotation.web.oauth2.login.UserInfoEndpointDsl import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository import org.springframework.security.web.authentication.AuthenticationFailureHandler import org.springframework.security.web.authentication.AuthenticationSuccessHandler -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest /** * A Kotlin DSL to configure [HttpSecurity] OAuth 2.0 login using idiomatic Kotlin code. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/OAuth2ResourceServerDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/OAuth2ResourceServerDsl.kt similarity index 94% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/OAuth2ResourceServerDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/OAuth2ResourceServerDsl.kt index d881c27f14b..0dfeced425d 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/OAuth2ResourceServerDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/OAuth2ResourceServerDsl.kt @@ -14,17 +14,17 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.authentication.AuthenticationManagerResolver import org.springframework.security.config.annotation.web.builders.HttpSecurity -import org.springframework.security.config.web.servlet.oauth2.resourceserver.JwtDsl -import org.springframework.security.config.web.servlet.oauth2.resourceserver.OpaqueTokenDsl +import org.springframework.security.config.annotation.web.oauth2.resourceserver.JwtDsl +import org.springframework.security.config.annotation.web.oauth2.resourceserver.OpaqueTokenDsl import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver import org.springframework.security.web.AuthenticationEntryPoint import org.springframework.security.web.access.AccessDeniedHandler -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest /** * A Kotlin DSL to configure [HttpSecurity] OAuth 2.0 resource server support using diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/PasswordManagementDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/PasswordManagementDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/PasswordManagementDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/PasswordManagementDsl.kt index 474dca8704d..3d8f2e3ed0a 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/PasswordManagementDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/PasswordManagementDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.PasswordManagementConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/PortMapperDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/PortMapperDsl.kt similarity index 96% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/PortMapperDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/PortMapperDsl.kt index d23f584fe06..a2671a271c4 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/PortMapperDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/PortMapperDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.PortMapperConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/RememberMeDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/RememberMeDsl.kt similarity index 98% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/RememberMeDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/RememberMeDsl.kt index db69d5d4f69..9f6ff66cf14 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/RememberMeDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/RememberMeDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/RequestCacheDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/RequestCacheDsl.kt similarity index 96% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/RequestCacheDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/RequestCacheDsl.kt index b57f017538f..738e0a06132 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/RequestCacheDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/RequestCacheDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.RequestCacheConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/RequiresChannelDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/RequiresChannelDsl.kt similarity index 99% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/RequiresChannelDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/RequiresChannelDsl.kt index a7149014c2e..c567dc56792 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/RequiresChannelDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/RequiresChannelDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.ChannelSecurityConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/Saml2Dsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/Saml2Dsl.kt similarity index 97% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/Saml2Dsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/Saml2Dsl.kt index 3c658e2397a..810bf54447a 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/Saml2Dsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/Saml2Dsl.kt @@ -14,10 +14,9 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.authentication.AuthenticationManager -import org.springframework.security.config.annotation.web.HttpSecurityBuilder import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.saml2.Saml2LoginConfigurer import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/SecurityMarker.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/SecurityMarker.kt similarity index 93% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/SecurityMarker.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/SecurityMarker.kt index d86554668e0..f82ffeafdae 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/SecurityMarker.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/SecurityMarker.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web /** * Marker annotation indicating that the annotated class is part of the security DSL. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/SessionManagementDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/SessionManagementDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/SessionManagementDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/SessionManagementDsl.kt index c0405ff4f86..52df70a3dc7 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/SessionManagementDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/SessionManagementDsl.kt @@ -14,11 +14,11 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.config.annotation.web.builders.HttpSecurity -import org.springframework.security.config.web.servlet.session.SessionConcurrencyDsl -import org.springframework.security.config.web.servlet.session.SessionFixationDsl +import org.springframework.security.config.annotation.web.session.SessionConcurrencyDsl +import org.springframework.security.config.annotation.web.session.SessionFixationDsl import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.web.authentication.AuthenticationFailureHandler diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/X509Dsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/X509Dsl.kt similarity index 97% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/X509Dsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/X509Dsl.kt index 5abcb3a5185..85652b8fa7d 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/X509Dsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/X509Dsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.springframework.security.authentication.AuthenticationDetailsSource import org.springframework.security.config.annotation.web.builders.HttpSecurity @@ -26,7 +26,7 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedA import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails import org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest /** * A Kotlin DSL to configure [HttpSecurity] X509 based pre authentication diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/CacheControlDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CacheControlDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/CacheControlDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CacheControlDsl.kt index 316015b0160..eb63d73c30b 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/CacheControlDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CacheControlDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/ContentSecurityPolicyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/ContentSecurityPolicyDsl.kt similarity index 96% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/ContentSecurityPolicyDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/ContentSecurityPolicyDsl.kt index 270b1d14b4d..559da5275de 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/ContentSecurityPolicyDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/ContentSecurityPolicyDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/ContentTypeOptionsDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/ContentTypeOptionsDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/ContentTypeOptionsDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/ContentTypeOptionsDsl.kt index 92014ae4063..98cf2da39cb 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/ContentTypeOptionsDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/ContentTypeOptionsDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CrossOriginEmbedderPolicyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CrossOriginEmbedderPolicyDsl.kt new file mode 100644 index 00000000000..f24c33ec933 --- /dev/null +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CrossOriginEmbedderPolicyDsl.kt @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.config.annotation.web.headers + +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer +import org.springframework.security.web.header.writers.CrossOriginEmbedderPolicyHeaderWriter + +/** + * A Kotlin DSL to configure the [HttpSecurity] Cross-Origin-Embedder-Policy header using + * idiomatic Kotlin code. + * + * @author Marcus Da Coregio + * @since 5.7 + * @property policy the policy to be used in the response header. + */ +@HeadersSecurityMarker +class CrossOriginEmbedderPolicyDsl { + + var policy: CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy? = null + + internal fun get(): (HeadersConfigurer.CrossOriginEmbedderPolicyConfig) -> Unit { + return { crossOriginEmbedderPolicy -> + policy?.also { + crossOriginEmbedderPolicy.policy(policy) + } + } + } +} diff --git a/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CrossOriginOpenerPolicyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CrossOriginOpenerPolicyDsl.kt new file mode 100644 index 00000000000..2a9fc2a3b8e --- /dev/null +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CrossOriginOpenerPolicyDsl.kt @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.config.annotation.web.headers + +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer +import org.springframework.security.web.header.writers.CrossOriginOpenerPolicyHeaderWriter + +/** + * A Kotlin DSL to configure the [HttpSecurity] Cross-Origin-Opener-Policy header using + * idiomatic Kotlin code. + * + * @author Marcus Da Coregio + * @since 5.7 + * @property policy the policy to be used in the response header. + */ +@HeadersSecurityMarker +class CrossOriginOpenerPolicyDsl { + + var policy: CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy? = null + + internal fun get(): (HeadersConfigurer.CrossOriginOpenerPolicyConfig) -> Unit { + return { crossOriginOpenerPolicy -> + policy?.also { + crossOriginOpenerPolicy.policy(policy) + } + } + } +} diff --git a/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CrossOriginResourcePolicyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CrossOriginResourcePolicyDsl.kt new file mode 100644 index 00000000000..cd5fbe03e74 --- /dev/null +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/CrossOriginResourcePolicyDsl.kt @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.config.annotation.web.headers + +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer +import org.springframework.security.web.header.writers.CrossOriginResourcePolicyHeaderWriter + +/** + * A Kotlin DSL to configure the [HttpSecurity] Cross-Origin-Resource-Policy header using + * idiomatic Kotlin code. + * + * @author Marcus Da Coregio + * @since 5.7 + * @property policy the policy to be used in the response header. + */ +@HeadersSecurityMarker +class CrossOriginResourcePolicyDsl { + + var policy: CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy? = null + + internal fun get(): (HeadersConfigurer.CrossOriginResourcePolicyConfig) -> Unit { + return { crossOriginResourcePolicy -> + policy?.also { + crossOriginResourcePolicy.policy(policy) + } + } + } +} diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/FrameOptionsDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/FrameOptionsDsl.kt similarity index 96% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/FrameOptionsDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/FrameOptionsDsl.kt index 3bf766ca98a..a4a1c20b106 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/FrameOptionsDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/FrameOptionsDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/HeadersSecurityMarker.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/HeadersSecurityMarker.kt similarity index 92% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/HeadersSecurityMarker.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/HeadersSecurityMarker.kt index 67a97f56c05..93cdaa95b14 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/HeadersSecurityMarker.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/HeadersSecurityMarker.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers /** * Marker annotation indicating that the annotated class is part of the headers security DSL. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/HttpPublicKeyPinningDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/HttpPublicKeyPinningDsl.kt similarity index 97% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/HttpPublicKeyPinningDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/HttpPublicKeyPinningDsl.kt index 74fbb6272a7..987278476f9 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/HttpPublicKeyPinningDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/HttpPublicKeyPinningDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/HttpStrictTransportSecurityDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/HttpStrictTransportSecurityDsl.kt similarity index 97% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/HttpStrictTransportSecurityDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/HttpStrictTransportSecurityDsl.kt index e23e6d36b85..dfe5aa1015d 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/HttpStrictTransportSecurityDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/HttpStrictTransportSecurityDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/PermissionsPolicyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/PermissionsPolicyDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/PermissionsPolicyDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/PermissionsPolicyDsl.kt index e668931bcd6..2dd77b1fe9b 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/PermissionsPolicyDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/PermissionsPolicyDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/ReferrerPolicyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/ReferrerPolicyDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/ReferrerPolicyDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/ReferrerPolicyDsl.kt index 1ac54d94c02..3f08fa88efb 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/ReferrerPolicyDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/ReferrerPolicyDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/XssProtectionConfigDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/XssProtectionConfigDsl.kt similarity index 96% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/XssProtectionConfigDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/XssProtectionConfigDsl.kt index a48a30af10a..295ddc82db8 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/headers/XssProtectionConfigDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/XssProtectionConfigDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/client/AuthorizationCodeGrantDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/client/AuthorizationCodeGrantDsl.kt similarity index 97% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/client/AuthorizationCodeGrantDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/client/AuthorizationCodeGrantDsl.kt index b1ab6eca61f..35356b09e12 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/client/AuthorizationCodeGrantDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/client/AuthorizationCodeGrantDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.client +package org.springframework.security.config.annotation.web.oauth2.client import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2ClientConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/client/OAuth2ClientSecurityMarker.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/client/OAuth2ClientSecurityMarker.kt similarity index 91% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/client/OAuth2ClientSecurityMarker.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/client/OAuth2ClientSecurityMarker.kt index 3b6722a2590..df40bcd5f63 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/client/OAuth2ClientSecurityMarker.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/client/OAuth2ClientSecurityMarker.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.client +package org.springframework.security.config.annotation.web.oauth2.client /** * Marker annotation indicating that the annotated class is part of the OAuth 2.0 client security DSL. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/AuthorizationEndpointDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/AuthorizationEndpointDsl.kt similarity index 96% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/AuthorizationEndpointDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/AuthorizationEndpointDsl.kt index 27c7982c6db..96289fa825d 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/AuthorizationEndpointDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/AuthorizationEndpointDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.login +package org.springframework.security.config.annotation.web.oauth2.login import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/OAuth2LoginSecurityMarker.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/OAuth2LoginSecurityMarker.kt similarity index 92% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/OAuth2LoginSecurityMarker.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/OAuth2LoginSecurityMarker.kt index 24ab0807d9d..0120f623b1c 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/OAuth2LoginSecurityMarker.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/OAuth2LoginSecurityMarker.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.login +package org.springframework.security.config.annotation.web.oauth2.login /** * Marker annotation indicating that the annotated class is part of the OAuth 2.0 login security DSL. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/RedirectionEndpointDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/RedirectionEndpointDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/RedirectionEndpointDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/RedirectionEndpointDsl.kt index ac63d88c9c1..094623aa159 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/RedirectionEndpointDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/RedirectionEndpointDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.login +package org.springframework.security.config.annotation.web.oauth2.login import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/TokenEndpointDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/TokenEndpointDsl.kt similarity index 95% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/TokenEndpointDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/TokenEndpointDsl.kt index ddba776d551..8628044299a 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/TokenEndpointDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/TokenEndpointDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.login +package org.springframework.security.config.annotation.web.oauth2.login import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/UserInfoEndpointDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/UserInfoEndpointDsl.kt similarity index 98% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/UserInfoEndpointDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/UserInfoEndpointDsl.kt index 0a5073fc9a9..ab536582340 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/login/UserInfoEndpointDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/login/UserInfoEndpointDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.login +package org.springframework.security.config.annotation.web.oauth2.login import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/JwtDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/JwtDsl.kt similarity index 97% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/JwtDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/JwtDsl.kt index a3b5cbc71a2..a91e277401c 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/JwtDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/JwtDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.resourceserver +package org.springframework.security.config.annotation.web.oauth2.resourceserver import org.springframework.core.convert.converter.Converter import org.springframework.security.authentication.AbstractAuthenticationToken diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/OAuth2ResourceServerSecurityMarker.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OAuth2ResourceServerSecurityMarker.kt similarity index 91% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/OAuth2ResourceServerSecurityMarker.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OAuth2ResourceServerSecurityMarker.kt index c561531ae97..fc24a96203a 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/OAuth2ResourceServerSecurityMarker.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OAuth2ResourceServerSecurityMarker.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.resourceserver +package org.springframework.security.config.annotation.web.oauth2.resourceserver /** * Marker annotation indicating that the annotated class is part of the OAuth 2.0 resource server security DSL. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/OpaqueTokenDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OpaqueTokenDsl.kt similarity index 97% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/OpaqueTokenDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OpaqueTokenDsl.kt index 5c8ab0c3f53..a0d84177636 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/OpaqueTokenDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OpaqueTokenDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.resourceserver +package org.springframework.security.config.annotation.web.oauth2.resourceserver import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.annotation.web.builders.HttpSecurity diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/session/SessionConcurrencyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionConcurrencyDsl.kt similarity index 97% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/session/SessionConcurrencyDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionConcurrencyDsl.kt index e0af442a9c0..0d33c0702a5 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/session/SessionConcurrencyDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionConcurrencyDsl.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.session +package org.springframework.security.config.annotation.web.session import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/session/SessionFixationDsl.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionFixationDsl.kt similarity index 94% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/session/SessionFixationDsl.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionFixationDsl.kt index b02a7d52746..92634a2dd76 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/session/SessionFixationDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionFixationDsl.kt @@ -14,12 +14,12 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.session +package org.springframework.security.config.annotation.web.session import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer -import javax.servlet.http.HttpServletRequest -import javax.servlet.http.HttpSession +import jakarta.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpSession /** * A Kotlin DSL to configure session fixation protection using idiomatic diff --git a/config/src/main/kotlin/org/springframework/security/config/web/servlet/session/SessionSecurityMarker.kt b/config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionSecurityMarker.kt similarity index 92% rename from config/src/main/kotlin/org/springframework/security/config/web/servlet/session/SessionSecurityMarker.kt rename to config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionSecurityMarker.kt index 6e5ef671b7a..5e32e6be3d6 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/session/SessionSecurityMarker.kt +++ b/config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionSecurityMarker.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.session +package org.springframework.security.config.annotation.web.session /** * Marker annotation indicating that the annotated class is part of the session security DSL. diff --git a/config/src/main/kotlin/org/springframework/security/config/web/server/AuthorizeExchangeDsl.kt b/config/src/main/kotlin/org/springframework/security/config/web/server/AuthorizeExchangeDsl.kt index 8df31aaca51..bfd029ec986 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/server/AuthorizeExchangeDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/web/server/AuthorizeExchangeDsl.kt @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -22,6 +22,7 @@ import org.springframework.security.authorization.AuthorizationDecision import org.springframework.security.authorization.ReactiveAuthorizationManager import org.springframework.security.core.Authentication import org.springframework.security.web.server.authorization.AuthorizationContext +import org.springframework.security.web.server.authorization.IpAddressReactiveAuthorizationManager import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers import org.springframework.security.web.util.matcher.RequestMatcher @@ -108,6 +109,13 @@ class AuthorizeExchangeDsl { fun hasAnyAuthority(vararg authorities: String): ReactiveAuthorizationManager = AuthorityReactiveAuthorizationManager.hasAnyAuthority(*authorities) + /** + * Require a specific IP or range of IP addresses. + * @since 5.7 + */ + fun hasIpAddress(ipAddress: String): ReactiveAuthorizationManager = + IpAddressReactiveAuthorizationManager.hasIpAddress(ipAddress) + /** * Require an authenticated user. */ diff --git a/config/src/main/kotlin/org/springframework/security/config/web/server/ServerCrossOriginEmbedderPolicyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/web/server/ServerCrossOriginEmbedderPolicyDsl.kt new file mode 100644 index 00000000000..cf5ae7ec9d9 --- /dev/null +++ b/config/src/main/kotlin/org/springframework/security/config/web/server/ServerCrossOriginEmbedderPolicyDsl.kt @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.config.web.server + +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.web.server.header.CrossOriginEmbedderPolicyServerHttpHeadersWriter + +/** + * A Kotlin DSL to configure the [HttpSecurity] Cross-Origin-Embedder-Policy header using + * idiomatic Kotlin code. + * + * @author Marcus Da Coregio + * @since 5.7 + * @property policy the policy to be used in the response header. + */ +@ServerSecurityMarker +class ServerCrossOriginEmbedderPolicyDsl { + + var policy: CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy? = null + + internal fun get(): (ServerHttpSecurity.HeaderSpec.CrossOriginEmbedderPolicySpec) -> Unit { + return { crossOriginEmbedderPolicy -> + policy?.also { + crossOriginEmbedderPolicy.policy(policy) + } + } + } +} diff --git a/config/src/main/kotlin/org/springframework/security/config/web/server/ServerCrossOriginOpenerPolicyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/web/server/ServerCrossOriginOpenerPolicyDsl.kt new file mode 100644 index 00000000000..70d6576c837 --- /dev/null +++ b/config/src/main/kotlin/org/springframework/security/config/web/server/ServerCrossOriginOpenerPolicyDsl.kt @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.config.web.server + +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.web.server.header.CrossOriginOpenerPolicyServerHttpHeadersWriter + +/** + * A Kotlin DSL to configure the [HttpSecurity] Cross-Origin-Opener-Policy header using + * idiomatic Kotlin code. + * + * @author Marcus Da Coregio + * @since 5.7 + * @property policy the policy to be used in the response header. + */ +@ServerSecurityMarker +class ServerCrossOriginOpenerPolicyDsl { + + var policy: CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy? = null + + internal fun get(): (ServerHttpSecurity.HeaderSpec.CrossOriginOpenerPolicySpec) -> Unit { + return { crossOriginOpenerPolicy -> + policy?.also { + crossOriginOpenerPolicy.policy(policy) + } + } + } +} diff --git a/config/src/main/kotlin/org/springframework/security/config/web/server/ServerCrossOriginResourcePolicyDsl.kt b/config/src/main/kotlin/org/springframework/security/config/web/server/ServerCrossOriginResourcePolicyDsl.kt new file mode 100644 index 00000000000..580ee355ee7 --- /dev/null +++ b/config/src/main/kotlin/org/springframework/security/config/web/server/ServerCrossOriginResourcePolicyDsl.kt @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.config.web.server + +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.web.server.header.CrossOriginResourcePolicyServerHttpHeadersWriter + +/** + * A Kotlin DSL to configure the [HttpSecurity] Cross-Origin-Resource-Policy header using + * idiomatic Kotlin code. + * + * @author Marcus Da Coregio + * @since 5.7 + * @property policy the policy to be used in the response header. + */ +@ServerSecurityMarker +class ServerCrossOriginResourcePolicyDsl { + + var policy: CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy? = null + + internal fun get(): (ServerHttpSecurity.HeaderSpec.CrossOriginResourcePolicySpec) -> Unit { + return { crossOriginResourcePolicy -> + policy?.also { + crossOriginResourcePolicy.policy(policy) + } + } + } +} diff --git a/config/src/main/kotlin/org/springframework/security/config/web/server/ServerHeadersDsl.kt b/config/src/main/kotlin/org/springframework/security/config/web/server/ServerHeadersDsl.kt index f38b1527218..37bd1f177a9 100644 --- a/config/src/main/kotlin/org/springframework/security/config/web/server/ServerHeadersDsl.kt +++ b/config/src/main/kotlin/org/springframework/security/config/web/server/ServerHeadersDsl.kt @@ -16,7 +16,12 @@ package org.springframework.security.config.web.server -import org.springframework.security.web.server.header.* +import org.springframework.security.web.server.header.CacheControlServerHttpHeadersWriter +import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter +import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter +import org.springframework.security.web.server.header.StrictTransportSecurityServerHttpHeadersWriter +import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter +import org.springframework.security.web.server.header.XXssProtectionServerHttpHeadersWriter /** * A Kotlin DSL to configure [ServerHttpSecurity] headers using idiomatic Kotlin code. @@ -35,6 +40,9 @@ class ServerHeadersDsl { private var referrerPolicy: ((ServerHttpSecurity.HeaderSpec.ReferrerPolicySpec) -> Unit)? = null private var featurePolicyDirectives: String? = null private var permissionsPolicy: ((ServerHttpSecurity.HeaderSpec.PermissionsPolicySpec) -> Unit)? = null + private var crossOriginOpenerPolicy: ((ServerHttpSecurity.HeaderSpec.CrossOriginOpenerPolicySpec) -> Unit)? = null + private var crossOriginEmbedderPolicy: ((ServerHttpSecurity.HeaderSpec.CrossOriginEmbedderPolicySpec) -> Unit)? = null + private var crossOriginResourcePolicy: ((ServerHttpSecurity.HeaderSpec.CrossOriginResourcePolicySpec) -> Unit)? = null private var disabled = false @@ -157,6 +165,39 @@ class ServerHeadersDsl { this.permissionsPolicy = ServerPermissionsPolicyDsl().apply(permissionsPolicyConfig).get() } + /** + * Allows configuration for + * Cross-Origin-Opener-Policy header. + * + * @since 5.7 + * @param crossOriginOpenerPolicyConfig the customization to apply to the header + */ + fun crossOriginOpenerPolicy(crossOriginOpenerPolicyConfig: ServerCrossOriginOpenerPolicyDsl.() -> Unit) { + this.crossOriginOpenerPolicy = ServerCrossOriginOpenerPolicyDsl().apply(crossOriginOpenerPolicyConfig).get() + } + + /** + * Allows configuration for + * Cross-Origin-Embedder-Policy header. + * + * @since 5.7 + * @param crossOriginEmbedderPolicyConfig the customization to apply to the header + */ + fun crossOriginEmbedderPolicy(crossOriginEmbedderPolicyConfig: ServerCrossOriginEmbedderPolicyDsl.() -> Unit) { + this.crossOriginEmbedderPolicy = ServerCrossOriginEmbedderPolicyDsl().apply(crossOriginEmbedderPolicyConfig).get() + } + + /** + * Allows configuration for + * Cross-Origin-Resource-Policy header. + * + * @since 5.7 + * @param crossOriginResourcePolicyConfig the customization to apply to the header + */ + fun crossOriginResourcePolicy(crossOriginResourcePolicyConfig: ServerCrossOriginResourcePolicyDsl.() -> Unit) { + this.crossOriginResourcePolicy = ServerCrossOriginResourcePolicyDsl().apply(crossOriginResourcePolicyConfig).get() + } + /** * Disables HTTP response headers. */ @@ -194,6 +235,15 @@ class ServerHeadersDsl { referrerPolicy?.also { headers.referrerPolicy(referrerPolicy) } + crossOriginOpenerPolicy?.also { + headers.crossOriginOpenerPolicy(crossOriginOpenerPolicy) + } + crossOriginEmbedderPolicy?.also { + headers.crossOriginEmbedderPolicy(crossOriginEmbedderPolicy) + } + crossOriginResourcePolicy?.also { + headers.crossOriginResourcePolicy(crossOriginResourcePolicy) + } if (disabled) { headers.disable() } diff --git a/config/src/main/resources/META-INF/spring.schemas b/config/src/main/resources/META-INF/spring.schemas index a67252965d7..4098d6b8c16 100644 --- a/config/src/main/resources/META-INF/spring.schemas +++ b/config/src/main/resources/META-INF/spring.schemas @@ -1,4 +1,5 @@ -http\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-5.6.xsd +http\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-6.0.xsd +http\://www.springframework.org/schema/security/spring-security-6.0.xsd=org/springframework/security/config/spring-security-6.0.xsd http\://www.springframework.org/schema/security/spring-security-5.6.xsd=org/springframework/security/config/spring-security-5.6.xsd http\://www.springframework.org/schema/security/spring-security-5.5.xsd=org/springframework/security/config/spring-security-5.5.xsd http\://www.springframework.org/schema/security/spring-security-5.4.xsd=org/springframework/security/config/spring-security-5.4.xsd @@ -17,7 +18,8 @@ http\://www.springframework.org/schema/security/spring-security-2.0.xsd=org/spri http\://www.springframework.org/schema/security/spring-security-2.0.1.xsd=org/springframework/security/config/spring-security-2.0.1.xsd http\://www.springframework.org/schema/security/spring-security-2.0.2.xsd=org/springframework/security/config/spring-security-2.0.2.xsd http\://www.springframework.org/schema/security/spring-security-2.0.4.xsd=org/springframework/security/config/spring-security-2.0.4.xsd -https\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-5.6.xsd +https\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-6.0.xsd +https\://www.springframework.org/schema/security/spring-security-6.0.xsd=org/springframework/security/config/spring-security-6.0.xsd https\://www.springframework.org/schema/security/spring-security-5.6.xsd=org/springframework/security/config/spring-security-5.6.xsd https\://www.springframework.org/schema/security/spring-security-5.5.xsd=org/springframework/security/config/spring-security-5.5.xsd https\://www.springframework.org/schema/security/spring-security-5.4.xsd=org/springframework/security/config/spring-security-5.4.xsd diff --git a/config/src/main/resources/org/springframework/security/config/spring-security-6.0.rnc b/config/src/main/resources/org/springframework/security/config/spring-security-6.0.rnc new file mode 100644 index 00000000000..42b1349c0e2 --- /dev/null +++ b/config/src/main/resources/org/springframework/security/config/spring-security-6.0.rnc @@ -0,0 +1,1151 @@ +namespace a = "https://relaxng.org/ns/compatibility/annotations/1.0" +datatypes xsd = "http://www.w3.org/2001/XMLSchema-datatypes" + +default namespace = "http://www.springframework.org/schema/security" + +start = http | ldap-server | authentication-provider | ldap-authentication-provider | any-user-service | ldap-server | ldap-authentication-provider + +hash = + ## Defines the hashing algorithm used on user passwords. Bcrypt is recommended. + attribute hash {"bcrypt"} +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:nonNegativeInteger } +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 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.attlist &= + ## Explicitly specifies which embedded ldap server should use. Values are 'apacheds' and 'unboundid'. By default, it will depends if the library is available in the classpath. + attribute mode { "apacheds" | "unboundid" }? + +ldap-server-ref-attribute = + ## The optional server to use. If omitted, and a default LDAP server is registered (using 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? + +method-security = + ## Provides method security for all beans registered in the Spring application context. Specifically, beans will be scanned for matches with Spring Security annotations. Where there is a match, the beans will automatically be proxied and security authorization applied to the methods accordingly. Interceptors are invoked in the order specified in AuthorizationInterceptorsOrder. Use can create your own interceptors using Spring AOP. + element method-security {method-security.attlist, expression-handler?} +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 "true". + attribute pre-post-enabled {xsd:boolean}? +method-security.attlist &= + ## Specifies whether the use of Spring Security's @Secured annotations should be enabled for this application context. Defaults to "false". + attribute secured-enabled {xsd:boolean}? +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 "false". + attribute jsr250-enabled {xsd:boolean}? +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 = + ## 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 element. + element pre-invocation-advice {ref} + +post-invocation-advice = + ## Customizes the PostInvocationAdviceProvider with the ref as the PostInvocationAuthorizationAdvice for the 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? & oauth2-login? & oauth2-client? & oauth2-resource-server? & openid-login? & x509? & jee? & http-basic? & logout? & password-management? & 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 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 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 &= + ## 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 /?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}? + +oauth2-login = + ## Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider. + element oauth2-login {oauth2-login.attlist} +oauth2-login.attlist &= + ## Reference to the ClientRegistrationRepository + attribute client-registration-repository-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the OAuth2AuthorizedClientRepository + attribute authorized-client-repository-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the OAuth2AuthorizedClientService + attribute authorized-client-service-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the AuthorizationRequestRepository + attribute authorization-request-repository-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the OAuth2AuthorizationRequestResolver + attribute authorization-request-resolver-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the OAuth2AccessTokenResponseClient + attribute access-token-response-client-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the GrantedAuthoritiesMapper + attribute user-authorities-mapper-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the OAuth2UserService + attribute user-service-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the OpenID Connect OAuth2UserService + attribute oidc-user-service-ref {xsd:token}? +oauth2-login.attlist &= + ## The URI where the filter processes authentication requests + attribute login-processing-url {xsd:token}? +oauth2-login.attlist &= + ## The URI to send users to login + attribute login-page {xsd:token}? +oauth2-login.attlist &= + ## Reference to the AuthenticationSuccessHandler + attribute authentication-success-handler-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the AuthenticationFailureHandler + attribute authentication-failure-handler-ref {xsd:token}? +oauth2-login.attlist &= + ## Reference to the JwtDecoderFactory used by OidcAuthorizationCodeAuthenticationProvider + attribute jwt-decoder-factory-ref {xsd:token}? + +oauth2-client = + ## Configures OAuth 2.0 Client support. + element oauth2-client {oauth2-client.attlist, (authorization-code-grant?) } +oauth2-client.attlist &= + ## Reference to the ClientRegistrationRepository + attribute client-registration-repository-ref {xsd:token}? +oauth2-client.attlist &= + ## Reference to the OAuth2AuthorizedClientRepository + attribute authorized-client-repository-ref {xsd:token}? +oauth2-client.attlist &= + ## Reference to the OAuth2AuthorizedClientService + attribute authorized-client-service-ref {xsd:token}? + +authorization-code-grant = + ## Configures OAuth 2.0 Authorization Code Grant. + element authorization-code-grant {authorization-code-grant.attlist, empty} +authorization-code-grant.attlist &= + ## Reference to the AuthorizationRequestRepository + attribute authorization-request-repository-ref {xsd:token}? +authorization-code-grant.attlist &= + ## Reference to the OAuth2AuthorizationRequestResolver + attribute authorization-request-resolver-ref {xsd:token}? +authorization-code-grant.attlist &= + ## Reference to the OAuth2AccessTokenResponseClient + attribute access-token-response-client-ref {xsd:token}? + +client-registrations = + ## Container element for client(s) registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. + element client-registrations {client-registration+, provider*} + +client-registration = + ## Represents a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. + element client-registration {client-registration.attlist} +client-registration.attlist &= + ## The ID that uniquely identifies the client registration. + attribute registration-id {xsd:token} +client-registration.attlist &= + ## The client identifier. + attribute client-id {xsd:token} +client-registration.attlist &= + ## The client secret. + attribute client-secret {xsd:token}? +client-registration.attlist &= + ## The method used to authenticate the client with the provider. The supported values are client_secret_basic, client_secret_post and none (public clients). + attribute client-authentication-method {"client_secret_basic" | "basic" | "client_secret_post" | "post" | "none"}? +client-registration.attlist &= + ## The OAuth 2.0 Authorization Framework defines four Authorization Grant types. The supported values are authorization_code, client_credentials, password and implicit. + attribute authorization-grant-type {"authorization_code" | "client_credentials" | "password" | "implicit"}? +client-registration.attlist &= + ## The client’s registered redirect URI that the Authorization Server redirects the end-user’s user-agent to after the end-user has authenticated and authorized access to the client. + attribute redirect-uri {xsd:token}? +client-registration.attlist &= + ## A comma-separated list of scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile. + attribute scope {xsd:token}? +client-registration.attlist &= + ## A descriptive name used for the client. The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page. + attribute client-name {xsd:token}? +client-registration.attlist &= + ## A reference to the associated provider. May reference a 'provider' element or use one of the common providers (google, github, facebook, okta). + attribute provider-id {xsd:token} + +provider = + ## The configuration information for an OAuth 2.0 or OpenID Connect 1.0 Provider. + element provider {provider.attlist} +provider.attlist &= + ## The ID that uniquely identifies the provider. + attribute provider-id {xsd:token} +provider.attlist &= + ## The Authorization Endpoint URI for the Authorization Server. + attribute authorization-uri {xsd:token}? +provider.attlist &= + ## The Token Endpoint URI for the Authorization Server. + attribute token-uri {xsd:token}? +provider.attlist &= + ## The UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user. + attribute user-info-uri {xsd:token}? +provider.attlist &= + ## The authentication method used when sending the access token to the UserInfo Endpoint. The supported values are header, form and query. + attribute user-info-authentication-method {"header" | "form" | "query"}? +provider.attlist &= + ## The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user. + attribute user-info-user-name-attribute {xsd:token}? +provider.attlist &= + ## The URI used to retrieve the JSON Web Key (JWK) Set from the Authorization Server, which contains the cryptographic key(s) used to verify the JSON Web Signature (JWS) of the ID Token and optionally the UserInfo Response. + attribute jwk-set-uri {xsd:token}? +provider.attlist &= + ## The URI used to discover the configuration information for an OAuth 2.0 or OpenID Connect 1.0 Provider. + attribute issuer-uri {xsd:token}? + +oauth2-resource-server = + ## Configures authentication support as an OAuth 2.0 Resource Server. + element oauth2-resource-server {oauth2-resource-server.attlist, (jwt? & opaque-token?)} +oauth2-resource-server.attlist &= + ## Reference to an AuthenticationManagerResolver + attribute authentication-manager-resolver-ref {xsd:token}? +oauth2-resource-server.attlist &= + ## Reference to a BearerTokenResolver + attribute bearer-token-resolver-ref {xsd:token}? +oauth2-resource-server.attlist &= + ## Reference to a AuthenticationEntryPoint + attribute entry-point-ref {xsd:token}? + +jwt = + ## Configures JWT authentication + element jwt {jwt.attlist} +jwt.attlist &= + ## The URI to use to collect the JWK Set for verifying JWTs + attribute jwk-set-uri {xsd:token}? +jwt.attlist &= + ## Reference to a JwtDecoder + attribute decoder-ref {xsd:token}? +jwt.attlist &= + ## Reference to a Converter + attribute jwt-authentication-converter-ref {xsd:token}? + +opaque-token = + ## Configuration Opaque Token authentication + element opaque-token {opaque-token.attlist} +opaque-token.attlist &= + ## The URI to use to introspect opaque token attributes + attribute introspection-uri {xsd:token}? +opaque-token.attlist &= + ## The Client ID to use to authenticate the introspection request + attribute client-id {xsd:token}? +opaque-token.attlist &= + ## The Client secret to use to authenticate the introspection request + attribute client-secret {xsd:token}? +opaque-token.attlist &= + ## Reference to an OpaqueTokenIntrospector + attribute introspector-ref {xsd:token}? + +openid-login = + ## Sets up form login for authentication with an Open ID identity. NOTE: The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2. + 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. NOTE: The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2. + element openid-attribute {openid-attribute.attlist} + +openid-attribute.attlist &= + ## Specifies the name of the attribute that you wish to get back. For example, email. + attribute name {xsd:token} +openid-attribute.attlist &= + ## Specifies the attribute type. For example, https://axschema.org/contact/email. See your OP's documentation for valid attribute types. + attribute type {xsd:token} +openid-attribute.attlist &= + ## Specifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. Default is false. + attribute required {xsd:boolean}? +openid-attribute.attlist &= + ## Specifies the number of attributes that you wish to get back. For example, return 3 emails. The default value is 1. + attribute count {xsd:int}? + + +filter-chain-map = + ## Used to explicitly configure a FilterChainProxy instance with a FilterChainMap + element filter-chain-map {filter-chain-map.attlist, filter-chain+} +filter-chain-map.attlist &= + request-matcher? + +filter-chain = + ## Used within to define a specific URL pattern and the list of filters which apply to the URLs matching that pattern. When multiple filter-chain elements are assembled in a list in order to configure a FilterChainProxy, the most specific patterns must be placed at the top of the list, with most general ones at the bottom. + element filter-chain {filter-chain.attlist, empty} +filter-chain.attlist &= + (pattern | request-matcher-ref) +filter-chain.attlist &= + ## A comma separated list of bean names that implement Filter that should be processed for this FilterChain. If the value is none, then no Filters will be used for this FilterChain. + attribute filters {xsd:token} + +pattern = + ## The request URL pattern which will be mapped to the FilterChain. + attribute pattern {xsd:token} +request-matcher-ref = + ## Allows a RequestMatcher instance to be used, as an alternative to pattern-matching. + attribute request-matcher-ref {xsd:token} + +filter-security-metadata-source = + ## Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the 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}? + +password-management = + ## Adds support for the password management. + element password-management {password-management.attlist, empty} + +password-management.attlist &= + ## The change password page. Defaults to "/change-password". + attribute change-password-page {xsd:string}? + +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:token}? +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? & permissions-policy? & cross-origin-opener-policy? & cross-origin-embedder-policy? & cross-origin-resource-policy? & header*)} +headers-options.attlist &= + ## Specifies if the default headers should be disabled. Default false. + attribute defaults-disabled {xsd:token}? +headers-options.attlist &= + ## Specifies if headers should be disabled. Default false. + attribute disabled {xsd:token}? +hsts = + ## Adds support for HTTP Strict Transport Security (HSTS) + element hsts {hsts-options.attlist} +hsts-options.attlist &= + ## Specifies if HTTP Strict Transport Security (HSTS) should be disabled. Default false. + attribute disabled {xsd:boolean}? +hsts-options.attlist &= + ## Specifies if subdomains should be included. Default true. + attribute include-subdomains {xsd:boolean}? +hsts-options.attlist &= + ## Specifies the maximum amount of time the host should be considered a Known HSTS Host. Default one year. + attribute max-age-seconds {xsd:integer}? +hsts-options.attlist &= + ## The RequestMatcher instance to be used to determine if the header should be set. Default is if HttpServletRequest.isSecure() is true. + attribute request-matcher-ref { xsd:token }? +hsts-options.attlist &= + ## Specifies if preload should be included. Default false. + attribute preload {xsd:boolean}? + +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}? + +permissions-policy = + ## Adds support for Permissions Policy + element permissions-policy {permissions-options.attlist} +permissions-options.attlist &= + ## The policies for the Permissions-Policy header. + attribute policy {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'. + ## Deprecated ALLOW-FROM is an obsolete directive that no longer works in modern browsers. Instead use + ## Content-Security-Policy with the + ## frame-ancestors + ## directive. + 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}? + +cross-origin-opener-policy = + ## Adds support for Cross-Origin-Opener-Policy header + element cross-origin-opener-policy {cross-origin-opener-policy-options.attlist,empty} +cross-origin-opener-policy-options.attlist &= + ## The policies for the Cross-Origin-Opener-Policy header. + attribute policy {"unsafe-none","same-origin","same-origin-allow-popups"}? + +cross-origin-embedder-policy = + ## Adds support for Cross-Origin-Embedder-Policy header + element cross-origin-embedder-policy {cross-origin-embedder-policy-options.attlist,empty} +cross-origin-embedder-policy-options.attlist &= + ## The policies for the Cross-Origin-Embedder-Policy header. + attribute policy {"unsafe-none","require-corp"}? + +cross-origin-resource-policy = + ## Adds support for Cross-Origin-Resource-Policy header + element cross-origin-resource-policy {cross-origin-resource-policy-options.attlist,empty} +cross-origin-resource-policy-options.attlist &= + ## The policies for the Cross-Origin-Resource-Policy header. + attribute policy {"cross-origin","same-origin","same-site"}? + +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" | "OAUTH2_AUTHORIZATION_REQUEST_FILTER" | "X509_FILTER" | "PRE_AUTH_FILTER" | "CAS_FILTER" | "OAUTH2_LOGIN_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" | "OAUTH2_AUTHORIZATION_CODE_GRANT_FILTER" | "WELL_KNOWN_CHANGE_PASSWORD_REDIRECT_FILTER" | "SESSION_MANAGEMENT_FILTER" | "EXCEPTION_TRANSLATION_FILTER" | "FILTER_SECURITY_INTERCEPTOR" | "SWITCH_USER_FILTER" | "LAST" diff --git a/config/src/main/resources/org/springframework/security/config/spring-security-6.0.xsd b/config/src/main/resources/org/springframework/security/config/spring-security-6.0.xsd new file mode 100644 index 00000000000..201953d2cf1 --- /dev/null +++ b/config/src/main/resources/org/springframework/security/config/spring-security-6.0.xsd @@ -0,0 +1,3358 @@ + + + + + + Defines the hashing algorithm used on user passwords. Bcrypt is recommended. + + + + + + + + + + + + + Whether a string should be base64 encoded + + + + + + + + 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. + + + + + + + + + + + + + + + + Specifies an IP port number. Used to configure an embedded LDAP server, for example. + + + + + + + + Specifies a URL. + + + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + + + Defines a reference to a Spring bean Id. + + + + + + + + Defines a reference to a cache for use with a UserDetailsService. + + + + + + + + A reference to a user-service (or UserDetailsService bean) Id + + + + + + + + A reference to an AuthenticationManager bean + + + + + + + + A reference to a DataSource bean + + + + + + + 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. + + + + + + + + + Defines a reference to a Spring bean Id. + + + + + + Defines the hashing algorithm used on user passwords. Bcrypt is recommended. + + + + + + + + + + + + + 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. + + + + + + + + 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. + + + + + + + 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. + + + + + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + Specifies a URL. + + + + + + Specifies an IP port number. Used to configure an embedded LDAP server, for example. + + + + + + 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. + + + + + + The password for the manager DN. This is required if the manager-dn is specified. + + + + + + Explicitly specifies an ldif file resource to load into an embedded LDAP server. The + default is classpath*:*.ldiff + + + + + + Optional root suffix for the embedded LDAP server. Default is "dc=springframework,dc=org" + + + + + + Explicitly specifies which embedded ldap server should use. Values are 'apacheds' and + 'unboundid'. By default, it will depends if the library is available in the classpath. + + + + + + + + + + + + + + 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. + + + + + + + + Group search filter. Defaults to (uniqueMember={0}). The substituted parameter is the DN + of the user. + + + + + + + + Search base for group membership searches. Defaults to "" (searching from the root). + + + + + + + + The LDAP filter used to search for users (optional). For example "(uid={0})". The + substituted parameter is the user's login name. + + + + + + + + Search base for user searches. Defaults to "". Only used with a 'user-search-filter'. + + + + + + + + The LDAP attribute name which contains the role name which will be used within Spring + Security. Defaults to "cn". + + + + + + + + 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 + + + + + + + + + + + + + + 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 + + + + + + + This element configures a LdapUserDetailsService which is a combination of a + FilterBasedLdapUserSearch and a DefaultLdapAuthoritiesPopulator. + + + + + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + 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. + + + + + + The LDAP filter used to search for users (optional). For example "(uid={0})". The + substituted parameter is the user's login name. + + + + + + Search base for user searches. Defaults to "". Only used with a 'user-search-filter'. + + + + + + Group search filter. Defaults to (uniqueMember={0}). The substituted parameter is the DN + of the user. + + + + + + Search base for group membership searches. Defaults to "" (searching from the root). + + + + + + The LDAP attribute name which contains the role name which will be used within Spring + Security. Defaults to "cn". + + + + + + Defines a reference to a cache for use with a UserDetailsService. + + + + + + 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. + + + + + + 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 + + + + + + + + + + + + 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 + + + + + + + + + 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. + + + + + + Search base for user searches. Defaults to "". Only used with a 'user-search-filter'. + + + + + + The LDAP filter used to search for users (optional). For example "(uid={0})". The + substituted parameter is the user's login name. + + + + + + Search base for group membership searches. Defaults to "" (searching from the root). + + + + + + Group search filter. Defaults to (uniqueMember={0}). The substituted parameter is the DN + of the user. + + + + + + The LDAP attribute name which contains the role name which will be used within Spring + Security. Defaults to "cn". + + + + + + 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. + + + + + + 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. + + + + + + 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 + + + + + + + + + + + + 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 + + + + + + + + + The attribute in the directory which contains the user password. Defaults to + "userPassword". + + + + + + Defines the hashing algorithm used on user passwords. Bcrypt is recommended. + + + + + + + + + + + + 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 + + + + + + + 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". + + + + + + + + + + + + + + Optional AccessDecisionManager bean ID to be used by the created method security + interceptor. + + + + + + + + + A method name + + + + + + Access configuration attributes list that applies to the method, e.g. "ROLE_A,ROLE_B". + + + + + + + Creates a MethodSecurityMetadataSource instance + + + + + + + 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". + + + + + + + + + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + 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. + + + + + + + Provides method security for all beans registered in the Spring application context. + Specifically, beans will be scanned for matches with Spring Security annotations. Where + there is a match, the beans will automatically be proxied and security authorization + applied to the methods accordingly. Interceptors are invoked in the order specified in + AuthorizationInterceptorsOrder. Use can create your own interceptors using Spring AOP. + + + + + + + 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. + + + + + + + + + + + + + + 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 "true". + + + + + + Specifies whether the use of Spring Security's @Secured annotations should be enabled for + this application context. Defaults to "false". + + + + + + 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 + "false". + + + + + + If true, class-based proxying will be used instead of interface-based proxying. + + + + + + + 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. + + + + + + + + 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. + + + + + + + Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and + post invocation metadata from the annotated methods. + + + + + + + + + Customizes the PreInvocationAuthorizationAdviceVoter with the ref as the + PreInvocationAuthorizationAdviceVoter for the <pre-post-annotation-handling> element. + + + + + + + + + Customizes the PostInvocationAdviceProvider with the ref as the + PostInvocationAuthorizationAdvice for the <pre-post-annotation-handling> element. + + + + + + + + + + + + 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. + + + + + + + + + + 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. + + + + + + + + + Allows addition of extra AfterInvocationProvider beans which should be called by the + MethodSecurityInterceptor created by global-method-security. + + + + + + + + + + + + + + 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". + + + + + + + + + + + + Specifies whether the use of Spring Security's @Secured annotations should be enabled for + this application context. Defaults to "disabled". + + + + + + + + + + + + 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". + + + + + + + + + + + + Optional AccessDecisionManager bean ID to override the default used for method security. + + + + + + Optional RunAsmanager implementation which will be used by the configured + MethodSecurityInterceptor + + + + + + Allows the advice "order" to be set for the method security interceptor. + + + + + + If true, class based proxying will be used instead of interface based proxying. + + + + + + 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. + + + + + + + + + + + An external MethodSecurityMetadataSource instance can be supplied which will take priority + over other sources (such as the default annotations). + + + + + + A reference to an AuthenticationManager bean + + + + + + + + + + + + + + + An AspectJ expression, including the 'execution' keyword. For example, 'execution(int + com.foo.TargetObject.countLength(String))' (without the quotes). + + + + + + Access configuration attributes list that applies to all methods matching the pointcut, + e.g. "ROLE_A,ROLE_B" + + + + + + + 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. + + + + + + + + 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. + + + + + + + + + + + + + + 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. + + + + + + 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. + + + + + + + Creates an authorization rule for a websocket message. + + + + + + + + + + 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. + + + + + + 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'. + + + + + + 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). + + + + + + + + + + + + + + + + + + + + Allows a custom instance of HttpFirewall to be injected into the FilterChainProxy created + by the namespace. + + + + + + + + + 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". + + + + + + + Specifies the access attributes and/or filter list for a particular set of URLs. + + + + + + + + + Defines the access-denied strategy that should be used. An access denied page can be + defined or a reference to an AccessDeniedHandler instance. + + + + + + + + + Sets up a form login configuration for authentication with a username and password + + + + + + + + + + + + Sets up form login for authentication with an Open ID identity. NOTE: The OpenID 1.0 and + 2.0 protocols have been deprecated and users are <a + href="https://openid.net/specs/openid-connect-migration-1_0.html">encouraged to + migrate</a> to <a href="https://openid.net/connect/">OpenID Connect</a>, which is + supported by <code>spring-security-oauth2</code>. + + + + + + + + + + A reference to a user-service (or UserDetailsService bean) Id + + + + + + + + Adds support for X.509 client authentication. + + + + + + + + + + Adds support for basic authentication + + + + + + + + + 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. + + + + + + + + + + Session-management related functionality is implemented by the addition of a + SessionManagementFilter to the filter stack. + + + + + + + Enables concurrent session control, limiting the number of authenticated sessions a user + may have at the same time. + + + + + + + + + + + + + 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. + + + + + + + + + Adds support for automatically granting all anonymous web requests a particular principal + identity and a corresponding granted authority. + + + + + + + + + Defines the list of mappings between http and https ports for use in redirects + + + + + + + Provides a method to map http ports to https ports when forcing a redirect. + + + + + + + + + + + + + + + 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. + + + + + + + + + + + + + + + + + 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. + + + + + + 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. + + + + + + + + + + + Allows a RequestMatcher instance to be used, as an alternative to pattern-matching. + + + + + + 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. + + + + + + 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. + + + + + + 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. + + + + + + + + + + + + + + A reference to a SecurityContextRepository bean. This can be used to customize how the + SecurityContext is stored between requests. + + + + + + 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. + + + + + + + + + + + + + + Provides versions of HttpServletRequest security methods such as isUserInRole() and + getPrincipal() which are implemented by accessing the Spring SecurityContext. Defaults to + "true". + + + + + + If available, runs the request as the Subject acquired from the JaasAuthenticationToken. + Defaults to "false". + + + + + + Optional attribute specifying the ID of the AccessDecisionManager implementation which + should be used for authorizing HTTP requests. + + + + + + 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". + + + + + + Allows a customized AuthenticationEntryPoint to be set on the ExceptionTranslationFilter. + + + + + + Corresponds to the observeOncePerRequest property of FilterSecurityInterceptor. Defaults + to "true" + + + + + + Prevents the jsessionid parameter from being added to rendered URLs. Defaults to "true" + (rewriting is disabled). + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + A reference to an AuthenticationManager bean + + + + + + + + + Defines a reference to a Spring bean Id. + + + + + + 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. + + + + + + + + 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. + + + + + + + + + The request URL pattern which will be mapped to the FilterChain. + + + + + + Allows a RequestMatcher instance to be used, as an alternative to pattern-matching. + + + + + + The access configuration attributes that apply for the configured path. + + + + + + The HTTP Method for which the access configuration attributes should apply. If not + specified, the attributes will apply to any method. + + + + + + + + + + + + + + + + + + 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. + + + + + + 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 '/'. + + + + + + + + + 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. + + + + + + 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). + + + + + + Specifies whether a logout also causes HttpSession invalidation, which is generally + desirable. If unspecified, defaults to true. + + + + + + A reference to a LogoutSuccessHandler implementation which will be used to determine the + destination to which the user is taken after logging out. + + + + + + A comma-separated list of the names of cookies which should be deleted when the user logs + out + + + + + + + Allow the RequestCache used for saving requests during the login process to be set + + + + + + + + + + + The URL that the login form is posted to. If unspecified, it defaults to /login. + + + + + + The name of the request parameter which contains the username. Defaults to 'username'. + + + + + + The name of the request parameter which contains the password. Defaults to 'password'. + + + + + + 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. + + + + + + Whether the user should always be redirected to the default-target-url after login. + + + + + + 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. + + + + + + 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. + + + + + + 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 + + + + + + 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 + + + + + + Reference to an AuthenticationDetailsSource which will be used by the authentication + filter + + + + + + The URL for the ForwardAuthenticationFailureHandler + + + + + + The URL for the ForwardAuthenticationSuccessHandler + + + + + + + Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider. + + + + + + + + + + Reference to the ClientRegistrationRepository + + + + + + Reference to the OAuth2AuthorizedClientRepository + + + + + + Reference to the OAuth2AuthorizedClientService + + + + + + Reference to the AuthorizationRequestRepository + + + + + + Reference to the OAuth2AuthorizationRequestResolver + + + + + + Reference to the OAuth2AccessTokenResponseClient + + + + + + Reference to the GrantedAuthoritiesMapper + + + + + + Reference to the OAuth2UserService + + + + + + Reference to the OpenID Connect OAuth2UserService + + + + + + The URI where the filter processes authentication requests + + + + + + The URI to send users to login + + + + + + Reference to the AuthenticationSuccessHandler + + + + + + Reference to the AuthenticationFailureHandler + + + + + + Reference to the JwtDecoderFactory used by OidcAuthorizationCodeAuthenticationProvider + + + + + + + Configures OAuth 2.0 Client support. + + + + + + + + + + + + + Reference to the ClientRegistrationRepository + + + + + + Reference to the OAuth2AuthorizedClientRepository + + + + + + Reference to the OAuth2AuthorizedClientService + + + + + + + Configures OAuth 2.0 Authorization Code Grant. + + + + + + + + + + Reference to the AuthorizationRequestRepository + + + + + + Reference to the OAuth2AuthorizationRequestResolver + + + + + + Reference to the OAuth2AccessTokenResponseClient + + + + + + + Container element for client(s) registered with an OAuth 2.0 or OpenID Connect 1.0 + Provider. + + + + + + + + + + + + Represents a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. + + + + + + + + + + The ID that uniquely identifies the client registration. + + + + + + The client identifier. + + + + + + The client secret. + + + + + + The method used to authenticate the client with the provider. The supported values are + client_secret_basic, client_secret_post and none (public clients). + + + + + + + + + + + + + + + The OAuth 2.0 Authorization Framework defines four Authorization Grant types. The + supported values are authorization_code, client_credentials, password and implicit. + + + + + + + + + + + + + + The client’s registered redirect URI that the Authorization Server redirects the + end-user’s user-agent to after the end-user has authenticated and authorized access to the + client. + + + + + + A comma-separated list of scope(s) requested by the client during the Authorization + Request flow, such as openid, email, or profile. + + + + + + A descriptive name used for the client. The name may be used in certain scenarios, such as + when displaying the name of the client in the auto-generated login page. + + + + + + A reference to the associated provider. May reference a 'provider' element or use one of + the common providers (google, github, facebook, okta). + + + + + + + The configuration information for an OAuth 2.0 or OpenID Connect 1.0 Provider. + + + + + + + + + + The ID that uniquely identifies the provider. + + + + + + The Authorization Endpoint URI for the Authorization Server. + + + + + + The Token Endpoint URI for the Authorization Server. + + + + + + The UserInfo Endpoint URI used to access the claims/attributes of the authenticated + end-user. + + + + + + The authentication method used when sending the access token to the UserInfo Endpoint. The + supported values are header, form and query. + + + + + + + + + + + + + The name of the attribute returned in the UserInfo Response that references the Name or + Identifier of the end-user. + + + + + + The URI used to retrieve the JSON Web Key (JWK) Set from the Authorization Server, which + contains the cryptographic key(s) used to verify the JSON Web Signature (JWS) of the ID + Token and optionally the UserInfo Response. + + + + + + The URI used to discover the configuration information for an OAuth 2.0 or OpenID Connect + 1.0 Provider. + + + + + + + Configures authentication support as an OAuth 2.0 Resource Server. + + + + + + + + + + + + + + Reference to an AuthenticationManagerResolver + + + + + + Reference to a BearerTokenResolver + + + + + + Reference to a AuthenticationEntryPoint + + + + + + + Configures JWT authentication + + + + + + + + + + The URI to use to collect the JWK Set for verifying JWTs + + + + + + Reference to a JwtDecoder + + + + + + Reference to a Converter<Jwt, AbstractAuthenticationToken> + + + + + + + Configuration Opaque Token authentication + + + + + + + + + + The URI to use to introspect opaque token attributes + + + + + + The Client ID to use to authenticate the introspection request + + + + + + The Client secret to use to authenticate the introspection request + + + + + + Reference to an OpaqueTokenIntrospector + + + + + + + + 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. + + + + + + + + + + + + + A regular expression which will be compared against the claimed identity, when deciding + which attribute-exchange configuration to use during authentication. + + + + + + + Attributes used when making an OpenID AX Fetch Request. NOTE: The OpenID 1.0 and 2.0 + protocols have been deprecated and users are <a + href="https://openid.net/specs/openid-connect-migration-1_0.html">encouraged to + migrate</a> to <a href="https://openid.net/connect/">OpenID Connect</a>, which is + supported by <code>spring-security-oauth2</code>. + + + + + + + + + + Specifies the name of the attribute that you wish to get back. For example, email. + + + + + + Specifies the attribute type. For example, https://axschema.org/contact/email. See your + OP's documentation for valid attribute types. + + + + + + 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. + + + + + + Specifies the number of attributes that you wish to get back. For example, return 3 + emails. The default value is 1. + + + + + + + Used to explicitly configure a FilterChainProxy instance with a FilterChainMap + + + + + + + + + + + + + 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. + + + + + + + + + + + + + + + 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. + + + + + + + + + + The request URL pattern which will be mapped to the FilterChain. + + + + + + Allows a RequestMatcher instance to be used, as an alternative to pattern-matching. + + + + + + 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. + + + + + + + + The request URL pattern which will be mapped to the FilterChain. + + + + + + + + Allows a RequestMatcher instance to be used, as an alternative to pattern-matching. + + + + + + + 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. + + + + + + + Specifies the access attributes and/or filter list for a particular set of URLs. + + + + + + + + + + + + + + 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. + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + 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. + + + + + + + + + + + + + + + + + Sets the AuthenticationEntryPoint which is used by the BasicAuthenticationFilter. + + + + + + Reference to an AuthenticationDetailsSource which will be used by the authentication + filter + + + + + + + Adds support for the password management. + + + + + + + + + + The change password page. Defaults to "/change-password". + + + + + + + + + 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. + + + + + + + + + + + + + + The URL to which a user will be redirected if they submit an invalid session indentifier. + Typically used to detect session timeouts. + + + + + + Allows injection of the InvalidSessionStrategy instance used by the + SessionManagementFilter + + + + + + Allows injection of the SessionAuthenticationStrategy instance used by the + SessionManagementFilter + + + + + + 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. + + + + + + + + + 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. + + + + + + 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. + + + + + + Allows injection of the SessionInformationExpiredStrategy instance used by the + ConcurrentSessionFilter + + + + + + 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. + + + + + + Allows you to define an alias for the SessionRegistry bean in order to access it in your + own configuration. + + + + + + Allows you to define an external SessionRegistry bean to be used by the concurrency + control setup. + + + + + + + + + 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. + + + + + + Reference to a PersistentTokenRepository bean for use with the persistent token + remember-me implementation. + + + + + + A reference to a DataSource bean + + + + + + + A reference to a user-service (or UserDetailsService bean) Id + + + + + + Exports the internally defined RememberMeServices as a bean alias, allowing it to be used + by other beans in the application context. + + + + + + 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. + + + + + + The period (in seconds) for which the remember-me cookie should be valid. + + + + + + Reference to an AuthenticationSuccessHandler bean which should be used to handle a + successful remember-me authentication. + + + + + + The name of the request parameter which toggles remember-me authentication. Defaults to + 'remember-me'. + + + + + + The name of cookie which store the token for remember-me authentication. Defaults to + 'remember-me'. + + + + + + + + Reference to a PersistentTokenRepository bean for use with the persistent token + remember-me implementation. + + + + + + + + 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. + + + + + + + + + + + + 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. + + + + + + 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". + + + + + + 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". + + + + + + With the default namespace setup, the anonymous "authentication" facility is automatically + enabled. You can disable it using this property. + + + + + + + + + + The http port to use. + + + + + + + + The https port to use. + + + + + + + + + The regular expression used to obtain the username from the certificate's subject. + Defaults to matching on the common name using the pattern "CN=(.*?),". + + + + + + A reference to a user-service (or UserDetailsService bean) Id + + + + + + Reference to an AuthenticationDetailsSource which will be used by the authentication + filter + + + + + + + Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration + with container authentication. + + + + + + + + + + A comma-separate list of roles to look for in the incoming HttpServletRequest. + + + + + + A reference to a user-service (or UserDetailsService bean) Id + + + + + + + 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. + + + + + + + Indicates that the contained user-service should be used as an authentication source. + + + + + + + + element which defines a password encoding strategy. Used by an authentication provider to + convert submitted passwords to hashed versions, for example. + + + + + + + + + + + + + Sets up an ldap authentication provider + + + + + + + Specifies that an LDAP provider should use an LDAP compare operation of the user's + password to authenticate the user + + + + + + + element which defines a password encoding strategy. Used by an authentication provider to + convert submitted passwords to hashed versions, for example. + + + + + + + + + + + + + + + + + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + An alias you wish to use for the AuthenticationManager bean (not required it you are using + a specific id) + + + + + + If set to true, the AuthenticationManger will attempt to clear any credentials data in the + returned Authentication object, once the user has been authenticated. + + + + + + + + + Defines a reference to a Spring bean Id. + + + + + + A reference to a user-service (or UserDetailsService bean) Id + + + + + + + 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. + + + + + + + Represents a user in the application. + + + + + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + + + + + The location of a Properties file where each line is in the format of + username=password,grantedAuthority[,grantedAuthority][,enabled|disabled] + + + + + + + + + The username assigned to the user. + + + + + + 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. + + + + + + One of more authorities granted to the user. Separate authorities with a comma (but no + space). For example, "ROLE_USER,ROLE_ADMINISTRATOR" + + + + + + Can be set to "true" to mark an account as locked and unusable. + + + + + + Can be set to "true" to mark an account as disabled and unusable. + + + + + + + Causes creation of a JDBC-based UserDetailsService. + + + + + + A bean identifier, used for referring to the bean elsewhere in the context. + + + + + + + + + + The bean ID of the DataSource which provides the required tables. + + + + + + Defines a reference to a cache for use with a UserDetailsService. + + + + + + An SQL statement to query a username, password, and enabled status given a username. + Default is "select username,password,enabled from users where username = ?" + + + + + + An SQL statement to query for a user's granted authorities given a username. The default + is "select username, authority from authorities where username = ?" + + + + + + 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" + + + + + + 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. + + + + + + + Element for configuration of the CsrfFilter for protection against CSRF. It also updates + the default RequestCache to only replay "GET" requests. + + + + + + + + + + Specifies if csrf protection should be disabled. Default false (i.e. CSRF protection is + enabled). + + + + + + The RequestMatcher instance to be used to determine if CSRF should be applied. Default is + any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS" + + + + + + The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository wrapped by + LazyCsrfTokenRepository. + + + + + + + Element for configuration of the HeaderWritersFilter. Enables easy setting for the + X-Frame-Options, X-XSS-Protection and X-Content-Type-Options headers. + + + + + + + + + + + + + + + + + + + + + + + + + + Specifies if the default headers should be disabled. Default false. + + + + + + Specifies if headers should be disabled. Default false. + + + + + + + Adds support for HTTP Strict Transport Security (HSTS) + + + + + + + + + + Specifies if HTTP Strict Transport Security (HSTS) should be disabled. Default false. + + + + + + Specifies if subdomains should be included. Default true. + + + + + + Specifies the maximum amount of time the host should be considered a Known HSTS Host. + Default one year. + + + + + + The RequestMatcher instance to be used to determine if the header should be set. Default + is if HttpServletRequest.isSecure() is true. + + + + + + Specifies if preload should be included. Default false. + + + + + + + Element for configuration of CorsFilter. If no CorsFilter or CorsConfigurationSource is + specified a HandlerMappingIntrospector is used as the CorsConfigurationSource + + + + + + + + + + Defines a reference to a Spring bean Id. + + + + + + Specifies a bean id that is a CorsConfigurationSource used to construct the CorsFilter to + use + + + + + + + Adds support for HTTP Public Key Pinning (HPKP). + + + + + + + + + + + + + + + + + + The list with pins + + + + + + + + + + + A pin is specified using the base64-encoded SPKI fingerprint as value and the + cryptographic hash algorithm as attribute + + + + + + The cryptographic hash algorithm + + + + + + + + + Specifies if HTTP Public Key Pinning (HPKP) should be disabled. Default false. + + + + + + Specifies if subdomains should be included. Default false. + + + + + + Sets the value for the max-age directive of the Public-Key-Pins header. Default 60 days. + + + + + + Specifies if the browser should only report pin validation failures. Default true. + + + + + + Specifies the URI to which the browser should report pin validation failures. + + + + + + + Adds support for Content Security Policy (CSP) + + + + + + + + + + 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. + + + + + + Set to true, to enable the Content-Security-Policy-Report-Only header for reporting policy + violations only. Defaults to false. + + + + + + + Adds support for Referrer Policy + + + + + + + + + + The policies for the Referrer-Policy header. + + + + + + + + + + + + + + + + + + + Adds support for Feature Policy + + + + + + + + + + The security policy directive(s) for the Feature-Policy header. + + + + + + + Adds support for Permissions Policy + + + + + + + + + + The policies for the Permissions-Policy header. + + + + + + + Adds Cache-Control no-cache, no-store, must-revalidate, Pragma no-cache, and Expires 0 for + every request + + + + + + + + + + Specifies if Cache Control should be disabled. Default false. + + + + + + + Enable basic clickjacking support for newer browsers (IE8+), will set the X-Frame-Options + header. + + + + + + + + + + If disabled, the X-Frame-Options header will not be included. Default false. + + + + + + Specify the policy to use for the X-Frame-Options-Header. + + + + + + + + + + + + + Specify the strategy to use when ALLOW-FROM is chosen. + + + + + + + + + + + + + Defines a reference to a Spring bean Id. + + + + + + Specify a value to use for the chosen strategy. + + + + + + Specify the request parameter to use for the origin when using a 'whitelist' or 'regexp' + based strategy. Default is 'from'. Deprecated ALLOW-FROM is an obsolete directive that no + longer works in modern browsers. Instead use Content-Security-Policy with the <a + href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors">frame-ancestors</a> + directive. + + + + + + + Enable basic XSS browser protection, supported by newer browsers (IE8+), will set the + X-XSS-Protection header. + + + + + + + + + + disable the X-XSS-Protection header. Default is 'false' meaning it is enabled. + + + + + + specify that XSS Protection should be explicitly enabled or disabled. Default is 'true' + meaning it is enabled. + + + + + + Add mode=block to the header or not, default is on. + + + + + + + Add a X-Content-Type-Options header to the resopnse. Value is always 'nosniff'. + + + + + + + + + + If disabled, the X-Content-Type-Options header will not be included. Default false. + + + + + + + Adds support for Cross-Origin-Opener-Policy header + + + + + + + + + + The policies for the Cross-Origin-Opener-Policy header. + + + + + + + + + + + + + + Adds support for Cross-Origin-Embedder-Policy header + + + + + + + + + + The policies for the Cross-Origin-Embedder-Policy header. + + + + + + + + + + + + + Adds support for Cross-Origin-Resource-Policy header + + + + + + + + + + The policies for the Cross-Origin-Resource-Policy header. + + + + + + + + + + + + + + Add additional headers to the response. + + + + + + + + + + The name of the header to add. + + + + + + The value for the header. + + + + + + Defines a reference to a Spring bean Id. + + + + + + + + Used to indicate that a filter bean declaration should be incorporated into the security + filter chain. + + + + + + + + + + + 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. + + + + + + The filter immediately before which the custom-filter should be placed in the chain + + + + + + The explicit position at which the custom-filter should be placed in the chain. Use if you + are replacing a standard filter. + + + + + + + + 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. + + + + + + + + The filter immediately before which the custom-filter should be placed in the chain + + + + + + + + The explicit position at which the custom-filter should be placed in the chain. Use if you + are replacing a standard filter. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/src/test/java/org/springframework/security/config/FilterChainProxyConfigTests.java b/config/src/test/java/org/springframework/security/config/FilterChainProxyConfigTests.java index edd33b4b10b..b0dde842f57 100644 --- a/config/src/test/java/org/springframework/security/config/FilterChainProxyConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/FilterChainProxyConfigTests.java @@ -18,10 +18,10 @@ import java.util.List; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java b/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java index 31d31c7a937..4e6d6ed9767 100644 --- a/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java +++ b/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java @@ -83,7 +83,7 @@ public void pre32SchemaAreNotSupported() { // SEC-1868 @Test public void initDoesNotLogErrorWhenFilterChainProxyFailsToLoad() throws Exception { - String className = "javax.servlet.Filter"; + String className = "jakarta.servlet.Filter"; Log logger = mock(Log.class); SecurityNamespaceHandler handler = new SecurityNamespaceHandler(); ReflectionTestUtils.setField(handler, "logger", logger); @@ -94,7 +94,7 @@ public void initDoesNotLogErrorWhenFilterChainProxyFailsToLoad() throws Exceptio @Test public void filterNoClassDefFoundError() throws Exception { - String className = "javax.servlet.Filter"; + String className = "jakarta.servlet.Filter"; expectClassUtilsForNameThrowsNoClassDefFoundError(className); assertThatExceptionOfType(BeanDefinitionParsingException.class) .isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK)) @@ -103,7 +103,7 @@ public void filterNoClassDefFoundError() throws Exception { @Test public void filterNoClassDefFoundErrorNoHttpBlock() throws Exception { - String className = "javax.servlet.Filter"; + String className = "jakarta.servlet.Filter"; expectClassUtilsForNameThrowsNoClassDefFoundError(className); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); // should load just fine since no http block diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTests.java index 54d57347c5b..f7ed82570ad 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2021 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. @@ -19,11 +19,17 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper; import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper; +import org.springframework.security.ldap.DefaultSpringSecurityContextSource; +import org.springframework.security.ldap.authentication.NullLdapAuthoritiesPopulator; +import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator; +import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; public class LdapAuthenticationProviderConfigurerTests { @@ -42,4 +48,27 @@ public void getAuthoritiesMapper() throws Exception { assertThat(this.configurer.getAuthoritiesMapper()).isInstanceOf(NullAuthoritiesMapper.class); } + @Test + public void customAuthoritiesPopulator() throws Exception { + assertThat(ReflectionTestUtils.getField(this.configurer, "ldapAuthoritiesPopulator")).isNull(); + this.configurer.ldapAuthoritiesPopulator(new NullLdapAuthoritiesPopulator()); + assertThat(ReflectionTestUtils.getField(this.configurer, "ldapAuthoritiesPopulator")) + .isInstanceOf(NullLdapAuthoritiesPopulator.class); + } + + @Test + public void configureWhenObjectPostProcessorThenAuthoritiesPopulatorIsPostProcessed() { + LdapAuthoritiesPopulator populator = mock(LdapAuthoritiesPopulator.class); + assertThat(ReflectionTestUtils.getField(this.configurer, "ldapAuthoritiesPopulator")).isNull(); + this.configurer.contextSource(new DefaultSpringSecurityContextSource("ldap://localhost:389")); + this.configurer.addObjectPostProcessor(new ObjectPostProcessor() { + @Override + public O postProcess(O object) { + return (O) populator; + } + }); + ReflectionTestUtils.invokeMethod(this.configurer, "getLdapAuthoritiesPopulator"); + assertThat(ReflectionTestUtils.getField(this.configurer, "ldapAuthoritiesPopulator")).isSameAs(populator); + } + } diff --git a/config/src/test/java/org/springframework/security/config/annotation/issue50/Issue50Tests.java b/config/src/test/java/org/springframework/security/config/annotation/issue50/Issue50Tests.java index 6de1764992b..1a2b82b0048 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/issue50/Issue50Tests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/issue50/Issue50Tests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.issue50; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/annotation/issue50/domain/User.java b/config/src/test/java/org/springframework/security/config/annotation/issue50/domain/User.java index d30ada88c45..0a5a1d1d85a 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/issue50/domain/User.java +++ b/config/src/test/java/org/springframework/security/config/annotation/issue50/domain/User.java @@ -16,10 +16,10 @@ package org.springframework.security.config.annotation.issue50.domain; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityService.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityService.java index b3675705c03..3638e844851 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityService.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityService.java @@ -18,8 +18,8 @@ import java.util.List; -import javax.annotation.security.DenyAll; -import javax.annotation.security.PermitAll; +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PostAuthorize; diff --git a/config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java b/config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java index ddc1c1f634f..222c20abe2c 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.sec2758; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.RolesAllowed; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistryTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistryTests.java index 1b38cac950b..bc8b85adf2a 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistryTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistryTests.java @@ -18,7 +18,7 @@ import java.util.List; -import javax.servlet.DispatcherType; +import jakarta.servlet.DispatcherType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/HttpSecurityHeadersTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/HttpSecurityHeadersTests.java index 39b800955c0..72e00cf57fd 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/HttpSecurityHeadersTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/HttpSecurityHeadersTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/SampleWebSecurityConfigurerAdapterTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/SampleWebSecurityConfigurerAdapterTests.java index 176ba69bb7a..9248f84bb3f 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/SampleWebSecurityConfigurerAdapterTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/SampleWebSecurityConfigurerAdapterTests.java @@ -18,7 +18,7 @@ import java.util.Base64; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java index 563696b7942..4a126cf7db2 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java @@ -20,10 +20,10 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistrationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistrationTests.java index 3991a622cf7..a38a37f28d3 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistrationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistrationTests.java @@ -18,11 +18,11 @@ import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpConfigurationTests.java index 53635b93d89..445dd6cc3b8 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpConfigurationTests.java @@ -18,19 +18,16 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.cas.web.CasAuthenticationFilter; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @@ -41,9 +38,6 @@ import org.springframework.web.filter.OncePerRequestFilter; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -70,16 +64,6 @@ public void configureWhenAddFilterUnregisteredThenThrowsBeanCreationException() + " Consider using addFilterBefore or addFilterAfter instead."); } - // https://github.com/spring-projects/spring-security-javaconfig/issues/104 - @Test - public void configureWhenAddFilterCasAuthenticationFilterThenFilterAdded() throws Exception { - CasAuthenticationFilterConfig.CAS_AUTHENTICATION_FILTER = spy(new CasAuthenticationFilter()); - this.spring.register(CasAuthenticationFilterConfig.class).autowire(); - this.mockMvc.perform(get("/")); - verify(CasAuthenticationFilterConfig.CAS_AUTHENTICATION_FILTER).doFilter(any(ServletRequest.class), - any(ServletResponse.class), any(FilterChain.class)); - } - @Test public void configureWhenConfigIsRequestMatchersJavadocThenAuthorizationApplied() throws Exception { this.spring.register(RequestMatcherRegistryConfigs.class).autowire(); @@ -121,21 +105,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } - @EnableWebSecurity - static class CasAuthenticationFilterConfig extends WebSecurityConfigurerAdapter { - - static CasAuthenticationFilter CAS_AUTHENTICATION_FILTER; - - @Override - protected void configure(HttpSecurity http) { - // @formatter:off - http - .addFilter(CAS_AUTHENTICATION_FILTER); - // @formatter:on - } - - } - @EnableWebSecurity static class RequestMatcherRegistryConfigs extends WebSecurityConfigurerAdapter { diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpSecurityAddFilterTest.java b/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpSecurityAddFilterTest.java index d3b5044c427..19519b6b671 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpSecurityAddFilterTest.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpSecurityAddFilterTest.java @@ -20,11 +20,11 @@ import java.util.List; import java.util.stream.Collectors; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.assertj.core.api.ListAssert; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java index ae167e0e5cb..a51e3490a6b 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java @@ -18,8 +18,9 @@ import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/builders/WebSecurityTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/builders/WebSecurityTests.java index 275c5d23c9b..3076cb5d2ba 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/builders/WebSecurityTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/builders/WebSecurityTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.builders; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfigurationTests.java index 813723e2839..d6d00d7f4c3 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfigurationTests.java @@ -18,12 +18,13 @@ import java.util.concurrent.Callable; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import com.google.common.net.HttpHeaders; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -47,6 +48,7 @@ import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.security.config.Customizer.withDefaults; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; @@ -200,6 +202,24 @@ public void loginWhenUsingDefaultsThenDefaultLogoutSuccessPageGenerated() throws this.mockMvc.perform(get("/login?logout")).andExpect(status().isOk()); } + @Test + public void configureWhenAuthorizeHttpRequestsBeforeAuthorizeRequestThenException() { + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy( + () -> this.spring.register(AuthorizeHttpRequestsBeforeAuthorizeRequestsConfig.class).autowire()) + .withMessageContaining( + "authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one."); + } + + @Test + public void configureWhenAuthorizeHttpRequestsAfterAuthorizeRequestThenException() { + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy( + () -> this.spring.register(AuthorizeHttpRequestsAfterAuthorizeRequestsConfig.class).autowire()) + .withMessageContaining( + "authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one."); + } + @RestController static class NameController { @@ -270,6 +290,44 @@ UserDetailsService userDetailsService() { } + @EnableWebSecurity + static class AuthorizeHttpRequestsBeforeAuthorizeRequestsConfig { + + @Bean + SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + // @formatter:off + return http + .authorizeHttpRequests((requests) -> requests + .anyRequest().authenticated() + ) + .authorizeRequests((requests) -> requests + .anyRequest().authenticated() + ) + .build(); + // @formatter:on + } + + } + + @EnableWebSecurity + static class AuthorizeHttpRequestsAfterAuthorizeRequestsConfig { + + @Bean + SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + // @formatter:off + return http + .authorizeRequests((requests) -> requests + .anyRequest().authenticated() + ) + .authorizeHttpRequests((requests) -> requests + .anyRequest().authenticated() + ) + .build(); + // @formatter:on + } + + } + @RestController static class BaseController { diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java index d70f27453c6..4f7876c0dbc 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configuration; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationResourceServerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationResourceServerTests.java index 251ccbd88cc..4b5f4cb24f9 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationResourceServerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationResourceServerTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configuration; -import javax.annotation.PreDestroy; +import jakarta.annotation.PreDestroy; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationTests.java index e0e57c86c45..6a20b0fafd4 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationTests.java @@ -20,8 +20,8 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java index ce9977c7c5d..9a4985cc55c 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -22,8 +22,8 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.Filter; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.Filter; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -33,6 +33,7 @@ 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.core.annotation.Order; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; @@ -62,7 +63,7 @@ import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator; +import org.springframework.security.web.access.RequestMatcherDelegatingWebInvocationPrivilegeEvaluator; import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator; import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler; import org.springframework.test.web.servlet.MockMvc; @@ -84,6 +85,7 @@ * @author Rob Winch * @author Joe Grandja * @author Evgeniy Cheban + * @author Marcus Da Coregio */ @ExtendWith(SpringTestContextExtension.class) public class WebSecurityConfigurationTests { @@ -218,10 +220,10 @@ public void securityExpressionHandlerWhenPermissionEvaluatorBeanThenPermissionEv } @Test - public void loadConfigWhenDefaultWebInvocationPrivilegeEvaluatorThenDefaultIsRegistered() { + public void loadConfigWhenDefaultWebInvocationPrivilegeEvaluatorThenRequestMatcherIsRegistered() { this.spring.register(WebInvocationPrivilegeEvaluatorDefaultsConfig.class).autowire(); assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class)) - .isInstanceOf(DefaultWebInvocationPrivilegeEvaluator.class); + .isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class); } @Test @@ -229,7 +231,7 @@ public void loadConfigWhenSecurityFilterChainBeanThenDefaultWebInvocationPrivile this.spring.register(AuthorizeRequestsFilterChainConfig.class).autowire(); assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class)) - .isInstanceOf(DefaultWebInvocationPrivilegeEvaluator.class); + .isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class); } // SEC-2303 @@ -375,6 +377,69 @@ public void loadConfigWhenMultipleAuthenticationManagersAndWebSecurityConfigurer assertThat(filterChains.get(1).matches(request)).isTrue(); } + @Test + public void loadConfigWhenTwoSecurityFilterChainsThenRequestMatcherDelegatingWebInvocationPrivilegeEvaluator() { + this.spring.register(TwoSecurityFilterChainConfig.class).autowire(); + assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class)) + .isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class); + } + + @Test + public void loadConfigWhenTwoSecurityFilterChainDebugThenRequestMatcherDelegatingWebInvocationPrivilegeEvaluator() { + this.spring.register(TwoSecurityFilterChainConfig.class).autowire(); + assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class)) + .isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class); + } + + // gh-10554 + @Test + public void loadConfigWhenMultipleSecurityFilterChainsThenWebInvocationPrivilegeEvaluatorApplySecurity() { + this.spring.register(MultipleSecurityFilterChainConfig.class).autowire(); + WebInvocationPrivilegeEvaluator privilegeEvaluator = this.spring.getContext() + .getBean(WebInvocationPrivilegeEvaluator.class); + assertUserPermissions(privilegeEvaluator); + assertAdminPermissions(privilegeEvaluator); + assertAnotherUserPermission(privilegeEvaluator); + } + + // gh-10554 + @Test + public void loadConfigWhenMultipleSecurityFilterChainAndIgnoringThenWebInvocationPrivilegeEvaluatorAcceptsNullAuthenticationOnIgnored() { + this.spring.register(MultipleSecurityFilterChainIgnoringConfig.class).autowire(); + WebInvocationPrivilegeEvaluator privilegeEvaluator = this.spring.getContext() + .getBean(WebInvocationPrivilegeEvaluator.class); + assertUserPermissions(privilegeEvaluator); + assertAdminPermissions(privilegeEvaluator); + assertAnotherUserPermission(privilegeEvaluator); + // null authentication + assertThat(privilegeEvaluator.isAllowed("/user", null)).isFalse(); + assertThat(privilegeEvaluator.isAllowed("/admin", null)).isFalse(); + assertThat(privilegeEvaluator.isAllowed("/another", null)).isFalse(); + assertThat(privilegeEvaluator.isAllowed("/ignoring1", null)).isTrue(); + assertThat(privilegeEvaluator.isAllowed("/ignoring1/child", null)).isTrue(); + } + + private void assertAnotherUserPermission(WebInvocationPrivilegeEvaluator privilegeEvaluator) { + Authentication anotherUser = new TestingAuthenticationToken("anotherUser", "password", "ROLE_ANOTHER"); + assertThat(privilegeEvaluator.isAllowed("/user", anotherUser)).isFalse(); + assertThat(privilegeEvaluator.isAllowed("/admin", anotherUser)).isFalse(); + assertThat(privilegeEvaluator.isAllowed("/another", anotherUser)).isTrue(); + } + + private void assertAdminPermissions(WebInvocationPrivilegeEvaluator privilegeEvaluator) { + Authentication admin = new TestingAuthenticationToken("admin", "password", "ROLE_ADMIN"); + assertThat(privilegeEvaluator.isAllowed("/user", admin)).isFalse(); + assertThat(privilegeEvaluator.isAllowed("/admin", admin)).isTrue(); + assertThat(privilegeEvaluator.isAllowed("/another", admin)).isTrue(); + } + + private void assertUserPermissions(WebInvocationPrivilegeEvaluator privilegeEvaluator) { + Authentication user = new TestingAuthenticationToken("user", "password", "ROLE_USER"); + assertThat(privilegeEvaluator.isAllowed("/user", user)).isTrue(); + assertThat(privilegeEvaluator.isAllowed("/admin", user)).isFalse(); + assertThat(privilegeEvaluator.isAllowed("/another", user)).isTrue(); + } + @EnableWebSecurity @Import(AuthenticationTestConfiguration.class) static class SortedWebSecurityConfigurerAdaptersConfig { @@ -1008,4 +1073,125 @@ protected AuthenticationManager authenticationManager() { } + @EnableWebSecurity + static class TwoSecurityFilterChainConfig { + + @Bean + @Order(Ordered.HIGHEST_PRECEDENCE) + public SecurityFilterChain path1(HttpSecurity http) throws Exception { + // @formatter:off + http + .requestMatchers((requests) -> requests.antMatchers("/path1/**")) + .authorizeRequests((requests) -> requests.anyRequest().authenticated()); + // @formatter:on + return http.build(); + } + + @Bean + @Order(Ordered.LOWEST_PRECEDENCE) + public SecurityFilterChain permitAll(HttpSecurity http) throws Exception { + http.authorizeRequests((requests) -> requests.anyRequest().permitAll()); + return http.build(); + } + + } + + @EnableWebSecurity(debug = true) + static class TwoSecurityFilterChainDebugConfig { + + @Bean + @Order(Ordered.HIGHEST_PRECEDENCE) + public SecurityFilterChain path1(HttpSecurity http) throws Exception { + // @formatter:off + http + .requestMatchers((requests) -> requests.antMatchers("/path1/**")) + .authorizeRequests((requests) -> requests.anyRequest().authenticated()); + // @formatter:on + return http.build(); + } + + @Bean + @Order(Ordered.LOWEST_PRECEDENCE) + public SecurityFilterChain permitAll(HttpSecurity http) throws Exception { + http.authorizeRequests((requests) -> requests.anyRequest().permitAll()); + return http.build(); + } + + } + + @EnableWebSecurity + @Import(AuthenticationTestConfiguration.class) + static class MultipleSecurityFilterChainConfig { + + @Bean + @Order(Ordered.HIGHEST_PRECEDENCE) + public SecurityFilterChain notAuthorized(HttpSecurity http) throws Exception { + // @formatter:off + http + .requestMatchers((requests) -> requests.antMatchers("/user")) + .authorizeRequests((requests) -> requests.anyRequest().hasRole("USER")); + // @formatter:on + return http.build(); + } + + @Bean + @Order(Ordered.HIGHEST_PRECEDENCE + 1) + public SecurityFilterChain path1(HttpSecurity http) throws Exception { + // @formatter:off + http + .requestMatchers((requests) -> requests.antMatchers("/admin")) + .authorizeRequests((requests) -> requests.anyRequest().hasRole("ADMIN")); + // @formatter:on + return http.build(); + } + + @Bean + @Order(Ordered.LOWEST_PRECEDENCE) + public SecurityFilterChain permitAll(HttpSecurity http) throws Exception { + http.authorizeRequests((requests) -> requests.anyRequest().permitAll()); + return http.build(); + } + + } + + @EnableWebSecurity + @Import(AuthenticationTestConfiguration.class) + static class MultipleSecurityFilterChainIgnoringConfig { + + @Bean + public WebSecurityCustomizer webSecurityCustomizer() { + return (web) -> web.ignoring().antMatchers("/ignoring1/**"); + } + + @Bean + @Order(Ordered.HIGHEST_PRECEDENCE) + public SecurityFilterChain notAuthorized(HttpSecurity http) throws Exception { + // @formatter:off + http + .requestMatchers((requests) -> requests.antMatchers("/user")) + .authorizeRequests((requests) -> requests.anyRequest().hasRole("USER")); + // @formatter:on + return http.build(); + } + + @Bean + @Order(Ordered.HIGHEST_PRECEDENCE + 1) + public SecurityFilterChain admin(HttpSecurity http) throws Exception { + // @formatter:off + http + .requestMatchers((requests) -> requests.antMatchers("/admin")) + .authorizeRequests((requests) -> requests.anyRequest().hasRole("ADMIN")); + // @formatter:on + return http.build(); + } + + @Bean + @Order(Ordered.LOWEST_PRECEDENCE) + public SecurityFilterChain permitAll(HttpSecurity http) throws Exception { + http.authorizeRequests((requests) -> requests.anyRequest().permitAll()); + return http.build(); + } + + } + } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeRequestsTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeRequestsTests.java index cc8c9dc8856..d3e972094a7 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeRequestsTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeRequestsTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ChannelSecurityConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ChannelSecurityConfigurerTests.java index 041419e50d9..309e7383e8d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ChannelSecurityConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ChannelSecurityConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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,6 +16,11 @@ package org.springframework.security.config.annotation.web.configurers; +import java.io.IOException; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -27,6 +32,8 @@ import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.test.SpringTestContext; import org.springframework.security.config.test.SpringTestContextExtension; +import org.springframework.security.web.PortMapperImpl; +import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.access.channel.ChannelDecisionManagerImpl; import org.springframework.security.web.access.channel.ChannelProcessingFilter; import org.springframework.security.web.access.channel.InsecureChannelProcessor; @@ -44,6 +51,7 @@ * * @author Rob Winch * @author Eleftheria Stein + * @author Onur Kagan Ozcan */ @ExtendWith(SpringTestContextExtension.class) public class ChannelSecurityConfigurerTests { @@ -93,6 +101,12 @@ public void requestWhenRequiresChannelConfiguredInLambdaThenRedirectsToHttps() t this.mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/")); } + @Test + public void requestWhenRequiresChannelConfiguredWithUrlRedirectThenRedirectsToUrlWithHttps() throws Exception { + this.spring.register(RequiresChannelWithTestUrlRedirectStrategy.class).autowire(); + this.mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/test")); + } + @EnableWebSecurity static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter { @@ -155,4 +169,35 @@ protected void configure(HttpSecurity http) throws Exception { } + @EnableWebSecurity + static class RequiresChannelWithTestUrlRedirectStrategy extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + .portMapper() + .portMapper(new PortMapperImpl()) + .and() + .requiresChannel() + .redirectStrategy(new TestUrlRedirectStrategy()) + .anyRequest() + .requiresSecure(); + // @formatter:on + } + + } + + static class TestUrlRedirectStrategy implements RedirectStrategy { + + @Override + public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) + throws IOException { + String redirectUrl = url + "test"; + redirectUrl = response.encodeRedirectURL(redirectUrl); + response.sendRedirect(redirectUrl); + } + + } + } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java index 750609bf149..56f09bd9218 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ import java.net.URI; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -320,6 +320,17 @@ public void getWhenCustomAccessDeniedHandlerThenHandlerIsUsed() throws Exception any(HttpServletResponse.class), any()); } + @Test + public void getWhenCustomDefaultAccessDeniedHandlerForThenHandlerIsUsed() throws Exception { + DefaultAccessDeniedHandlerForConfig.DENIED_HANDLER = mock(AccessDeniedHandler.class); + DefaultAccessDeniedHandlerForConfig.MATCHER = mock(RequestMatcher.class); + given(DefaultAccessDeniedHandlerForConfig.MATCHER.matches(any())).willReturn(true); + this.spring.register(DefaultAccessDeniedHandlerForConfig.class, BasicController.class).autowire(); + this.mvc.perform(post("/")).andExpect(status().isOk()); + verify(DefaultAccessDeniedHandlerForConfig.DENIED_HANDLER).handle(any(HttpServletRequest.class), + any(HttpServletResponse.class), any()); + } + @Test public void loginWhenNoCsrfTokenThenRespondsWithForbidden() throws Exception { this.spring.register(FormLoginConfig.class).autowire(); @@ -608,6 +619,24 @@ protected void configure(HttpSecurity http) throws Exception { } + @EnableWebSecurity + static class DefaultAccessDeniedHandlerForConfig extends WebSecurityConfigurerAdapter { + + static AccessDeniedHandler DENIED_HANDLER; + + static RequestMatcher MATCHER; + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + .exceptionHandling() + .defaultAccessDeniedHandlerFor(DENIED_HANDLER, MATCHER); + // @formatter:on + } + + } + @EnableWebSecurity static class FormLoginConfig extends WebSecurityConfigurerAdapter { diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/DefaultFiltersTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/DefaultFiltersTests.java index 37f9b28c72a..be2da0c432a 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/DefaultFiltersTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/DefaultFiltersTests.java @@ -20,8 +20,8 @@ import java.util.List; import java.util.stream.Collectors; -import javax.servlet.Filter; -import javax.servlet.ServletException; +import jakarta.servlet.Filter; +import jakarta.servlet.ServletException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExceptionHandlingConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExceptionHandlingConfigurerTests.java index 06d66a0f89a..25b64b421a6 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExceptionHandlingConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExceptionHandlingConfigurerTests.java @@ -16,8 +16,8 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java index cc64f4b92a9..2b2f2a0b55c 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -26,11 +26,16 @@ import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; 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.test.SpringTestContext; import org.springframework.security.config.test.SpringTestContextExtension; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.header.writers.CrossOriginEmbedderPolicyHeaderWriter; +import org.springframework.security.web.header.writers.CrossOriginOpenerPolicyHeaderWriter; +import org.springframework.security.web.header.writers.CrossOriginResourcePolicyHeaderWriter; import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy; import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter.XFrameOptionsMode; import org.springframework.test.web.servlet.MockMvc; @@ -52,6 +57,7 @@ * @author Eddú Meléndez * @author Vedran Pavic * @author Eleftheria Stein + * @author Marcus Da Coregio */ @ExtendWith(SpringTestContextExtension.class) public class HeadersConfigurerTests { @@ -514,6 +520,30 @@ public void getWhenHstsConfiguredWithPreloadInLambdaThenStrictTransportSecurityH assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.STRICT_TRANSPORT_SECURITY); } + @Test + public void getWhenCustomCrossOriginPoliciesInLambdaThenCrossOriginPolicyHeadersWithCustomValuesInResponse() + throws Exception { + this.spring.register(CrossOriginCustomPoliciesInLambdaConfig.class).autowire(); + MvcResult mvcResult = this.mvc.perform(get("/")) + .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin")) + .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp")) + .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin")).andReturn(); + assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, + HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY); + } + + @Test + public void getWhenCustomCrossOriginPoliciesThenCrossOriginPolicyHeadersWithCustomValuesInResponse() + throws Exception { + this.spring.register(CrossOriginCustomPoliciesConfig.class).autowire(); + MvcResult mvcResult = this.mvc.perform(get("/")) + .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin")) + .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp")) + .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin")).andReturn(); + assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, + HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY); + } + @EnableWebSecurity static class HeadersConfig extends WebSecurityConfigurerAdapter { @@ -1146,4 +1176,50 @@ protected void configure(HttpSecurity http) throws Exception { } + @EnableWebSecurity + static class CrossOriginCustomPoliciesInLambdaConfig { + + @Bean + SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + // @formatter:off + http.headers((headers) -> headers + .defaultsDisabled() + .crossOriginOpenerPolicy((policy) -> policy + .policy(CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy.SAME_ORIGIN) + ) + .crossOriginEmbedderPolicy((policy) -> policy + .policy(CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP) + ) + .crossOriginResourcePolicy((policy) -> policy + .policy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.SAME_ORIGIN) + ) + ); + // @formatter:on + return http.build(); + } + + } + + @EnableWebSecurity + static class CrossOriginCustomPoliciesConfig { + + @Bean + SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + // @formatter:off + http.headers() + .defaultsDisabled() + .crossOriginOpenerPolicy() + .policy(CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy.SAME_ORIGIN) + .and() + .crossOriginEmbedderPolicy() + .policy(CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP) + .and() + .crossOriginResourcePolicy() + .policy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.SAME_ORIGIN); + // @formatter:on + return http.build(); + } + + } + } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.java index 58f83e9d085..0b441f69882 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.java @@ -16,8 +16,8 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpSecurityAntMatchersTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpSecurityAntMatchersTests.java index 73d366be009..7719249759a 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpSecurityAntMatchersTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpSecurityAntMatchersTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpSecurityRequestMatchersTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpSecurityRequestMatchersTests.java index 9e60e93994f..02ea35edfec 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpSecurityRequestMatchersTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpSecurityRequestMatchersTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/Issue55Tests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/Issue55Tests.java index e0f25237b12..069aca52536 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/Issue55Tests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/Issue55Tests.java @@ -19,7 +19,7 @@ import java.lang.reflect.InvocationTargetException; import java.util.List; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpBasicTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpBasicTests.java index b66fa2de263..77c257c91b9 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpBasicTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpBasicTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.http.HttpHeaders; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.java index cb0d6cc089d..83621fabae3 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.java @@ -20,10 +20,10 @@ import java.util.List; import java.util.stream.Collectors; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.assertj.core.api.ListAssert; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java index a2f2cbbde05..ec529e249ae 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFormLoginTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFormLoginTests.java index 90d8a2a6ed8..fe03e67fc31 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFormLoginTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFormLoginTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpLogoutTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpLogoutTests.java index a5d1884b29c..9c468d87b70 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpLogoutTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpLogoutTests.java @@ -20,7 +20,7 @@ import java.util.Optional; import java.util.function.Predicate; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.assertj.core.api.Condition; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java index d57a9ab8bf6..31af12b0144 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpRequestCacheTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpRequestCacheTests.java index ea4ba0442e3..b9ec9faa4ba 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpRequestCacheTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpRequestCacheTests.java @@ -16,9 +16,9 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java index 7e2cfa0e413..0414368d7e9 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java @@ -16,8 +16,8 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpX509Tests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpX509Tests.java index d54a0a286e2..7cbfd570317 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpX509Tests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpX509Tests.java @@ -21,11 +21,14 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import javax.servlet.http.HttpServletRequest; +import javax.security.auth.x500.X500Principal; +import jakarta.servlet.http.HttpServletRequest; + +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.style.BCStyle; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import sun.security.x509.X500Name; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -240,12 +243,8 @@ protected void configure(HttpSecurity http) throws Exception { } private String extractCommonName(X509Certificate certificate) { - try { - return ((X500Name) certificate.getSubjectDN()).getCommonName(); - } - catch (Exception ex) { - throw new IllegalArgumentException(ex); - } + X500Principal principal = certificate.getSubjectX500Principal(); + return new X500Name(principal.getName()).getRDNs(BCStyle.CN)[0].getFirst().getValue().toString(); } } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.java index 9487d6ee0a9..ad2c6cbdc74 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.java @@ -16,9 +16,9 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceSessionManagementTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceSessionManagementTests.java index c88a240965b..b20b51d399a 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceSessionManagementTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceSessionManagementTests.java @@ -21,8 +21,8 @@ import java.util.Date; import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java index 70752fb1c5f..9a5174f810c 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,11 +61,32 @@ public void performWhenUsingPermitAllExactUrlRequestMatcherThenMatchesExactUrl() this.mvc.perform(getWithCsrf).andExpect(status().isFound()); } + @Test + public void performWhenUsingPermitAllExactUrlRequestMatcherThenMatchesExactUrlWithAuthorizeHttp() throws Exception { + this.spring.register(PermitAllConfigAuthorizeHttpRequests.class).autowire(); + MockHttpServletRequestBuilder request = get("/app/xyz").contextPath("/app"); + this.mvc.perform(request).andExpect(status().isNotFound()); + MockHttpServletRequestBuilder getWithQuery = get("/app/xyz?def").contextPath("/app"); + this.mvc.perform(getWithQuery).andExpect(status().isFound()); + MockHttpServletRequestBuilder postWithQueryAndCsrf = post("/app/abc?def").with(csrf()).contextPath("/app"); + this.mvc.perform(postWithQueryAndCsrf).andExpect(status().isNotFound()); + MockHttpServletRequestBuilder getWithCsrf = get("/app/abc").with(csrf()).contextPath("/app"); + this.mvc.perform(getWithCsrf).andExpect(status().isFound()); + } + @Test public void configureWhenNotAuthorizeRequestsThenException() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire()) - .withMessageContaining("permitAll only works with HttpSecurity.authorizeRequests"); + .isThrownBy(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire()).withMessageContaining( + "permitAll only works with either HttpSecurity.authorizeRequests() or HttpSecurity.authorizeHttpRequests()"); + } + + @Test + public void configureWhenBothAuthorizeRequestsAndAuthorizeHttpRequestsThenException() { + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(PermitAllConfigWithBothConfigs.class).autowire()) + .withMessageContaining( + "permitAll only works with either HttpSecurity.authorizeRequests() or HttpSecurity.authorizeHttpRequests()"); } @EnableWebSecurity @@ -86,6 +107,45 @@ protected void configure(HttpSecurity http) throws Exception { } + @EnableWebSecurity + static class PermitAllConfigAuthorizeHttpRequests extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + .authorizeHttpRequests() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/xyz").permitAll() + .loginProcessingUrl("/abc?def").permitAll(); + // @formatter:on + } + + } + + @EnableWebSecurity + static class PermitAllConfigWithBothConfigs extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + .authorizeRequests() + .anyRequest().authenticated() + .and() + .authorizeHttpRequests() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/xyz").permitAll() + .loginProcessingUrl("/abc?def").permitAll(); + // @formatter:on + } + + } + @EnableWebSecurity static class NoAuthorizedUrlsConfig extends WebSecurityConfigurerAdapter { diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java index aa91f3a8f16..643f1d0d0e9 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java @@ -18,8 +18,8 @@ import java.util.Collections; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.java index c3a38ef24d1..fc62d353648 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.java @@ -16,8 +16,8 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.java index bd1f4e937b9..f1faf2f76e5 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurerTests.java index f86916d26a5..4b48ce8ec88 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurerTests.java @@ -18,10 +18,10 @@ import java.util.List; -import javax.servlet.Filter; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerServlet31Tests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerServlet31Tests.java index e833999f1a6..5a766e1c073 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerServlet31Tests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerServlet31Tests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerSessionAuthenticationStrategyTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerSessionAuthenticationStrategyTests.java index 1b68b8a866a..5c9befad9dd 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerSessionAuthenticationStrategyTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerSessionAuthenticationStrategyTests.java @@ -16,8 +16,8 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java index 7fdf966b529..58619d310ff 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java @@ -16,9 +16,9 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationConfigurerTests.java index 914ea135ea9..7caa7e33d3c 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationConfigurerTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.annotation.web.configurers; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationsTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationsTests.java index e8540437740..f36bdb3f103 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationsTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationsTests.java @@ -18,7 +18,7 @@ import java.util.List; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurerTests.java index fdb28a46fd0..c1087c3e888 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurerTests.java @@ -19,8 +19,8 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java index f43127de1ec..32626bf8b8d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java @@ -32,8 +32,8 @@ import java.util.Map; import java.util.stream.Collectors; -import javax.annotation.PreDestroy; -import javax.servlet.http.HttpServletRequest; +import jakarta.annotation.PreDestroy; +import jakarta.servlet.http.HttpServletRequest; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java index b37040eff36..83e555430df 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java @@ -24,9 +24,9 @@ import java.util.Collection; import java.util.Collections; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java index adbfd09e765..dc6e49a2e53 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java @@ -41,9 +41,9 @@ import org.springframework.security.web.csrf.DefaultCsrfToken; import org.springframework.stereotype.Controller; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -139,7 +139,7 @@ protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) @Configuration @EnableWebSocketMessageBroker - static class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { + static class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerTests.java index 8d0ad848357..a9ad443d6d5 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerTests.java @@ -19,7 +19,7 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/core/GrantedAuthorityDefaultsJcTests.java b/config/src/test/java/org/springframework/security/config/core/GrantedAuthorityDefaultsJcTests.java index e90098d4471..ec3f02e95ae 100644 --- a/config/src/test/java/org/springframework/security/config/core/GrantedAuthorityDefaultsJcTests.java +++ b/config/src/test/java/org/springframework/security/config/core/GrantedAuthorityDefaultsJcTests.java @@ -18,11 +18,11 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/core/GrantedAuthorityDefaultsXmlTests.java b/config/src/test/java/org/springframework/security/config/core/GrantedAuthorityDefaultsXmlTests.java index 8fb04ed1d53..f459db36a5c 100644 --- a/config/src/test/java/org/springframework/security/config/core/GrantedAuthorityDefaultsXmlTests.java +++ b/config/src/test/java/org/springframework/security/config/core/GrantedAuthorityDefaultsXmlTests.java @@ -18,11 +18,11 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/core/HelloWorldMessageService.java b/config/src/test/java/org/springframework/security/config/core/HelloWorldMessageService.java index 452a20042fb..9ab9b3442dd 100755 --- a/config/src/test/java/org/springframework/security/config/core/HelloWorldMessageService.java +++ b/config/src/test/java/org/springframework/security/config/core/HelloWorldMessageService.java @@ -16,7 +16,7 @@ package org.springframework.security.config.core; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.RolesAllowed; import org.springframework.security.access.prepost.PreAuthorize; diff --git a/config/src/test/java/org/springframework/security/config/doc/XsdDocumentedTests.java b/config/src/test/java/org/springframework/security/config/doc/XsdDocumentedTests.java index 35d857c84a9..e6aca7c4613 100644 --- a/config/src/test/java/org/springframework/security/config/doc/XsdDocumentedTests.java +++ b/config/src/test/java/org/springframework/security/config/doc/XsdDocumentedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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,10 @@ package org.springframework.security.config.doc; +import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -60,11 +61,11 @@ public class XsdDocumentedTests { "nsa-frame-options-from-parameter"); // @formatter:on - String referenceLocation = "../docs/modules/ROOT/pages/servlet/appendix/namespace.adoc"; + String referenceLocation = "../docs/modules/ROOT/pages/servlet/appendix/namespace"; String schema31xDocumentLocation = "org/springframework/security/config/spring-security-3.1.xsd"; - String schemaDocumentLocation = "org/springframework/security/config/spring-security-5.6.xsd"; + String schemaDocumentLocation = "org/springframework/security/config/spring-security-6.0.xsd"; XmlSupport xml = new XmlSupport(); @@ -149,8 +150,8 @@ public void sizeWhenReadingFilesystemThenIsCorrectNumberOfSchemaFiles() throws I .getParentFile() .list((dir, name) -> name.endsWith(".xsd")); // @formatter:on - assertThat(schemas.length).isEqualTo(18) - .withFailMessage("the count is equal to 18, if not then schemaDocument needs updating"); + assertThat(schemas.length).isEqualTo(19) + .withFailMessage("the count is equal to 19, if not then schemaDocument needs updating"); } /** @@ -163,7 +164,7 @@ public void sizeWhenReadingFilesystemThenIsCorrectNumberOfSchemaFiles() throws I public void countReferencesWhenReviewingDocumentationThenEntireSchemaIsIncluded() throws IOException { Map elementsByElementName = this.xml.elementsByElementName(this.schemaDocumentLocation); // @formatter:off - List documentIds = Files.lines(Paths.get(this.referenceLocation)) + List documentIds = namespaceLines() .filter((line) -> line.matches("\\[\\[(nsa-.*)\\]\\]")) .map((line) -> line.substring(2, line.length() - 2)) .collect(Collectors.toList()); @@ -189,7 +190,7 @@ public void countLinksWhenReviewingDocumentationThenParentsAndChildrenAreCorrect Map> docAttrNameToParents = new TreeMap<>(); String docAttrName = null; Map> currentDocAttrNameToElmt = null; - List lines = Files.readAllLines(Paths.get(this.referenceLocation)); + List lines = namespaceLines().collect(Collectors.toList()); for (String line : lines) { if (line.matches("^\\[\\[.*\\]\\]$")) { String id = line.substring(2, line.length() - 2); @@ -212,6 +213,13 @@ else if (id.endsWith("-attributes") || docAttrName != null && !id.startsWith(doc String elmtId = line.replaceAll(expression, "$1"); currentDocAttrNameToElmt.computeIfAbsent(docAttrName, (key) -> new ArrayList<>()).add(elmtId); } + else { + expression = ".*xref:.*#(nsa-.*)\\[.*\\]"; + if (line.matches(expression)) { + String elmtId = line.replaceAll(expression, "$1"); + currentDocAttrNameToElmt.computeIfAbsent(docAttrName, (key) -> new ArrayList<>()).add(elmtId); + } + } } } Map elementNameToElement = this.xml.elementsByElementName(this.schemaDocumentLocation); @@ -295,4 +303,17 @@ public void countWhenReviewingDocumentationThenAllElementsDocumented() throws IO assertThat(notDocAttrIds).isEmpty(); } + private Stream namespaceLines() { + return Stream.of(new File(this.referenceLocation).listFiles()).map(File::toPath).flatMap(this::fileLines); + } + + private Stream fileLines(Path path) { + try { + return Files.lines(path); + } + catch (Exception ex) { + throw new RuntimeException(ex); + } + } + } diff --git a/config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java b/config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java index 3a831ac78af..9c31a81089c 100644 --- a/config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java @@ -16,8 +16,8 @@ package org.springframework.security.config.http; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpStatus; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java b/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java index ce17aebd9ac..99a4465da37 100644 --- a/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java @@ -19,9 +19,9 @@ import java.net.URI; import java.util.List; -import javax.servlet.Filter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpStatus; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java b/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java index c03c855c47c..82a3c924981 100644 --- a/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java @@ -18,9 +18,9 @@ import java.util.List; -import javax.servlet.Filter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/http/HttpConfigTests.java b/config/src/test/java/org/springframework/security/config/http/HttpConfigTests.java index 990a6482211..40ba00ce494 100644 --- a/config/src/test/java/org/springframework/security/config/http/HttpConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/HttpConfigTests.java @@ -16,8 +16,8 @@ package org.springframework.security.config.http; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponseWrapper; import org.apache.http.HttpStatus; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java b/config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java index c399b1994ab..088bd5334d8 100644 --- a/config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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,6 +48,7 @@ * @author Tim Ysewyn * @author Josh Cummings * @author Rafiullah Hamedy + * @author Marcus Da Coregio */ @ExtendWith(SpringTestContextExtension.class) public class HttpHeadersConfigTests { @@ -733,6 +734,53 @@ public void requestWhenReferrerPolicyConfiguredWithSameOriginThenRespondsWithSam // @formatter:on } + @Test + public void requestWhenCrossOriginOpenerPolicyWithSameOriginAllowPopupsThenRespondsWithSameOriginAllowPopups() + throws Exception { + this.spring.configLocations(this.xml("DefaultsDisabledWithCrossOriginOpenerPolicy")).autowire(); + // @formatter:off + this.mvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(excludesDefaults()) + .andExpect(header().string("Cross-Origin-Opener-Policy", "same-origin-allow-popups")); + // @formatter:on + } + + @Test + public void requestWhenCrossOriginEmbedderPolicyWithRequireCorpThenRespondsWithRequireCorp() throws Exception { + this.spring.configLocations(this.xml("DefaultsDisabledWithCrossOriginEmbedderPolicy")).autowire(); + // @formatter:off + this.mvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(excludesDefaults()) + .andExpect(header().string("Cross-Origin-Embedder-Policy", "require-corp")); + // @formatter:on + } + + @Test + public void requestWhenCrossOriginResourcePolicyWithSameOriginThenRespondsWithSameOrigin() throws Exception { + this.spring.configLocations(this.xml("DefaultsDisabledWithCrossOriginResourcePolicy")).autowire(); + // @formatter:off + this.mvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(excludesDefaults()) + .andExpect(header().string("Cross-Origin-Resource-Policy", "same-origin")); + // @formatter:on + } + + @Test + public void requestWhenCrossOriginPoliciesRespondsCrossOriginPolicies() throws Exception { + this.spring.configLocations(this.xml("DefaultsDisabledWithCrossOriginPolicies")).autowire(); + // @formatter:off + this.mvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(excludesDefaults()) + .andExpect(header().string("Cross-Origin-Opener-Policy", "same-origin")) + .andExpect(header().string("Cross-Origin-Embedder-Policy", "require-corp")) + .andExpect(header().string("Cross-Origin-Resource-Policy", "same-origin")); + // @formatter:on + } + private static ResultMatcher includesDefaults() { return includes(defaultHeaders); } diff --git a/config/src/test/java/org/springframework/security/config/http/HttpInterceptUrlTests.java b/config/src/test/java/org/springframework/security/config/http/HttpInterceptUrlTests.java index 462fa5dd385..106dd0cc203 100644 --- a/config/src/test/java/org/springframework/security/config/http/HttpInterceptUrlTests.java +++ b/config/src/test/java/org/springframework/security/config/http/HttpInterceptUrlTests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.http; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java b/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java index 2ebd408395f..1c4a87b2922 100644 --- a/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java @@ -19,7 +19,7 @@ import java.util.Collections; import java.util.Map; -import javax.servlet.ServletRegistration; +import jakarta.servlet.ServletRegistration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java index 0fc87cfe8cb..9f6128b0898 100644 --- a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java @@ -32,11 +32,12 @@ import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.spi.LoginModule; -import javax.servlet.Filter; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; + +import jakarta.servlet.Filter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponseWrapper; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; diff --git a/config/src/test/java/org/springframework/security/config/http/NamespaceHttpBasicTests.java b/config/src/test/java/org/springframework/security/config/http/NamespaceHttpBasicTests.java index 1616a8b6c77..3366458955b 100644 --- a/config/src/test/java/org/springframework/security/config/http/NamespaceHttpBasicTests.java +++ b/config/src/test/java/org/springframework/security/config/http/NamespaceHttpBasicTests.java @@ -19,8 +19,8 @@ import java.lang.reflect.Method; import java.util.Base64; -import javax.servlet.Filter; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java index e5613347138..2a43d604e14 100644 --- a/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java @@ -30,7 +30,7 @@ import java.util.Properties; import java.util.stream.Collectors; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; diff --git a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java b/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java index 80a43d8859d..dee0a388181 100644 --- a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java @@ -19,8 +19,8 @@ import java.util.HashSet; import java.util.Set; -import javax.servlet.Filter; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.Filter; +import jakarta.servlet.http.HttpServletRequest; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; diff --git a/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java b/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java index 3843c280bd4..8cc9fe2516d 100644 --- a/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java @@ -18,7 +18,7 @@ import java.util.Collections; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java b/config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java index 7371dc5ec5f..a14b5c9c905 100644 --- a/config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.http.HttpHeaders; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java index c21f42b9850..e64e54f7e9d 100644 --- a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java +++ b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java @@ -16,7 +16,7 @@ package org.springframework.security.config.http; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigTests.java b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigTests.java index dc5c4c1a634..e4cbcb4f433 100644 --- a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigTests.java @@ -20,12 +20,12 @@ import java.security.Principal; import java.util.List; -import javax.servlet.Filter; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; +import jakarta.servlet.Filter; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponseWrapper; import org.apache.http.HttpStatus; import org.junit.jupiter.api.Test; diff --git a/config/src/test/java/org/springframework/security/config/http/customconfigurer/CustomHttpSecurityConfigurerTests.java b/config/src/test/java/org/springframework/security/config/http/customconfigurer/CustomHttpSecurityConfigurerTests.java index 3644ed52eab..a6bf001e363 100644 --- a/config/src/test/java/org/springframework/security/config/http/customconfigurer/CustomHttpSecurityConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/http/customconfigurer/CustomHttpSecurityConfigurerTests.java @@ -18,7 +18,7 @@ import java.util.Properties; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java index c4d08dc5295..378abd27ee9 100644 --- a/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java @@ -208,24 +208,6 @@ public void duplicateElementCausesError() { .isThrownBy(() -> setContext("" + "")); } - // SEC-936 - @Test - public void worksWithoutTargetOrClass() { - // @formatter:off - setContext("" - + "" - + " " - + " " - + "" - + ConfigTestUtils.AUTH_PROVIDER_XML); - // @formatter:on - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", - AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); - SecurityContextHolder.getContext().setAuthentication(token); - this.target = (BusinessService) this.appContext.getBean("businessService"); - assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someUserMethod1); - } - // Expression configuration tests @SuppressWarnings("unchecked") @Test diff --git a/config/src/test/java/org/springframework/security/config/method/sec2136/JpaPermissionEvaluator.java b/config/src/test/java/org/springframework/security/config/method/sec2136/JpaPermissionEvaluator.java index d186330f0ee..db25f03c7d4 100644 --- a/config/src/test/java/org/springframework/security/config/method/sec2136/JpaPermissionEvaluator.java +++ b/config/src/test/java/org/springframework/security/config/method/sec2136/JpaPermissionEvaluator.java @@ -18,7 +18,7 @@ import java.io.Serializable; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.PermissionEvaluator; diff --git a/config/src/test/java/org/springframework/security/config/test/SpringTestContext.java b/config/src/test/java/org/springframework/security/config/test/SpringTestContext.java index 36a741b99ad..3ca308e511c 100644 --- a/config/src/test/java/org/springframework/security/config/test/SpringTestContext.java +++ b/config/src/test/java/org/springframework/security/config/test/SpringTestContext.java @@ -20,10 +20,10 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; import org.springframework.mock.web.MockServletConfig; diff --git a/config/src/test/java/org/springframework/security/config/web/server/HeaderSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/HeaderSpecTests.java index a3167f2d140..f4b85f45bad 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/HeaderSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/HeaderSpecTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -30,6 +30,9 @@ import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter; import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter; +import org.springframework.security.web.server.header.CrossOriginEmbedderPolicyServerHttpHeadersWriter; +import org.springframework.security.web.server.header.CrossOriginOpenerPolicyServerHttpHeadersWriter; +import org.springframework.security.web.server.header.CrossOriginResourcePolicyServerHttpHeadersWriter; import org.springframework.security.web.server.header.FeaturePolicyServerHttpHeadersWriter; import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter; import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy; @@ -48,6 +51,7 @@ * @author Rob Winch * @author Vedran Pavic * @author Ankur Pathak + * @author Marcus Da Coregio * @since 5.0 */ public class HeaderSpecTests { @@ -406,6 +410,53 @@ public void headersWhenCustomHeadersWriter() { assertHeaders(); } + @Test + public void headersWhenCrossOriginPoliciesCustomEnabledThenCustomCrossOriginPoliciesWritten() { + this.expectedHeaders.add(CrossOriginOpenerPolicyServerHttpHeadersWriter.OPENER_POLICY, + CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS + .getPolicy()); + this.expectedHeaders.add(CrossOriginEmbedderPolicyServerHttpHeadersWriter.EMBEDDER_POLICY, + CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP.getPolicy()); + this.expectedHeaders.add(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY, + CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN.getPolicy()); + // @formatter:off + this.http.headers() + .crossOriginOpenerPolicy() + .policy(CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS) + .and() + .crossOriginEmbedderPolicy() + .policy(CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP) + .and() + .crossOriginResourcePolicy() + .policy(CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN); + // @formatter:on + assertHeaders(); + } + + @Test + public void headersWhenCrossOriginPoliciesCustomEnabledInLambdaThenCustomCrossOriginPoliciesWritten() { + this.expectedHeaders.add(CrossOriginOpenerPolicyServerHttpHeadersWriter.OPENER_POLICY, + CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS + .getPolicy()); + this.expectedHeaders.add(CrossOriginEmbedderPolicyServerHttpHeadersWriter.EMBEDDER_POLICY, + CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP.getPolicy()); + this.expectedHeaders.add(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY, + CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN.getPolicy()); + // @formatter:off + this.http.headers() + .crossOriginOpenerPolicy((policy) -> policy + .policy(CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS) + ) + .crossOriginEmbedderPolicy((policy) -> policy + .policy(CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP) + ) + .crossOriginResourcePolicy((policy) -> policy + .policy(CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN) + ); + // @formatter:on + assertHeaders(); + } + private void expectHeaderNamesNotPresent(String... headerNames) { for (String headerName : headerNames) { this.expectedHeaders.remove(headerName); diff --git a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java index ef3ff4db4d5..4a6d0c373c8 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java @@ -28,7 +28,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import javax.annotation.PreDestroy; +import jakarta.annotation.PreDestroy; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; @@ -70,7 +70,6 @@ import org.springframework.security.web.server.authentication.HttpStatusServerEntryPoint; import org.springframework.security.web.server.authentication.ServerAuthenticationConverter; import org.springframework.security.web.server.authorization.HttpStatusServerAccessDeniedHandler; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @@ -93,7 +92,7 @@ * Tests for * {@link org.springframework.security.config.web.server.ServerHttpSecurity.OAuth2ResourceServerSpec} */ -@ExtendWith({ SpringExtension.class, SpringTestContextExtension.class }) +@ExtendWith({ SpringTestContextExtension.class }) public class OAuth2ResourceServerSpecTests { private String expired = "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE1MzUwMzc4OTd9.jqZDDjfc2eysX44lHXEIr9XFd2S8vjIZHCccZU-dRWMRJNsQ1QN5VNnJGklqJBXJR4qgla6cmVqPOLkUHDb0sL0nxM5XuzQaG5ZzKP81RV88shFyAiT0fD-6nl1k-Fai-Fu-VkzSpNXgeONoTxDaYhdB-yxmgrgsApgmbOTE_9AcMk-FQDXQ-pL9kynccFGV0lZx4CA7cyknKN7KBxUilfIycvXODwgKCjj_1WddLTCNGYogJJSg__7NoxzqbyWd3udbHVjqYq7GsMMrGB4_2kBD4CkghOSNcRHbT_DIXowxfAVT7PAg7Q0E5ruZsr2zPZacEUDhJ6-wbvlA0FAOUg"; diff --git a/config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java b/config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java index 1c5eb64faa8..7496bc9c2d9 100644 --- a/config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java @@ -40,7 +40,7 @@ import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageType; -import org.springframework.messaging.support.ChannelInterceptorAdapter; +import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.messaging.support.GenericMessage; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.expression.SecurityExpressionOperations; @@ -444,7 +444,7 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) } - static class ExceptingInterceptor extends ChannelInterceptorAdapter { + static class ExceptingInterceptor implements ChannelInterceptor { @Override public Message preSend(Message message, MessageChannel channel) { diff --git a/config/src/test/java/org/springframework/security/htmlunit/server/WebTestClientWebConnection.java b/config/src/test/java/org/springframework/security/htmlunit/server/WebTestClientWebConnection.java index a2fed90d58d..91e948bf904 100644 --- a/config/src/test/java/org/springframework/security/htmlunit/server/WebTestClientWebConnection.java +++ b/config/src/test/java/org/springframework/security/htmlunit/server/WebTestClientWebConnection.java @@ -60,8 +60,8 @@ public WebTestClientWebConnection(WebTestClient webTestClient, WebClient webClie * Validate the supplied {@code contextPath}. *

* If the value is not {@code null}, it must conform to - * {@link javax.servlet.http.HttpServletRequest#getContextPath()} which states that it - * can be an empty string and otherwise must start with a "/" character and not end + * {@link jakarta.servlet.http.HttpServletRequest#getContextPath()} which states that + * it can be an empty string and otherwise must start with a "/" character and not end * with a "/" character. * @param contextPath the path to validate */ diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/AnonymousDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/AnonymousDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/AnonymousDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/AnonymousDslTests.kt index 754a9d91ff7..2387a2c64d5 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/AnonymousDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/AnonymousDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/AuthorizeRequestsDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/AuthorizeRequestsDslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/AuthorizeRequestsDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/AuthorizeRequestsDslTests.kt index 279d78b359a..94c31ff7684 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/AuthorizeRequestsDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/AuthorizeRequestsDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/CorsDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/CorsDslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/CorsDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/CorsDslTests.kt index bd33989bb7c..c5a21e72ac0 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/CorsDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/CorsDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.Test diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/CsrfDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/CsrfDslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/CsrfDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/CsrfDslTests.kt index 19b885e29b7..8ecca56eb38 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/CsrfDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/CsrfDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.mockkObject diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/ExceptionHandlingDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/ExceptionHandlingDslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/ExceptionHandlingDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/ExceptionHandlingDslTests.kt index 43a525148f7..d49e106d72e 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/ExceptionHandlingDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/ExceptionHandlingDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.jupiter.api.Test diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/FormLoginDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/FormLoginDslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/FormLoginDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/FormLoginDslTests.kt index 16783f1307c..f60692be1cb 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/FormLoginDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/FormLoginDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.mockkObject @@ -40,7 +40,7 @@ import org.springframework.test.web.servlet.get import org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import org.springframework.web.bind.annotation.GetMapping -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest /** * Tests for [FormLoginDsl] diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/HeadersDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/HeadersDslTests.kt similarity index 97% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/HeadersDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/HeadersDslTests.kt index c2cbfb371dd..c21f1b52ed0 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/HeadersDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/HeadersDslTests.kt @@ -14,18 +14,18 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.annotation.Bean import org.springframework.http.HttpHeaders import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.headers.PermissionsPolicyDsl import org.springframework.security.web.header.writers.StaticHeadersWriter import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/HttpBasicDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/HttpBasicDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/HttpBasicDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/HttpBasicDslTests.kt index cb6f6b47f8c..31e2f05721d 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/HttpBasicDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/HttpBasicDslTests.kt @@ -14,12 +14,12 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.mockkObject import io.mockk.verify -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/HttpSecurityDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/HttpSecurityDslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/HttpSecurityDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/HttpSecurityDslTests.kt index eea2c3bff1e..860afdf5670 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/HttpSecurityDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/HttpSecurityDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.mockkObject @@ -52,7 +52,7 @@ import org.springframework.test.web.servlet.get import org.springframework.test.web.servlet.post import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.web.servlet.config.annotation.EnableWebMvc -import javax.servlet.Filter +import jakarta.servlet.Filter /** * Tests for [HttpSecurityDsl] diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/LogoutDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/LogoutDslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/LogoutDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/LogoutDslTests.kt index 2bf1af54716..ecf5eafa46b 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/LogoutDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/LogoutDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.mockkObject diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2ClientDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/OAuth2ClientDslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2ClientDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/OAuth2ClientDslTests.kt index ba45eb97cbb..2becea07133 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2ClientDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/OAuth2ClientDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.mockkObject diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2LoginDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/OAuth2LoginDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2LoginDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/OAuth2LoginDslTests.kt index f0b146a3c18..3a878b316e2 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2LoginDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/OAuth2LoginDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.mockkObject @@ -42,7 +42,7 @@ import org.springframework.test.web.servlet.get import org.springframework.test.web.servlet.post import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest /** * Tests for [OAuth2LoginDsl] diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2ResourceServerDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/OAuth2ResourceServerDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2ResourceServerDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/OAuth2ResourceServerDslTests.kt index 72b0fae55e8..b111f27f412 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2ResourceServerDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/OAuth2ResourceServerDslTests.kt @@ -14,13 +14,13 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import io.mockk.verify -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/PasswordManagementDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/PasswordManagementDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/PasswordManagementDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/PasswordManagementDslTests.kt index af302cf96ff..53d9b3ed188 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/PasswordManagementDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/PasswordManagementDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/PortMapperDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/PortMapperDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/PortMapperDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/PortMapperDslTests.kt index 7f020208c82..14e221ed36c 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/PortMapperDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/PortMapperDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/RememberMeDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/RememberMeDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/RememberMeDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/RememberMeDslTests.kt index 17efacf3a4d..c4de4e92895 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/RememberMeDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/RememberMeDslTests.kt @@ -14,24 +14,19 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web -import io.mockk.Called -import io.mockk.confirmVerified import io.mockk.every import io.mockk.justRun import io.mockk.mockk import io.mockk.mockkObject import io.mockk.verify -import javax.servlet.http.HttpServletRequest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.fail import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.core.annotation.Order -import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpSession import org.springframework.security.authentication.RememberMeAuthenticationToken import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder @@ -39,7 +34,6 @@ 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.test.SpringTestContext -import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.core.Authentication import org.springframework.security.core.authority.AuthorityUtils import org.springframework.security.core.userdetails.PasswordEncodedUser diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/RequestCacheDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/RequestCacheDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/RequestCacheDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/RequestCacheDslTests.kt index 52ee0492e58..8a50adb1ec2 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/RequestCacheDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/RequestCacheDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/RequiresChannelDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/RequiresChannelDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/RequiresChannelDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/RequiresChannelDslTests.kt index 3ec020307bc..5f7190790ca 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/RequiresChannelDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/RequiresChannelDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.mockkObject import io.mockk.verify diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/Saml2DslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/Saml2DslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/Saml2DslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/Saml2DslTests.kt index a9dc47a2daf..da48324474e 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/Saml2DslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/Saml2DslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.mockk diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/SessionManagementDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/SessionManagementDslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/SessionManagementDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/SessionManagementDslTests.kt index 25302355ea2..334a22388e8 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/SessionManagementDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/SessionManagementDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.every import io.mockk.justRun diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/X509DslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/X509DslTests.kt similarity index 99% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/X509DslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/X509DslTests.kt index e0f6577f149..71be4040737 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/X509DslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/X509DslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet +package org.springframework.security.config.annotation.web import io.mockk.mockk import java.security.cert.Certificate diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/CacheControlDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/CacheControlDslTests.kt similarity index 96% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/CacheControlDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/CacheControlDslTests.kt index ab2782ac43b..c058f368d94 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/CacheControlDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/CacheControlDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @@ -23,7 +23,7 @@ import org.springframework.http.HttpHeaders import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.test.web.servlet.MockMvc diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ContentSecurityPolicyDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ContentSecurityPolicyDslTests.kt similarity index 96% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ContentSecurityPolicyDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ContentSecurityPolicyDslTests.kt index b312311cd65..130e143dfab 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ContentSecurityPolicyDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ContentSecurityPolicyDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @@ -22,7 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired 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.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ContentTypeOptionsDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ContentTypeOptionsDslTests.kt similarity index 95% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ContentTypeOptionsDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ContentTypeOptionsDslTests.kt index ce682ed76d4..75efe8c8c06 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ContentTypeOptionsDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ContentTypeOptionsDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @@ -22,7 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired 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.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/FrameOptionsDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/FrameOptionsDslTests.kt similarity index 97% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/FrameOptionsDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/FrameOptionsDslTests.kt index 021dda0848f..215b015b1bd 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/FrameOptionsDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/FrameOptionsDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @@ -22,7 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired 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.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/HttpPublicKeyPinningDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/HttpPublicKeyPinningDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/HttpPublicKeyPinningDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/HttpPublicKeyPinningDslTests.kt index e4759fb2840..3ffd42a66d8 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/HttpPublicKeyPinningDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/HttpPublicKeyPinningDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test @@ -25,7 +25,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/HttpStrictTransportSecurityDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/HttpStrictTransportSecurityDslTests.kt similarity index 97% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/HttpStrictTransportSecurityDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/HttpStrictTransportSecurityDslTests.kt index 374eb607c30..00decf1d0a9 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/HttpStrictTransportSecurityDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/HttpStrictTransportSecurityDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test @@ -23,7 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired 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.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.server.header.StrictTransportSecurityServerHttpHeadersWriter diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ReferrerPolicyDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ReferrerPolicyDslTests.kt similarity index 95% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ReferrerPolicyDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ReferrerPolicyDslTests.kt index c9d3c04d067..76dc74bfd8c 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ReferrerPolicyDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ReferrerPolicyDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @@ -22,7 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired 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.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/XssProtectionConfigDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/XssProtectionConfigDslTests.kt similarity index 97% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/XssProtectionConfigDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/XssProtectionConfigDslTests.kt index 8b10f28cce4..93622c15fbb 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/XssProtectionConfigDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/XssProtectionConfigDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.headers +package org.springframework.security.config.annotation.web.headers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @@ -22,7 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired 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.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.server.header.XXssProtectionServerHttpHeadersWriter diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/client/AuthorizationCodeGrantDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/client/AuthorizationCodeGrantDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/client/AuthorizationCodeGrantDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/client/AuthorizationCodeGrantDslTests.kt index 72e5db552e3..d624a781c90 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/client/AuthorizationCodeGrantDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/client/AuthorizationCodeGrantDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.client +package org.springframework.security.config.annotation.web.oauth2.client import io.mockk.every import io.mockk.mockk @@ -31,7 +31,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.config.oauth2.client.CommonOAuth2Provider import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/AuthorizationEndpointDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/AuthorizationEndpointDslTests.kt similarity index 97% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/AuthorizationEndpointDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/AuthorizationEndpointDslTests.kt index c4dff79baf6..84d0d792978 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/AuthorizationEndpointDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/AuthorizationEndpointDslTests.kt @@ -14,12 +14,12 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.login +package org.springframework.security.config.annotation.web.oauth2.login import io.mockk.every import io.mockk.mockkObject import io.mockk.verify -import javax.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletRequest import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired @@ -31,7 +31,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.config.oauth2.client.CommonOAuth2Provider import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/RedirectionEndpointDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/RedirectionEndpointDslTests.kt similarity index 97% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/RedirectionEndpointDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/RedirectionEndpointDslTests.kt index 9487e857ec8..051436c93ac 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/RedirectionEndpointDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/RedirectionEndpointDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.login +package org.springframework.security.config.annotation.web.oauth2.login import io.mockk.every import io.mockk.mockkObject @@ -29,7 +29,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.config.oauth2.client.CommonOAuth2Provider import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/TokenEndpointDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/TokenEndpointDslTests.kt similarity index 97% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/TokenEndpointDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/TokenEndpointDslTests.kt index 9dc1df0cb51..63f526a88c0 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/TokenEndpointDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/TokenEndpointDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.login +package org.springframework.security.config.annotation.web.oauth2.login import io.mockk.every import io.mockk.mockkObject @@ -30,7 +30,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.config.oauth2.client.CommonOAuth2Provider import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/UserInfoEndpointDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/UserInfoEndpointDslTests.kt similarity index 97% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/UserInfoEndpointDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/UserInfoEndpointDslTests.kt index 477504ec5c3..23d7e42281d 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/login/UserInfoEndpointDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/UserInfoEndpointDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.login +package org.springframework.security.config.annotation.web.oauth2.login import io.mockk.every import io.mockk.mockk @@ -31,7 +31,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.config.oauth2.client.CommonOAuth2Provider import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/JwtDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/JwtDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/JwtDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/JwtDslTests.kt index b0d92a53bd5..fe57a566ce0 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/JwtDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/JwtDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.resourceserver +package org.springframework.security.config.annotation.web.oauth2.resourceserver import io.mockk.every import io.mockk.mockk @@ -35,7 +35,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.core.Authentication import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames import org.springframework.security.oauth2.jwt.Jwt diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/OpaqueTokenDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OpaqueTokenDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/OpaqueTokenDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OpaqueTokenDslTests.kt index 218e0618b94..634cae0a78b 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/oauth2/resourceserver/OpaqueTokenDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OpaqueTokenDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.oauth2.resourceserver +package org.springframework.security.config.annotation.web.oauth2.resourceserver import io.mockk.every import io.mockk.mockkObject @@ -35,7 +35,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.core.Authentication import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal import org.springframework.security.oauth2.core.TestOAuth2AccessTokens diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/session/SessionConcurrencyDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/session/SessionConcurrencyDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/session/SessionConcurrencyDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/session/SessionConcurrencyDslTests.kt index f35ca1284fa..5a44272c710 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/session/SessionConcurrencyDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/session/SessionConcurrencyDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.session +package org.springframework.security.config.annotation.web.session import io.mockk.every import io.mockk.mockkObject @@ -30,7 +30,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.core.session.SessionInformation import org.springframework.security.core.session.SessionRegistry import org.springframework.security.core.session.SessionRegistryImpl diff --git a/config/src/test/kotlin/org/springframework/security/config/web/servlet/session/SessionFixationDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/annotation/web/session/SessionFixationDslTests.kt similarity index 98% rename from config/src/test/kotlin/org/springframework/security/config/web/servlet/session/SessionFixationDslTests.kt rename to config/src/test/kotlin/org/springframework/security/config/annotation/web/session/SessionFixationDslTests.kt index c28d9397027..349bcfe747d 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/servlet/session/SessionFixationDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/annotation/web/session/SessionFixationDslTests.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.security.config.web.servlet.session +package org.springframework.security.config.annotation.web.session import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @@ -28,7 +28,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetailsService -import org.springframework.security.config.web.servlet.invoke +import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.provisioning.InMemoryUserDetailsManager diff --git a/config/src/test/kotlin/org/springframework/security/config/web/server/AuthorizeExchangeDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/web/server/AuthorizeExchangeDslTests.kt index fd840ebd936..870b9a92834 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/server/AuthorizeExchangeDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/web/server/AuthorizeExchangeDslTests.kt @@ -22,16 +22,16 @@ import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Bean import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity -import org.springframework.security.core.userdetails.MapReactiveUserDetailsService -import org.springframework.security.core.userdetails.User import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService +import org.springframework.security.core.userdetails.User import org.springframework.security.web.server.SecurityWebFilterChain import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.reactive.config.EnableWebFlux -import java.util.* +import java.util.Base64 /** * Tests for [AuthorizeExchangeDsl] @@ -181,4 +181,40 @@ class AuthorizeExchangeDslTests { return MapReactiveUserDetailsService(user) } } + + @Test + fun `request when ip address does not match then responds with forbidden`() { + this.spring.register(HasIpAddressConfig::class.java).autowire() + + this.client + .get() + .uri("/") + .header("Authorization", "Basic " + Base64.getEncoder().encodeToString("user:password".toByteArray())) + .exchange() + .expectStatus().isForbidden + } + + @EnableWebFluxSecurity + @EnableWebFlux + open class HasIpAddressConfig { + @Bean + open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, hasIpAddress("10.0.0.0/24")) + } + httpBasic { } + } + } + + @Bean + open fun userDetailsService(): MapReactiveUserDetailsService { + val user = User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .roles("USER") + .build() + return MapReactiveUserDetailsService(user) + } + } } diff --git a/config/src/test/kotlin/org/springframework/security/config/web/server/ServerHeadersDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/web/server/ServerHeadersDslTests.kt index 3c404e28075..c68de3b4e7b 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/server/ServerHeadersDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/web/server/ServerHeadersDslTests.kt @@ -28,6 +28,9 @@ import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter import org.springframework.security.web.server.SecurityWebFilterChain import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter +import org.springframework.security.web.server.header.CrossOriginEmbedderPolicyServerHttpHeadersWriter +import org.springframework.security.web.server.header.CrossOriginOpenerPolicyServerHttpHeadersWriter +import org.springframework.security.web.server.header.CrossOriginResourcePolicyServerHttpHeadersWriter import org.springframework.security.web.server.header.StrictTransportSecurityServerHttpHeadersWriter import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter import org.springframework.security.web.server.header.XXssProtectionServerHttpHeadersWriter @@ -133,4 +136,60 @@ class ServerHeadersDslTests { } } } + + @Test + fun `request when no cross-origin policies configured then does not write cross-origin policies headers in response`() { + this.spring.register(CrossOriginPoliciesConfig::class.java).autowire() + + this.client.get() + .uri("/") + .exchange() + .expectHeader().doesNotExist("Cross-Origin-Opener-Policy") + .expectHeader().doesNotExist("Cross-Origin-Embedder-Policy") + .expectHeader().doesNotExist("Cross-Origin-Resource-Policy") + } + + @EnableWebFluxSecurity + @EnableWebFlux + open class CrossOriginPoliciesConfig { + @Bean + open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + headers { } + } + } + } + + @Test + fun `request when cross-origin custom policies configured then cross-origin custom policies headers in response`() { + this.spring.register(CrossOriginPoliciesCustomConfig::class.java).autowire() + + this.client.get() + .uri("/") + .exchange() + .expectHeader().valueEquals("Cross-Origin-Opener-Policy", "same-origin") + .expectHeader().valueEquals("Cross-Origin-Embedder-Policy", "require-corp") + .expectHeader().valueEquals("Cross-Origin-Resource-Policy", "same-origin") + } + + @EnableWebFluxSecurity + @EnableWebFlux + open class CrossOriginPoliciesCustomConfig { + @Bean + open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + headers { + crossOriginOpenerPolicy { + policy = CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN + } + crossOriginEmbedderPolicy { + policy = CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP + } + crossOriginResourcePolicy { + policy = CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN + } + } + } + } + } } diff --git a/config/src/test/kotlin/org/springframework/security/config/web/server/ServerJwtDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/web/server/ServerJwtDslTests.kt index 52b92a041f6..2f01d9d5383 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/server/ServerJwtDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/web/server/ServerJwtDslTests.kt @@ -23,7 +23,7 @@ import java.math.BigInteger import java.security.KeyFactory import java.security.interfaces.RSAPublicKey import java.security.spec.RSAPublicKeySpec -import javax.annotation.PreDestroy +import jakarta.annotation.PreDestroy import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.assertj.core.api.Assertions.assertThat diff --git a/config/src/test/kotlin/org/springframework/security/config/web/server/ServerOpaqueTokenDslTests.kt b/config/src/test/kotlin/org/springframework/security/config/web/server/ServerOpaqueTokenDslTests.kt index c201df93347..efa51a4b73e 100644 --- a/config/src/test/kotlin/org/springframework/security/config/web/server/ServerOpaqueTokenDslTests.kt +++ b/config/src/test/kotlin/org/springframework/security/config/web/server/ServerOpaqueTokenDslTests.kt @@ -33,7 +33,7 @@ import org.springframework.security.oauth2.server.resource.introspection.Reactiv import org.springframework.security.web.server.SecurityWebFilterChain import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.web.reactive.config.EnableWebFlux -import javax.annotation.PreDestroy +import jakarta.annotation.PreDestroy /** * Tests for [ServerOpaqueTokenDsl] diff --git a/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginEmbedderPolicy.xml b/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginEmbedderPolicy.xml new file mode 100644 index 00000000000..cfa473c0d55 --- /dev/null +++ b/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginEmbedderPolicy.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + diff --git a/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginOpenerPolicy.xml b/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginOpenerPolicy.xml new file mode 100644 index 00000000000..1e688e556be --- /dev/null +++ b/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginOpenerPolicy.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + diff --git a/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginPolicies.xml b/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginPolicies.xml new file mode 100644 index 00000000000..d667ebc5e95 --- /dev/null +++ b/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginPolicies.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + diff --git a/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginResourcePolicy.xml b/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginResourcePolicy.xml new file mode 100644 index 00000000000..667933f8d6b --- /dev/null +++ b/config/src/test/resources/org/springframework/security/config/http/HttpHeadersConfigTests-DefaultsDisabledWithCrossOriginResourcePolicy.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + diff --git a/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CollidingFilters.xml b/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CollidingFilters.xml index 905a1ad7025..e6a66cd5bf9 100644 --- a/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CollidingFilters.xml +++ b/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CollidingFilters.xml @@ -29,7 +29,7 @@ - + diff --git a/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CustomFilters.xml b/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CustomFilters.xml index 024ee1f6624..e2e1ffbdc6e 100644 --- a/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CustomFilters.xml +++ b/config/src/test/resources/org/springframework/security/config/http/MiscHttpConfigTests-CustomFilters.xml @@ -33,7 +33,7 @@ - + diff --git a/core/spring-security-core.gradle b/core/spring-security-core.gradle index 213f24f92c5..173b5baba1e 100644 --- a/core/spring-security-core.gradle +++ b/core/spring-security-core.gradle @@ -13,8 +13,7 @@ dependencies { optional 'com.fasterxml.jackson.core:jackson-databind' optional 'io.projectreactor:reactor-core' - optional 'javax.annotation:jsr250-api' - optional 'net.sf.ehcache:ehcache' + optional 'jakarta.annotation:jakarta.annotation-api' optional 'org.aspectj:aspectjrt' optional 'org.springframework:spring-jdbc' optional 'org.springframework:spring-tx' diff --git a/core/src/main/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSource.java b/core/src/main/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSource.java index 2cc9700280b..0c279c92131 100644 --- a/core/src/main/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSource.java +++ b/core/src/main/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSource.java @@ -22,9 +22,9 @@ import java.util.Collection; import java.util.List; -import javax.annotation.security.DenyAll; -import javax.annotation.security.PermitAll; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.security.access.ConfigAttribute; diff --git a/core/src/main/java/org/springframework/security/access/annotation/Jsr250SecurityConfig.java b/core/src/main/java/org/springframework/security/access/annotation/Jsr250SecurityConfig.java index 133498535b1..17580721a58 100644 --- a/core/src/main/java/org/springframework/security/access/annotation/Jsr250SecurityConfig.java +++ b/core/src/main/java/org/springframework/security/access/annotation/Jsr250SecurityConfig.java @@ -16,8 +16,8 @@ package org.springframework.security.access.annotation; -import javax.annotation.security.DenyAll; -import javax.annotation.security.PermitAll; +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; import org.springframework.security.access.SecurityConfig; diff --git a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationException.java b/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationException.java deleted file mode 100644 index 001192aec15..00000000000 --- a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationException.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.authentication.rcp; - -import org.springframework.core.NestedRuntimeException; -import org.springframework.security.core.SpringSecurityCoreVersion; - -/** - * Thrown if a RemoteAuthenticationManager cannot validate the presented - * authentication request. - *

- * This is thrown rather than the normal AuthenticationException because - * AuthenticationException contains additional properties which may cause - * issues for the remoting protocol. - * - * @author Ben Alex - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public class RemoteAuthenticationException extends NestedRuntimeException { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - /** - * Constructs a RemoteAuthenticationException with the specified message - * and no root cause. - * @param msg the detail message - */ - public RemoteAuthenticationException(String msg) { - super(msg); - } - -} diff --git a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManager.java b/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManager.java deleted file mode 100644 index a1db8acc51d..00000000000 --- a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManager.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.authentication.rcp; - -import java.util.Collection; - -import org.springframework.security.core.GrantedAuthority; - -/** - * Allows remote clients to attempt authentication. - * - * @author Ben Alex - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public interface RemoteAuthenticationManager { - - /** - * Attempts to authenticate the remote client using the presented username and - * password. If authentication is successful, a collection of {@code GrantedAuthority} - * objects will be returned. - *

- * In order to maximise remoting protocol compatibility, a design decision was taken - * to operate with minimal arguments and return only the minimal amount of information - * required for remote clients to enable/disable relevant user interface commands etc. - * There is nothing preventing users from implementing their own equivalent package - * that works with more complex object types. - * @param username the username the remote client wishes to authenticate with. - * @param password the password the remote client wishes to authenticate with. - * @return all of the granted authorities the specified username and password have - * access to. - * @throws RemoteAuthenticationException if the authentication failed. - */ - Collection attemptAuthentication(String username, String password) - throws RemoteAuthenticationException; - -} diff --git a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImpl.java b/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImpl.java deleted file mode 100644 index 1d32b90ee5c..00000000000 --- a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.authentication.rcp; - -import java.util.Collection; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.util.Assert; - -/** - * Server-side processor of a remote authentication request. - *

- * This bean requires no security interceptor to protect it. Instead, the bean uses the - * configured AuthenticationManager to resolve an authentication request. - * - * @author Ben Alex - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public class RemoteAuthenticationManagerImpl implements RemoteAuthenticationManager, InitializingBean { - - private AuthenticationManager authenticationManager; - - @Override - public void afterPropertiesSet() { - Assert.notNull(this.authenticationManager, "authenticationManager is required"); - } - - @Override - public Collection attemptAuthentication(String username, String password) - throws RemoteAuthenticationException { - UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken(username, password); - try { - return this.authenticationManager.authenticate(request).getAuthorities(); - } - catch (AuthenticationException ex) { - throw new RemoteAuthenticationException(ex.getMessage()); - } - } - - protected AuthenticationManager getAuthenticationManager() { - return this.authenticationManager; - } - - public void setAuthenticationManager(AuthenticationManager authenticationManager) { - this.authenticationManager = authenticationManager; - } - -} diff --git a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProvider.java b/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProvider.java deleted file mode 100644 index c7164a0b97c..00000000000 --- a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProvider.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.authentication.rcp; - -import java.util.Collection; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.util.Assert; - -/** - * Client-side object which queries a {@link RemoteAuthenticationManager} to validate an - * authentication request. - *

- * A new Authentication object is created by this class comprising the - * request Authentication object's principal, - * credentials and the GrantedAuthority[]s returned by the - * RemoteAuthenticationManager. - *

- * The RemoteAuthenticationManager should not require any special username or - * password setting on the remoting client proxy factory to execute the call. Instead the - * entire authentication request must be encapsulated solely within the - * Authentication request object. In practical terms this means the - * RemoteAuthenticationManager will not be protected by BASIC or any - * other HTTP-level authentication. - *

- *

- * If authentication fails, a RemoteAuthenticationException will be thrown. - * This exception should be caught and displayed to the user, enabling them to retry with - * alternative credentials etc. - *

- * - * @author Ben Alex - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public class RemoteAuthenticationProvider implements AuthenticationProvider, InitializingBean { - - private RemoteAuthenticationManager remoteAuthenticationManager; - - @Override - public void afterPropertiesSet() { - Assert.notNull(this.remoteAuthenticationManager, "remoteAuthenticationManager is mandatory"); - } - - @Override - public Authentication authenticate(Authentication authentication) throws AuthenticationException { - String username = authentication.getPrincipal().toString(); - Object credentials = authentication.getCredentials(); - String password = (credentials != null) ? credentials.toString() : null; - Collection authorities = this.remoteAuthenticationManager - .attemptAuthentication(username, password); - return new UsernamePasswordAuthenticationToken(username, password, authorities); - } - - public RemoteAuthenticationManager getRemoteAuthenticationManager() { - return this.remoteAuthenticationManager; - } - - public void setRemoteAuthenticationManager(RemoteAuthenticationManager remoteAuthenticationManager) { - this.remoteAuthenticationManager = remoteAuthenticationManager; - } - - @Override - public boolean supports(Class authentication) { - return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); - } - -} diff --git a/core/src/main/java/org/springframework/security/authentication/rcp/package-info.java b/core/src/main/java/org/springframework/security/authentication/rcp/package-info.java deleted file mode 100644 index 731e7ecd7b6..00000000000 --- a/core/src/main/java/org/springframework/security/authentication/rcp/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Allows remote clients to authenticate and obtain a populated - * Authentication object. - * @deprecated as of 5.6.0 with no replacement - */ -package org.springframework.security.authentication.rcp; diff --git a/core/src/main/java/org/springframework/security/authorization/AuthorityAuthorizationManager.java b/core/src/main/java/org/springframework/security/authorization/AuthorityAuthorizationManager.java index 8cfc0dcf0ae..1959c8c4165 100644 --- a/core/src/main/java/org/springframework/security/authorization/AuthorityAuthorizationManager.java +++ b/core/src/main/java/org/springframework/security/authorization/AuthorityAuthorizationManager.java @@ -133,8 +133,10 @@ private boolean isGranted(Authentication authentication) { private boolean isAuthorized(Authentication authentication) { for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) { - if (this.authorities.contains(grantedAuthority)) { - return true; + for (GrantedAuthority authority : this.authorities) { + if (authority.getAuthority().equals(grantedAuthority.getAuthority())) { + return true; + } } } return false; diff --git a/core/src/main/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManager.java b/core/src/main/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManager.java index 5c98cf3061a..6a91cfb8938 100644 --- a/core/src/main/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManager.java +++ b/core/src/main/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManager.java @@ -45,9 +45,10 @@ public class AuthorityReactiveAuthorizationManager implements ReactiveAuthori @Override public Mono check(Mono authentication, T object) { // @formatter:off - return authentication.filter((a) -> a.isAuthenticated()) + return authentication.filter(Authentication::isAuthenticated) .flatMapIterable(Authentication::getAuthorities) - .any(this.authorities::contains) + .map(GrantedAuthority::getAuthority) + .any((grantedAuthority) -> this.authorities.stream().anyMatch((authority) -> authority.getAuthority().equals(grantedAuthority))) .map((granted) -> ((AuthorizationDecision) new AuthorityAuthorizationDecision(granted, this.authorities))) .defaultIfEmpty(new AuthorityAuthorizationDecision(false, this.authorities)); // @formatter:on diff --git a/core/src/main/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.java b/core/src/main/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.java index 38b6f03b1bf..b5a0f3b9921 100644 --- a/core/src/main/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.java +++ b/core/src/main/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.java @@ -18,9 +18,9 @@ import java.util.function.Supplier; -import javax.annotation.security.DenyAll; -import javax.annotation.security.PermitAll; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; diff --git a/core/src/main/java/org/springframework/security/authorization/method/Jsr250AuthorizationManager.java b/core/src/main/java/org/springframework/security/authorization/method/Jsr250AuthorizationManager.java index ccf8da60410..6f276c59343 100644 --- a/core/src/main/java/org/springframework/security/authorization/method/Jsr250AuthorizationManager.java +++ b/core/src/main/java/org/springframework/security/authorization/method/Jsr250AuthorizationManager.java @@ -22,9 +22,9 @@ import java.util.Set; import java.util.function.Supplier; -import javax.annotation.security.DenyAll; -import javax.annotation.security.PermitAll; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; import org.aopalliance.intercept.MethodInvocation; diff --git a/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java b/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java index 2b13e626773..682ae359130 100644 --- a/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java +++ b/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java @@ -43,7 +43,7 @@ public final class SpringSecurityCoreVersion { * N.B. Classes are not intended to be serializable between different versions. See * SEC-1709 for why we still need a serial version. */ - public static final long SERIAL_VERSION_UID = 560L; + public static final long SERIAL_VERSION_UID = 600L; static final String MIN_SPRING_VERSION = getSpringVersion(); diff --git a/core/src/main/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCache.java b/core/src/main/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCache.java deleted file mode 100644 index 1aba15b2186..00000000000 --- a/core/src/main/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCache.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.core.userdetails.cache; - -import net.sf.ehcache.Ehcache; -import net.sf.ehcache.Element; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.core.log.LogMessage; -import org.springframework.security.core.userdetails.UserCache; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.util.Assert; - -/** - * Caches User objects using a Spring IoC defined - * EHCACHE. - * - * @author Ben Alex - * @deprecated since 5.6. In favor of JCache based implementations - */ -@Deprecated -public class EhCacheBasedUserCache implements UserCache, InitializingBean { - - private static final Log logger = LogFactory.getLog(EhCacheBasedUserCache.class); - - private Ehcache cache; - - @Override - public void afterPropertiesSet() { - Assert.notNull(this.cache, "cache mandatory"); - } - - public Ehcache getCache() { - return this.cache; - } - - @Override - public UserDetails getUserFromCache(String username) { - Element element = this.cache.get(username); - logger.debug(LogMessage.of(() -> "Cache hit: " + (element != null) + "; username: " + username)); - return (element != null) ? (UserDetails) element.getValue() : null; - } - - @Override - public void putUserInCache(UserDetails user) { - Element element = new Element(user.getUsername(), user); - logger.debug(LogMessage.of(() -> "Cache put: " + element.getKey())); - this.cache.put(element); - } - - public void removeUserFromCache(UserDetails user) { - logger.debug(LogMessage.of(() -> "Cache remove: " + user.getUsername())); - this.removeUserFromCache(user.getUsername()); - } - - @Override - public void removeUserFromCache(String username) { - this.cache.remove(username); - } - - public void setCache(Ehcache cache) { - this.cache = cache; - } - -} diff --git a/core/src/main/java/org/springframework/security/jackson2/SecurityJackson2Modules.java b/core/src/main/java/org/springframework/security/jackson2/SecurityJackson2Modules.java index febd2b755cc..b049032cd2c 100644 --- a/core/src/main/java/org/springframework/security/jackson2/SecurityJackson2Modules.java +++ b/core/src/main/java/org/springframework/security/jackson2/SecurityJackson2Modules.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2020 the original author or authors. + * Copyright 2015-2021 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. @@ -84,6 +84,8 @@ public final class SecurityJackson2Modules { private static final String javaTimeJackson2ModuleClass = "com.fasterxml.jackson.datatype.jsr310.JavaTimeModule"; + private static final String ldapJackson2ModuleClass = "org.springframework.security.ldap.jackson2.LdapJackson2Module"; + private SecurityJackson2Modules() { } @@ -120,7 +122,7 @@ public static List getModules(ClassLoader loader) { for (String className : securityJackson2ModuleClasses) { addToModulesList(loader, modules, className); } - if (ClassUtils.isPresent("javax.servlet.http.Cookie", loader)) { + if (ClassUtils.isPresent("jakarta.servlet.http.Cookie", loader)) { addToModulesList(loader, modules, webServletJackson2ModuleClass); } if (ClassUtils.isPresent("org.springframework.security.oauth2.client.OAuth2AuthorizedClient", loader)) { @@ -129,6 +131,9 @@ public static List getModules(ClassLoader loader) { if (ClassUtils.isPresent(javaTimeJackson2ModuleClass, loader)) { addToModulesList(loader, modules, javaTimeJackson2ModuleClass); } + if (ClassUtils.isPresent(ldapJackson2ModuleClass, loader)) { + addToModulesList(loader, modules, ldapJackson2ModuleClass); + } return modules; } @@ -204,6 +209,7 @@ static class AllowlistTypeIdResolver implements TypeIdResolver { names.add("java.util.HashMap"); names.add("java.util.LinkedHashMap"); names.add("org.springframework.security.core.context.SecurityContextImpl"); + names.add("java.util.Arrays$ArrayList"); ALLOWLIST_CLASS_NAMES = Collections.unmodifiableSet(names); } diff --git a/core/src/test/java/org/springframework/security/access/annotation/BusinessService.java b/core/src/test/java/org/springframework/security/access/annotation/BusinessService.java index 7d42e18f3c0..cafb805b1c9 100644 --- a/core/src/test/java/org/springframework/security/access/annotation/BusinessService.java +++ b/core/src/test/java/org/springframework/security/access/annotation/BusinessService.java @@ -19,8 +19,8 @@ import java.io.Serializable; import java.util.List; -import javax.annotation.security.PermitAll; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; import org.springframework.security.access.prepost.PreAuthorize; diff --git a/core/src/test/java/org/springframework/security/access/annotation/Jsr250BusinessServiceImpl.java b/core/src/test/java/org/springframework/security/access/annotation/Jsr250BusinessServiceImpl.java index 09aa5ae48c3..b19b19bfcfa 100644 --- a/core/src/test/java/org/springframework/security/access/annotation/Jsr250BusinessServiceImpl.java +++ b/core/src/test/java/org/springframework/security/access/annotation/Jsr250BusinessServiceImpl.java @@ -19,8 +19,8 @@ import java.util.ArrayList; import java.util.List; -import javax.annotation.security.PermitAll; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; /** * @author Luke Taylor diff --git a/core/src/test/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSourceTests.java b/core/src/test/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSourceTests.java index 4c6697d6a6e..2ee09b82be5 100644 --- a/core/src/test/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSourceTests.java +++ b/core/src/test/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSourceTests.java @@ -18,8 +18,8 @@ import java.util.Collection; -import javax.annotation.security.PermitAll; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -63,7 +63,7 @@ public void methodWithRolesAllowedHasCorrectAttribute() throws Exception { public void permitAllMethodHasPermitAllAttribute() throws Exception { ConfigAttribute[] accessAttributes = findAttributes("permitAllMethod"); assertThat(accessAttributes).hasSize(1); - assertThat(accessAttributes[0].toString()).isEqualTo("javax.annotation.security.PermitAll"); + assertThat(accessAttributes[0].toString()).isEqualTo("jakarta.annotation.security.PermitAll"); } @Test diff --git a/core/src/test/java/org/springframework/security/access/annotation/RequireAdminRole.java b/core/src/test/java/org/springframework/security/access/annotation/RequireAdminRole.java index 70e68eda6ea..71d4dbf4f07 100644 --- a/core/src/test/java/org/springframework/security/access/annotation/RequireAdminRole.java +++ b/core/src/test/java/org/springframework/security/access/annotation/RequireAdminRole.java @@ -19,7 +19,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.RolesAllowed; import org.springframework.security.access.prepost.PreAuthorize; diff --git a/core/src/test/java/org/springframework/security/access/annotation/RequireUserRole.java b/core/src/test/java/org/springframework/security/access/annotation/RequireUserRole.java index a11b7fc6def..575a326f01b 100644 --- a/core/src/test/java/org/springframework/security/access/annotation/RequireUserRole.java +++ b/core/src/test/java/org/springframework/security/access/annotation/RequireUserRole.java @@ -19,7 +19,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.RolesAllowed; import org.springframework.security.access.prepost.PreAuthorize; diff --git a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java index 1771721b7f0..4292ce37034 100644 --- a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java @@ -22,6 +22,7 @@ import org.junit.jupiter.api.Test; +import org.springframework.cache.Cache; import org.springframework.dao.DataRetrievalFailureException; import org.springframework.security.authentication.AccountExpiredException; import org.springframework.security.authentication.AuthenticationServiceException; @@ -41,8 +42,8 @@ import org.springframework.security.core.userdetails.UserDetailsPasswordService; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache; import org.springframework.security.core.userdetails.cache.NullUserCache; +import org.springframework.security.core.userdetails.cache.SpringCacheBasedUserCache; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.NoOpPasswordEncoder; @@ -326,8 +327,8 @@ public void testGettersSetters() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(new BCryptPasswordEncoder()); assertThat(provider.getPasswordEncoder().getClass()).isEqualTo(BCryptPasswordEncoder.class); - provider.setUserCache(new EhCacheBasedUserCache()); - assertThat(provider.getUserCache().getClass()).isEqualTo(EhCacheBasedUserCache.class); + provider.setUserCache(new SpringCacheBasedUserCache(mock(Cache.class))); + assertThat(provider.getUserCache().getClass()).isEqualTo(SpringCacheBasedUserCache.class); assertThat(provider.isForcePrincipalAsString()).isFalse(); provider.setForcePrincipalAsString(true); assertThat(provider.isForcePrincipalAsString()).isTrue(); diff --git a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java deleted file mode 100644 index 51e89c29ce0..00000000000 --- a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.authentication.rcp; - -import org.junit.jupiter.api.Test; - -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.Authentication; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * Tests {@link RemoteAuthenticationManagerImpl}. - * - * @author Ben Alex - */ -public class RemoteAuthenticationManagerImplTests { - - @Test - public void testFailedAuthenticationReturnsRemoteAuthenticationException() { - RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); - AuthenticationManager am = mock(AuthenticationManager.class); - given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); - manager.setAuthenticationManager(am); - assertThatExceptionOfType(RemoteAuthenticationException.class) - .isThrownBy(() -> manager.attemptAuthentication("rod", "password")); - } - - @Test - public void testStartupChecksAuthenticationManagerSet() throws Exception { - RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); - assertThatIllegalArgumentException().isThrownBy(manager::afterPropertiesSet); - manager.setAuthenticationManager(mock(AuthenticationManager.class)); - manager.afterPropertiesSet(); - } - - @Test - public void testSuccessfulAuthentication() { - RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); - AuthenticationManager am = mock(AuthenticationManager.class); - given(am.authenticate(any(Authentication.class))).willReturn(new TestingAuthenticationToken("u", "p", "A")); - manager.setAuthenticationManager(am); - manager.attemptAuthentication("rod", "password"); - } - -} diff --git a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java deleted file mode 100644 index e2276352949..00000000000 --- a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.authentication.rcp; - -import java.util.Collection; - -import org.junit.jupiter.api.Test; - -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.AuthorityUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests {@link RemoteAuthenticationProvider}. - * - * @author Ben Alex - */ -public class RemoteAuthenticationProviderTests { - - @Test - public void testExceptionsGetPassedBackToCaller() { - RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); - provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false)); - assertThatExceptionOfType(RemoteAuthenticationException.class) - .isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"))); - } - - @Test - public void testGettersSetters() { - RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); - provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true)); - assertThat(provider.getRemoteAuthenticationManager()).isNotNull(); - } - - @Test - public void testStartupChecksAuthenticationManagerSet() throws Exception { - RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); - assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet); - provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true)); - provider.afterPropertiesSet(); - } - - @Test - public void testSuccessfulAuthenticationCreatesObject() { - RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); - provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true)); - Authentication result = provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password")); - assertThat(result.getPrincipal()).isEqualTo("rod"); - assertThat(result.getCredentials()).isEqualTo("password"); - assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains("foo"); - } - - @Test - public void testNullCredentialsDoesNotCauseNullPointerException() { - RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); - provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false)); - assertThatExceptionOfType(RemoteAuthenticationException.class) - .isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("rod", null))); - } - - @Test - public void testSupports() { - RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); - assertThat(provider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); - } - - private class MockRemoteAuthenticationManager implements RemoteAuthenticationManager { - - private boolean grantAccess; - - MockRemoteAuthenticationManager(boolean grantAccess) { - this.grantAccess = grantAccess; - } - - @Override - public Collection attemptAuthentication(String username, String password) - throws RemoteAuthenticationException { - if (this.grantAccess) { - return AuthorityUtils.createAuthorityList("foo"); - } - else { - throw new RemoteAuthenticationException("as requested"); - } - } - - } - -} diff --git a/core/src/test/java/org/springframework/security/authorization/AuthorityAuthorizationManagerTests.java b/core/src/test/java/org/springframework/security/authorization/AuthorityAuthorizationManagerTests.java index 43d8d0631cf..ce5d40604b5 100644 --- a/core/src/test/java/org/springframework/security/authorization/AuthorityAuthorizationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authorization/AuthorityAuthorizationManagerTests.java @@ -16,12 +16,14 @@ package org.springframework.security.authorization; +import java.util.Collections; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -133,6 +135,30 @@ public void hasAuthorityWhenUserHasNotAuthorityThenDeniedDecision() { assertThat(manager.check(authentication, object).isGranted()).isFalse(); } + @Test + public void hasAuthorityWhenUserHasCustomAuthorityThenGrantedDecision() { + AuthorityAuthorizationManager manager = AuthorityAuthorizationManager.hasAuthority("ADMIN"); + GrantedAuthority customGrantedAuthority = () -> "ADMIN"; + + Supplier authentication = () -> new TestingAuthenticationToken("user", "password", + Collections.singletonList(customGrantedAuthority)); + Object object = new Object(); + + assertThat(manager.check(authentication, object).isGranted()).isTrue(); + } + + @Test + public void hasAuthorityWhenUserHasNotCustomAuthorityThenDeniedDecision() { + AuthorityAuthorizationManager manager = AuthorityAuthorizationManager.hasAuthority("ADMIN"); + GrantedAuthority customGrantedAuthority = () -> "USER"; + + Supplier authentication = () -> new TestingAuthenticationToken("user", "password", + Collections.singletonList(customGrantedAuthority)); + Object object = new Object(); + + assertThat(manager.check(authentication, object).isGranted()).isFalse(); + } + @Test public void hasAnyRoleWhenUserHasAnyRoleThenGrantedDecision() { AuthorityAuthorizationManager manager = AuthorityAuthorizationManager.hasAnyRole("ADMIN", "USER"); diff --git a/core/src/test/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManagerTests.java b/core/src/test/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManagerTests.java index 2fd6ac42e43..ac937cfbf62 100644 --- a/core/src/test/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManagerTests.java @@ -27,6 +27,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -88,6 +89,24 @@ public void checkWhenHasAuthorityAndAuthorizedThenReturnTrue() { assertThat(granted).isTrue(); } + @Test + public void checkWhenHasCustomAuthorityAndAuthorizedThenReturnTrue() { + GrantedAuthority customGrantedAuthority = () -> "ADMIN"; + this.authentication = new TestingAuthenticationToken("rob", "secret", + Collections.singletonList(customGrantedAuthority)); + boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted(); + assertThat(granted).isTrue(); + } + + @Test + public void checkWhenHasCustomAuthorityAndAuthenticatedAndWrongAuthoritiesThenReturnFalse() { + GrantedAuthority customGrantedAuthority = () -> "USER"; + this.authentication = new TestingAuthenticationToken("rob", "secret", + Collections.singletonList(customGrantedAuthority)); + boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted(); + assertThat(granted).isFalse(); + } + @Test public void checkWhenHasRoleAndAuthorizedThenReturnTrue() { this.manager = AuthorityReactiveAuthorizationManager.hasRole("ADMIN"); diff --git a/core/src/test/java/org/springframework/security/authorization/method/Jsr250AuthorizationManagerTests.java b/core/src/test/java/org/springframework/security/authorization/method/Jsr250AuthorizationManagerTests.java index 504effbab83..8e8db58b51c 100644 --- a/core/src/test/java/org/springframework/security/authorization/method/Jsr250AuthorizationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authorization/method/Jsr250AuthorizationManagerTests.java @@ -20,9 +20,9 @@ import java.lang.annotation.RetentionPolicy; import java.util.function.Supplier; -import javax.annotation.security.DenyAll; -import javax.annotation.security.PermitAll; -import javax.annotation.security.RolesAllowed; +import jakarta.annotation.security.DenyAll; +import jakarta.annotation.security.PermitAll; +import jakarta.annotation.security.RolesAllowed; import org.junit.jupiter.api.Test; diff --git a/core/src/test/java/org/springframework/security/core/JavaVersionTests.java b/core/src/test/java/org/springframework/security/core/JavaVersionTests.java index 80a8e2ef388..f36cb6f7180 100644 --- a/core/src/test/java/org/springframework/security/core/JavaVersionTests.java +++ b/core/src/test/java/org/springframework/security/core/JavaVersionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2021 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. @@ -29,7 +29,7 @@ */ public class JavaVersionTests { - private static final int JDK8_CLASS_VERSION = 52; + private static final int JDK17_CLASS_VERSION = 61; @Test public void authenticationCorrectJdkCompatibility() throws Exception { @@ -44,7 +44,7 @@ private void assertClassVersion(Class clazz) throws Exception { data.readInt(); data.readShort(); // minor int major = data.readShort(); - assertThat(major).isEqualTo(JDK8_CLASS_VERSION); + assertThat(major).isEqualTo(JDK17_CLASS_VERSION); } } diff --git a/core/src/test/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCacheTests.java b/core/src/test/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCacheTests.java deleted file mode 100644 index 907290dd63c..00000000000 --- a/core/src/test/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCacheTests.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.core.userdetails.cache; - -import net.sf.ehcache.Cache; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Ehcache; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.User; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests {@link EhCacheBasedUserCache}. - * - * @author Ben Alex - */ -public class EhCacheBasedUserCacheTests { - - private static CacheManager cacheManager; - - @BeforeAll - public static void initCacheManaer() { - cacheManager = CacheManager.create(); - cacheManager.addCache(new Cache("ehcacheusercachetests", 500, false, false, 30, 30)); - } - - @AfterAll - public static void shutdownCacheManager() { - cacheManager.removalAll(); - cacheManager.shutdown(); - } - - private Ehcache getCache() { - Ehcache cache = cacheManager.getCache("ehcacheusercachetests"); - cache.removeAll(); - return cache; - } - - private User getUser() { - return new User("john", "password", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); - } - - @Test - public void cacheOperationsAreSuccessful() throws Exception { - EhCacheBasedUserCache cache = new EhCacheBasedUserCache(); - cache.setCache(getCache()); - cache.afterPropertiesSet(); - // Check it gets stored in the cache - cache.putUserInCache(getUser()); - assertThat(getUser().getPassword()).isEqualTo(cache.getUserFromCache(getUser().getUsername()).getPassword()); - // Check it gets removed from the cache - cache.removeUserFromCache(getUser()); - assertThat(cache.getUserFromCache(getUser().getUsername())).isNull(); - // Check it doesn't return values for null or unknown users - assertThat(cache.getUserFromCache(null)).isNull(); - assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull(); - } - - @Test - public void startupDetectsMissingCache() throws Exception { - EhCacheBasedUserCache cache = new EhCacheBasedUserCache(); - assertThatIllegalArgumentException().isThrownBy(cache::afterPropertiesSet); - Ehcache myCache = getCache(); - cache.setCache(myCache); - assertThat(cache.getCache()).isEqualTo(myCache); - } - -} diff --git a/crypto/src/main/java/org/springframework/security/crypto/password/DelegatingPasswordEncoder.java b/crypto/src/main/java/org/springframework/security/crypto/password/DelegatingPasswordEncoder.java index d83dec021d7..811c558155b 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/password/DelegatingPasswordEncoder.java +++ b/crypto/src/main/java/org/springframework/security/crypto/password/DelegatingPasswordEncoder.java @@ -53,7 +53,9 @@ * Such that "id" is an identifier used to look up which {@link PasswordEncoder} should be * used and "encodedPassword" is the original encoded password for the selected * {@link PasswordEncoder}. The "id" must be at the beginning of the password, start with - * "{" and end with "}". If the "id" cannot be found, the "id" will be null. + * "{" (id prefix) and end with "}" (id suffix). Both id prefix and id suffix can be + * customized via {@link #DelegatingPasswordEncoder(String, Map, String, String)}. If the + * "id" cannot be found, the "id" will be null. * * For example, the following might be a list of passwords encoded using different "id". * All of the original passwords are "password". @@ -116,14 +118,19 @@ * * @author Rob Winch * @author Michael Simons + * @author heowc * @since 5.0 * @see org.springframework.security.crypto.factory.PasswordEncoderFactories */ public class DelegatingPasswordEncoder implements PasswordEncoder { - private static final String PREFIX = "{"; + private static final String DEFAULT_ID_PREFIX = "{"; - private static final String SUFFIX = "}"; + private static final String DEFAULT_ID_SUFFIX = "}"; + + private final String idPrefix; + + private final String idSuffix; private final String idForEncode; @@ -142,9 +149,31 @@ public class DelegatingPasswordEncoder implements PasswordEncoder { * {@link #matches(CharSequence, String)} */ public DelegatingPasswordEncoder(String idForEncode, Map idToPasswordEncoder) { + this(idForEncode, idToPasswordEncoder, DEFAULT_ID_PREFIX, DEFAULT_ID_SUFFIX); + } + + /** + * Creates a new instance + * @param idForEncode the id used to lookup which {@link PasswordEncoder} should be + * used for {@link #encode(CharSequence)} + * @param idToPasswordEncoder a Map of id to {@link PasswordEncoder} used to determine + * which {@link PasswordEncoder} should be used for + * @param idPrefix the prefix that denotes the start of the id in the encoded results + * @param idSuffix the suffix that denotes the end of an id in the encoded results + * {@link #matches(CharSequence, String)} + */ + public DelegatingPasswordEncoder(String idForEncode, Map idToPasswordEncoder, + String idPrefix, String idSuffix) { if (idForEncode == null) { throw new IllegalArgumentException("idForEncode cannot be null"); } + if (idPrefix == null) { + throw new IllegalArgumentException("prefix cannot be null"); + } + if (idSuffix == null || idSuffix.isEmpty()) { + throw new IllegalArgumentException("suffix cannot be empty"); + } + if (!idToPasswordEncoder.containsKey(idForEncode)) { throw new IllegalArgumentException( "idForEncode " + idForEncode + "is not found in idToPasswordEncoder " + idToPasswordEncoder); @@ -153,16 +182,18 @@ public DelegatingPasswordEncoder(String idForEncode, Map(idToPasswordEncoder); + this.idPrefix = idPrefix; + this.idSuffix = idSuffix; } /** @@ -188,7 +219,7 @@ public void setDefaultPasswordEncoderForMatches(PasswordEncoder defaultPasswordE @Override public String encode(CharSequence rawPassword) { - return PREFIX + this.idForEncode + SUFFIX + this.passwordEncoderForEncode.encode(rawPassword); + return this.idPrefix + this.idForEncode + this.idSuffix + this.passwordEncoderForEncode.encode(rawPassword); } @Override @@ -209,15 +240,15 @@ private String extractId(String prefixEncodedPassword) { if (prefixEncodedPassword == null) { return null; } - int start = prefixEncodedPassword.indexOf(PREFIX); + int start = prefixEncodedPassword.indexOf(this.idPrefix); if (start != 0) { return null; } - int end = prefixEncodedPassword.indexOf(SUFFIX, start); + int end = prefixEncodedPassword.indexOf(this.idSuffix, start); if (end < 0) { return null; } - return prefixEncodedPassword.substring(start + 1, end); + return prefixEncodedPassword.substring(start + this.idPrefix.length(), end); } @Override @@ -233,8 +264,8 @@ public boolean upgradeEncoding(String prefixEncodedPassword) { } private String extractEncodedPassword(String prefixEncodedPassword) { - int start = prefixEncodedPassword.indexOf(SUFFIX); - return prefixEncodedPassword.substring(start + 1); + int start = prefixEncodedPassword.indexOf(this.idSuffix); + return prefixEncodedPassword.substring(start + this.idSuffix.length()); } /** diff --git a/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java b/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java index 9f3c3f18ac7..dca1bc8b06a 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java @@ -36,6 +36,7 @@ /** * @author Rob Winch * @author Michael Simons + * @author heowc * @since 5.0 */ @ExtendWith(MockitoExtension.class) @@ -64,12 +65,16 @@ public class DelegatingPasswordEncoderTests { private DelegatingPasswordEncoder passwordEncoder; + private DelegatingPasswordEncoder onlySuffixPasswordEncoder; + @BeforeEach public void setup() { this.delegates = new HashMap<>(); this.delegates.put(this.bcryptId, this.bcrypt); this.delegates.put("noop", this.noop); this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates); + + this.onlySuffixPasswordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "", "$"); } @Test @@ -83,6 +88,49 @@ public void constructorWhenIdForEncodeDoesNotExistThenIllegalArgumentException() .isThrownBy(() -> new DelegatingPasswordEncoder(this.bcryptId + "INVALID", this.delegates)); } + @Test + public void constructorWhenPrefixIsNull() { + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingPasswordEncoder(this.bcryptId, this.delegates, null, "$")); + } + + @Test + public void constructorWhenSuffixIsNull() { + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "$", null)); + } + + @Test + public void constructorWhenPrefixIsEmpty() { + assertThat(new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "", "$")).isNotNull(); + } + + @Test + public void constructorWhenSuffixIsEmpty() { + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "$", "")); + } + + @Test + public void constructorWhenPrefixAndSuffixAreEmpty() { + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "", "")); + } + + @Test + public void constructorWhenIdContainsPrefixThenIllegalArgumentException() { + this.delegates.put('$' + this.bcryptId, this.bcrypt); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "$", "$")); + } + + @Test + public void constructorWhenIdContainsSuffixThenIllegalArgumentException() { + this.delegates.put(this.bcryptId + '$', this.bcrypt); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "", "$")); + } + @Test public void setDefaultPasswordEncoderForMatchesWhenNullThenIllegalArgumentException() { assertThatIllegalArgumentException() @@ -104,6 +152,12 @@ public void encodeWhenValidThenUsesIdForEncode() { assertThat(this.passwordEncoder.encode(this.rawPassword)).isEqualTo(this.bcryptEncodedPassword); } + @Test + public void encodeWhenValidBySpecifyDelegatingPasswordEncoderThenUsesIdForEncode() { + given(this.bcrypt.encode(this.rawPassword)).willReturn(this.encodedPassword); + assertThat(this.onlySuffixPasswordEncoder.encode(this.rawPassword)).isEqualTo("bcrypt$" + this.encodedPassword); + } + @Test public void matchesWhenBCryptThenDelegatesToBCrypt() { given(this.bcrypt.matches(this.rawPassword, this.encodedPassword)).willReturn(true); @@ -112,6 +166,14 @@ public void matchesWhenBCryptThenDelegatesToBCrypt() { verifyZeroInteractions(this.noop); } + @Test + public void matchesWhenBCryptBySpecifyDelegatingPasswordEncoderThenDelegatesToBCrypt() { + given(this.bcrypt.matches(this.rawPassword, this.encodedPassword)).willReturn(true); + assertThat(this.onlySuffixPasswordEncoder.matches(this.rawPassword, "bcrypt$" + this.encodedPassword)).isTrue(); + verify(this.bcrypt).matches(this.rawPassword, this.encodedPassword); + verifyZeroInteractions(this.noop); + } + @Test public void matchesWhenNoopThenDelegatesToNoop() { given(this.noop.matches(this.rawPassword, this.encodedPassword)).willReturn(true); diff --git a/data/spring-security-data.gradle b/data/spring-security-data.gradle index e0c9f14dab7..3e915ef871d 100644 --- a/data/spring-security-data.gradle +++ b/data/spring-security-data.gradle @@ -3,7 +3,7 @@ apply plugin: 'io.spring.convention.spring-module' dependencies { management platform(project(":spring-security-dependencies")) api project(':spring-security-core') - api 'javax.xml.bind:jaxb-api' + api 'jakarta.xml.bind:jakarta.xml.bind-api' api 'org.springframework.data:spring-data-commons' api 'org.springframework:spring-core' diff --git a/dependencies/spring-security-dependencies.gradle b/dependencies/spring-security-dependencies.gradle index b2cc1be458d..fd7f082982c 100644 --- a/dependencies/spring-security-dependencies.gradle +++ b/dependencies/spring-security-dependencies.gradle @@ -11,7 +11,7 @@ dependencies { api platform("io.projectreactor:reactor-bom:2020.0.12") api platform("io.rsocket:rsocket-bom:1.1.1") api platform("org.junit:junit-bom:5.8.1") - api platform("org.springframework.data:spring-data-bom:2021.1.0-M1") + api platform("org.springframework.data:spring-data-bom:2022.1.0-SNAPSHOT") api platform("org.jetbrains.kotlin:kotlin-bom:$kotlinVersion") api platform("org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.5.2") api platform("com.fasterxml.jackson:jackson-bom:2.13.0") @@ -27,14 +27,13 @@ dependencies { api "commons-collections:commons-collections:3.2.2" api "commons-logging:commons-logging:1.2" api "io.mockk:mockk:1.12.0" - api "io.projectreactor.tools:blockhound:1.0.6.RELEASE" - api "javax.annotation:jsr250-api:1.0" - api "javax.servlet.jsp.jstl:javax.servlet.jsp.jstl-api:1.2.2" - api "javax.servlet.jsp:javax.servlet.jsp-api:2.3.3" - api "javax.servlet:javax.servlet-api:4.0.1" - api "javax.xml.bind:jaxb-api:2.3.1" + api "jakarta.annotation:jakarta.annotation-api:2.0.0" + api "jakarta.servlet.jsp.jstl:jakarta.servlet.jsp.jstl-api:2.0.0" + api "jakarta.servlet.jsp:jakarta.servlet.jsp-api:3.0.0" + api "jakarta.servlet:jakarta.servlet-api:5.0.0" + api "jakarta.xml.bind:jakarta.xml.bind-api:3.0.1" + api "jakarta.persistence:jakarta.persistence-api:3.0.0" api "ldapsdk:ldapsdk:4.1" - api "net.sf.ehcache:ehcache:2.10.9.2" api "net.sourceforge.htmlunit:htmlunit:2.54.0" api "net.sourceforge.nekohtml:nekohtml:1.9.22" api "org.apache.directory.server:apacheds-core-entry:1.5.5" @@ -49,11 +48,11 @@ dependencies { api "org.assertj:assertj-core:3.21.0" api "org.bouncycastle:bcpkix-jdk15on:1.69" api "org.bouncycastle:bcprov-jdk15on:1.69" - api "org.eclipse.jetty:jetty-server:9.4.44.v20210927" - api "org.eclipse.jetty:jetty-servlet:9.4.44.v20210927" - api "org.eclipse.persistence:javax.persistence:2.2.1" + api "org.eclipse.jetty:jetty-server:11.0.6" + api "org.eclipse.jetty:jetty-servlet:11.0.6" + api "jakarta.persistence:jakarta.persistence-api:3.0.0" api "org.hamcrest:hamcrest:2.2" - api "org.hibernate:hibernate-entitymanager:5.6.0.Final" + api "org.hibernate:hibernate-core-jakarta:5.6.0.Final" api "org.hsqldb:hsqldb:2.6.0" api "org.jasig.cas.client:cas-client-core:3.6.2" api "org.mockito:mockito-core:3.12.4" @@ -64,7 +63,7 @@ dependencies { api "org.opensaml:opensaml-saml-api:$openSamlVersion" api "org.opensaml:opensaml-saml-impl:$openSamlVersion" api "org.python:jython:2.5.3" - api "org.seleniumhq.selenium:htmlunit-driver:2.54.0" + api "org.seleniumhq.selenium:htmlunit-driver:2.52.0" api "org.seleniumhq.selenium:selenium-java:3.141.59" api "org.seleniumhq.selenium:selenium-support:3.141.59" api "org.skyscreamer:jsonassert:1.5.0" diff --git a/docs/antora-playbook.yml b/docs/antora-playbook.yml new file mode 100644 index 00000000000..ec4e8a7a686 --- /dev/null +++ b/docs/antora-playbook.yml @@ -0,0 +1,28 @@ +site: + title: Spring Security + url: https://docs.spring.io/spring-security/reference/ +asciidoc: + attributes: + page-pagination: true +content: + sources: + - url: https://github.com/spring-io/spring-generated-docs + branches: [spring-projects/spring-security/*] + - url: https://github.com/spring-projects/spring-security + branches: [main,5.6.x,5.7.x] + tags: ['5.6.*','!5.6.0-M*','5.7.*'] + start_path: docs +urls: + latest_version_segment_strategy: redirect:to + latest_version_segment: '' + redirect_facility: httpd +ui: + bundle: + url: https://github.com/spring-io/antora-ui-spring/releases/download/latest/ui-bundle.zip + snapshot: true + +pipeline: + extensions: + - require: ./antora/extensions/version-fix.js + - require: ./antora/extensions/major-minor-segment.js + - require: ./antora/extensions/root-component-name.js diff --git a/docs/antora.yml b/docs/antora.yml index 0237a48024c..04b0215cee9 100644 --- a/docs/antora.yml +++ b/docs/antora.yml @@ -1,5 +1,3 @@ name: ROOT -title: Spring Security -start_page: ROOT:index.adoc -nav: -- modules/ROOT/nav.adoc +version: '6.0.0' +prerelease: '-SNAPSHOT' diff --git a/docs/antora/extensions/major-minor-segment.js b/docs/antora/extensions/major-minor-segment.js new file mode 100644 index 00000000000..eec07645444 --- /dev/null +++ b/docs/antora/extensions/major-minor-segment.js @@ -0,0 +1,200 @@ +// https://gitlab.com/antora/antora/-/issues/132#note_712132072 +'use strict' + +const { posix: path } = require('path') + +module.exports.register = (pipeline, { config }) => { + pipeline.on('contentClassified', ({ contentCatalog }) => { + contentCatalog.getComponents().forEach(component => { + const componentName = component.name; + const generationToVersion = new Map(); + component.versions.forEach(version => { + const generation = getGeneration(version.version); + const original = generationToVersion.get(generation); + if (original === undefined || (original.prerelease && !version.prerelease)) { + generationToVersion.set(generation, version); + } + }); + + const versionToGeneration = Array.from(generationToVersion.entries()).reduce((acc, entry) => { + const [ generation, version ] = entry; + acc.set(version.version, generation); + return acc; + }, new Map()); + + contentCatalog.findBy({ component: componentName }).forEach((file) => { + const candidateVersion = file.src.version; + if (versionToGeneration.has(candidateVersion)) { + const generation = versionToGeneration.get(candidateVersion); + if (file.out) { + if (file.out) { + file.out.dirname = file.out.dirname.replace(candidateVersion, generation) + file.out.path = file.out.path.replace(candidateVersion, generation); + } + } + if (file.pub) { + file.pub.url = file.pub.url.replace(candidateVersion, generation) + } + } + }); + versionToGeneration.forEach((generation, mappedVersion) => { + contentCatalog.getComponent(componentName).versions.filter(version => version.version === mappedVersion).forEach((version) => { + version.url = version.url.replace(mappedVersion, generation); + }) + const symbolicVersionAlias = createSymbolicVersionAlias( + componentName, + mappedVersion, + generation, + 'redirect:to' + ) + symbolicVersionAlias.src.version = generation; + contentCatalog.addFile(symbolicVersionAlias); + }); + }) + }) +} + +function createSymbolicVersionAlias (component, version, symbolicVersionSegment, strategy) { + if (symbolicVersionSegment == null || symbolicVersionSegment === version) return + const family = 'alias' + const baseVersionAliasSrc = { component, module: 'ROOT', family, relative: '', basename: '', stem: '', extname: '' } + const symbolicVersionAliasSrc = Object.assign({}, baseVersionAliasSrc, { version: symbolicVersionSegment }) + const symbolicVersionAlias = { + src: symbolicVersionAliasSrc, + pub: computePub( + symbolicVersionAliasSrc, + computeOut(symbolicVersionAliasSrc, family, symbolicVersionSegment), + family + ), + } + const originalVersionAliasSrc = Object.assign({}, baseVersionAliasSrc, { version }) + const originalVersionSegment = computeVersionSegment(component, version, 'original') + const originalVersionAlias = { + src: originalVersionAliasSrc, + pub: computePub( + originalVersionAliasSrc, + computeOut(originalVersionAliasSrc, family, originalVersionSegment), + family + ), + } + if (strategy === 'redirect:to') { + originalVersionAlias.out = undefined + originalVersionAlias.rel = symbolicVersionAlias + return originalVersionAlias + } else { + symbolicVersionAlias.out = undefined + symbolicVersionAlias.rel = originalVersionAlias + return symbolicVersionAlias + } +} + + +function computeOut (src, family, version, htmlUrlExtensionStyle) { + let { component, module: module_, basename, extname, relative, stem } = src + if (module_ === 'ROOT') module_ = '' + let indexifyPathSegment = '' + let familyPathSegment = '' + + if (family === 'page') { + if (stem !== 'index' && htmlUrlExtensionStyle === 'indexify') { + basename = 'index.html' + indexifyPathSegment = stem + } else if (extname === '.adoc') { + basename = stem + '.html' + } + } else if (family === 'image') { + familyPathSegment = '_images' + } else if (family === 'attachment') { + familyPathSegment = '_attachments' + } + const modulePath = path.join(component, version, module_) + const dirname = path.join(modulePath, familyPathSegment, path.dirname(relative), indexifyPathSegment) + const path_ = path.join(dirname, basename) + const moduleRootPath = path.relative(dirname, modulePath) || '.' + const rootPath = path.relative(dirname, '') || '.' + + return { dirname, basename, path: path_, moduleRootPath, rootPath } +} + +function computePub (src, out, family, version, htmlUrlExtensionStyle) { + const pub = {} + let url + if (family === 'nav') { + const urlSegments = version ? [src.component, version] : [src.component] + if (src.module && src.module !== 'ROOT') urlSegments.push(src.module) + // an artificial URL used for resolving page references in navigation model + url = '/' + urlSegments.join('/') + '/' + pub.moduleRootPath = '.' + } else if (family === 'page') { + const urlSegments = out.path.split('/') + const lastUrlSegmentIdx = urlSegments.length - 1 + if (htmlUrlExtensionStyle === 'drop') { + // drop just the .html extension or, if the filename is index.html, the whole segment + const lastUrlSegment = urlSegments[lastUrlSegmentIdx] + urlSegments[lastUrlSegmentIdx] = + lastUrlSegment === 'index.html' ? '' : lastUrlSegment.substr(0, lastUrlSegment.length - 5) + } else if (htmlUrlExtensionStyle === 'indexify') { + urlSegments[lastUrlSegmentIdx] = '' + } + url = '/' + urlSegments.join('/') + } else { + url = '/' + out.path + if (family === 'alias' && !src.relative.length) pub.splat = true + } + + pub.url = ~url.indexOf(' ') ? url.replace(SPACE_RX, '%20') : url + + if (out) { + pub.moduleRootPath = out.moduleRootPath + pub.rootPath = out.rootPath + } + + return pub +} + +function computeVersionSegment (name, version, mode) { + if (mode === 'original') return !version || version === 'master' ? '' : version + const strategy = this.latestVersionUrlSegmentStrategy + // NOTE: special exception; revisit in Antora 3 + if (!version || version === 'master') { + if (mode !== 'alias') return '' + if (strategy === 'redirect:to') return + } + if (strategy === 'redirect:to' || strategy === (mode === 'alias' ? 'redirect:from' : 'replace')) { + const component = this.getComponent(name) + const componentVersion = component && this.getComponentVersion(component, version) + if (componentVersion) { + const segment = + componentVersion === component.latest + ? this.latestVersionUrlSegment + : componentVersion === component.latestPrerelease + ? this.latestPrereleaseVersionUrlSegment + : undefined + return segment == null ? version : segment + } + } + return version +} + +function getGeneration(version) { + if (!version) return version; + const firstIndex = version.indexOf('.') + if (firstIndex < 0) { + return version; + } + const secondIndex = version.indexOf('.', firstIndex + 1); + const result = version.substr(0, secondIndex); + return result; +} + +function out(args) { + console.log(JSON.stringify(args, no_data, 2)); +} + + +function no_data(key, value) { + if (key == "data" || key == "files") { + return value ? "__data__" : value; + } + return value; +} \ No newline at end of file diff --git a/docs/antora/extensions/root-component-name.js b/docs/antora/extensions/root-component-name.js new file mode 100644 index 00000000000..dcc8dc482c7 --- /dev/null +++ b/docs/antora/extensions/root-component-name.js @@ -0,0 +1,40 @@ +// https://gitlab.com/antora/antora/-/issues/132#note_712132072 +'use strict' + +const { posix: path } = require('path') + +module.exports.register = (pipeline, { config }) => { + pipeline.on('contentClassified', ({ contentCatalog }) => { + const rootComponentName = config.rootComponentName || 'ROOT' + const rootComponentNameLength = rootComponentName.length + contentCatalog.findBy({ component: rootComponentName }).forEach((file) => { + if (file.out) { + file.out.dirname = file.out.dirname.substr(rootComponentNameLength) + file.out.path = file.out.path.substr(rootComponentNameLength + 1) + file.out.rootPath = fixPath(file.out.rootPath) + } + if (file.pub) { + file.pub.url = file.pub.url.substr(rootComponentNameLength + 1) + if (file.pub.rootPath) { + file.pub.rootPath = fixPath(file.pub.rootPath) + } + } + if (file.rel) { + if (file.rel.pub) { + file.rel.pub.url = file.rel.pub.url.substr(rootComponentNameLength + 1) + file.rel.pub.rootPath = fixPath(file.rel.pub.rootPath); + } + } + }) + const rootComponent = contentCatalog.getComponent(rootComponentName) + rootComponent?.versions?.forEach((version) => { + version.url = version.url.substr(rootComponentName.length + 1) + }) + // const siteStartPage = contentCatalog.getById({ component: '', version: '', module: '', family: 'alias', relative: 'index.adoc' }) + // if (siteStartPage) delete siteStartPage.out + }) + + function fixPath(path) { + return path.split('/').slice(1).join('/') || '.' + } +} \ No newline at end of file diff --git a/docs/antora/extensions/version-fix.js b/docs/antora/extensions/version-fix.js new file mode 100644 index 00000000000..8c3270f8a86 --- /dev/null +++ b/docs/antora/extensions/version-fix.js @@ -0,0 +1,30 @@ +// https://gitlab.com/antora/antora/-/issues/132#note_712132072 +'use strict' + + +module.exports.register = (pipeline, { config }) => { + + pipeline.on('contentAggregated', ({ contentAggregate }) => { + contentAggregate.forEach(aggregate => { + if (aggregate.name === "" && aggregate.displayVersion === 5.6) { + aggregate.name = "ROOT"; + aggregate.version = "5.6.0-RC1" + aggregate.startPage = "ROOT:index.adoc" + aggregate.displayVersion = `${aggregate.version}` + delete aggregate.prerelease + } + }) + }) +} + +function out(args) { + console.log(JSON.stringify(args, no_data, 2)); +} + + +function no_data(key, value) { + if (key == "data" || key == "files") { + return value ? "__data__" : value; + } + return value; +} diff --git a/docs/local-antora-playbook.yml b/docs/local-antora-playbook.yml new file mode 100644 index 00000000000..8e2678cb293 --- /dev/null +++ b/docs/local-antora-playbook.yml @@ -0,0 +1,26 @@ +site: + title: Spring Security + url: https://docs.spring.io/spring-security/reference/ +asciidoc: + attributes: + page-pagination: true +content: + sources: + - url: ../../spring-io/spring-generated-docs + branches: [spring-projects/spring-security/*] + - url: ../../spring-projects/spring-security + branches: [main,5.6.x] + start_path: docs +urls: + latest_version_segment_strategy: redirect:to + latest_version_segment: '' + redirect_facility: httpd +ui: + bundle: + url: https://github.com/spring-io/antora-ui-spring/releases/download/latest/ui-bundle.zip + snapshot: true + +pipeline: + extensions: + - require: ./antora/extensions/major-minor-segment.js + - require: ./antora/extensions/root-component-name.js diff --git a/docs/modules/ROOT/assets/images/servlet/authorization/authorizationfilter.odg b/docs/modules/ROOT/assets/images/servlet/authorization/authorizationfilter.odg new file mode 100644 index 00000000000..5ef95428f95 Binary files /dev/null and b/docs/modules/ROOT/assets/images/servlet/authorization/authorizationfilter.odg differ diff --git a/docs/modules/ROOT/assets/images/servlet/authorization/authorizationfilter.png b/docs/modules/ROOT/assets/images/servlet/authorization/authorizationfilter.png new file mode 100644 index 00000000000..8118785797c Binary files /dev/null and b/docs/modules/ROOT/assets/images/servlet/authorization/authorizationfilter.png differ diff --git a/docs/modules/ROOT/assets/images/servlet/authorization/authorizationhierarchy.odg b/docs/modules/ROOT/assets/images/servlet/authorization/authorizationhierarchy.odg new file mode 100644 index 00000000000..bcfc3c34d42 Binary files /dev/null and b/docs/modules/ROOT/assets/images/servlet/authorization/authorizationhierarchy.odg differ diff --git a/docs/modules/ROOT/assets/images/servlet/authorization/authorizationhierarchy.png b/docs/modules/ROOT/assets/images/servlet/authorization/authorizationhierarchy.png new file mode 100644 index 00000000000..86dc1ac3534 Binary files /dev/null and b/docs/modules/ROOT/assets/images/servlet/authorization/authorizationhierarchy.png differ diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc index f08028dcdf8..f69fee64e6c 100644 --- a/docs/modules/ROOT/nav.adoc +++ b/docs/modules/ROOT/nav.adoc @@ -42,21 +42,27 @@ *** xref:servlet/authentication/anonymous.adoc[Anonymous] *** xref:servlet/authentication/preauth.adoc[Pre-Authentication] *** xref:servlet/authentication/jaas.adoc[JAAS] -*** xref:servlet/authentication/cas.adoc[CAS] *** xref:servlet/authentication/x509.adoc[X509] *** xref:servlet/authentication/runas.adoc[Run-As] *** xref:servlet/authentication/logout.adoc[Logout] *** xref:servlet/authentication/events.adoc[Authentication Events] ** xref:servlet/authorization/index.adoc[Authorization] *** xref:servlet/authorization/architecture.adoc[Authorization Architecture] -*** xref:servlet/authorization/authorize-requests.adoc[Authorize HTTP Requests] +*** xref:servlet/authorization/authorize-http-requests.adoc[Authorize HTTP Requests] +*** xref:servlet/authorization/authorize-requests.adoc[Authorize HTTP Requests with FilterSecurityInterceptor] *** xref:servlet/authorization/expression-based.adoc[Expression-Based Access Control] *** xref:servlet/authorization/secure-objects.adoc[Secure Object Implementations] *** xref:servlet/authorization/method-security.adoc[Method Security] *** xref:servlet/authorization/acls.adoc[Domain Object Security ACLs] ** xref:servlet/oauth2/index.adoc[OAuth2] -*** xref:servlet/oauth2/oauth2-login.adoc[OAuth2 Log In] -*** xref:servlet/oauth2/oauth2-client.adoc[OAuth2 Client] +*** xref:servlet/oauth2/login/index.adoc[OAuth2 Log In] +**** xref:servlet/oauth2/login/core.adoc[Core Configuration] +**** xref:servlet/oauth2/login/advanced.adoc[Advanced Configuration] +*** xref:servlet/oauth2/client/index.adoc[OAuth2 Client] +**** xref:servlet/oauth2/client/core.adoc[Core Interfaces and Classes] +**** xref:servlet/oauth2/client/authorization-grants.adoc[OAuth2 Authorization Grants] +**** xref:servlet/oauth2/client/client-authentication.adoc[OAuth2 Client Authentication] +**** xref:servlet/oauth2/client/authorized-clients.adoc[OAuth2 Authorized Clients] *** xref:servlet/oauth2/resource-server/index.adoc[OAuth2 Resource Server] **** xref:servlet/oauth2/resource-server/jwt.adoc[JWT] **** xref:servlet/oauth2/resource-server/opaque-token.adoc[Opaque Token] @@ -75,7 +81,11 @@ *** xref:servlet/exploits/http.adoc[] *** xref:servlet/exploits/firewall.adoc[] ** xref:servlet/integrations/index.adoc[Integrations] +*** xref:servlet/integrations/concurrency.adoc[Concurrency] +*** xref:servlet/integrations/jackson.adoc[Jackson] +*** xref:servlet/integrations/localization.adoc[Localization] *** xref:servlet/integrations/servlet-api.adoc[Servlet APIs] +*** xref:servlet/integrations/data.adoc[Spring Data] *** xref:servlet/integrations/mvc.adoc[Spring MVC] *** xref:servlet/integrations/websocket.adoc[WebSocket] *** xref:servlet/integrations/cors.adoc[Spring's CORS Support] @@ -100,7 +110,12 @@ *** xref:servlet/test/mockmvc/result-handlers.adoc[Security ResultHandlers] ** xref:servlet/appendix/index.adoc[Appendix] *** xref:servlet/appendix/database-schema.adoc[Database Schemas] -*** xref:servlet/appendix/namespace.adoc[XML Namespace] +*** xref:servlet/appendix/namespace/index.adoc[XML Namespace] +**** xref:servlet/appendix/namespace/authentication-manager.adoc[Authentication Services] +**** xref:servlet/appendix/namespace/http.adoc[Web Security] +**** xref:servlet/appendix/namespace/method-security.adoc[Method Security] +**** xref:servlet/appendix/namespace/ldap.adoc[LDAP Security] +**** xref:servlet/appendix/namespace/websocket.adoc[WebSocket Security] *** xref:servlet/appendix/faq.adoc[FAQ] * xref:reactive/index.adoc[Reactive Applications] ** xref:reactive/getting-started.adoc[Getting Started] @@ -110,8 +125,14 @@ ** Authorization *** xref:reactive/authorization/method.adoc[EnableReactiveMethodSecurity] ** xref:reactive/oauth2/index.adoc[OAuth2] -*** xref:reactive/oauth2/login.adoc[OAuth2 Log In] -*** xref:reactive/oauth2/oauth2-client.adoc[OAuth2 Client] +*** xref:reactive/oauth2/login/index.adoc[OAuth2 Log In] +**** xref:reactive/oauth2/login/core.adoc[Core Configuration] +**** xref:reactive/oauth2/login/advanced.adoc[Advanced Configuration] +*** xref:reactive/oauth2/client/index.adoc[OAuth2 Client] +**** xref:reactive/oauth2/client/core.adoc[Core Interfaces and Classes] +**** xref:reactive/oauth2/client/authorization-grants.adoc[OAuth2 Authorization Grants] +**** xref:reactive/oauth2/client/client-authentication.adoc[OAuth2 Client Authentication] +**** xref:reactive/oauth2/client/authorized-clients.adoc[OAuth2 Authorized Clients] *** xref:reactive/oauth2/resource-server/index.adoc[OAuth2 Resource Server] **** xref:reactive/oauth2/resource-server/jwt.adoc[JWT] **** xref:reactive/oauth2/resource-server/opaque-token.adoc[Opaque Token] diff --git a/docs/modules/ROOT/pages/features/authentication/index.adoc b/docs/modules/ROOT/pages/features/authentication/index.adoc index fb4cc5cab92..9c9eddae344 100644 --- a/docs/modules/ROOT/pages/features/authentication/index.adoc +++ b/docs/modules/ROOT/pages/features/authentication/index.adoc @@ -6,6 +6,6 @@ Authentication is how we verify the identity of who is trying to access a partic A common way to authenticate users is by requiring the user to enter a username and password. Once authentication is performed we know the identity and can perform authorization. -Spring Security provides built in support for authenticating users. +Spring Security provides built-in support for authenticating users. This section is dedicated to generic authentication support that applies in both Servlet and WebFlux environments. -Refer to the sections on authentication for xref:servlet/authentication/index.adoc#servlet-authentication[Servlet] and WebFlux for details on what is supported for each stack. +See the sections on authentication for xref:servlet/authentication/index.adoc#servlet-authentication[Servlet] and WebFlux for details on what is supported for each stack. diff --git a/docs/modules/ROOT/pages/features/authentication/password-storage.adoc b/docs/modules/ROOT/pages/features/authentication/password-storage.adoc index dcbf3ab8ad3..a3a934e067f 100644 --- a/docs/modules/ROOT/pages/features/authentication/password-storage.adoc +++ b/docs/modules/ROOT/pages/features/authentication/password-storage.adoc @@ -1,70 +1,70 @@ [[authentication-password-storage]] = Password Storage -Spring Security's `PasswordEncoder` interface is used to perform a one way transformation of a password to allow the password to be stored securely. -Given `PasswordEncoder` is a one way transformation, it is not intended when the password transformation needs to be two way (i.e. storing credentials used to authenticate to a database). -Typically `PasswordEncoder` is used for storing a password that needs to be compared to a user provided password at the time of authentication. +Spring Security's `PasswordEncoder` interface is used to perform a one-way transformation of a password to let the password be stored securely. +Given `PasswordEncoder` is a one-way transformation, it is not useful when the password transformation needs to be two-way (such as storing credentials used to authenticate to a database). +Typically, `PasswordEncoder` is used for storing a password that needs to be compared to a user-provided password at the time of authentication. [[authentication-password-storage-history]] == Password Storage History -Throughout the years the standard mechanism for storing passwords has evolved. -In the beginning passwords were stored in plain text. +Throughout the years, the standard mechanism for storing passwords has evolved. +In the beginning, passwords were stored in plaintext. The passwords were assumed to be safe because the data store the passwords were saved in required credentials to access it. -However, malicious users were able to find ways to get large "data dumps" of usernames and passwords using attacks like SQL Injection. -As more and more user credentials became public security experts realized we needed to do more to protect users' passwords. +However, malicious users were able to find ways to get large "`data dumps`" of usernames and passwords by using attacks such as SQL Injection. +As more and more user credentials became public, security experts realized that we needed to do more to protect users' passwords. -Developers were then encouraged to store passwords after running them through a one way hash such as SHA-256. +Developers were then encouraged to store passwords after running them through a one way hash, such as SHA-256. When a user tried to authenticate, the hashed password would be compared to the hash of the password that they typed. -This meant that the system only needed to store the one way hash of the password. -If a breach occurred, then only the one way hashes of the passwords were exposed. -Since the hashes were one way and it was computationally difficult to guess the passwords given the hash, it would not be worth the effort to figure out each password in the system. -To defeat this new system malicious users decided to create lookup tables known as https://en.wikipedia.org/wiki/Rainbow_table[Rainbow Tables]. +This meant that the system only needed to store the one-way hash of the password. +If a breach occurred, only the one-way hashes of the passwords were exposed. +Since the hashes were one-way and it was computationally difficult to guess the passwords given the hash, it would not be worth the effort to figure out each password in the system. +To defeat this new system, malicious users decided to create lookup tables known as https://en.wikipedia.org/wiki/Rainbow_table[Rainbow Tables]. Rather than doing the work of guessing each password every time, they computed the password once and stored it in a lookup table. To mitigate the effectiveness of Rainbow Tables, developers were encouraged to use salted passwords. -Instead of using just the password as input to the hash function, random bytes (known as salt) would be generated for every users' password. -The salt and the user's password would be ran through the hash function which produced a unique hash. +Instead of using just the password as input to the hash function, random bytes (known as salt) would be generated for every user's password. +The salt and the user's password would be run through the hash function to produce a unique hash. The salt would be stored alongside the user's password in clear text. Then when a user tried to authenticate, the hashed password would be compared to the hash of the stored salt and the password that they typed. The unique salt meant that Rainbow Tables were no longer effective because the hash was different for every salt and password combination. -In modern times we realize that cryptographic hashes (like SHA-256) are no longer secure. +In modern times, we realize that cryptographic hashes (like SHA-256) are no longer secure. The reason is that with modern hardware we can perform billions of hash calculations a second. This means that we can crack each password individually with ease. Developers are now encouraged to leverage adaptive one-way functions to store a password. -Validation of passwords with adaptive one-way functions are intentionally resource (i.e. CPU, memory, etc) intensive. -An adaptive one-way function allows configuring a "work factor" which can grow as hardware gets better. -It is recommended that the "work factor" be tuned to take about 1 second to verify a password on your system. -This trade off is to make it difficult for attackers to crack the password, but not so costly it puts excessive burden on your own system. -Spring Security has attempted to provide a good starting point for the "work factor", but users are encouraged to customize the "work factor" for their own system since the performance will vary drastically from system to system. +Validation of passwords with adaptive one-way functions are intentionally resource-intensive (they intentionally use a lot of CPU, memory, or other resources). +An adaptive one-way function allows configuring a "`work factor`" that can grow as hardware gets better. +We recommend that the "`work factor`" be tuned to take about one second to verify a password on your system. +This trade off is to make it difficult for attackers to crack the password, but not so costly that it puts excessive burden on your own system or irritates users. +Spring Security has attempted to provide a good starting point for the "`work factor`", but we encourage users to customize the "`work factor`" for their own system, since the performance varies drastically from system to system. Examples of adaptive one-way functions that should be used include <>, <>, <>, and <>. -Because adaptive one-way functions are intentionally resource intensive, validating a username and password for every request will degrade performance of an application significantly. -There is nothing Spring Security (or any other library) can do to speed up the validation of the password since security is gained by making the validation resource intensive. -Users are encouraged to exchange the long term credentials (i.e. username and password) for a short term credential (i.e. session, OAuth Token, etc). +Because adaptive one-way functions are intentionally resource intensive, validating a username and password for every request can significantly degrade the performance of an application. +There is nothing Spring Security (or any other library) can do to speed up the validation of the password, since security is gained by making the validation resource intensive. +Users are encouraged to exchange the long term credentials (that is, username and password) for a short term credential (such as a session, and OAuth Token, and so on). The short term credential can be validated quickly without any loss in security. [[authentication-password-storage-dpe]] == DelegatingPasswordEncoder -Prior to Spring Security 5.0 the default `PasswordEncoder` was `NoOpPasswordEncoder` which required plain text passwords. -Based upon the <> section you might expect that the default `PasswordEncoder` is now something like `BCryptPasswordEncoder`. +Prior to Spring Security 5.0, the default `PasswordEncoder` was `NoOpPasswordEncoder`, which required plain-text passwords. +Based on the <> section, you might expect that the default `PasswordEncoder` would now be something like `BCryptPasswordEncoder`. However, this ignores three real world problems: -- There are many applications using old password encodings that cannot easily migrate -- The best practice for password storage will change again -- As a framework Spring Security cannot make breaking changes frequently +- Many applications use old password encodings that cannot easily migrate. +- The best practice for password storage will change again. +- As a framework, Spring Security cannot make breaking changes frequently. -Instead Spring Security introduces `DelegatingPasswordEncoder` which solves all of the problems by: +Instead Spring Security introduces `DelegatingPasswordEncoder`, which solves all of the problems by: -- Ensuring that passwords are encoded using the current password storage recommendations +- Ensuring that passwords are encoded by using the current password storage recommendations - Allowing for validating passwords in modern and legacy formats - Allowing for upgrading the encoding in the future -You can easily construct an instance of `DelegatingPasswordEncoder` using `PasswordEncoderFactories`. +You can easily construct an instance of `DelegatingPasswordEncoder` by using `PasswordEncoderFactories`: .Create Default DelegatingPasswordEncoder ==== @@ -82,7 +82,7 @@ val passwordEncoder: PasswordEncoder = PasswordEncoderFactories.createDelegating ---- ==== -Alternatively, you may create your own custom instance. For example: +Alternatively, you can create your own custom instance: .Create Custom DelegatingPasswordEncoder ==== @@ -129,11 +129,11 @@ The general format for a password is: ---- ==== -Such that `id` is an identifier used to look up which `PasswordEncoder` should be used and `encodedPassword` is the original encoded password for the selected `PasswordEncoder`. -The `id` must be at the beginning of the password, start with `{` and end with `}`. -If the `id` cannot be found, the `id` will be null. -For example, the following might be a list of passwords encoded using different `id`. -All of the original passwords are "password". +`id` is an identifier that is used to look up which `PasswordEncoder` should be used and `encodedPassword` is the original encoded password for the selected `PasswordEncoder`. +The `id` must be at the beginning of the password, start with `{`, and end with `}`. +If the `id` cannot be found, the `id` is set to null. +For example, the following might be a list of passwords encoded using different `id` values. +All of the original passwords are `password`. .DelegatingPasswordEncoder Encoded Passwords Example ==== @@ -147,16 +147,16 @@ All of the original passwords are "password". ---- ==== -<1> The first password would have a `PasswordEncoder` id of `bcrypt` and encodedPassword of `$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG`. -When matching it would delegate to `BCryptPasswordEncoder` -<2> The second password would have a `PasswordEncoder` id of `noop` and encodedPassword of `password`. -When matching it would delegate to `NoOpPasswordEncoder` -<3> The third password would have a `PasswordEncoder` id of `pbkdf2` and encodedPassword of `5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc`. -When matching it would delegate to `Pbkdf2PasswordEncoder` -<4> The fourth password would have a `PasswordEncoder` id of `scrypt` and encodedPassword of `$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=` -When matching it would delegate to `SCryptPasswordEncoder` -<5> The final password would have a `PasswordEncoder` id of `sha256` and encodedPassword of `97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0`. -When matching it would delegate to `StandardPasswordEncoder` +<1> The first password has a `PasswordEncoder` id of `bcrypt` and an `encodedPassword` value of `$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG`. +When matching, it would delegate to `BCryptPasswordEncoder` +<2> The second password has a `PasswordEncoder` id of `noop` and `encodedPassword` value of `password`. +When matching, it would delegate to `NoOpPasswordEncoder` +<3> The third password has a `PasswordEncoder` id of `pbkdf2` and `encodedPassword` value of `5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc`. +When matching, it would delegate to `Pbkdf2PasswordEncoder` +<4> The fourth password has a `PasswordEncoder` id of `scrypt` and `encodedPassword` value of `$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=` +When matching, it would delegate to `SCryptPasswordEncoder` +<5> The final password has a `PasswordEncoder` id of `sha256` and `encodedPassword` value of `97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0`. +When matching, it would delegate to `StandardPasswordEncoder` [NOTE] ==== @@ -169,9 +169,9 @@ For example, BCrypt passwords often start with `$2a$`. [[authentication-password-storage-dpe-encoding]] === Password Encoding -The `idForEncode` passed into the constructor determines which `PasswordEncoder` will be used for encoding passwords. -In the `DelegatingPasswordEncoder` we constructed above, that means that the result of encoding `password` would be delegated to `BCryptPasswordEncoder` and be prefixed with `+{bcrypt}+`. -The end result would look like: +The `idForEncode` passed into the constructor determines which `PasswordEncoder` is used for encoding passwords. +In the `DelegatingPasswordEncoder` we constructed earlier, that means that the result of encoding `password` is delegated to `BCryptPasswordEncoder` and be prefixed with `+{bcrypt}+`. +The end result looks like the following example: .DelegatingPasswordEncoder Encode Example ==== @@ -184,15 +184,15 @@ The end result would look like: [[authentication-password-storage-dpe-matching]] === Password Matching -Matching is done based upon the `+{id}+` and the mapping of the `id` to the `PasswordEncoder` provided in the constructor. +Matching is based upon the `+{id}+` and the mapping of the `id` to the `PasswordEncoder` provided in the constructor. Our example in <> provides a working example of how this is done. -By default, the result of invoking `matches(CharSequence, String)` with a password and an `id` that is not mapped (including a null id) will result in an `IllegalArgumentException`. -This behavior can be customized using `DelegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(PasswordEncoder)`. +By default, the result of invoking `matches(CharSequence, String)` with a password and an `id` that is not mapped (including a null id) results in an `IllegalArgumentException`. +This behavior can be customized by using `DelegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(PasswordEncoder)`. -By using the `id` we can match on any password encoding, but encode passwords using the most modern password encoding. +By using the `id`, we can match on any password encoding but encode passwords by using the most modern password encoding. This is important, because unlike encryption, password hashes are designed so that there is no simple way to recover the plaintext. -Since there is no way to recover the plaintext, it makes it difficult to migrate the passwords. -While it is simple for users to migrate `NoOpPasswordEncoder`, we chose to include it by default to make it simple for the getting started experience. +Since there is no way to recover the plaintext, it is difficult to migrate the passwords. +While it is simple for users to migrate `NoOpPasswordEncoder`, we chose to include it by default to make it simple for the getting-started experience. [[authentication-password-storage-dep-getting-started]] === Getting Started Experience @@ -227,7 +227,7 @@ println(user.password) ---- ==== -If you are creating multiple users, you can also reuse the builder. +If you are creating multiple users, you can also reuse the builder: .withDefaultPasswordEncoder Reusing the Builder ==== @@ -273,7 +273,7 @@ For production, you should <>: +For example, the following example encodes the password of `password` for use with <>: .Spring Boot CLI encodepassword Example ==== @@ -287,44 +287,48 @@ spring encodepassword password [[authentication-password-storage-dpe-troubleshoot]] === Troubleshooting -The following error occurs when one of the passwords that are stored has no id as described in <>. +The following error occurs when one of the passwords that are stored has no `id`, as described in <>. +==== ---- java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:233) at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:196) ---- +==== -The easiest way to resolve the error is to switch to explicitly providing the `PasswordEncoder` that your passwords are encoded with. The easiest way to resolve it is to figure out how your passwords are currently being stored and explicitly provide the correct `PasswordEncoder`. -If you are migrating from Spring Security 4.2.x you can revert to the previous behavior by <>. +If you are migrating from Spring Security 4.2.x, you can revert to the previous behavior by <>. -Alternatively, you can prefix all of your passwords with the correct id and continue to use `DelegatingPasswordEncoder`. +Alternatively, you can prefix all of your passwords with the correct `id` and continue to use `DelegatingPasswordEncoder`. For example, if you are using BCrypt, you would migrate your password from something like: +==== ---- $2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG ---- +==== to - +==== [source,attrs="-attributes"] ---- {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG ---- +==== -For a complete listing of the mappings refer to the Javadoc on -https://docs.spring.io/spring-security/site/docs/5.0.x/api/org/springframework/security/crypto/factory/PasswordEncoderFactories.html[PasswordEncoderFactories]. +For a complete listing of the mappings, see the Javadoc for +https://docs.spring.io/spring-security/site/docs/5.0.x/api/org/springframework/security/crypto/factory/PasswordEncoderFactories.html[`PasswordEncoderFactories`]. [[authentication-password-storage-bcrypt]] == BCryptPasswordEncoder The `BCryptPasswordEncoder` implementation uses the widely supported https://en.wikipedia.org/wiki/Bcrypt[bcrypt] algorithm to hash the passwords. -In order to make it more resistent to password cracking, bcrypt is deliberately slow. +To make it more resistant to password cracking, bcrypt is deliberately slow. Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. -The default implementation of `BCryptPasswordEncoder` uses strength 10 as mentioned in the Javadoc of https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.html[BCryptPasswordEncoder]. You are encouraged to +The default implementationThe default implementation of `BCryptPasswordEncoder` uses strength 10 as mentioned in the Javadoc of https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.html[`BCryptPasswordEncoder`]. You are encouraged to tune and test the strength parameter on your own system so that it takes roughly 1 second to verify a password. .BCryptPasswordEncoder @@ -353,7 +357,7 @@ assertTrue(encoder.matches("myPassword", result)) The `Argon2PasswordEncoder` implementation uses the https://en.wikipedia.org/wiki/Argon2[Argon2] algorithm to hash the passwords. Argon2 is the winner of the https://en.wikipedia.org/wiki/Password_Hashing_Competition[Password Hashing Competition]. -In order to defeat password cracking on custom hardware, Argon2 is a deliberately slow algorithm that requires large amounts of memory. +To defeat password cracking on custom hardware, Argon2 is a deliberately slow algorithm that requires large amounts of memory. Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. The current implementation of the `Argon2PasswordEncoder` requires BouncyCastle. @@ -382,7 +386,7 @@ assertTrue(encoder.matches("myPassword", result)) == Pbkdf2PasswordEncoder The `Pbkdf2PasswordEncoder` implementation uses the https://en.wikipedia.org/wiki/PBKDF2[PBKDF2] algorithm to hash the passwords. -In order to defeat password cracking PBKDF2 is a deliberately slow algorithm. +To defeat password cracking PBKDF2 is a deliberately slow algorithm. Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. This algorithm is a good choice when FIPS certification is required. @@ -410,8 +414,8 @@ assertTrue(encoder.matches("myPassword", result)) [[authentication-password-storage-scrypt]] == SCryptPasswordEncoder -The `SCryptPasswordEncoder` implementation uses https://en.wikipedia.org/wiki/Scrypt[scrypt] algorithm to hash the passwords. -In order to defeat password cracking on custom hardware scrypt is a deliberately slow algorithm that requires large amounts of memory. +The `SCryptPasswordEncoder` implementation uses the https://en.wikipedia.org/wiki/Scrypt[scrypt] algorithm to hash the passwords. +To defeat password cracking on custom hardware, scrypt is a deliberately slow algorithm that requires large amounts of memory. Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. .SCryptPasswordEncoder @@ -436,20 +440,20 @@ assertTrue(encoder.matches("myPassword", result)) ==== [[authentication-password-storage-other]] -== Other PasswordEncoders +== Other ``PasswordEncoder``s There are a significant number of other `PasswordEncoder` implementations that exist entirely for backward compatibility. They are all deprecated to indicate that they are no longer considered secure. -However, there are no plans to remove them since it is difficult to migrate existing legacy systems. +However, there are no plans to remove them, since it is difficult to migrate existing legacy systems. [[authentication-password-storage-configuration]] == Password Storage Configuration Spring Security uses <> by default. -However, this can be customized by exposing a `PasswordEncoder` as a Spring bean. +However, you can customize this by exposing a `PasswordEncoder` as a Spring bean. -If you are migrating from Spring Security 4.2.x you can revert to the previous behavior by exposing a `NoOpPasswordEncoder` bean. +If you are migrating from Spring Security 4.2.x, you can revert to the previous behavior by exposing a `NoOpPasswordEncoder` bean. [WARNING] ==== diff --git a/docs/modules/ROOT/pages/features/exploits/csrf.adoc b/docs/modules/ROOT/pages/features/exploits/csrf.adoc index 8c9517363ec..7f800be3e2b 100644 --- a/docs/modules/ROOT/pages/features/exploits/csrf.adoc +++ b/docs/modules/ROOT/pages/features/exploits/csrf.adoc @@ -4,7 +4,7 @@ = Cross Site Request Forgery (CSRF) Spring provides comprehensive support for protecting against https://en.wikipedia.org/wiki/Cross-site_request_forgery[Cross Site Request Forgery (CSRF)] attacks. -In the following sections we will explore: +In the following sections, we explore: * <> * <> @@ -14,7 +14,7 @@ In the following sections we will explore: [NOTE] ==== This portion of the documentation discusses the general topic of CSRF protection. -Refer to the relevant sections for specific information on CSRF protection for xref:servlet/exploits/csrf.adoc#servlet-csrf[servlet] and xref:reactive/exploits/csrf.adoc#webflux-csrf[WebFlux] based applications. +See the relevant sections for specific information on CSRF protection for xref:servlet/exploits/csrf.adoc#servlet-csrf[servlet] and xref:reactive/exploits/csrf.adoc#webflux-csrf[WebFlux] based applications. ==== [[csrf-explained]] @@ -85,16 +85,16 @@ You like to win money, so you click on the submit button. In the process, you have unintentionally transferred $100 to a malicious user. This happens because, while the evil website cannot see your cookies, the cookies associated with your bank are still sent along with the request. -Worst yet, this whole process could have been automated using JavaScript. -This means you didn't even need to click on the button. +Worse yet, this whole process could have been automated by using JavaScript. +This means you did not even need to click on the button. Furthermore, it could just as easily happen when visiting an honest site that is a victim of a https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)[XSS attack]. So how do we protect our users from such attacks? [[csrf-protection]] == Protecting Against CSRF Attacks The reason that a CSRF attack is possible is that the HTTP request from the victim's website and the request from the attacker's website are exactly the same. -This means there is no way to reject requests coming from the evil website and allow requests coming from the bank's website. -To protect against CSRF attacks we need to ensure there is something in the request that the evil site is unable to provide so we can differentiate the two requests. +This means there is no way to reject requests coming from the evil website and allow only requests coming from the bank's website. +To protect against CSRF attacks, we need to ensure there is something in the request that the evil site is unable to provide so we can differentiate the two requests. Spring provides two mechanisms to protect against CSRF attacks: @@ -103,19 +103,19 @@ Spring provides two mechanisms to protect against CSRF attacks: [NOTE] ==== -Both protections require that <> +Both protections require that <>. ==== [[csrf-protection-idempotent]] === Safe Methods Must be Idempotent -In order for <> against CSRF to work, the application must ensure that https://tools.ietf.org/html/rfc7231#section-4.2.1["safe" HTTP methods are idempotent]. -This means that requests with the HTTP method `GET`, `HEAD`, `OPTIONS`, and `TRACE` should not change the state of the application. +For <> against CSRF to work, the application must ensure that https://tools.ietf.org/html/rfc7231#section-4.2.1["safe" HTTP methods are idempotent]. +This means that requests with the HTTP `GET`, `HEAD`, `OPTIONS`, and `TRACE` methods should not change the state of the application. [[csrf-protection-stp]] === Synchronizer Token Pattern The predominant and most comprehensive way to protect against CSRF attacks is to use the https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#synchronizer-token-pattern[Synchronizer Token Pattern]. -This solution is to ensure that each HTTP request requires, in addition to our session cookie, a secure random generated value called a CSRF token must be present in the HTTP request. +This solution is to ensure that each HTTP request requires, in addition to our session cookie, a secure random generated value called a CSRF token be present in the HTTP request. When an HTTP request is submitted, the server must look up the expected CSRF token and compare it against the actual CSRF token in the HTTP request. If the values do not match, the HTTP request should be rejected. @@ -124,13 +124,13 @@ The key to this working is that the actual CSRF token should be in a part of the For example, requiring the actual CSRF token in an HTTP parameter or an HTTP header will protect against CSRF attacks. Requiring the actual CSRF token in a cookie does not work because cookies are automatically included in the HTTP request by the browser. -We can relax the expectations to only require the actual CSRF token for each HTTP request that updates state of the application. +We can relax the expectations to require only the actual CSRF token for each HTTP request that updates the state of the application. For that to work, our application must ensure that <>. -This improves usability since we want to allow linking to our website using links from external sites. -Additionally, we do not want to include the random token in HTTP GET as this can cause the tokens to be leaked. +This improves usability, since we want to allow linking to our website from external sites. +Additionally, we do not want to include the random token in HTTP GET, as this can cause the tokens to be leaked. -Let's take a look at how <> would change when using the Synchronizer Token Pattern. -Assume the actual CSRF token is required to be in an HTTP parameter named `_csrf`. +Consider how <> would change when we use the Synchronizer Token Pattern. +Assume that the actual CSRF token is required to be in an HTTP parameter named `_csrf`. Our application's transfer form would look like: .Synchronizer Token Form @@ -184,11 +184,11 @@ A server can specify the `SameSite` attribute when setting a cookie to indicate [NOTE] ==== Spring Security does not directly control the creation of the session cookie, so it does not provide support for the SameSite attribute. -https://spring.io/projects/spring-session[Spring Session] provides support for the `SameSite` attribute in servlet based applications. -Spring Framework's https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/server/session/CookieWebSessionIdResolver.html[CookieWebSessionIdResolver] provides out of the box support for the `SameSite` attribute in WebFlux based applications. +https://spring.io/projects/spring-session[Spring Session] provides support for the `SameSite` attribute in servlet-based applications. +Spring Framework's https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/server/session/CookieWebSessionIdResolver.html[`CookieWebSessionIdResolver`] provides out of the box support for the `SameSite` attribute in WebFlux-based applications. ==== -An example, HTTP response header with the `SameSite` attribute might look like: +An example, of an HTTP response header with the `SameSite` attribute might look like: .SameSite HTTP response ==== @@ -200,49 +200,49 @@ Set-Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly; Same Valid values for the `SameSite` attribute are: -* `Strict` - when specified any request coming from the https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-2.1[same-site] will include the cookie. -Otherwise, the cookie will not be included in the HTTP request. -* `Lax` - when specified cookies will be sent when coming from the https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-2.1[same-site] or when the request comes from top-level navigations and the <>. -Otherwise, the cookie will not be included in the HTTP request. +* `Strict`: When specified, any request coming from the https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-2.1[same-site] includes the cookie. +Otherwise, the cookie is not included in the HTTP request. +* `Lax`: When specified, cookies are sent when coming from the https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-2.1[same-site] or when the request comes from top-level navigations and the <>. +Otherwise, the cookie is not included in the HTTP request. -Let's take a look at how <> could be protected using the `SameSite` attribute. +Consider how <> could be protected using the `SameSite` attribute. The bank application can protect against CSRF by specifying the `SameSite` attribute on the session cookie. -With the `SameSite` attribute set on our session cookie, the browser will continue to send the `JSESSIONID` cookie with requests coming from the banking website. -However, the browser will no longer send the `JSESSIONID` cookie with a transfer request coming from the evil website. +With the `SameSite` attribute set on our session cookie, the browser continues to send the `JSESSIONID` cookie with requests coming from the banking website. +However, the browser no longer sends the `JSESSIONID` cookie with a transfer request coming from the evil website. Since the session is no longer present in the transfer request coming from the evil website, the application is protected from the CSRF attack. -There are some important https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-5[considerations] that one should be aware about when using `SameSite` attribute to protect against CSRF attacks. +There are some important https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-5[considerations] to be aware of when using `SameSite` attribute to protect against CSRF attacks. Setting the `SameSite` attribute to `Strict` provides a stronger defense but can confuse users. -Consider a user that stays logged into a social media site hosted at https://social.example.com. +Consider a user who stays logged into a social media site hosted at https://social.example.com. The user receives an email at https://email.example.org that includes a link to the social media site. If the user clicks on the link, they would rightfully expect to be authenticated to the social media site. -However, if the `SameSite` attribute is `Strict` the cookie would not be sent and so the user would not be authenticated. +However, if the `SameSite` attribute is `Strict`, the cookie would not be sent and so the user would not be authenticated. [NOTE] ==== We could improve the protection and usability of `SameSite` protection against CSRF attacks by implementing https://github.com/spring-projects/spring-security/issues/7537[gh-7537]. ==== -Another obvious consideration is that in order for the `SameSite` attribute to protect users, the browser must support the `SameSite` attribute. +Another obvious consideration is that, in order for the `SameSite` attribute to protect users, the browser must support the `SameSite` attribute. Most modern browsers do https://developer.mozilla.org/en-US/docs/Web/HTTP/headers/Set-Cookie#Browser_compatibility[support the SameSite attribute]. However, older browsers that are still in use may not. -For this reason, it is generally recommended to use the `SameSite` attribute as a defense in depth rather than the sole protection against CSRF attacks. +For this reason, we generally recommend using the `SameSite` attribute as a defense in depth rather than the sole protection against CSRF attacks. [[csrf-when]] == When to use CSRF protection When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. -If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection. +If you are creating a service that is used only by non-browser clients, you likely want to disable CSRF protection. [[csrf-when-json]] === CSRF protection and JSON -A common question is "do I need to protect JSON requests made by javascript?" -The short answer is, it depends. -However, you must be very careful as there are CSRF exploits that can impact JSON requests. -For example, a malicious user can create a http://blog.opensecurityresearch.com/2012/02/json-csrf-with-parameter-padding.html[CSRF with JSON using the following form]: +A common question is "`do I need to protect JSON requests made by JavaScript?`" +The short answer is: It depends. +However, you must be very careful, as there are CSRF exploits that can impact JSON requests. +For example, a malicious user can create a http://blog.opensecurityresearch.com/2012/02/json-csrf-with-parameter-padding.html[CSRF with JSON by using the following form]: .CSRF with JSON form ==== @@ -257,7 +257,7 @@ For example, a malicious user can create a http://blog.opensecurityresearch.com/ ==== -This will produce the following JSON structure +This produces the following JSON structure .CSRF with JSON request ==== @@ -271,8 +271,8 @@ This will produce the following JSON structure ---- ==== -If an application were not validating the Content-Type, then it would be exposed to this exploit. -Depending on the setup, a Spring MVC application that validates the Content-Type could still be exploited by updating the URL suffix to end with `.json` as shown below: +If an application were not validating the `Content-Type` header, it would be exposed to this exploit. +Depending on the setup, a Spring MVC application that validates the Content-Type could still be exploited by updating the URL suffix to end with `.json`, as follows: .CSRF with JSON Spring MVC form ==== @@ -289,15 +289,15 @@ Depending on the setup, a Spring MVC application that validates the Content-Type [[csrf-when-stateless]] === CSRF and Stateless Browser Applications What if my application is stateless? -That doesn't necessarily mean you are protected. +That does not necessarily mean you are protected. In fact, if a user does not need to perform any actions in the web browser for a given request, they are likely still vulnerable to CSRF attacks. -For example, consider an application that uses a custom cookie that contains all the state within it for authentication instead of the JSESSIONID. -When the CSRF attack is made the custom cookie will be sent with the request in the same manner that the JSESSIONID cookie was sent in our previous example. -This application will be vulnerable to CSRF attacks. +For example, consider an application that uses a custom cookie that contains all the state within it for authentication (instead of the JSESSIONID). +When the CSRF attack is made, the custom cookie is sent with the request in the same manner that the JSESSIONID cookie was sent in our previous example. +This application is vulnerable to CSRF attacks. Applications that use basic authentication are also vulnerable to CSRF attacks. -The application is vulnerable since the browser will automatically include the username and password in any requests in the same manner that the JSESSIONID cookie was sent in our previous example. +The application is vulnerable since the browser automatically includes the username and password in any requests in the same manner that the JSESSIONID cookie was sent in our previous example. [[csrf-considerations]] == CSRF Considerations @@ -308,89 +308,90 @@ There are a few special considerations to consider when implementing protection [[csrf-considerations-login]] === Logging In -In order to protect against https://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests[forging log in requests] the log in HTTP request should be protected against CSRF attacks. -Protecting against forging log in requests is necessary so that a malicious user cannot read a victim's sensitive information. +To protect against https://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests[forging login requests], the login HTTP request should be protected against CSRF attacks. +Protecting against forging login requests is necessary so that a malicious user cannot read a victim's sensitive information. The attack is performed as follows: -* A malicious user performs a CSRF log in using the malicious user's credentials. +. A malicious user performs a CSRF login with the malicious user's credentials. The victim is now authenticated as the malicious user. -* The malicious user then tricks the victim to visit the compromised website and enter sensitive information -* The information is associated to the malicious user's account so the malicious user can log in with their own credentials and view the vicitim's sensitive information +. The malicious user then tricks the victim into visiting the compromised website and entering sensitive information. +. The information is associated to the malicious user's account so the malicious user can log in with their own credentials and view the victim's sensitive information. -A possible complication to ensuring log in HTTP requests are protected against CSRF attacks is that the user might experience a session timeout that causes the request to be rejected. -A session timeout is surprising to users who do not expect to need to have a session in order to log in. +A possible complication to ensuring login HTTP requests are protected against CSRF attacks is that the user might experience a session timeout that causes the request to be rejected. +A session timeout is surprising to users who do not expect to need to have a session to log in. For more information refer to <>. [[csrf-considerations-logout]] === Logging Out -In order to protect against forging log out requests, the log out HTTP request should be protected against CSRF attacks. -Protecting against forging log out requests is necessary so a malicious user cannot read a victim's sensitive information. -For details on the attack refer to https://labs.detectify.com/2017/03/15/loginlogout-csrf-time-to-reconsider/[this blog post]. +To protect against forging logout requests, the logout HTTP request should be protected against CSRF attacks. +Protecting against forging logout requests is necessary so that a malicious user cannot read a victim's sensitive information. +For details on the attack, see https://labs.detectify.com/2017/03/15/loginlogout-csrf-time-to-reconsider/[this blog post]. -A possible complication to ensuring log out HTTP requests are protected against CSRF attacks is that the user might experience a session timeout that causes the request to be rejected. -A session timeout is surprising to users who do not expect to need to have a session in order to log out. -For more information refer to <>. +A possible complication to ensuring logout HTTP requests are protected against CSRF attacks is that the user might experience a session timeout that causes the request to be rejected. +A session timeout is surprising to users who do not expect to have a session to log out. +For more information, see <>. [[csrf-considerations-timeouts]] === CSRF and Session Timeouts More often than not, the expected CSRF token is stored in the session. -This means that as soon as the session expires the server will not find an expected CSRF token and reject the HTTP request. -There are a number of options to solve timeouts each of which come with trade offs. +This means that, as soon as the session expires, the server does not find an expected CSRF token and rejects the HTTP request. +There are a number of options (each of which come with trade offs) to solve timeouts: * The best way to mitigate the timeout is by using JavaScript to request a CSRF token on form submission. The form is then updated with the CSRF token and submitted. * Another option is to have some JavaScript that lets the user know their session is about to expire. The user can click a button to continue and refresh the session. * Finally, the expected CSRF token could be stored in a cookie. -This allows the expected CSRF token to outlive the session. +This lets the expected CSRF token outlive the session. + -One might ask why the expected CSRF token isn't stored in a cookie by default. +One might ask why the expected CSRF token is not stored in a cookie by default. This is because there are known exploits in which headers (for example, to specify the cookies) can be set by another domain. -This is the same reason Ruby on Rails https://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails/[no longer skips CSRF checks when the header X-Requested-With is present]. +This is the same reason Ruby on Rails https://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails/[no longer skips a CSRF checks when the header X-Requested-With is present]. See https://web.archive.org/web/20210221120355/https://lists.webappsec.org/pipermail/websecurity_lists.webappsec.org/2011-February/007533.html[this webappsec.org thread] for details on how to perform the exploit. Another disadvantage is that by removing the state (that is, the timeout), you lose the ability to forcibly invalidate the token if it is compromised. -// FIXME: Document timeout with lengthy form expire. We do not want to automatically replay that request because it can lead to exploit +// FIXME: Document timeout with lengthy form expire. We do not want to automatically replay that request because it can lead to an exploit. [[csrf-considerations-multipart]] === Multipart (file upload) -Protecting multipart requests (file uploads) from CSRF attacks causes a https://en.wikipedia.org/wiki/Chicken_or_the_egg[chicken and the egg] problem. -In order to prevent a CSRF attack from occurring, the body of the HTTP request must be read to obtain actual CSRF token. -However, reading the body means that the file will be uploaded which means an external site can upload a file. +Protecting multipart requests (file uploads) from CSRF attacks causes a https://en.wikipedia.org/wiki/Chicken_or_the_egg[chicken or the egg] problem. +To prevent a CSRF attack from occurring, the body of the HTTP request must be read to obtain the actual CSRF token. +However, reading the body means that the file is uploaded, which means an external site can upload a file. -There are two options to using CSRF protection with multipart/form-data. -Each option has its trade-offs. +There are two options to using CSRF protection with multipart/form-data: * <> * <> +Each option has its trade-offs. + [NOTE] ==== -Before you integrate Spring Security's CSRF protection with multipart file upload, ensure that you can upload without the CSRF protection first. -More information about using multipart forms with Spring can be found within the https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web.html#mvc-multipart[1.1.11. Multipart Resolver] section of the Spring reference and the https://docs.spring.io/spring/docs/5.2.x/javadoc-api/org/springframework/web/multipart/support/MultipartFilter.html[MultipartFilter javadoc]. +Before you integrate Spring Security's CSRF protection with multipart file upload, you should first ensure that you can upload without the CSRF protection. +More information about using multipart forms with Spring, see the https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web.html#mvc-multipart[1.1.11. Multipart Resolver] section of the Spring reference and the https://docs.spring.io/spring/docs/5.2.x/javadoc-api/org/springframework/web/multipart/support/MultipartFilter.html[`MultipartFilter` Javadoc]. ==== [[csrf-considerations-multipart-body]] ==== Place CSRF Token in the Body The first option is to include the actual CSRF token in the body of the request. -By placing the CSRF token in the body, the body will be read before authorization is performed. +By placing the CSRF token in the body, the body is read before authorization is performed. This means that anyone can place temporary files on your server. -However, only authorized users will be able to submit a file that is processed by your application. -In general, this is the recommended approach because the temporary file upload should have a negligible impact on most servers. +However, only authorized users can submit a file that is processed by your application. +In general, this is the recommended approach, because the temporary file upload should have a negligible impact on most servers. [[csrf-considerations-multipart-url]] ==== Include CSRF Token in URL -If allowing unauthorized users to upload temporary files is not acceptable, an alternative is to include the expected CSRF token as a query parameter in the action attribute of the form. +If letting unauthorized users upload temporary files is not acceptable, an alternative is to include the expected CSRF token as a query parameter in the action attribute of the form. The disadvantage to this approach is that query parameters can be leaked. More generally, it is considered best practice to place sensitive data within the body or headers to ensure it is not leaked. -Additional information can be found in https://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3[RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI's]. +You can find additional information in https://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3[RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI's]. [[csrf-considerations-override-method]] ==== HiddenHttpMethodFilter -In some applications a form parameter can be used to override the HTTP method. -For example, the form below could be used to treat the HTTP method as a `delete` rather than a `post`. +Some applications can use a form parameter to override the HTTP method. +For example, the following form can treat the HTTP method as a `delete` rather than a `post`. .CSRF Hidden HTTP Method Form ==== @@ -409,5 +410,5 @@ For example, the form below could be used to treat the HTTP method as a `delete` Overriding the HTTP method occurs in a filter. That filter must be placed before Spring Security's support. -Note that overriding only happens on a `post`, so this is actually unlikely to cause any real problems. -However, it is still best practice to ensure it is placed before Spring Security's filters. +Note that overriding happens only on a `post`, so this is actually unlikely to cause any real problems. +However, it is still best practice to ensure that it is placed before Spring Security's filters. diff --git a/docs/modules/ROOT/pages/features/exploits/headers.adoc b/docs/modules/ROOT/pages/features/exploits/headers.adoc index be19d3028cb..6c308499873 100644 --- a/docs/modules/ROOT/pages/features/exploits/headers.adoc +++ b/docs/modules/ROOT/pages/features/exploits/headers.adoc @@ -4,19 +4,19 @@ [NOTE] ==== This portion of the documentation discusses the general topic of Security HTTP Response Headers. -Refer to the relevant sections for specific information on Security HTTP Response Headers xref:servlet/exploits/headers.adoc#servlet-headers[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers[WebFlux] based applications. +See the relevant sections for specific information on Security HTTP Response Headers in xref:servlet/exploits/headers.adoc#servlet-headers[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers[WebFlux]-based applications. ==== -There are many https://owasp.org/www-project-secure-headers/#div-headers[HTTP response headers] that can be used to increase the security of web applications. -This section is dedicated to the various HTTP response headers that Spring Security provides explicit support for. -If necessary, Spring Security can also be configured to provide <>. +You can use https://owasp.org/www-project-secure-headers/#div-headers[HTTP response headers] in many ways to increase the security of web applications. +This section is dedicated to the various HTTP response headers for which Spring Security provides explicit support for. +If necessary, you can also configure Spring Security to provide <>. [[headers-default]] == Default Security Headers [NOTE] ==== -Refer to the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-default[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-default[webflux] based applications. +See the relevant sections for how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-default[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-default[webflux]-based applications. ==== Spring Security provides a default set of security related HTTP response headers to provide secure defaults. @@ -37,10 +37,13 @@ X-XSS-Protection: 1; mode=block ---- ==== -NOTE: Strict-Transport-Security is only added on HTTPS requests +[NOTE] +==== +Strict-Transport-Security is added only on HTTPS requests +==== If the defaults do not meet your needs, you can easily remove, modify, or add headers from these defaults. -For additional details on each of these headers, refer to the corresponding sections: +For additional details on each of these headers, see the corresponding sections: * <> * <> @@ -53,12 +56,12 @@ For additional details on each of these headers, refer to the corresponding sect [NOTE] ==== -Refer to the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-cache-control[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-cache-control[webflux] based applications. +See to the relevant sections for how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-cache-control[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-cache-control[webflux]-based applications. ==== -Spring Security's default is to disable caching to protect user's content. +Spring Security's default is to disable caching to protect the user's content. -If a user authenticates to view sensitive information and then logs out, we don't want a malicious user to be able to click the back button to view the sensitive information. +If a user authenticates to view sensitive information and then logs out, we do not want a malicious user to be able to click the back button to view the sensitive information. The cache control headers that are sent by default are: .Default Cache Control HTTP Response Headers @@ -71,9 +74,9 @@ Expires: 0 ---- ==== -In order to be secure by default, Spring Security adds these headers by default. -However, if your application provides its own cache control headers Spring Security will back out of the way. -This allows for applications to ensure that static resources like CSS and JavaScript can be cached. +To be secure by default, Spring Security adds these headers by default. +However, if your application provides its own cache control headers, Spring Security backs out of the way. +This allows for applications to ensure that static resources (such as CSS and JavaScript) can be cached. [[headers-content-type-options]] @@ -84,22 +87,22 @@ This allows for applications to ensure that static resources like CSS and JavaSc Refer to the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-content-type-options[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-content-type-options[webflux] based applications. ==== -Historically browsers, including Internet Explorer, would try to guess the content type of a request using https://en.wikipedia.org/wiki/Content_sniffing[content sniffing]. +Historically, browsers, including Internet Explorer, would try to guess the content type of a request by using https://en.wikipedia.org/wiki/Content_sniffing[content sniffing]. This allowed browsers to improve the user experience by guessing the content type on resources that had not specified the content type. For example, if a browser encountered a JavaScript file that did not have the content type specified, it would be able to guess the content type and then run it. [NOTE] ==== -There are many additional things one should do (i.e. only display the document in a distinct domain, ensure Content-Type header is set, sanitize the document, etc) when allowing content to be uploaded. +There are many additional things one should do (such as only display the document in a distinct domain, ensure Content-Type header is set, sanitize the document, and others) when allowing content to be uploaded. However, these measures are out of the scope of what Spring Security provides. -It is also important to point out when disabling content sniffing, you must specify the content type in order for things to work properly. +It is also important to point out that, when disabling content sniffing, you must specify the content type in order for things to work properly. ==== -The problem with content sniffing is that this allowed malicious users to use polyglots (i.e. a file that is valid as multiple content types) to perform XSS attacks. +The problem with content sniffing is that this allowed malicious users to use polyglots (that is, a file that is valid as multiple content types) to perform XSS attacks. For example, some sites may allow users to submit a valid postscript document to a website and view it. -A malicious user might create a http://webblaze.cs.berkeley.edu/papers/barth-caballero-song.pdf[postscript document that is also a valid JavaScript file] and perform a XSS attack with it. +A malicious user might create a http://webblaze.cs.berkeley.edu/papers/barth-caballero-song.pdf[postscript document that is also a valid JavaScript file] and perform an XSS attack with it. -Spring Security disables content sniffing by default by adding the following header to HTTP responses: +By default, Spring Security disables content sniffing by adding the following header to HTTP responses: .nosniff HTTP Response Header ==== @@ -117,23 +120,23 @@ X-Content-Type-Options: nosniff Refer to the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-hsts[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-hsts[webflux] based applications. ==== -When you type in your bank's website, do you enter mybank.example.com or do you enter https://mybank.example.com[]? -If you omit the https protocol, you are potentially vulnerable to https://en.wikipedia.org/wiki/Man-in-the-middle_attack[Man in the Middle attacks]. -Even if the website performs a redirect to https://mybank.example.com a malicious user could intercept the initial HTTP request and manipulate the response (e.g. redirect to https://mibank.example.com and steal their credentials). +When you type in your bank's website, do you enter `mybank.example.com` or do you enter `https://mybank.example.com`? +If you omit the `https` protocol, you are potentially vulnerable to https://en.wikipedia.org/wiki/Man-in-the-middle_attack[Man-in-the-Middle attacks]. +Even if the website performs a redirect to https://mybank.example.com, a malicious user could intercept the initial HTTP request and manipulate the response (for example, redirect to https://mibank.example.com and steal their credentials). -Many users omit the https protocol and this is why https://tools.ietf.org/html/rfc6797[HTTP Strict Transport Security (HSTS)] was created. -Once mybank.example.com is added as a https://tools.ietf.org/html/rfc6797#section-5.1[HSTS host], a browser can know ahead of time that any request to mybank.example.com should be interpreted as https://mybank.example.com. -This greatly reduces the possibility of a Man in the Middle attack occurring. +Many users omit the `https` protocol, and this is why https://tools.ietf.org/html/rfc6797[HTTP Strict Transport Security (HSTS)] was created. +Once `mybank.example.com` is added as a https://tools.ietf.org/html/rfc6797#section-5.1[HSTS host], a browser can know ahead of time that any request to mybank.example.com should be interpreted as https://mybank.example.com. +This greatly reduces the possibility of a Man-in-the-Middle attack occurring. [NOTE] ==== -In accordance with https://tools.ietf.org/html/rfc6797#section-7.2[RFC6797], the HSTS header is only injected into HTTPS responses. -In order for the browser to acknowledge the header, the browser must first trust the CA that signed the SSL certificate used to make the connection (not just the SSL certificate). +In accordance with https://tools.ietf.org/html/rfc6797#section-7.2[RFC6797], the HSTS header is injected only into HTTPS responses. +For the browser to acknowledge the header, the browser must first trust the CA that signed the SSL certificate used to make the connection (not just the SSL certificate). ==== One way for a site to be marked as a HSTS host is to have the host preloaded into the browser. -Another is to add the `Strict-Transport-Security` header to the response. -For example, Spring Security's default behavior is to add the following header which instructs the browser to treat the domain as an HSTS host for a year (there are approximately 31536000 seconds in a year): +Another way is to add the `Strict-Transport-Security` header to the response. +For example, Spring Security's default behavior is to add the following header, which instructs the browser to treat the domain as an HSTS host for a year (there are 31536000 seconds in a non-leap year): .Strict Transport Security HTTP Response Header @@ -144,37 +147,37 @@ Strict-Transport-Security: max-age=31536000 ; includeSubDomains ; preload ---- ==== -The optional `includeSubDomains` directive instructs the browser that subdomains (e.g. secure.mybank.example.com) should also be treated as an HSTS domain. +The optional `includeSubDomains` directive instructs the browser that subdomains (such as `secure.mybank.example.com`) should also be treated as an HSTS domain. -The optional `preload` directive instructs the browser that domain should be preloaded in browser as HSTS domain. -For more details on HSTS preload please see https://hstspreload.org. +The optional `preload` directive instructs the browser that the domain should be preloaded in browser as an HSTS domain. +For more details on HSTS preload, see https://hstspreload.org. [[headers-hpkp]] == HTTP Public Key Pinning (HPKP) [NOTE] ==== -In order to remain passive Spring Security still provides xref:servlet/exploits/headers.adoc#servlet-headers-hpkp[support for HPKP in servlet environments], but for the reasons listed above HPKP is no longer recommended by the security team. +To remain passive, Spring Security still provides xref:servlet/exploits/headers.adoc#servlet-headers-hpkp[support for HPKP in servlet environments]. +However, for the reasons listed earlier, HPKP is no longer recommended by the Spring Security team. ==== -https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning[HTTP Public Key Pinning (HPKP)] specifies to a web client which public key to use with certain web server to prevent Man in the Middle (MITM) attacks with forged certificates. +https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning[HTTP Public Key Pinning (HPKP)] specifies to a web client which public key to use with a certain web server to prevent Man-in-the-Middle (MITM) attacks with forged certificates. When used correctly, HPKP could add additional layers of protection against compromised certificates. -However, due to the complexity of HPKP many experts no longer recommend using it and https://www.chromestatus.com/feature/5903385005916160[Chrome has even removed support] for it. +However, due to the complexity of HPKP, many experts no longer recommend using it and https://www.chromestatus.com/feature/5903385005916160[Chrome has even removed support] for it. [[headers-hpkp-deprecated]] -For additional details around why HPKP is no longer recommended read https://blog.qualys.com/ssllabs/2016/09/06/is-http-public-key-pinning-dead[ -Is HTTP Public Key Pinning Dead?] and https://scotthelme.co.uk/im-giving-up-on-hpkp/[I'm giving up on HPKP]. +For additional details around why HPKP is no longer recommended, read https://blog.qualys.com/ssllabs/2016/09/06/is-http-public-key-pinning-dead[Is HTTP Public Key Pinning Dead?] and https://scotthelme.co.uk/im-giving-up-on-hpkp/[I'm giving up on HPKP]. [[headers-frame-options]] == X-Frame-Options [NOTE] ==== -Refer to the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-frame-options[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-frame-options[webflux] based applications. +See the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-frame-options[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-frame-options[webflux] based applications. ==== -Allowing your website to be added to a frame can be a security issue. -For example, using clever CSS styling users could be tricked into clicking on something that they were not intending. +Letting your website be added to a frame can be a security issue. +For example, by using clever CSS styling, users could be tricked into clicking on something that they were not intending. For example, a user that is logged into their bank might click a button that grants access to other users. This sort of attack is known as https://en.wikipedia.org/wiki/Clickjacking[Clickjacking]. @@ -184,38 +187,42 @@ Another modern approach to dealing with clickjacking is to use <>. ==== There are a number ways to mitigate clickjacking attacks. -For example, to protect legacy browsers from clickjacking attacks you can use https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Best-for-now_Legacy_Browser_Frame_Breaking_Script[frame breaking code]. +For example, to protect legacy browsers from clickjacking attacks, you can use https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Best-for-now_Legacy_Browser_Frame_Breaking_Script[frame breaking code]. While not perfect, the frame breaking code is the best you can do for the legacy browsers. A more modern approach to address clickjacking is to use https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options[X-Frame-Options] header. -By default Spring Security disables rendering pages within an iframe using with the following header: +By default, Spring Security disables rendering pages within an iframe by using with the following header: +==== [source] ---- X-Frame-Options: DENY ---- +==== [[headers-xss-protection]] == X-XSS-Protection [NOTE] ==== -Refer to the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-xss-protection[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-xss-protection[webflux] based applications. +See the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-xss-protection[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-xss-protection[webflux]-based applications. ==== -Some browsers have built in support for filtering out https://www.owasp.org/index.php/Testing_for_Reflected_Cross_site_scripting_(OWASP-DV-001)[reflected XSS attacks]. -This is by no means foolproof, but does assist in XSS protection. +Some browsers have built-in support for filtering out https://www.owasp.org/index.php/Testing_for_Reflected_Cross_site_scripting_(OWASP-DV-001)[reflected XSS attacks]. +This is by no means foolproof but does assist in XSS protection. The filtering is typically enabled by default, so adding the header typically just ensures it is enabled and instructs the browser what to do when a XSS attack is detected. For example, the filter might try to change the content in the least invasive way to still render everything. -At times, this type of replacement can become a https://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/[XSS vulnerability in itself]. +At times, this type of replacement can become an https://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/[XSS vulnerability in itself]. Instead, it is best to block the content rather than attempt to fix it. -By default Spring Security blocks the content using the following header: +By default, Spring Security blocks the content by using the following header: +==== [source] ---- X-XSS-Protection: 1; mode=block ---- +==== [[headers-csp]] @@ -223,20 +230,20 @@ X-XSS-Protection: 1; mode=block [NOTE] ==== -Refer to the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-csp[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-csp[webflux] based applications. +See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-csp[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-csp[webflux]-based applications. ==== -https://www.w3.org/TR/CSP2/[Content Security Policy (CSP)] is a mechanism that web applications can leverage to mitigate content injection vulnerabilities, such as cross-site scripting (XSS). +https://www.w3.org/TR/CSP2/[Content Security Policy (CSP)] is a mechanism that web applications can use to mitigate content injection vulnerabilities, such as cross-site scripting (XSS). CSP is a declarative policy that provides a facility for web application authors to declare and ultimately inform the client (user-agent) about the sources from which the web application expects to load resources. [NOTE] ==== Content Security Policy is not intended to solve all content injection vulnerabilities. -Instead, CSP can be leveraged to help reduce the harm caused by content injection attacks. +Instead, you can use CSP to help reduce the harm caused by content injection attacks. As a first line of defense, web application authors should validate their input and encode their output. ==== -A web application may employ the use of CSP by including one of the following HTTP headers in the response: +A web application can use CSP by including one of the following HTTP headers in the response: * `Content-Security-Policy` * `Content-Security-Policy-Report-Only` @@ -244,7 +251,7 @@ A web application may employ the use of CSP by including one of the following HT Each of these headers are used as a mechanism to deliver a security policy to the client. A security policy contains a set of security policy directives, each responsible for declaring the restrictions for a particular resource representation. -For example, a web application can declare that it expects to load scripts from specific, trusted sources, by including the following header in the response: +For example, a web application can declare that it expects to load scripts from specific, trusted sources by including the following header in the response: .Content Security Policy Example ==== @@ -254,10 +261,10 @@ Content-Security-Policy: script-src https://trustedscripts.example.com ---- ==== -An attempt to load a script from another source other than what is declared in the `script-src` directive will be blocked by the user-agent. -Additionally, if the https://www.w3.org/TR/CSP2/#directive-report-uri[report-uri] directive is declared in the security policy, then the violation will be reported by the user-agent to the declared URL. +An attempt to load a script from another source other than what is declared in the `script-src` directive is blocked by the user-agent. +Additionally, if the https://www.w3.org/TR/CSP2/#directive-report-uri[report-uri] directive is declared in the security policy, the violation will be reported by the user-agent to the declared URL. -For example, if a web application violates the declared security policy, the following response header will instruct the user-agent to send violation reports to the URL specified in the policy's `report-uri` directive. +For example, if a web application violates the declared security policy, the following response header instructs the user-agent to send violation reports to the URL specified in the policy's `report-uri` directive. .Content Security Policy with report-uri ==== @@ -267,13 +274,13 @@ Content-Security-Policy: script-src https://trustedscripts.example.com; report-u ---- ==== -https://www.w3.org/TR/CSP2/#violation-reports[Violation reports] are standard JSON structures that can be captured either by the web application's own API or by a publicly hosted CSP violation reporting service, such as, https://report-uri.com/. +https://www.w3.org/TR/CSP2/#violation-reports[Violation reports] are standard JSON structures that can be captured either by the web application's own API or by a publicly hosted CSP violation reporting service, such as https://report-uri.io/. -The `Content-Security-Policy-Report-Only` header provides the capability for web application authors and administrators to monitor security policies, rather than enforce them. -This header is typically used when experimenting and/or developing security policies for a site. +The `Content-Security-Policy-Report-Only` header provides the capability for web application authors and administrators to monitor security policies rather than enforce them. +This header is typically used when experimenting or developing security policies for a site. When a policy is deemed effective, it can be enforced by using the `Content-Security-Policy` header field instead. -Given the following response header, the policy declares that scripts may be loaded from one of two possible sources. +Given the following response header, the policy declares that scripts can be loaded from one of two possible sources. .Content Security Policy Report Only ==== @@ -283,10 +290,10 @@ Content-Security-Policy-Report-Only: script-src 'self' https://trustedscripts.ex ---- ==== -If the site violates this policy, by attempting to load a script from _evil.com_, the user-agent will send a violation report to the declared URL specified by the _report-uri_ directive, but still allow the violating resource to load nevertheless. +If the site violates this policy, by attempting to load a script from `evil.example.com`, the user-agent sends a violation report to the declared URL specified by the `report-uri` directive but still lets the violating resource load. Applying Content Security Policy to a web application is often a non-trivial undertaking. -The following resources may provide further assistance in developing effective security policies for your site. +The following resources may provide further assistance in developing effective security policies for your site: https://www.html5rocks.com/en/tutorials/security/content-security-policy/[An Introduction to Content Security Policy] @@ -299,13 +306,13 @@ https://www.w3.org/TR/CSP2/[W3C Candidate Recommendation] [NOTE] ==== -Refer to the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-referrer[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-referrer[webflux] based applications. +See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-referrer[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-referrer[webflux]-based applications. ==== -https://www.w3.org/TR/referrer-policy[Referrer Policy] is a mechanism that web applications can leverage to manage the referrer field, which contains the last +https://www.w3.org/TR/referrer-policy[Referrer Policy] is a mechanism that web applications can use to manage the referrer field, which contains the last page the user was on. -Spring Security's approach is to use https://www.w3.org/TR/referrer-policy/[Referrer Policy] header, which provides different https://www.w3.org/TR/referrer-policy/#referrer-policies[policies]: +Spring Security's approach is to use the https://www.w3.org/TR/referrer-policy/[Referrer Policy] header, which provides different https://www.w3.org/TR/referrer-policy/#referrer-policies[policies]: .Referrer Policy Example ==== @@ -322,10 +329,10 @@ The Referrer-Policy response header instructs the browser to let the destination [NOTE] ==== -Refer to the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-feature[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-feature[webflux] based applications. +See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-feature[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-feature[webflux]-based applications. ==== -https://wicg.github.io/feature-policy/[Feature Policy] is a mechanism that allows web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser. +https://wicg.github.io/feature-policy/[Feature Policy] is a mechanism that lets web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser. .Feature Policy Example ==== @@ -335,7 +342,7 @@ Feature-Policy: geolocation 'self' ---- ==== -With Feature Policy, developers can opt-in to a set of "policies" for the browser to enforce on specific features used throughout your site. +With Feature Policy, developers can opt-in to a set of "`policies`" for the browser to enforce on specific features used throughout your site. These policies restrict what APIs the site can access or modify the browser's default behavior for certain features. @@ -344,10 +351,10 @@ These policies restrict what APIs the site can access or modify the browser's de [NOTE] ==== -Refer to the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-permissions[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-permissions[webflux] based applications. +See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-permissions[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-permissions[webflux]-based applications. ==== -https://w3c.github.io/webappsec-permissions-policy/[Permissions Policy] is a mechanism that allows web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser. +https://w3c.github.io/webappsec-permissions-policy/[Permissions Policy] is a mechanism that lets web developers selectively enable, disable, and modify the behavior of certain APIs and web features in the browser. .Permissions Policy Example ==== @@ -366,15 +373,17 @@ These policies restrict what APIs the site can access or modify the browser's de [NOTE] ==== -Refer to the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-clear-site-data[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-clear-site-data[webflux] based applications. +See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-clear-site-data[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-clear-site-data[webflux]- based applications. ==== -https://www.w3.org/TR/clear-site-data/[Clear Site Data] is a mechanism by which any browser-side data - cookies, local storage, and the like - can be removed when an HTTP response contains this header: +https://www.w3.org/TR/clear-site-data/[Clear Site Data] is a mechanism by which any browser-side data (cookies, local storage, and the like) can be removed when an HTTP response contains this header: +==== [source] ---- Clear-Site-Data: "cache", "cookies", "storage", "executionContexts" ---- +==== This is a nice clean-up action to perform on logout. @@ -384,7 +393,7 @@ This is a nice clean-up action to perform on logout. [NOTE] ==== -Refer to the relevant section to see how to configure xref:servlet/exploits/headers.adoc#servlet-headers-custom[servlet] based applications. +See the relevant section to see how to configure xref:servlet/exploits/headers.adoc#servlet-headers-custom[servlet] based applications. ==== Spring Security has mechanisms to make it convenient to add the more common security headers to your application. diff --git a/docs/modules/ROOT/pages/features/exploits/http.adoc b/docs/modules/ROOT/pages/features/exploits/http.adoc index fcffae7a256..217e497dea7 100644 --- a/docs/modules/ROOT/pages/features/exploits/http.adoc +++ b/docs/modules/ROOT/pages/features/exploits/http.adoc @@ -1,7 +1,7 @@ [[http]] = HTTP -All HTTP based communication, including https://www.troyhunt.com/heres-why-your-static-website-needs-https/[static resources], should be protected https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html[using TLS]. +All HTTP-based communication, including https://www.troyhunt.com/heres-why-your-static-website-needs-https/[static resources], should be protected by https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html[using TLS]. As a framework, Spring Security does not handle HTTP connections and thus does not provide support for HTTPS directly. However, it does provide a number of features that help with HTTPS usage. @@ -9,7 +9,7 @@ However, it does provide a number of features that help with HTTPS usage. [[http-redirect]] == Redirect to HTTPS -When a client uses HTTP, Spring Security can be configured to redirect to HTTPS both xref:servlet/exploits/http.adoc#servlet-http-redirect[Servlet] and xref:reactive/exploits/http.adoc#webflux-http-redirect[WebFlux] environments. +When a client uses HTTP, you can configure Spring Security to redirect to HTTPS in both xref:servlet/exploits/http.adoc#servlet-http-redirect[Servlet] and xref:reactive/exploits/http.adoc#webflux-http-redirect[WebFlux] environments. [[http-hsts]] == Strict Transport Security @@ -19,14 +19,14 @@ Spring Security provides support for xref:features/exploits/headers.adoc#headers [[http-proxy-server]] == Proxy Server Configuration -When using a proxy server it is important to ensure that you have configured your application properly. -For example, many applications will have a load balancer that responds to request for https://example.com/ by forwarding the request to an application server at https://192.168.1:8080. -Without proper configuration, the application server will not know that the load balancer exists and treat the request as though https://192.168.1:8080 was requested by the client. +When using a proxy server, it is important to ensure that you have configured your application properly. +For example, many applications have a load balancer that responds to request for https://example.com/ by forwarding the request to an application server at https://192.168.1:8080 +Without proper configuration, the application server can not know that the load balancer exists and treats the request as though https://192.168.1:8080 was requested by the client. -To fix this you can use https://tools.ietf.org/html/rfc7239[RFC 7239] to specify that a load balancer is being used. -To make the application aware of this, you need to either configure your application server aware of the X-Forwarded headers. -For example Tomcat uses the https://tomcat.apache.org/tomcat-8.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html[RemoteIpValve] and Jetty uses https://www.eclipse.org/jetty/javadoc/jetty-9/org/eclipse/jetty/server/ForwardedRequestCustomizer.html[ForwardedRequestCustomizer]. -Alternatively, Spring users can leverage https://github.com/spring-projects/spring-framework/blob/v4.3.3.RELEASE/spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java[ForwardedHeaderFilter]. +To fix this, you can use https://tools.ietf.org/html/rfc7239[RFC 7239] to specify that a load balancer is being used. +To make the application aware of this, you need to configure your application server to be aware of the X-Forwarded headers. +For example, Tomcat uses https://tomcat.apache.org/tomcat-8.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html[`RemoteIpValve`] and Jetty uses https://download.eclipse.org/jetty/stable-9/apidocs/org/eclipse/jetty/server/ForwardedRequestCustomizer.html[`ForwardedRequestCustomizer`]. +Alternatively, Spring users can use https://github.com/spring-projects/spring-framework/blob/v4.3.3.RELEASE/spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java[`ForwardedHeaderFilter`]. -Spring Boot users may use the `server.use-forward-headers` property to configure the application. +Spring Boot users can use the `server.use-forward-headers` property to configure the application. See the https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-use-tomcat-behind-a-proxy-server[Spring Boot documentation] for further details. diff --git a/docs/modules/ROOT/pages/features/exploits/index.adoc b/docs/modules/ROOT/pages/features/exploits/index.adoc index ec5de58e85d..a37947ce57b 100644 --- a/docs/modules/ROOT/pages/features/exploits/index.adoc +++ b/docs/modules/ROOT/pages/features/exploits/index.adoc @@ -4,4 +4,4 @@ Spring Security provides protection against common exploits. Whenever possible, the protection is enabled by default. -Below you will find high level description of the various exploits that Spring Security protects against. +This section describes the various exploits that Spring Security protects against. diff --git a/docs/modules/ROOT/pages/features/integrations/concurrency.adoc b/docs/modules/ROOT/pages/features/integrations/concurrency.adoc index fbb049c9e99..32535f27204 100644 --- a/docs/modules/ROOT/pages/features/integrations/concurrency.adoc +++ b/docs/modules/ROOT/pages/features/integrations/concurrency.adoc @@ -44,7 +44,7 @@ fun run() { While very simple, it makes it seamless to transfer the SecurityContext from one Thread to another. This is important since, in most cases, the SecurityContextHolder acts on a per Thread basis. -For example, you might have used Spring Security's xref:servlet/appendix/namespace.adoc#nsa-global-method-security[] support to secure one of your services. +For example, you might have used Spring Security's xref:servlet/appendix/namespace/method-security.adoc#nsa-global-method-security[] support to secure one of your services. You can now easily transfer the `SecurityContext` of the current `Thread` to the `Thread` that invokes the secured service. An example of how you might do this can be found below: diff --git a/docs/modules/ROOT/pages/features/integrations/cryptography.adoc b/docs/modules/ROOT/pages/features/integrations/cryptography.adoc index 137b3e8b694..5553b51110c 100644 --- a/docs/modules/ROOT/pages/features/integrations/cryptography.adoc +++ b/docs/modules/ROOT/pages/features/integrations/cryptography.adoc @@ -1,23 +1,26 @@ [[crypto]] = Spring Security Crypto Module - [[spring-security-crypto-introduction]] -== Introduction The Spring Security Crypto module provides support for symmetric encryption, key generation, and password encoding. The code is distributed as part of the core module but has no dependencies on any other Spring Security (or Spring) code. [[spring-security-crypto-encryption]] == Encryptors -The Encryptors class provides factory methods for constructing symmetric encryptors. -Using this class, you can create ByteEncryptors to encrypt data in raw byte[] form. -You can also construct TextEncryptors to encrypt text strings. +The {security-api-url}org/springframework/security/crypto/encrypt/Encryptors.html[`Encryptors`] class provides factory methods for constructing symmetric encryptors. +This class lets you create {security-api-url}org/springframework/security/crypto/encrypt/BytesEncryptor.html[`BytesEncryptor`] instances to encrypt data in raw `byte[]` form. +You can also construct {security-api-url}org/springframework/security/crypto/encrypt/TextEncryptor.html[TextEncryptor] instances to encrypt text strings. Encryptors are thread-safe. +[NOTE] +==== +Both `BytesEncryptor` and `TextEncryptor` are interfaces. `BytesEncryptor` has multiple implementations. +==== + [[spring-security-crypto-encryption-bytes]] === BytesEncryptor -Use the `Encryptors.stronger` factory method to construct a BytesEncryptor: +You can use the `Encryptors.stronger` factory method to construct a `BytesEncryptor`: .BytesEncryptor ==== @@ -34,16 +37,16 @@ Encryptors.stronger("password", "salt") ---- ==== -The "stronger" encryption method creates an encryptor using 256 bit AES encryption with +The `stronger` encryption method creates an encryptor by using 256-bit AES encryption with Galois Counter Mode (GCM). -It derives the secret key using PKCS #5's PBKDF2 (Password-Based Key Derivation Function #2). +It derives the secret key by using PKCS #5's PBKDF2 (Password-Based Key Derivation Function #2). This method requires Java 6. -The password used to generate the SecretKey should be kept in a secure place and not be shared. -The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised. -A 16-byte random initialization vector is also applied so each encrypted message is unique. +The password used to generate the `SecretKey` should be kept in a secure place and should not be shared. +The salt is used to prevent dictionary attacks against the key in the event that your encrypted data is compromised. +A 16-byte random initialization vector is also applied so that each encrypted message is unique. The provided salt should be in hex-encoded String form, be random, and be at least 8 bytes in length. -Such a salt may be generated using a KeyGenerator: +You can generate such a salt by using a `KeyGenerator`: .Generating a key ==== @@ -60,14 +63,14 @@ val salt = KeyGenerators.string().generateKey() // generates a random 8-byte sal ---- ==== -Users may also use the `standard` encryption method, which is 256-bit AES in Cipher Block Chaining (CBC) Mode. +You can also use the `standard` encryption method, which is 256-bit AES in Cipher Block Chaining (CBC) Mode. This mode is not https://en.wikipedia.org/wiki/Authenticated_encryption[authenticated] and does not provide any guarantees about the authenticity of the data. -For a more secure alternative, users should prefer `Encryptors.stronger`. +For a more secure alternative, use `Encryptors.stronger`. [[spring-security-crypto-encryption-text]] === TextEncryptor -Use the Encryptors.text factory method to construct a standard TextEncryptor: +You can use the `Encryptors.text` factory method to construct a standard TextEncryptor: .TextEncryptor ==== @@ -84,10 +87,10 @@ Encryptors.text("password", "salt") ---- ==== -A TextEncryptor uses a standard BytesEncryptor to encrypt text data. -Encrypted results are returned as hex-encoded strings for easy storage on the filesystem or in the database. +A `TextEncryptor` uses a standard `BytesEncryptor` to encrypt text data. +Encrypted results are returned as hex-encoded strings for easy storage on the filesystem or in a database. -Use the Encryptors.queryableText factory method to construct a "queryable" TextEncryptor: +You can use the `Encryptors.queryableText` factory method to construct a "`queryable`" `TextEncryptor`: .Queryable TextEncryptor ==== @@ -104,21 +107,21 @@ Encryptors.queryableText("password", "salt") ---- ==== -The difference between a queryable TextEncryptor and a standard TextEncryptor has to do with initialization vector (iv) handling. -The iv used in a queryable TextEncryptor#encrypt operation is shared, or constant, and is not randomly generated. -This means the same text encrypted multiple times will always produce the same encryption result. -This is less secure, but necessary for encrypted data that needs to be queried against. -An example of queryable encrypted text would be an OAuth apiKey. +The difference between a queryable `TextEncryptor` and a standard `TextEncryptor` has to do with initialization vector (IV) handling. +The IV used in a queryable `TextEncryptor.encrypt` operation is shared, or constant, and is not randomly generated. +This means the same text encrypted multiple times always produces the same encryption result. +This is less secure but necessary for encrypted data that needs to be queried against. +An example of queryable encrypted text would be an OAuth `apiKey`. [[spring-security-crypto-keygenerators]] == Key Generators -The KeyGenerators class provides a number of convenience factory methods for constructing different types of key generators. -Using this class, you can create a BytesKeyGenerator to generate byte[] keys. -You can also construct a StringKeyGenerator to generate string keys. -KeyGenerators are thread-safe. +The {security-api-url}org/springframework/security/crypto/keygen/KeyGenerators.html[`KeyGenerators`] class provides a number of convenience factory methods for constructing different types of key generators. +By using this class, you can create a {security-api-url}org/springframework/security/crypto/keygen/BytesKeyGenerator.html[`BytesKeyGenerator`] to generate `byte[]` keys. +You can also construct a {security-api-url}org/springframework/security/crypto/keygen/StringKeyGenerator.html`[StringKeyGenerator]` to generate string keys. +`KeyGenerators` is a thread-safe class. === BytesKeyGenerator -Use the KeyGenerators.secureRandom factory methods to generate a BytesKeyGenerator backed by a SecureRandom instance: +You can use the `KeyGenerators.secureRandom` factory methods to generate a `BytesKeyGenerator` backed by a `SecureRandom` instance: .BytesKeyGenerator ==== @@ -138,7 +141,7 @@ val key = generator.generateKey() ==== The default key length is 8 bytes. -There is also a KeyGenerators.secureRandom variant that provides control over the key length: +A `KeyGenerators.secureRandom` variant provides control over the key length: .KeyGenerators.secureRandom ==== @@ -155,7 +158,7 @@ KeyGenerators.secureRandom(16) ---- ==== -Use the KeyGenerators.shared factory method to construct a BytesKeyGenerator that always returns the same key on every invocation: +Use the `KeyGenerators.shared` factory method to construct a BytesKeyGenerator that always returns the same key on every invocation: .KeyGenerators.shared ==== @@ -173,7 +176,7 @@ KeyGenerators.shared(16) ==== === StringKeyGenerator -Use the KeyGenerators.string factory method to construct a 8-byte, SecureRandom KeyGenerator that hex-encodes each key as a String: +You can use the `KeyGenerators.string` factory method to construct an 8-byte, `SecureRandom` `KeyGenerator` that hex-encodes each key as a `String`: .StringKeyGenerator ==== @@ -192,9 +195,10 @@ KeyGenerators.string() [[spring-security-crypto-passwordencoders]] == Password Encoding -The password package of the spring-security-crypto module provides support for encoding passwords. +The password package of the `spring-security-crypto` module provides support for encoding passwords. `PasswordEncoder` is the central service interface and has the following signature: +==== [source,java] ---- public interface PasswordEncoder { @@ -204,16 +208,18 @@ String encode(String rawPassword); boolean matches(String rawPassword, String encodedPassword); } ---- +==== -The matches method returns true if the rawPassword, once encoded, equals the encodedPassword. +The `matches` method returns true if the `rawPassword`, once encoded, equals the `encodedPassword`. This method is designed to support password-based authentication schemes. -The `BCryptPasswordEncoder` implementation uses the widely supported "bcrypt" algorithm to hash the passwords. -Bcrypt uses a random 16 byte salt value and is a deliberately slow algorithm, in order to hinder password crackers. -The amount of work it does can be tuned using the "strength" parameter which takes values from 4 to 31. +The `BCryptPasswordEncoder` implementation uses the widely supported "`bcrypt`" algorithm to hash the passwords. +Bcrypt uses a random 16-byte salt value and is a deliberately slow algorithm, to hinder password crackers. +You can tune the amount of work it does by using the `strength` parameter, which takes a value from 4 to 31. The higher the value, the more work has to be done to calculate the hash. -The default value is 10. +The default value is `10`. You can change this value in your deployed system without affecting existing passwords, as the value is also stored in the encoded hash. +The following example uses the `BCryptPasswordEncoder`: .BCryptPasswordEncoder ==== @@ -239,7 +245,8 @@ assertTrue(encoder.matches("myPassword", result)) ==== The `Pbkdf2PasswordEncoder` implementation uses PBKDF2 algorithm to hash the passwords. -In order to defeat password cracking PBKDF2 is a deliberately slow algorithm and should be tuned to take about .5 seconds to verify a password on your system. +To defeat password cracking, PBKDF2 is a deliberately slow algorithm and should be tuned to take about .5 seconds to verify a password on your system. +The following system uses the `Pbkdf2PasswordEncoder`: .Pbkdf2PasswordEncoder diff --git a/docs/modules/ROOT/pages/features/integrations/jackson.adoc b/docs/modules/ROOT/pages/features/integrations/jackson.adoc index e1c407763b3..1f67bf98a20 100644 --- a/docs/modules/ROOT/pages/features/integrations/jackson.adoc +++ b/docs/modules/ROOT/pages/features/integrations/jackson.adoc @@ -42,6 +42,6 @@ The following Spring Security modules provide Jackson support: - spring-security-core (`CoreJackson2Module`) - spring-security-web (`WebJackson2Module`, `WebServletJackson2Module`, `WebServerJackson2Module`) -- xref:servlet/oauth2/oauth2-client.adoc#oauth2client[ spring-security-oauth2-client] (`OAuth2ClientJackson2Module`) +- xref:servlet/oauth2/client/index.adoc#oauth2client[ spring-security-oauth2-client] (`OAuth2ClientJackson2Module`) - spring-security-cas (`CasJackson2Module`) ==== diff --git a/docs/modules/ROOT/pages/getting-spring-security.adoc b/docs/modules/ROOT/pages/getting-spring-security.adoc index f99e18860fd..3ef44654727 100644 --- a/docs/modules/ROOT/pages/getting-spring-security.adoc +++ b/docs/modules/ROOT/pages/getting-spring-security.adoc @@ -1,7 +1,7 @@ [[getting]] = Getting Spring Security -This section discusses all you need to know about getting the Spring Security binaries. +This section describes how to get the Spring Security binaries. See xref:community.adoc#community-source[Source Code] for how to obtain the source code. == Release Numbering @@ -10,7 +10,7 @@ Spring Security versions are formatted as MAJOR.MINOR.PATCH such that: * MAJOR versions may contain breaking changes. Typically, these are done to provide improved security to match modern security practices. -* MINOR versions contain enhancements but are considered passive updates +* MINOR versions contain enhancements but are considered passive updates. * PATCH level should be perfectly compatible, forwards and backwards, with the possible exception of changes that fix bugs. @@ -18,14 +18,13 @@ Typically, these are done to provide improved security to match modern security == Usage with Maven As most open source projects, Spring Security deploys its dependencies as Maven artifacts. -The topics in this section provide detail on how to consume Spring Security when using Maven. +The topics in this section describe how to consume Spring Security when using Maven. [[getting-maven-boot]] === Spring Boot with Maven -Spring Boot provides a `spring-boot-starter-security` starter that aggregates Spring Security-related dependencies together. -The simplest and preferred way to use the starter is to use https://docs.spring.io/initializr/docs/current/reference/html/[Spring Initializr] by using an IDE integration (https://joshlong.com/jl/blogPost/tech_tip_geting_started_with_spring_boot.html[Eclipse], https://www.jetbrains.com/help/idea/spring-boot.html#d1489567e2[IntelliJ], https://github.com/AlexFalappa/nb-springboot/wiki/Quick-Tour[NetBeans]) or through https://start.spring.io. - +Spring Boot provides a `spring-boot-starter-security` starter that aggregates Spring Security-related dependencies. +The simplest and preferred way to use the starter is to use https://docs.spring.io/initializr/docs/current/reference/htmlsingle/[Spring Initializr] by using an IDE integration in (https://joshlong.com/jl/blogPost/tech_tip_geting_started_with_spring_boot.html[Eclipse] or https://www.jetbrains.com/help/idea/spring-boot.html#d1489567e2[IntelliJ], https://github.com/AlexFalappa/nb-springboot/wiki/Quick-Tour[NetBeans]) or through https://start.spring.io. Alternatively, you can manually add the starter, as the following example shows: @@ -44,7 +43,7 @@ Alternatively, you can manually add the starter, as the following example shows: ==== Since Spring Boot provides a Maven BOM to manage dependency versions, you do not need to specify a version. -If you wish to override the Spring Security version, you may do so by providing a Maven property, as the following example shows: +If you wish to override the Spring Security version, you can do so by providing a Maven property: .pom.xml ==== @@ -57,9 +56,9 @@ If you wish to override the Spring Security version, you may do so by providing ---- ==== -Since Spring Security makes breaking changes only in major releases, it is safe to use a newer version of Spring Security with Spring Boot. +Since Spring Security makes breaking changes only in major releases, you can safely use a newer version of Spring Security with Spring Boot. However, at times, you may need to update the version of Spring Framework as well. -You can do so by adding a Maven property, as the following example shows: +You can do so by adding a Maven property: .pom.xml ==== @@ -77,7 +76,7 @@ If you use additional features (such as LDAP, OpenID, and others), you need to a [[getting-maven-no-boot]] === Maven Without Spring Boot -When you use Spring Security without Spring Boot, the preferred way is to use Spring Security's BOM to ensure a consistent version of Spring Security is used throughout the entire project. The following example shows how to do so: +When you use Spring Security without Spring Boot, the preferred way is to use Spring Security's BOM to ensure that a consistent version of Spring Security is used throughout the entire project. The following example shows how to do so: .pom.xml ==== @@ -98,7 +97,7 @@ When you use Spring Security without Spring Boot, the preferred way is to use Sp ---- ==== -A minimal Spring Security Maven set of dependencies typically looks like the following: +A minimal Spring Security Maven set of dependencies typically looks like the following example: .pom.xml ==== @@ -122,7 +121,7 @@ If you use additional features (such as LDAP, OpenID, and others), you need to a Spring Security builds against Spring Framework {spring-core-version} but should generally work with any newer version of Spring Framework 5.x. Many users are likely to run afoul of the fact that Spring Security's transitive dependencies resolve Spring Framework {spring-core-version}, which can cause strange classpath problems. -The easiest way to resolve this is to use the `spring-framework-bom` within the `` section of your `pom.xml` as the following example shows: +The easiest way to resolve this is to use the `spring-framework-bom` within the `` section of your `pom.xml`: .pom.xml ==== @@ -145,14 +144,17 @@ The easiest way to resolve this is to use the `spring-framework-bom` within the The preceding example ensures that all the transitive dependencies of Spring Security use the Spring {spring-core-version} modules. -NOTE: This approach uses Maven's "`bill of materials`" (BOM) concept and is only available in Maven 2.0.9+. +[NOTE] +==== +This approach uses Maven's "`bill of materials`" (BOM) concept and is only available in Maven 2.0.9+. For additional details about how dependencies are resolved, see https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html[Maven's Introduction to the Dependency Mechanism documentation]. +==== [[maven-repositories]] === Maven Repositories -All GA releases (that is, versions ending in .RELEASE) are deployed to Maven Central, so no additional Maven repositories need to be declared in your pom. +All GA releases (that is, versions ending in .RELEASE) are deployed to Maven Central, so you need not declare additional Maven repositories in your pom. -If you use a SNAPSHOT version, you need to ensure that you have the Spring Snapshot repository defined, as the following example shows: +If you use a SNAPSHOT version, you need to ensure that you have the Spring Snapshot repository defined: .pom.xml ==== @@ -190,15 +192,15 @@ If you use a milestone or release candidate version, you need to ensure that you == Gradle As most open source projects, Spring Security deploys its dependencies as Maven artifacts, which allows for first-class Gradle support. -The following topics provide detail on how to consume Spring Security when using Gradle. +The following topics describe how to consume Spring Security when using Gradle. [[getting-gradle-boot]] === Spring Boot with Gradle -Spring Boot provides a `spring-boot-starter-security` starter that aggregates Spring Security related dependencies together. -The simplest and preferred method to use the starter is to use https://docs.spring.io/initializr/docs/current/reference/html/[Spring Initializr] by using an IDE integration (https://joshlong.com/jl/blogPost/tech_tip_geting_started_with_spring_boot.html[Eclipse], https://www.jetbrains.com/help/idea/spring-boot.html#d1489567e2[IntelliJ], https://github.com/AlexFalappa/nb-springboot/wiki/Quick-Tour[NetBeans]) or through https://start.spring.io. +Spring Boot provides a `spring-boot-starter-security` starter that aggregates Spring Security related dependencies. +The simplest and preferred method to use the starter is to use https://docs.spring.io/initializr/docs/current/reference/htmlsingle/[Spring Initializr] by using an IDE integration in (https://joshlong.com/jl/blogPost/tech_tip_geting_started_with_spring_boot.html[Eclipse] or https://www.jetbrains.com/help/idea/spring-boot.html#d1489567e2[IntelliJ], https://github.com/AlexFalappa/nb-springboot/wiki/Quick-Tour[NetBeans]) or through https://start.spring.io. -Alternatively, you can manually add the starter, as the following example shows: +Alternatively, you can manually add the starter: .build.gradle ==== @@ -212,7 +214,7 @@ dependencies { ==== Since Spring Boot provides a Maven BOM to manage dependency versions, you need not specify a version. -If you wish to override the Spring Security version, you may do so by providing a Gradle property, as the following example shows: +If you wish to override the Spring Security version, you can do so by providing a Gradle property: .build.gradle ==== @@ -223,9 +225,9 @@ ext['spring-security.version']='{spring-security-version}' ---- ==== -Since Spring Security makes breaking changes only in major releases, it is safe to use a newer version of Spring Security with Spring Boot. +Since Spring Security makes breaking changes only in major releases, you can safely use a newer version of Spring Security with Spring Boot. However, at times, you may need to update the version of Spring Framework as well. -You can do so by adding a Gradle property, as the following example shows: +You can do so by adding a Gradle property: .build.gradle ==== @@ -241,7 +243,7 @@ If you use additional features (such as LDAP, OpenID, and others), you need to a === Gradle Without Spring Boot When you use Spring Security without Spring Boot, the preferred way is to use Spring Security's BOM to ensure a consistent version of Spring Security is used throughout the entire project. -You can do so by using the https://github.com/spring-gradle-plugins/dependency-management-plugin[Dependency Management Plugin], as the following example shows: +You can do so by using the https://github.com/spring-gradle-plugins/dependency-management-plugin[Dependency Management Plugin]: .build.gradle ==== @@ -279,7 +281,7 @@ If you use additional features (such as LDAP, OpenID, and others), you need to a Spring Security builds against Spring Framework {spring-core-version} but should generally work with any newer version of Spring Framework 5.x. Many users are likely to run afoul of the fact that Spring Security's transitive dependencies resolve Spring Framework {spring-core-version}, which can cause strange classpath problems. The easiest way to resolve this is to use the `spring-framework-bom` within your `` section of your `pom.xml`. -You can do so by using the https://github.com/spring-gradle-plugins/dependency-management-plugin[Dependency Management Plugin], as the following example shows: +You can do so by using the https://github.com/spring-gradle-plugins/dependency-management-plugin[Dependency Management Plugin]: .build.gradle ==== @@ -302,7 +304,7 @@ The preceding example ensures that all the transitive dependencies of Spring Sec [[gradle-repositories]] === Gradle Repositories -All GA releases (that is, versions ending in .RELEASE) are deployed to Maven Central, so using the mavenCentral() repository is sufficient for GA releases. The following example shows how to do so: +All GA releases (that is, versions ending in .RELEASE) are deployed to Maven Central, so using the `mavenCentral()` repository is sufficient for GA releases. The following example shows how to do so: .build.gradle ==== @@ -314,7 +316,7 @@ repositories { ---- ==== -If you use a SNAPSHOT version, you need to ensure you have the Spring Snapshot repository defined, as the following example shows: +If you use a SNAPSHOT version, you need to ensure that you have the Spring Snapshot repository defined: .build.gradle ==== @@ -326,7 +328,7 @@ repositories { ---- ==== -If you use a milestone or release candidate version, you need to ensure that you have the Spring Milestone repository defined, as the following example shows: +If you use a milestone or release candidate version, you need to ensure that you have the Spring Milestone repository defined: .build.gradle ==== diff --git a/docs/modules/ROOT/pages/modules.adoc b/docs/modules/ROOT/pages/modules.adoc index 3503fea601b..9d02bff889c 100644 --- a/docs/modules/ROOT/pages/modules.adoc +++ b/docs/modules/ROOT/pages/modules.adoc @@ -8,13 +8,13 @@ Even if you do not use Maven, we recommend that you consult the `pom.xml` files Another good idea is to examine the libraries that are included in the sample applications. This section provides a reference of the modules in Spring Security and the additional dependencies that they require in order to function in a running application. -We don't include dependencies that are only used when building or testing Spring Security itself. -Nor do we include transitive dependencies which are required by external dependencies. +We do not include dependencies that are used only when building or testing Spring Security itself. +Nor do we include transitive dependencies that are required by external dependencies. -The version of Spring required is listed on the project website, so the specific versions are omitted for Spring dependencies below. -Note that some of the dependencies listed as "optional" below may still be required for other non-security functionality in a Spring application. -Also dependencies listed as "optional" may not actually be marked as such in the project's Maven POM files if they are used in most applications. -They are "optional" only in the sense that you don't need them unless you are using the specified functionality. +The version of Spring required is listed on the project website, so the specific versions are omitted for Spring dependencies in the examples. +Note that some of the dependencies listed as "`optional`" in the examples may still be required for other non-security functionality in a Spring application +Also dependencies listed as "`optional`" may not actually be marked as such in the project's Maven POM files if they are used in most applications. +They are "`optional`" only in the sense that you do not need them unless you use the specified functionality. Where a module depends on another Spring Security module, the non-optional dependencies of the module it depends on are also assumed to be required and are not listed separately. @@ -105,11 +105,11 @@ The main package is `org.springframework.security.web`. | spring-web | -| Spring web support classes are used extensively. +| Required for clients that use HTTP remoting support. | spring-jdbc | -| Required for JDBC-based persistent remember-me token repository (optional). +| Required for a JDBC-based persistent remember-me token repository (optional). | spring-tx | @@ -170,10 +170,9 @@ The top-level package is `org.springframework.security.ldap`. | | Data exception classes are required. -| apache-ds footnote:[The modules `apacheds-core`, `apacheds-core-entry`, `apacheds-protocol-shared`, `apacheds-protocol-ldap` and `apacheds-server-jndi` are required. -] +| apache-ds | 1.5.5 -| Required if you are using an embedded LDAP server (optional). +| Required if you are using an embedded LDAP server (optional). If you use `apache-ds`, the `apacheds-core`, `apacheds-core-entry`, `apacheds-protocol-shared`, `apacheds-protocol-ldap` and `apacheds-server-jndi` modules are required. | shared-ldap | 0.9.15 @@ -195,8 +194,8 @@ The top-level package is `org.springframework.security.oauth2.core`. [[spring-security-oauth2-client]] == OAuth 2.0 Client -- `spring-security-oauth2-client.jar` `spring-security-oauth2-client.jar` contains Spring Security's client support for OAuth 2.0 Authorization Framework and OpenID Connect Core 1.0. -It is required by applications that use OAuth 2.0 Login or OAuth Client support. -The top-level package is `org.springframework.security.oauth2.client`. +It is required by applications that use OAuth 2.0 or OpenID Connect Core 1.0, such as the client, the resource server, and the authorization server. +The top-level package is `org.springframework.security.oauth2.core`. [[spring-security-oauth2-jose]] @@ -218,7 +217,7 @@ It contains the following top-level packages: [[spring-security-oauth2-resource-server]] == OAuth 2.0 Resource Server -- `spring-security-oauth2-resource-server.jar` `spring-security-oauth2-resource-server.jar` contains Spring Security's support for OAuth 2.0 Resource Servers. -It is used to protect APIs via OAuth 2.0 Bearer Tokens. +It is used to protect APIs by using OAuth 2.0 Bearer Tokens. The top-level package is `org.springframework.security.oauth2.server.resource`. [[spring-security-acl]] @@ -237,7 +236,7 @@ The top-level package is `org.springframework.security.acls`. | ehcache | 1.6.2 -| Required if the Ehcache-based ACL cache implementation is used (optional if you are using your own implementation). +| Required if the Ehcache-based ACL cache implementation is used (optional if you use your own implementation). | spring-jdbc | @@ -278,8 +277,11 @@ This is the basis of the Spring Security integration. [[spring-security-openid]] == OpenID -- `spring-security-openid.jar` + [NOTE] +==== The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2. +==== This module contains OpenID web authentication support. It is used to authenticate users against an external OpenID server. diff --git a/docs/modules/ROOT/pages/reactive/authentication/x509.adoc b/docs/modules/ROOT/pages/reactive/authentication/x509.adoc index 880632b0603..270e3237761 100644 --- a/docs/modules/ROOT/pages/reactive/authentication/x509.adoc +++ b/docs/modules/ROOT/pages/reactive/authentication/x509.adoc @@ -1,9 +1,10 @@ [[reactive-x509]] = Reactive X.509 Authentication -Similar to xref:servlet/authentication/x509.adoc#servlet-x509[Servlet X.509 authentication], reactive x509 authentication filter allows extracting an authentication token from a certificate provided by a client. +Similar to xref:servlet/authentication/x509.adoc#servlet-x509[Servlet X.509 authentication], the reactive x509 authentication filter allows extracting an authentication token from a certificate provided by a client. + +The following example shows a reactive x509 security configuration: -Below is an example of a reactive x509 security configuration: ==== .Java [source,java,role="primary"] @@ -34,9 +35,9 @@ fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { ---- ==== -In the configuration above, when neither `principalExtractor` nor `authenticationManager` is provided defaults will be used. The default principal extractor is `SubjectDnX509PrincipalExtractor` which extracts the CN (common name) field from a certificate provided by a client. The default authentication manager is `ReactivePreAuthenticatedAuthenticationManager` which performs user account validation, checking that user account with a name extracted by `principalExtractor` exists and it is not locked, disabled, or expired. +In the preceding configuration, when neither `principalExtractor` nor `authenticationManager` is provided, defaults are used. The default principal extractor is `SubjectDnX509PrincipalExtractor`, which extracts the CN (common name) field from a certificate provided by a client. The default authentication manager is `ReactivePreAuthenticatedAuthenticationManager`, which performs user account validation, checking that a user account with a name extracted by `principalExtractor` exists and that it is not locked, disabled, or expired. -The next example demonstrates how these defaults can be overridden. +The following example demonstrates how these defaults can be overridden: ==== .Java @@ -90,6 +91,6 @@ fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? { ---- ==== -In this example, a username is extracted from the OU field of a client certificate instead of CN, and account lookup using `ReactiveUserDetailsService` is not performed at all. Instead, if the provided certificate issued to an OU named "Trusted Org Unit", a request will be authenticated. +In the previous example, a username is extracted from the OU field of a client certificate instead of CN, and account lookup using `ReactiveUserDetailsService` is not performed at all. Instead, if the provided certificate issued to an OU named "`Trusted Org Unit`", a request is authenticated. -For an example of configuring Netty and `WebClient` or `curl` command-line tool to use mutual TLS and enable X.509 authentication, please refer to https://github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration/authentication/x509. +For an example of configuring Netty and `WebClient` or `curl` command-line tool to use mutual TLS and enable X.509 authentication, see https://github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration/authentication/x509. diff --git a/docs/modules/ROOT/pages/reactive/authorization/method.adoc b/docs/modules/ROOT/pages/reactive/authorization/method.adoc index dc04d46be62..60d2d3544e4 100644 --- a/docs/modules/ROOT/pages/reactive/authorization/method.adoc +++ b/docs/modules/ROOT/pages/reactive/authorization/method.adoc @@ -1,12 +1,12 @@ [[jc-erms]] = EnableReactiveMethodSecurity -Spring Security supports method security using https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context] which is setup using `ReactiveSecurityContextHolder`. -For example, this demonstrates how to retrieve the currently logged in user's message. +Spring Security supports method security by using https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context], which is set up by `ReactiveSecurityContextHolder`. +The following example shows how to retrieve the currently logged in user's message: [NOTE] ==== -For this to work the return type of the method must be a `org.reactivestreams.Publisher` (i.e. `Mono`/`Flux`) or the function must be a Kotlin coroutine function. +For this example to work, the return type of the method must be a `org.reactivestreams.Publisher` (that is, a `Mono` or a `Flux`) or the function must be a Kotlin coroutine function. This is necessary to integrate with Reactor's `Context`. ==== @@ -45,7 +45,7 @@ StepVerifier.create(messageByUsername) ---- ==== -with `this::findMessageByUsername` defined as: +Where `this::findMessageByUsername` is defined as: ==== .Java @@ -65,7 +65,7 @@ fun findMessageByUsername(username: String): Mono { ---- ==== -Below is a minimal method security configuration when using method security in reactive applications. +The following minimal method security configures method security in reactive applications: ==== .Java @@ -139,7 +139,7 @@ class HelloWorldMessageService { ---- ==== -Or, the following class using Kotlin coroutines: +Alternatively, the following class uses Kotlin coroutines: ==== .Kotlin @@ -157,12 +157,12 @@ class HelloWorldMessageService { ==== -Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` will ensure that `findByMessage` is only invoked by a user with the role `ADMIN`. -It is important to note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`. -However, at this time we only support return type of `Boolean` or `boolean` of the expression. +Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` ensures that `findByMessage` is invoked only by a user with the `ADMIN` role. +Note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`. +However, at this time, we support only a return type of `Boolean` or `boolean` of the expression. This means that the expression must not block. -When integrating with xref:reactive/configuration/webflux.adoc#jc-webflux[WebFlux Security], the Reactor Context is automatically established by Spring Security according to the authenticated user. +When integrating with xref:reactive/configuration/webflux.adoc#jc-webflux[WebFlux Security], the Reactor Context is automatically established by Spring Security according to the authenticated user: ==== .Java @@ -198,7 +198,6 @@ public class SecurityConfig { return new MapReactiveUserDetailsService(rob, admin); } } - ---- .Kotlin @@ -234,4 +233,4 @@ class SecurityConfig { ---- ==== -You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method] +You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method]. diff --git a/docs/modules/ROOT/pages/reactive/configuration/webflux.adoc b/docs/modules/ROOT/pages/reactive/configuration/webflux.adoc index 7cd91bb1922..ea38e27d7bd 100644 --- a/docs/modules/ROOT/pages/reactive/configuration/webflux.adoc +++ b/docs/modules/ROOT/pages/reactive/configuration/webflux.adoc @@ -2,7 +2,7 @@ = WebFlux Security Spring Security's WebFlux support relies on a `WebFilter` and works the same for Spring WebFlux and Spring WebFlux.Fn. -You can find a few sample applications that demonstrate the code below: +A few sample applications demonstrate the code: * Hello WebFlux {gh-samples-url}/reactive/webflux/java/hello-security[hellowebflux] * Hello WebFlux.Fn {gh-samples-url}/reactive/webflux-fn/hello-security[hellowebfluxfn] @@ -11,7 +11,7 @@ You can find a few sample applications that demonstrate the code below: == Minimal WebFlux Security Configuration -You can find a minimal WebFlux Security configuration below: +The following listing shows a minimal WebFlux Security configuration: .Minimal WebFlux Security Configuration ==== @@ -53,11 +53,11 @@ class HelloWebfluxSecurityConfig { ----- ==== -This configuration provides form and http basic authentication, sets up authorization to require an authenticated user for accessing any page, sets up a default log in page and a default log out page, sets up security related HTTP headers, CSRF protection, and more. +This configuration provides form and HTTP basic authentication, sets up authorization to require an authenticated user for accessing any page, sets up a default login page and a default logout page, sets up security related HTTP headers, adds CSRF protection, and more. == Explicit WebFlux Security Configuration -You can find an explicit version of the minimal WebFlux Security configuration below: +The following page shows an explicit version of the minimal WebFlux Security configuration: .Explicit WebFlux Security Configuration ==== @@ -123,16 +123,16 @@ class HelloWebfluxSecurityConfig { ==== This configuration explicitly sets up all the same things as our minimal configuration. -From here you can easily make the changes to the defaults. +From here, you can more easily make changes to the defaults. -You can find more examples of explicit configuration in unit tests, by searching https://github.com/spring-projects/spring-security/search?q=path%3Aconfig%2Fsrc%2Ftest%2F+EnableWebFluxSecurity[EnableWebFluxSecurity in the `config/src/test/` directory]. +You can find more examples of explicit configuration in unit tests, by searching for https://github.com/spring-projects/spring-security/search?q=path%3Aconfig%2Fsrc%2Ftest%2F+EnableWebFluxSecurity[`EnableWebFluxSecurity` in the `config/src/test/` directory]. [[jc-webflux-multiple-filter-chains]] === Multiple Chains Support -You can configure multiple `SecurityWebFilterChain` instances to separate configuration by ``RequestMatcher``s. +You can configure multiple `SecurityWebFilterChain` instances to separate configuration by `RequestMatcher` instances. -For example, you can isolate configuration for URLs that start with `/api`, like so: +For example, you can isolate configuration for URLs that start with `/api`: ==== .Java @@ -211,17 +211,17 @@ open class MultiSecurityHttpConfig { } } ---- -==== <1> Configure a `SecurityWebFilterChain` with an `@Order` to specify which `SecurityWebFilterChain` Spring Security should consider first <2> Use `PathPatternParserServerWebExchangeMatcher` to state that this `SecurityWebFilterChain` will only apply to URL paths that start with `/api/` <3> Specify the authentication mechanisms that will be used for `/api/**` endpoints <4> Create another instance of `SecurityWebFilterChain` with lower precedence to match all other URLs <5> Specify the authentication mechanisms that will be used for the rest of the application +==== -Spring Security will select one `SecurityWebFilterChain` `@Bean` for each request. -It will match the requests in order by the `securityMatcher` definition. +Spring Security selects one `SecurityWebFilterChain` `@Bean` for each request. +It matches the requests in order by the `securityMatcher` definition. -In this case, that means that if the URL path starts with `/api`, then Spring Security will use `apiHttpSecurity`. -If the URL does not start with `/api` then Spring Security will default to `webHttpSecurity`, which has an implied `securityMatcher` that matches any request. +In this case, that means that, if the URL path starts with `/api`, Spring Security uses `apiHttpSecurity`. +If the URL does not start with `/api`, Spring Security defaults to `webHttpSecurity`, which has an implied `securityMatcher` that matches any request. diff --git a/docs/modules/ROOT/pages/reactive/exploits/csrf.adoc b/docs/modules/ROOT/pages/reactive/exploits/csrf.adoc index 6762324171a..662d2bfe738 100644 --- a/docs/modules/ROOT/pages/reactive/exploits/csrf.adoc +++ b/docs/modules/ROOT/pages/reactive/exploits/csrf.adoc @@ -12,27 +12,27 @@ The steps to using Spring Security's CSRF protection are outlined below: * <> [[webflux-csrf-idempotent]] -=== Use proper HTTP verbs +=== Use Proper HTTP Verbs The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. This is covered in detail in xref:features/exploits/csrf.adoc#csrf-protection-idempotent[Safe Methods Must be Idempotent]. [[webflux-csrf-configure]] === Configure CSRF Protection The next step is to configure Spring Security's CSRF protection within your application. -Spring Security's CSRF protection is enabled by default, but you may need to customize the configuration. -Below are a few common customizations. +By default, Spring Security's CSRF protection is enabled, but you may need to customize the configuration. +The next few subsections cover a few common customizations. [[webflux-csrf-configure-custom-repository]] ==== Custom CsrfTokenRepository -By default Spring Security stores the expected CSRF token in the `WebSession` using `WebSessionServerCsrfTokenRepository`. -There can be cases where users will want to configure a custom `ServerCsrfTokenRepository`. -For example, it might be desirable to persist the `CsrfToken` in a cookie to <>. +By default, Spring Security stores the expected CSRF token in the `WebSession` by using `WebSessionServerCsrfTokenRepository`. +Sometimes, you may need to configure a custom `ServerCsrfTokenRepository`. +For example, you may want to persist the `CsrfToken` in a cookie to <>. -By default the `CookieServerCsrfTokenRepository` will write to a cookie named `XSRF-TOKEN` and read it from a header named `X-XSRF-TOKEN` or the HTTP parameter `_csrf`. +By default, the `CookieServerCsrfTokenRepository` writes to a cookie named `XSRF-TOKEN` and read its from a header named `X-XSRF-TOKEN` or the HTTP `_csrf` parameter. These defaults come from https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection[AngularJS] -You can configure `CookieServerCsrfTokenRepository` in Java Configuration using: +You can configure `CookieServerCsrfTokenRepository` in Java Configuration: .Store CSRF Token in a Cookie ==== @@ -65,15 +65,15 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain [NOTE] ==== -The sample explicitly sets `cookieHttpOnly=false`. -This is necessary to allow JavaScript (i.e. AngularJS) to read it. -If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit `cookieHttpOnly=false` (by using `new CookieServerCsrfTokenRepository()` instead) to improve security. +The preceding sample explicitly sets `cookieHttpOnly=false`. +This is necessary to let JavaScript (in this case, AngularJS) to read it. +If you do not need the ability to read the cookie with JavaScript directly, we recommend to omitting `cookieHttpOnly=false` (by using `new CookieServerCsrfTokenRepository()` instead) to improve security. ==== [[webflux-csrf-configure-disable]] ==== Disable CSRF Protection -CSRF protection is enabled by default. -However, it is simple to disable CSRF protection if it xref:features/exploits/csrf.adoc#csrf-when[makes sense for your application]. +By default, CSRF protection is enabled. +However, you can disable CSRF protection if it xref:features/exploits/csrf.adoc#csrf-when[makes sense for your application]. The Java configuration below will disable CSRF protection. @@ -109,15 +109,15 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain [[webflux-csrf-include]] === Include the CSRF Token -In order for the xref:features/exploits/csrf.adoc#csrf-protection-stp[synchronizer token pattern] to protect against CSRF attacks, we must include the actual CSRF token in the HTTP request. -This must be included in a part of the request (i.e. form parameter, HTTP header, etc) that is not automatically included in the HTTP request by the browser. +For the xref:features/exploits/csrf.adoc#csrf-protection-stp[synchronizer token pattern] to protect against CSRF attacks, we must include the actual CSRF token in the HTTP request. +It must be included in a part of the request (a form parameter, an HTTP header, or other option) that is not automatically included in the HTTP request by the browser. -Spring Security's https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/server/csrf/CsrfWebFilter.html[CsrfWebFilter] exposes a https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfToken.html[Mono] as a `ServerWebExchange` attribute named `org.springframework.security.web.server.csrf.CsrfToken`. -This means that any view technology can access the `Mono` to expose the expected token as either a <> or <>. +Spring Security's https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/server/csrf/CsrfWebFilter.html[`CsrfWebFilter`] exposes a https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfToken.html[`Mono`] as a `ServerWebExchange` attribute named `org.springframework.security.web.server.csrf.CsrfToken`. +This means that any view technology can access the `Mono` to expose the expected token as either a <> or a <>. [[webflux-csrf-include-subscribe]] If your view technology does not provide a simple way to subscribe to the `Mono`, a common pattern is to use Spring's `@ControllerAdvice` to expose the `CsrfToken` directly. -For example, the following code will place the `CsrfToken` on the default attribute name (`_csrf`) used by Spring Security's <> to automatically include the CSRF token as a hidden input. +The following example places the `CsrfToken` on the default attribute name (`_csrf`) used by Spring Security's <> to automatically include the CSRF token as a hidden input: .`CsrfToken` as `@ModelAttribute` ==== @@ -155,8 +155,8 @@ Fortunately, Thymeleaf provides <> t [[webflux-csrf-include-form]] ==== Form URL Encoded -In order to post an HTML form the CSRF token must be included in the form as a hidden input. -For example, the rendered HTML might look like: +To post an HTML form, the CSRF token must be included in the form as a hidden input. +The following example shows what the rendered HTML might look like: .CSRF Token HTML ==== @@ -168,22 +168,22 @@ For example, the rendered HTML might look like: ---- ==== -Next we will discuss various ways of including the CSRF token in a form as a hidden input. +Next, we discuss various ways of including the CSRF token in a form as a hidden input. [[webflux-csrf-include-form-auto]] ===== Automatic CSRF Token Inclusion -Spring Security's CSRF support provides integration with Spring's https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/result/view/RequestDataValueProcessor.html[RequestDataValueProcessor] via its https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessor.html[CsrfRequestDataValueProcessor]. -In order for `CsrfRequestDataValueProcessor` to work, the `Mono` must be subscribed to and the `CsrfToken` must be <> that matches https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessor.html#DEFAULT_CSRF_ATTR_NAME[DEFAULT_CSRF_ATTR_NAME]. +Spring Security's CSRF support provides integration with Spring's https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/result/view/RequestDataValueProcessor.html[`RequestDataValueProcessor`] through its https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessor.html[`CsrfRequestDataValueProcessor`]. +For `CsrfRequestDataValueProcessor` to work, the `Mono` must be subscribed to and the `CsrfToken` must be <> that matches https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessor.html#DEFAULT_CSRF_ATTR_NAME[`DEFAULT_CSRF_ATTR_NAME`]. -Fortunately, Thymeleaf https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#integration-with-requestdatavalueprocessor[provides support] to take care of all the boilerplate for you by integrating with `RequestDataValueProcessor` to ensure that forms that have an unsafe HTTP method (i.e. post) will automatically include the actual CSRF token. +Fortunately, Thymeleaf https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#integration-with-requestdatavalueprocessor[takes care of all the boilerplate] for you by integrating with `RequestDataValueProcessor` to ensure that forms that have an unsafe HTTP method (POST) automatically include the actual CSRF token. [[webflux-csrf-include-form-attr]] ===== CsrfToken Request Attribute If the <> for including the actual CSRF token in the request do not work, you can take advantage of the fact that the `Mono` <> as a `ServerWebExchange` attribute named `org.springframework.security.web.server.csrf.CsrfToken`. -The Thymeleaf sample below assumes that you <> the `CsrfToken` on an attribute named `_csrf`. +The following Thymeleaf sample assumes that you <> the `CsrfToken` on an attribute named `_csrf`: .CSRF Token in Form with Request Attribute ==== @@ -202,19 +202,19 @@ The Thymeleaf sample below assumes that you <> to store the expected CSRF token in a cookie. -By storing the expected CSRF in a cookie, JavaScript frameworks like https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection[AngularJS] will automatically include the actual CSRF token in the HTTP request headers. +You can <> Spring Security to store the expected CSRF token in a cookie. +By storing the expected CSRF in a cookie, JavaScript frameworks, such as https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection[AngularJS], automatically include the actual CSRF token in the HTTP request headers. [[webflux-csrf-include-ajax-meta]] -===== Meta tags +===== Meta Tags An alternative pattern to <> is to include the CSRF token within your `meta` tags. The HTML might look something like this: @@ -233,8 +233,8 @@ The HTML might look something like this: ---- ==== -Once the meta tags contained the CSRF token, the JavaScript code would read the meta tags and include the CSRF token as a header. -If you were using jQuery, this could be done with the following: +Once the meta tags contain the CSRF token, the JavaScript code can read the meta tags and include the CSRF token as a header. +If you use jQuery, you could read the meta tags with the following code: .AJAX send CSRF Token ==== @@ -250,8 +250,8 @@ $(function () { ---- ==== -The sample below assumes that you <> the `CsrfToken` on an attribute named `_csrf`. -An example of doing this with Thymeleaf is shown below: +The following sample assumes that you <> the `CsrfToken` on an attribute named `_csrf`. +The following example does this with Thymeleaf: .CSRF meta tag JSP ==== @@ -272,28 +272,28 @@ An example of doing this with Thymeleaf is shown below: == CSRF Considerations There are a few special considerations to consider when implementing protection against CSRF attacks. This section discusses those considerations as it pertains to WebFlux environments. -Refer to xref:features/exploits/csrf.adoc#csrf-considerations[CSRF Considerations] for a more general discussion. +See xref:features/exploits/csrf.adoc#csrf-considerations[CSRF Considerations] for a more general discussion. [[webflux-considerations-csrf-login]] === Logging In -It is important to xref:features/exploits/csrf.adoc#csrf-considerations-login[require CSRF for log in] requests to protect against forging log in attempts. -Spring Security's WebFlux support does this out of the box. +You should xref:features/exploits/csrf.adoc#csrf-considerations-login[require CSRF for login] requests to protect against forged login attempts. +Spring Security's WebFlux support automatically does this. [[webflux-considerations-csrf-logout]] === Logging Out -It is important to xref:features/exploits/csrf.adoc#csrf-considerations-logout[require CSRF for log out] requests to protect against forging log out attempts. -By default Spring Security's `LogoutWebFilter` only processes HTTP post requests. -This ensures that log out requires a CSRF token and that a malicious user cannot forcibly log out your users. +You should xref:features/exploits/csrf.adoc#csrf-considerations-logout[require CSRF for logout] requests to protect against forging logout attempts. +By default, Spring Security's `LogoutWebFilter` only processes only HTTP post requests. +This ensures that logout requires a CSRF token and that a malicious user cannot forcibly log out your users. The easiest approach is to use a form to log out. -If you really want a link, you can use JavaScript to have the link perform a POST (i.e. maybe on a hidden form). -For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that will perform the POST. +If you really want a link, you can use JavaScript to have the link perform a POST (maybe on a hidden form). +For browsers with JavaScript that is disabled, you can optionally have the link take the user to a logout confirmation page that performs the POST. -If you really want to use HTTP GET with logout you can do so, but remember this is generally not recommended. -For example, the following Java Configuration will perform logout with the URL `/logout` is requested with any HTTP method: +If you really want to use HTTP GET with logout, you can do so, but remember that doing so is generally not recommended. +For example, the following Java Configuration logs out when the `/logout` URL is requested with any HTTP method: // FIXME: This should be a link to log out documentation @@ -330,16 +330,16 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain [[webflux-considerations-csrf-timeouts]] === CSRF and Session Timeouts -By default Spring Security stores the CSRF token in the `WebSession`. -This can lead to a situation where the session expires which means there is not an expected CSRF token to validate against. +By default, Spring Security stores the CSRF token in the `WebSession`. +This arrangement can lead to a situation where the session expires, which means that there is not an expected CSRF token to validate against. -We've already discussed xref:features/exploits/csrf.adoc#csrf-considerations-login[general solutions] to session timeouts. +We have already discussed xref:features/exploits/csrf.adoc#csrf-considerations-login[general solutions] to session timeouts. This section discusses the specifics of CSRF timeouts as it pertains to the WebFlux support. -It is simple to change storage of the expected CSRF token to be in a cookie. -For details, refer to the <> section. +You can change storage of the expected CSRF token to be in a cookie. +For details, see the <> section. -// FIXME: We should add a custom AccessDeniedHandler section in the reference and update the links above +// FIXME: We should add a custom AccessDeniedHandler section in the reference and update the earlier links // FIXME: We need a WebFlux multipart body vs action story. WebFlux always has multipart enabled. [[webflux-csrf-considerations-multipart]] @@ -349,7 +349,7 @@ This section discusses how to implement placing the CSRF token in the <. -You can disable `X-XSS-Protection` with the following Configuration: +By default, Spring Security instructs browsers to block reflected XSS attacks by using the <. +You can disable `X-XSS-Protection`: .X-XSS-Protection Customization ==== @@ -293,10 +293,10 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { [[webflux-headers-csp]] == Content Security Policy (CSP) -Spring Security does not add xref:features/exploits/headers.adoc#headers-csp[Content Security Policy] by default, because a reasonable default is impossible to know without context of the application. -The web application author must declare the security policy(s) to enforce and/or monitor for the protected resources. +By default, Spring Security does not add xref:features/exploits/headers.adoc#headers-csp[Content Security Policy], because a reasonable default is impossible to know without the context of the application. +The web application author must declare the security policies to enforce and/or monitor for the protected resources. -For example, given the following security policy: +For example, consider the following security policy: .Content Security Policy Example ==== @@ -306,7 +306,7 @@ Content-Security-Policy: script-src 'self' https://trustedscripts.example.com; o ---- ==== -You can enable the CSP header as shown below: +Given the preceding policy, you can enable the CSP header: .Content Security Policy ==== @@ -385,7 +385,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { [[webflux-headers-referrer]] == Referrer Policy -Spring Security does not add xref:features/exploits/headers.adoc#headers-referrer[Referrer Policy] headers by default. +By default, Spring Security does not add xref:features/exploits/headers.adoc#headers-referrer[Referrer Policy] headers. You can enable the Referrer Policy header using configuration as shown below: .Referrer Policy Configuration @@ -427,8 +427,8 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { [[webflux-headers-feature]] == Feature Policy -Spring Security does not add xref:features/exploits/headers.adoc#headers-feature[Feature Policy] headers by default. -The following `Feature-Policy` header: +By default, Spring Security does not add xref:features/exploits/headers.adoc#headers-feature[Feature Policy] headers. +Consider the following `Feature-Policy` header: .Feature-Policy Example ==== @@ -438,7 +438,7 @@ Feature-Policy: geolocation 'self' ---- ==== -You can enable the Feature Policy header as shown below: +You can enable the preceding Feature Policy header: .Feature-Policy Configuration ==== @@ -475,8 +475,8 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { [[webflux-headers-permissions]] == Permissions Policy -Spring Security does not add xref:features/exploits/headers.adoc#headers-permissions[Permissions Policy] headers by default. -The following `Permissions-Policy` header: +By default, Spring Security does not add xref:features/exploits/headers.adoc#headers-permissions[Permissions Policy] headers. +Consider the following `Permissions-Policy` header: .Permissions-Policy Example ==== @@ -486,7 +486,7 @@ Permissions-Policy: geolocation=(self) ---- ==== -You can enable the Permissions Policy header as shown below: +You can enable the preceding Permissions Policy header: .Permissions-Policy Configuration ==== @@ -527,8 +527,8 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { [[webflux-headers-clear-site-data]] == Clear Site Data -Spring Security does not add xref:features/exploits/headers.adoc#headers-clear-site-data[Clear-Site-Data] headers by default. -The following Clear-Site-Data header: +By default, Spring Security does not add xref:features/exploits/headers.adoc#headers-clear-site-data[Clear-Site-Data] headers. +Consider the following `Clear-Site-Data` header: .Clear-Site-Data Example ==== @@ -537,7 +537,7 @@ Clear-Site-Data: "cache", "cookies" ---- ==== -can be sent on log out with the following configuration: +You can send the `Clear-Site-Data` header on logout: .Clear-Site-Data Configuration ==== diff --git a/docs/modules/ROOT/pages/reactive/exploits/http.adoc b/docs/modules/ROOT/pages/reactive/exploits/http.adoc index e7a07bb20bc..b996ece6cb7 100644 --- a/docs/modules/ROOT/pages/reactive/exploits/http.adoc +++ b/docs/modules/ROOT/pages/reactive/exploits/http.adoc @@ -1,16 +1,16 @@ [[webflux-http]] = HTTP -All HTTP based communication should be protected xref:features/exploits/http.adoc#http[using TLS]. +All HTTP-based communication should be protected with xref:features/exploits/http.adoc#http[using TLS]. -Below you can find details around WebFlux specific features that assist with HTTPS usage. +This section covers details about using WebFlux-specific features that assist with HTTPS usage. [[webflux-http-redirect]] == Redirect to HTTPS -If a client makes a request using HTTP rather than HTTPS, Spring Security can be configured to redirect to HTTPS. +If a client makes a request using HTTP rather than HTTPS, you can configure Spring Security to redirect to HTTPS. -For example, the following Java configuration will redirect any HTTP requests to HTTPS: +The following Java configuration redirects any HTTP requests to HTTPS: .Redirect to HTTPS ==== @@ -39,9 +39,9 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain ---- ==== -The configuration can easily be wrapped around an if statement to only be turned on in production. -Alternatively, it can be enabled by looking for a property about the request that only happens in production. -For example, if the production environment adds a header named `X-Forwarded-Proto` the following Java Configuration could be used: +You can wrap the configuration can be wrapped around an `if` statement to be turned on only in production. +Alternatively, you can enable it by looking for a property about the request that happens only in production. +For example, if the production environment adds a header named `X-Forwarded-Proto`, you should use the following Java Configuration: .Redirect to HTTPS when X-Forwarded ==== diff --git a/docs/modules/ROOT/pages/reactive/integrations/rsocket.adoc b/docs/modules/ROOT/pages/reactive/integrations/rsocket.adoc index eed51eb691e..4bfbe6581a3 100644 --- a/docs/modules/ROOT/pages/reactive/integrations/rsocket.adoc +++ b/docs/modules/ROOT/pages/reactive/integrations/rsocket.adoc @@ -2,9 +2,9 @@ = RSocket Security Spring Security's RSocket support relies on a `SocketAcceptorInterceptor`. -The main entry point into security is found in the `PayloadSocketAcceptorInterceptor` which adapts the RSocket APIs to allow intercepting a `PayloadExchange` with `PayloadInterceptor` implementations. +The main entry point into security is in `PayloadSocketAcceptorInterceptor`, which adapts the RSocket APIs to allow intercepting a `PayloadExchange` with `PayloadInterceptor` implementations. -You can find a few sample applications that demonstrate the code below: +The following example shows a minimal RSocket Security configuration: * Hello RSocket {gh-samples-url}/reactive/rsocket/hello-security[hellorsocket] * https://github.com/rwinch/spring-flights/tree/security[Spring Flights] @@ -17,7 +17,7 @@ You can find a minimal RSocket Security configuration below: ==== .Java [source,java,role="primary"] ------ +---- @Configuration @EnableRSocketSecurity public class HelloRSocketSecurityConfig { @@ -32,7 +32,7 @@ public class HelloRSocketSecurityConfig { return new MapReactiveUserDetailsService(user); } } ------ +---- .Kotlin [source,kotlin,role="secondary"] @@ -57,10 +57,11 @@ This configuration enables < server.interceptors((registry) -> registry.forSocketAcceptor(interceptor)); } ---- +==== [[rsocket-authentication]] == RSocket Authentication -RSocket authentication is performed with `AuthenticationPayloadInterceptor` which acts as a controller to invoke a `ReactiveAuthenticationManager` instance. +RSocket authentication is performed with `AuthenticationPayloadInterceptor`, which acts as a controller to invoke a `ReactiveAuthenticationManager` instance. [[rsocket-authentication-setup-vs-request]] -=== Authentication at Setup vs Request Time +=== Authentication at Setup versus Request Time -Generally, authentication can occur at setup time and/or request time. +Generally, authentication can occur at setup time or at request time or both. Authentication at setup time makes sense in a few scenarios. -A common scenarios is when a single user (i.e. mobile connection) is leveraging an RSocket connection. -In this case only a single user is leveraging the connection, so authentication can be done once at connection time. +A common scenarios is when a single user (such as a mobile connection) uses an RSocket connection. +In this case, only a single user uses the connection, so authentication can be done once at connection time. -In a scenario where the RSocket connection is shared it makes sense to send credentials on each request. -For example, a web application that connects to an RSocket server as a downstream service would make a single connection that all users leverage. -In this case, if the RSocket server needs to perform authorization based on the web application's users credentials per request makes sense. +In a scenario where the RSocket connection is shared, it makes sense to send credentials on each request. +For example, a web application that connects to an RSocket server as a downstream service would make a single connection that all users use. +In this case, if the RSocket server needs to perform authorization based on the web application's users credentials, authentication for each request makes sense. -In some scenarios authentication at setup and per request makes sense. -Consider a web application as described previously. +In some scenarios, authentication at both setup and for each request makes sense. +Consider a web application, as described previously. If we need to restrict the connection to the web application itself, we can provide a credential with a `SETUP` authority at connection time. -Then each user would have different authorities but not the `SETUP` authority. +Then each user can have different authorities but not the `SETUP` authority. This means that individual users can make requests but not make additional connections. [[rsocket-authentication-simple]] === Simple Authentication -Spring Security has support for https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Simple.md[Simple Authentication Metadata Extension]. +Spring Security has support for the https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Simple.md[Simple Authentication Metadata Extension]. [NOTE] ==== -Basic Authentication drafts evolved into Simple Authentication and is only supported for backward compatibility. +Basic Authentication evolved into Simple Authentication and is only supported for backward compatibility. See `RSocketSecurity.basicAuthentication(Customizer)` for setting it up. ==== -The RSocket receiver can decode the credentials using `AuthenticationPayloadExchangeConverter` which is automatically setup using the `simpleAuthentication` portion of the DSL. -An explicit configuration can be found below. +The RSocket receiver can decode the credentials by using `AuthenticationPayloadExchangeConverter`, which is automatically setup by using the `simpleAuthentication` portion of the DSL. +The following example shows an explicit configuration: ==== .Java @@ -140,7 +142,7 @@ open fun rsocketInterceptor(rsocket: RSocketSecurity): PayloadSocketAcceptorInte ---- ==== -The RSocket sender can send credentials using `SimpleAuthenticationEncoder` which can be added to Spring's `RSocketStrategies`. +The RSocket sender can send credentials by using `SimpleAuthenticationEncoder`, which you can add to Spring's `RSocketStrategies`. ==== .Java @@ -158,7 +160,7 @@ strategies.encoder(SimpleAuthenticationEncoder()) ---- ==== -It can then be used to send a username and password to the receiver in the setup: +You can then use it to send a username and password to the receiver in the setup: ==== .Java @@ -227,11 +229,11 @@ open fun findRadar(code: String): Mono { [[rsocket-authentication-jwt]] === JWT -Spring Security has support for https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Bearer.md[Bearer Token Authentication Metadata Extension]. -The support comes in the form of authenticating a JWT (determining the JWT is valid) and then using the JWT to make authorization decisions. +Spring Security has support for the https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Bearer.md[Bearer Token Authentication Metadata Extension]. +The support comes in the form of authenticating a JWT (determining that the JWT is valid) and then using the JWT to make authorization decisions. -The RSocket receiver can decode the credentials using `BearerPayloadExchangeConverter` which is automatically setup using the `jwt` portion of the DSL. -An example configuration can be found below: +The RSocket receiver can decode the credentials by using `BearerPayloadExchangeConverter`, which is automatically setup by using the `jwt` portion of the DSL. +The following listing shows an example configuration: ==== .Java @@ -291,8 +293,8 @@ fun jwtDecoder(): ReactiveJwtDecoder { ---- ==== -The RSocket sender does not need to do anything special to send the token because the value is just a simple String. -For example, the token can be sent at setup time: +The RSocket sender does not need to do anything special to send the token, because the value is a simple `String`. +The following example sends the token at setup time: ==== .Java @@ -319,7 +321,7 @@ val requester = RSocketRequester.builder() ---- ==== -Alternatively or additionally, the token can be sent in a request. +Alternatively or additionally, you can send the token in a request: ==== .Java @@ -360,9 +362,9 @@ open fun findRadar(code: String): Mono { [[rsocket-authorization]] == RSocket Authorization -RSocket authorization is performed with `AuthorizationPayloadInterceptor` which acts as a controller to invoke a `ReactiveAuthorizationManager` instance. -The DSL can be used to setup authorization rules based upon the `PayloadExchange`. -An example configuration can be found below: +RSocket authorization is performed with `AuthorizationPayloadInterceptor`, which acts as a controller to invoke a `ReactiveAuthorizationManager` instance. +You can use the DSL to set up authorization rules based upon the `PayloadExchange`. +The following listing shows an example configuration: ==== .Java @@ -397,18 +399,18 @@ rsocket .anyExchange().permitAll() } // <6> ---- -==== -<1> Setting up a connection requires the authority `ROLE_SETUP` -<2> If the route is `fetch.profile.me` authorization only requires the user be authenticated -<3> In this rule we setup a custom matcher where authorization requires the user to have the authority `ROLE_CUSTOM` -<4> This rule leverages custom authorization. -The matcher expresses a variable with the name `username` that is made available in the `context`. +<1> Setting up a connection requires the `ROLE_SETUP` authority. +<2> If the route is `fetch.profile.me`, authorization only requires the user to be authenticated. +<3> In this rule, we set up a custom matcher, where authorization requires the user to have the `ROLE_CUSTOM` authority. +<4> This rule uses custom authorization. +The matcher expresses a variable with a name of `username` that is made available in the `context`. A custom authorization rule is exposed in the `checkFriends` method. -<5> This rule ensures that request that does not already have a rule will require the user to be authenticated. +<5> This rule ensures that a request that does not already have a rule requires the user to be authenticated. A request is where the metadata is included. It would not include additional payloads. <6> This rule ensures that any exchange that does not already have a rule is allowed for anyone. -In this example, it means that payloads that have no metadata have no authorization rules. +In this example, it means that payloads that have no metadata also have no authorization rules. +==== -It is important to understand that authorization rules are performed in order. -Only the first authorization rule that matches will be invoked. +Note that authorization rules are performed in order. +Only the first authorization rule that matches is invoked. diff --git a/docs/modules/ROOT/pages/reactive/oauth2/oauth2-client.adoc b/docs/modules/ROOT/pages/reactive/oauth2/client/authorization-grants.adoc similarity index 52% rename from docs/modules/ROOT/pages/reactive/oauth2/oauth2-client.adoc rename to docs/modules/ROOT/pages/reactive/oauth2/client/authorization-grants.adoc index a44e3312b39..11fe4d541b2 100644 --- a/docs/modules/ROOT/pages/reactive/oauth2/oauth2-client.adoc +++ b/docs/modules/ROOT/pages/reactive/oauth2/client/authorization-grants.adoc @@ -1,596 +1,21 @@ -[[webflux-oauth2-client]] -= OAuth 2.0 Client - -The OAuth 2.0 Client features provide support for the Client role as defined in the https://tools.ietf.org/html/rfc6749#section-1.1[OAuth 2.0 Authorization Framework]. - -At a high-level, the core features available are: - -.Authorization Grant support -* https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] -* https://tools.ietf.org/html/rfc6749#section-6[Refresh Token] -* https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] -* https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] -* https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[JWT Bearer] - -.Client Authentication support -* https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] - -.HTTP Client support -* <> (for requesting protected resources) - -The `ServerHttpSecurity.oauth2Client()` DSL provides a number of configuration options for customizing the core components used by OAuth 2.0 Client. - -The following code shows the complete configuration options provided by the `ServerHttpSecurity.oauth2Client()` DSL: - -.OAuth2 Client Configuration Options -==== -.Java -[source,java,role="primary"] ----- -@EnableWebFluxSecurity -public class OAuth2ClientSecurityConfig { - - @Bean - public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { - http - .oauth2Client(oauth2 -> oauth2 - .clientRegistrationRepository(this.clientRegistrationRepository()) - .authorizedClientRepository(this.authorizedClientRepository()) - .authorizationRequestRepository(this.authorizationRequestRepository()) - .authenticationConverter(this.authenticationConverter()) - .authenticationManager(this.authenticationManager()) - ); - - return http.build(); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@EnableWebFluxSecurity -class OAuth2ClientSecurityConfig { - - @Bean - fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { - http { - oauth2Client { - clientRegistrationRepository = clientRegistrationRepository() - authorizedClientRepository = authorizedClientRepository() - authorizationRequestRepository = authorizedRequestRepository() - authenticationConverter = authenticationConverter() - authenticationManager = authenticationManager() - } - } - - return http.build() - } -} ----- -==== - -The `ReactiveOAuth2AuthorizedClientManager` is responsible for managing the authorization (or re-authorization) of an OAuth 2.0 Client, in collaboration with one or more `ReactiveOAuth2AuthorizedClientProvider`(s). - -The following code shows an example of how to register a `ReactiveOAuth2AuthorizedClientManager` `@Bean` and associate it with a `ReactiveOAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( - ReactiveClientRegistrationRepository clientRegistrationRepository, - ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { - - ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = - ReactiveOAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build(); - - DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ReactiveClientRegistrationRepository, - authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { - val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build() - val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - -The following sections will go into more detail on the core components used by OAuth 2.0 Client and the configuration options available: - -* <> -** <> -** <> -** <> -** <> -** <> -* <> -** <> -** <> -** <> -** <> -** <> -* <> -** <> -* <> -** <> -* <> - - -[[oauth2Client-core-interface-class]] -== Core Interfaces / Classes - - -[[oauth2Client-client-registration]] -=== ClientRegistration - -`ClientRegistration` is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. - -A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details. - -`ClientRegistration` and its properties are defined as follows: - -[source,java] ----- -public final class ClientRegistration { - private String registrationId; <1> - private String clientId; <2> - private String clientSecret; <3> - private ClientAuthenticationMethod clientAuthenticationMethod; <4> - private AuthorizationGrantType authorizationGrantType; <5> - private String redirectUri; <6> - private Set scopes; <7> - private ProviderDetails providerDetails; - private String clientName; <8> - - public class ProviderDetails { - private String authorizationUri; <9> - private String tokenUri; <10> - private UserInfoEndpoint userInfoEndpoint; - private String jwkSetUri; <11> - private String issuerUri; <12> - private Map configurationMetadata; <13> - - public class UserInfoEndpoint { - private String uri; <14> - private AuthenticationMethod authenticationMethod; <15> - private String userNameAttributeName; <16> - - } - } -} ----- -<1> `registrationId`: The ID that uniquely identifies the `ClientRegistration`. -<2> `clientId`: The client identifier. -<3> `clientSecret`: The client secret. -<4> `clientAuthenticationMethod`: The method used to authenticate the Client with the Provider. -The supported values are *client_secret_basic*, *client_secret_post*, *private_key_jwt*, *client_secret_jwt* and *none* https://tools.ietf.org/html/rfc6749#section-2.1[(public clients)]. -<5> `authorizationGrantType`: The OAuth 2.0 Authorization Framework defines four https://tools.ietf.org/html/rfc6749#section-1.3[Authorization Grant] types. - The supported values are `authorization_code`, `client_credentials`, `password`, as well as, extension grant type `urn:ietf:params:oauth:grant-type:jwt-bearer`. -<6> `redirectUri`: The client's registered redirect URI that the _Authorization Server_ redirects the end-user's user-agent - to after the end-user has authenticated and authorized access to the client. -<7> `scopes`: The scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile. -<8> `clientName`: A descriptive name used for the client. -The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page. -<9> `authorizationUri`: The Authorization Endpoint URI for the Authorization Server. -<10> `tokenUri`: The Token Endpoint URI for the Authorization Server. -<11> `jwkSetUri`: The URI used to retrieve the https://tools.ietf.org/html/rfc7517[JSON Web Key (JWK)] Set from the Authorization Server, - which contains the cryptographic key(s) used to verify the https://tools.ietf.org/html/rfc7515[JSON Web Signature (JWS)] of the ID Token and optionally the UserInfo Response. -<12> `issuerUri`: Returns the issuer identifier uri for the OpenID Connect 1.0 provider or the OAuth 2.0 Authorization Server. -<13> `configurationMetadata`: The https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[OpenID Provider Configuration Information]. - This information will only be available if the Spring Boot 2.x property `spring.security.oauth2.client.provider.[providerId].issuerUri` is configured. -<14> `(userInfoEndpoint)uri`: The UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user. -<15> `(userInfoEndpoint)authenticationMethod`: The authentication method used when sending the access token to the UserInfo Endpoint. -The supported values are *header*, *form* and *query*. -<16> `userNameAttributeName`: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user. - -A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint]. - -`ClientRegistrations` provides convenience methods for configuring a `ClientRegistration` in this way, as can be seen in the following example: - -==== -.Java -[source,java,role="primary"] ----- -ClientRegistration clientRegistration = - ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build(); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build() ----- -==== - -The above code will query in series `https://idp.example.com/issuer/.well-known/openid-configuration`, and then `https://idp.example.com/.well-known/openid-configuration/issuer`, and finally `https://idp.example.com/.well-known/oauth-authorization-server/issuer`, stopping at the first to return a 200 response. - -As an alternative, you can use `ClientRegistrations.fromOidcIssuerLocation()` to only query the OpenID Connect Provider's Configuration endpoint. - -[[oauth2Client-client-registration-repo]] -=== ReactiveClientRegistrationRepository - -The `ReactiveClientRegistrationRepository` serves as a repository for OAuth 2.0 / OpenID Connect 1.0 `ClientRegistration`(s). - -[NOTE] -Client registration information is ultimately stored and owned by the associated Authorization Server. -This repository provides the ability to retrieve a sub-set of the primary client registration information, which is stored with the Authorization Server. - -Spring Boot 2.x auto-configuration binds each of the properties under `spring.security.oauth2.client.registration._[registrationId]_` to an instance of `ClientRegistration` and then composes each of the `ClientRegistration` instance(s) within a `ReactiveClientRegistrationRepository`. - -[NOTE] -The default implementation of `ReactiveClientRegistrationRepository` is `InMemoryReactiveClientRegistrationRepository`. - -The auto-configuration also registers the `ReactiveClientRegistrationRepository` as a `@Bean` in the `ApplicationContext` so that it is available for dependency-injection, if needed by the application. - -The following listing shows an example: - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @Autowired - private ReactiveClientRegistrationRepository clientRegistrationRepository; - - @GetMapping("/") - public Mono index() { - return this.clientRegistrationRepository.findByRegistrationId("okta") - ... - .thenReturn("index"); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - - @Autowired - private lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository - - @GetMapping("/") - fun index(): Mono { - return this.clientRegistrationRepository.findByRegistrationId("okta") - ... - .thenReturn("index") - } -} ----- -==== - -[[oauth2Client-authorized-client]] -=== OAuth2AuthorizedClient - -`OAuth2AuthorizedClient` is a representation of an Authorized Client. -A client is considered to be authorized when the end-user (Resource Owner) has granted authorization to the client to access its protected resources. - -`OAuth2AuthorizedClient` serves the purpose of associating an `OAuth2AccessToken` (and optional `OAuth2RefreshToken`) to a `ClientRegistration` (client) and resource owner, who is the `Principal` end-user that granted the authorization. - - -[[oauth2Client-authorized-repo-service]] -=== ServerOAuth2AuthorizedClientRepository / ReactiveOAuth2AuthorizedClientService - -`ServerOAuth2AuthorizedClientRepository` is responsible for persisting `OAuth2AuthorizedClient`(s) between web requests. -Whereas, the primary role of `ReactiveOAuth2AuthorizedClientService` is to manage `OAuth2AuthorizedClient`(s) at the application-level. - -From a developer perspective, the `ServerOAuth2AuthorizedClientRepository` or `ReactiveOAuth2AuthorizedClientService` provides the capability to lookup an `OAuth2AccessToken` associated with a client so that it may be used to initiate a protected resource request. - -The following listing shows an example: - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @Autowired - private ReactiveOAuth2AuthorizedClientService authorizedClientService; - - @GetMapping("/") - public Mono index(Authentication authentication) { - return this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()) - .map(OAuth2AuthorizedClient::getAccessToken) - ... - .thenReturn("index"); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - - @Autowired - private lateinit var authorizedClientService: ReactiveOAuth2AuthorizedClientService - - @GetMapping("/") - fun index(authentication: Authentication): Mono { - return this.authorizedClientService.loadAuthorizedClient("okta", authentication.name) - .map { it.accessToken } - ... - .thenReturn("index") - } -} ----- -==== - -[NOTE] -Spring Boot 2.x auto-configuration registers an `ServerOAuth2AuthorizedClientRepository` and/or `ReactiveOAuth2AuthorizedClientService` `@Bean` in the `ApplicationContext`. -However, the application may choose to override and register a custom `ServerOAuth2AuthorizedClientRepository` or `ReactiveOAuth2AuthorizedClientService` `@Bean`. - -The default implementation of `ReactiveOAuth2AuthorizedClientService` is `InMemoryReactiveOAuth2AuthorizedClientService`, which stores `OAuth2AuthorizedClient`(s) in-memory. - -Alternatively, the R2DBC implementation `R2dbcReactiveOAuth2AuthorizedClientService` may be configured for persisting `OAuth2AuthorizedClient`(s) in a database. - -[NOTE] -`R2dbcReactiveOAuth2AuthorizedClientService` depends on the table definition described in xref:servlet/appendix/database-schema.adoc#dbschema-oauth2-client[ OAuth 2.0 Client Schema]. - - -[[oauth2Client-authorized-manager-provider]] -=== ReactiveOAuth2AuthorizedClientManager / ReactiveOAuth2AuthorizedClientProvider - -The `ReactiveOAuth2AuthorizedClientManager` is responsible for the overall management of `OAuth2AuthorizedClient`(s). - -The primary responsibilities include: - -* Authorizing (or re-authorizing) an OAuth 2.0 Client, using a `ReactiveOAuth2AuthorizedClientProvider`. -* Delegating the persistence of an `OAuth2AuthorizedClient`, typically using a `ReactiveOAuth2AuthorizedClientService` or `ServerOAuth2AuthorizedClientRepository`. -* Delegating to a `ReactiveOAuth2AuthorizationSuccessHandler` when an OAuth 2.0 Client has been successfully authorized (or re-authorized). -* Delegating to a `ReactiveOAuth2AuthorizationFailureHandler` when an OAuth 2.0 Client fails to authorize (or re-authorize). - -A `ReactiveOAuth2AuthorizedClientProvider` implements a strategy for authorizing (or re-authorizing) an OAuth 2.0 Client. -Implementations will typically implement an authorization grant type, eg. `authorization_code`, `client_credentials`, etc. - -The default implementation of `ReactiveOAuth2AuthorizedClientManager` is `DefaultReactiveOAuth2AuthorizedClientManager`, which is associated with a `ReactiveOAuth2AuthorizedClientProvider` that may support multiple authorization grant types using a delegation-based composite. -The `ReactiveOAuth2AuthorizedClientProviderBuilder` may be used to configure and build the delegation-based composite. - -The following code shows an example of how to configure and build a `ReactiveOAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( - ReactiveClientRegistrationRepository clientRegistrationRepository, - ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { - - ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = - ReactiveOAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build(); - - DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ReactiveClientRegistrationRepository, - authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { - val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build() - val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - -When an authorization attempt succeeds, the `DefaultReactiveOAuth2AuthorizedClientManager` will delegate to the `ReactiveOAuth2AuthorizationSuccessHandler`, which (by default) will save the `OAuth2AuthorizedClient` via the `ServerOAuth2AuthorizedClientRepository`. -In the case of a re-authorization failure, eg. a refresh token is no longer valid, the previously saved `OAuth2AuthorizedClient` will be removed from the `ServerOAuth2AuthorizedClientRepository` via the `RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler`. -The default behaviour may be customized via `setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler)` and `setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler)`. - -The `DefaultReactiveOAuth2AuthorizedClientManager` is also associated with a `contextAttributesMapper` of type `Function>>`, which is responsible for mapping attribute(s) from the `OAuth2AuthorizeRequest` to a `Map` of attributes to be associated to the `OAuth2AuthorizationContext`. -This can be useful when you need to supply a `ReactiveOAuth2AuthorizedClientProvider` with required (supported) attribute(s), eg. the `PasswordReactiveOAuth2AuthorizedClientProvider` requires the resource owner's `username` and `password` to be available in `OAuth2AuthorizationContext.getAttributes()`. - -The following code shows an example of the `contextAttributesMapper`: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( - ReactiveClientRegistrationRepository clientRegistrationRepository, - ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { - - ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = - ReactiveOAuth2AuthorizedClientProviderBuilder.builder() - .password() - .refreshToken() - .build(); - - DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters, - // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` - authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()); - - return authorizedClientManager; -} - -private Function>> contextAttributesMapper() { - return authorizeRequest -> { - Map contextAttributes = Collections.emptyMap(); - ServerWebExchange exchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName()); - ServerHttpRequest request = exchange.getRequest(); - String username = request.getQueryParams().getFirst(OAuth2ParameterNames.USERNAME); - String password = request.getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD); - if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - contextAttributes = new HashMap<>(); - - // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes - contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username); - contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password); - } - return Mono.just(contextAttributes); - }; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ReactiveClientRegistrationRepository, - authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { - val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() - .password() - .refreshToken() - .build() - val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - - // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters, - // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` - authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()) - return authorizedClientManager -} - -private fun contextAttributesMapper(): Function>> { - return Function { authorizeRequest -> - var contextAttributes: MutableMap = mutableMapOf() - val exchange: ServerWebExchange = authorizeRequest.getAttribute(ServerWebExchange::class.java.name)!! - val request: ServerHttpRequest = exchange.request - val username: String? = request.queryParams.getFirst(OAuth2ParameterNames.USERNAME) - val password: String? = request.queryParams.getFirst(OAuth2ParameterNames.PASSWORD) - if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - contextAttributes = hashMapOf() - - // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes - contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username!! - contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password!! - } - Mono.just(contextAttributes) - } -} ----- -==== - -The `DefaultReactiveOAuth2AuthorizedClientManager` is designed to be used *_within_* the context of a `ServerWebExchange`. -When operating *_outside_* of a `ServerWebExchange` context, use `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager` instead. - -A _service application_ is a common use case for when to use an `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager`. -Service applications often run in the background, without any user interaction, and typically run under a system-level account instead of a user account. -An OAuth 2.0 Client configured with the `client_credentials` grant type can be considered a type of service application. - -The following code shows an example of how to configure an `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager` that provides support for the `client_credentials` grant type: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( - ReactiveClientRegistrationRepository clientRegistrationRepository, - ReactiveOAuth2AuthorizedClientService authorizedClientService) { - - ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = - ReactiveOAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials() - .build(); - - AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager = - new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientService); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ReactiveClientRegistrationRepository, - authorizedClientService: ReactiveOAuth2AuthorizedClientService): ReactiveOAuth2AuthorizedClientManager { - val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials() - .build() - val authorizedClientManager = AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientService) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - - [[oauth2Client-auth-grant-support]] -== Authorization Grant Support += Authorization Grant Support [[oauth2Client-auth-code-grant]] -=== Authorization Code +== Authorization Code [NOTE] Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] grant. -==== Obtaining Authorization +=== Obtaining Authorization [NOTE] Please refer to the https://tools.ietf.org/html/rfc6749#section-4.1.1[Authorization Request/Response] protocol flow for the Authorization Code grant. -==== Initiating the Authorization Request +=== Initiating the Authorization Request The `OAuth2AuthorizationRequestRedirectWebFilter` uses a `ServerOAuth2AuthorizationRequestResolver` to resolve an `OAuth2AuthorizationRequest` and initiate the Authorization Code grant flow by redirecting the end-user's user-agent to the Authorization Server's Authorization Endpoint. @@ -671,7 +96,7 @@ spring: Configuring the `redirect-uri` with `URI` template variables is especially useful when the OAuth 2.0 Client is running behind a xref:features/exploits/http.adoc#http-proxy-server[Proxy Server]. This ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`. -==== Customizing the Authorization Request +=== Customizing the Authorization Request One of the primary use cases a `ServerOAuth2AuthorizationRequestResolver` can realize is the ability to customize the Authorization Request with additional parameters above the standard parameters defined in the OAuth 2.0 Authorization Framework. @@ -818,7 +243,7 @@ private fun authorizationRequestCustomizer(): Consumer>`. The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-4.1.3[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the Authorization Code grant are added directly to the body of the request by the `WebClientReactiveAuthorizationCodeTokenResponseClient`. @@ -891,12 +316,12 @@ If you prefer to only add additional parameters, you can instead provide `WebCli IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveAuthorizationCodeTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. -==== Customizing the `WebClient` +=== Customizing the `WebClient` Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveAuthorizationCodeTokenResponseClient.setWebClient()` with a custom configured `WebClient`. @@ -959,13 +384,13 @@ class OAuth2ClientSecurityConfig { [[oauth2Client-refresh-token-grant]] -=== Refresh Token +== Refresh Token [NOTE] Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.5[Refresh Token]. -==== Refreshing an Access Token +=== Refreshing an Access Token [NOTE] Please refer to the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant. @@ -975,7 +400,7 @@ The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the The `WebClientReactiveRefreshTokenTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. -==== Customizing the Access Token Request +=== Customizing the Access Token Request If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveRefreshTokenTokenResponseClient.setParametersConverter()` with a custom `Converter>`. The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-6[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the Refresh Token grant are added directly to the body of the request by the `WebClientReactiveRefreshTokenTokenResponseClient`. @@ -987,12 +412,12 @@ If you prefer to only add additional parameters, you can instead provide `WebCli IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveRefreshTokenTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. -==== Customizing the `WebClient` +=== Customizing the `WebClient` Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveRefreshTokenTokenResponseClient.setWebClient()` with a custom configured `WebClient`. @@ -1043,13 +468,13 @@ If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2Au [[oauth2Client-client-creds-grant]] -=== Client Credentials +== Client Credentials [NOTE] Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] grant. -==== Requesting an Access Token +=== Requesting an Access Token [NOTE] Please refer to the https://tools.ietf.org/html/rfc6749#section-4.4.2[Access Token Request/Response] protocol flow for the Client Credentials grant. @@ -1059,7 +484,7 @@ The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the The `WebClientReactiveClientCredentialsTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. -==== Customizing the Access Token Request +=== Customizing the Access Token Request If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveClientCredentialsTokenResponseClient.setParametersConverter()` with a custom `Converter>`. The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-4.4.2[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the Client Credentials grant are added directly to the body of the request by the `WebClientReactiveClientCredentialsTokenResponseClient`. @@ -1071,12 +496,12 @@ If you prefer to only add additional parameters, you can instead provide `WebCli IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveClientCredentialsTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. -==== Customizing the `WebClient` +=== Customizing the `WebClient` Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveClientCredentialsTokenResponseClient.setWebClient()` with a custom configured `WebClient`. @@ -1119,7 +544,7 @@ authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsReactiveOAuth2AuthorizedClientProvider`, which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Client Credentials grant. -==== Using the Access Token +=== Using the Access Token Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: @@ -1240,13 +665,13 @@ If not provided, it will be obtained from the https://projectreactor.io/docs/cor [[oauth2Client-password-grant]] -=== Resource Owner Password Credentials +== Resource Owner Password Credentials [NOTE] Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] grant. -==== Requesting an Access Token +=== Requesting an Access Token [NOTE] Please refer to the https://tools.ietf.org/html/rfc6749#section-4.3.2[Access Token Request/Response] protocol flow for the Resource Owner Password Credentials grant. @@ -1256,7 +681,7 @@ The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the The `WebClientReactivePasswordTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. -==== Customizing the Access Token Request +=== Customizing the Access Token Request If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactivePasswordTokenResponseClient.setParametersConverter()` with a custom `Converter>`. The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-4.4.2[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the Resource Owner Password Credentials grant are added directly to the body of the request by the `WebClientReactivePasswordTokenResponseClient`. @@ -1268,12 +693,12 @@ If you prefer to only add additional parameters, you can instead provide `WebCli IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactivePasswordTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. -==== Customizing the `WebClient` +=== Customizing the `WebClient` Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactivePasswordTokenResponseClient.setWebClient()` with a custom configured `WebClient`. @@ -1317,7 +742,7 @@ authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) `ReactiveOAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordReactiveOAuth2AuthorizedClientProvider`, which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant. -==== Using the Access Token +=== Using the Access Token Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: @@ -1483,13 +908,13 @@ If not provided, it will be obtained from the https://projectreactor.io/docs/cor [[oauth2Client-jwt-bearer-grant]] -=== JWT Bearer +== JWT Bearer [NOTE] Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on the https://datatracker.ietf.org/doc/html/rfc7523[JWT Bearer] grant. -==== Requesting an Access Token +=== Requesting an Access Token [NOTE] Please refer to the https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[Access Token Request/Response] protocol flow for the JWT Bearer grant. @@ -1499,7 +924,7 @@ The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the The `WebClientReactiveJwtBearerTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. -==== Customizing the Access Token Request +=== Customizing the Access Token Request If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveJwtBearerTokenResponseClient.setParametersConverter()` with a custom `Converter>`. The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard https://tools.ietf.org/html/rfc6749#section-4.4.2[OAuth 2.0 Access Token Request] which is used to construct the request. Other parameters required by the JWT Bearer grant are added directly to the body of the request by the `WebClientReactiveJwtBearerTokenResponseClient`. @@ -1510,12 +935,12 @@ If you prefer to only add additional parameters, you can instead provide `WebCli IMPORTANT: The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveJwtBearerTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. -==== Customizing the `WebClient` +=== Customizing the `WebClient` Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveJwtBearerTokenResponseClient.setWebClient()` with a custom configured `WebClient`. @@ -1560,7 +985,7 @@ authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) ---- ==== -==== Using the Access Token +=== Using the Access Token Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: @@ -1673,408 +1098,3 @@ class OAuth2ResourceServerController { } ---- ==== - - -[[oauth2Client-client-auth-support]] -== Client Authentication Support - - -[[oauth2Client-jwt-bearer-auth]] -=== JWT Bearer - -[NOTE] -Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] Client Authentication. - -The default implementation for JWT Bearer Client Authentication is `NimbusJwtClientAuthenticationParametersConverter`, -which is a `Converter` that customizes the Token Request parameters by adding -a signed JSON Web Token (JWS) in the `client_assertion` parameter. - -The `java.security.PrivateKey` or `javax.crypto.SecretKey` used for signing the JWS -is supplied by the `com.nimbusds.jose.jwk.JWK` resolver associated with `NimbusJwtClientAuthenticationParametersConverter`. - - -==== Authenticate using `private_key_jwt` - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-authentication-method: private_key_jwt - authorization-grant-type: authorization_code - ... ----- - -The following example shows how to configure `WebClientReactiveAuthorizationCodeTokenResponseClient`: - -==== -.Java -[source,java,role="primary"] ----- -Function jwkResolver = (clientRegistration) -> { - if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { - // Assuming RSA key type - RSAPublicKey publicKey = ... - RSAPrivateKey privateKey = ... - return new RSAKey.Builder(publicKey) - .privateKey(privateKey) - .keyID(UUID.randomUUID().toString()) - .build(); - } - return null; -}; - -WebClientReactiveAuthorizationCodeTokenResponseClient tokenResponseClient = - new WebClientReactiveAuthorizationCodeTokenResponseClient(); -tokenResponseClient.addParametersConverter( - new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val jwkResolver: Function = - Function { clientRegistration -> - if (clientRegistration.clientAuthenticationMethod.equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { - // Assuming RSA key type - var publicKey: RSAPublicKey = ... - var privateKey: RSAPrivateKey = ... - RSAKey.Builder(publicKey) - .privateKey(privateKey) - .keyID(UUID.randomUUID().toString()) - .build() - } - null - } - -val tokenResponseClient = WebClientReactiveAuthorizationCodeTokenResponseClient() -tokenResponseClient.addParametersConverter( - NimbusJwtClientAuthenticationParametersConverter(jwkResolver) -) ----- -==== - - -==== Authenticate using `client_secret_jwt` - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-secret: okta-client-secret - client-authentication-method: client_secret_jwt - authorization-grant-type: client_credentials - ... ----- - -The following example shows how to configure `WebClientReactiveClientCredentialsTokenResponseClient`: - -==== -.Java -[source,java,role="primary"] ----- -Function jwkResolver = (clientRegistration) -> { - if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_JWT)) { - SecretKeySpec secretKey = new SecretKeySpec( - clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), - "HmacSHA256"); - return new OctetSequenceKey.Builder(secretKey) - .keyID(UUID.randomUUID().toString()) - .build(); - } - return null; -}; - -WebClientReactiveClientCredentialsTokenResponseClient tokenResponseClient = - new WebClientReactiveClientCredentialsTokenResponseClient(); -tokenResponseClient.addParametersConverter( - new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val jwkResolver = Function { clientRegistration: ClientRegistration -> - if (clientRegistration.clientAuthenticationMethod == ClientAuthenticationMethod.CLIENT_SECRET_JWT) { - val secretKey = SecretKeySpec( - clientRegistration.clientSecret.toByteArray(StandardCharsets.UTF_8), - "HmacSHA256" - ) - OctetSequenceKey.Builder(secretKey) - .keyID(UUID.randomUUID().toString()) - .build() - } - null -} - -val tokenResponseClient = WebClientReactiveClientCredentialsTokenResponseClient() -tokenResponseClient.addParametersConverter( - NimbusJwtClientAuthenticationParametersConverter(jwkResolver) -) ----- -==== - - -[[oauth2Client-additional-features]] -== Additional Features - - -[[oauth2Client-registered-authorized-client]] -=== Resolving an Authorized Client - -The `@RegisteredOAuth2AuthorizedClient` annotation provides the capability of resolving a method parameter to an argument value of type `OAuth2AuthorizedClient`. -This is a convenient alternative compared to accessing the `OAuth2AuthorizedClient` using the `ReactiveOAuth2AuthorizedClientManager` or `ReactiveOAuth2AuthorizedClientService`. - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @GetMapping("/") - public Mono index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { - return Mono.just(authorizedClient.getAccessToken()) - ... - .thenReturn("index"); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - @GetMapping("/") - fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): Mono { - return Mono.just(authorizedClient.accessToken) - ... - .thenReturn("index") - } -} ----- -==== - -The `@RegisteredOAuth2AuthorizedClient` annotation is handled by `OAuth2AuthorizedClientArgumentResolver`, which directly uses a <> and therefore inherits it's capabilities. - - -[[oauth2Client-webclient-webflux]] -== WebClient integration for Reactive Environments - -The OAuth 2.0 Client support integrates with `WebClient` using an `ExchangeFilterFunction`. - -The `ServerOAuth2AuthorizedClientExchangeFilterFunction` provides a simple mechanism for requesting protected resources by using an `OAuth2AuthorizedClient` and including the associated `OAuth2AccessToken` as a Bearer Token. -It directly uses an <> and therefore inherits the following capabilities: - -* An `OAuth2AccessToken` will be requested if the client has not yet been authorized. -** `authorization_code` - triggers the Authorization Request redirect to initiate the flow -** `client_credentials` - the access token is obtained directly from the Token Endpoint -** `password` - the access token is obtained directly from the Token Endpoint -* If the `OAuth2AccessToken` is expired, it will be refreshed (or renewed) if a `ReactiveOAuth2AuthorizedClientProvider` is available to perform the authorization - -The following code shows an example of how to configure `WebClient` with OAuth 2.0 Client support: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { - ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = - new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); - return WebClient.builder() - .filter(oauth2Client) - .build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { - val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) - return WebClient.builder() - .filter(oauth2Client) - .build() -} ----- -==== - -=== Providing the Authorized Client - -The `ServerOAuth2AuthorizedClientExchangeFilterFunction` determines the client to use (for a request) by resolving the `OAuth2AuthorizedClient` from the `ClientRequest.attributes()` (request attributes). - -The following code shows how to set an `OAuth2AuthorizedClient` as a request attribute: - -==== -.Java -[source,java,role="primary"] ----- -@GetMapping("/") -public Mono index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { - String resourceUri = ... - - return webClient - .get() - .uri(resourceUri) - .attributes(oauth2AuthorizedClient(authorizedClient)) <1> - .retrieve() - .bodyToMono(String.class) - ... - .thenReturn("index"); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@GetMapping("/") -fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): Mono { - val resourceUri: String = ... - - return webClient - .get() - .uri(resourceUri) - .attributes(oauth2AuthorizedClient(authorizedClient)) <1> - .retrieve() - .bodyToMono() - ... - .thenReturn("index") -} ----- -==== - -<1> `oauth2AuthorizedClient()` is a `static` method in `ServerOAuth2AuthorizedClientExchangeFilterFunction`. - -The following code shows how to set the `ClientRegistration.getRegistrationId()` as a request attribute: - -==== -.Java -[source,java,role="primary"] ----- -@GetMapping("/") -public Mono index() { - String resourceUri = ... - - return webClient - .get() - .uri(resourceUri) - .attributes(clientRegistrationId("okta")) <1> - .retrieve() - .bodyToMono(String.class) - ... - .thenReturn("index"); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@GetMapping("/") -fun index(): Mono { - val resourceUri: String = ... - - return webClient - .get() - .uri(resourceUri) - .attributes(clientRegistrationId("okta")) <1> - .retrieve() - .bodyToMono() - ... - .thenReturn("index") -} ----- -==== -<1> `clientRegistrationId()` is a `static` method in `ServerOAuth2AuthorizedClientExchangeFilterFunction`. - - -=== Defaulting the Authorized Client - -If neither `OAuth2AuthorizedClient` or `ClientRegistration.getRegistrationId()` is provided as a request attribute, the `ServerOAuth2AuthorizedClientExchangeFilterFunction` can determine the _default_ client to use depending on it's configuration. - -If `setDefaultOAuth2AuthorizedClient(true)` is configured and the user has authenticated using `ServerHttpSecurity.oauth2Login()`, the `OAuth2AccessToken` associated with the current `OAuth2AuthenticationToken` is used. - -The following code shows the specific configuration: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { - ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = - new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); - oauth2Client.setDefaultOAuth2AuthorizedClient(true); - return WebClient.builder() - .filter(oauth2Client) - .build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { - val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) - oauth2Client.setDefaultOAuth2AuthorizedClient(true) - return WebClient.builder() - .filter(oauth2Client) - .build() -} ----- -==== - -[WARNING] -It is recommended to be cautious with this feature since all HTTP requests will receive the access token. - -Alternatively, if `setDefaultClientRegistrationId("okta")` is configured with a valid `ClientRegistration`, the `OAuth2AccessToken` associated with the `OAuth2AuthorizedClient` is used. - -The following code shows the specific configuration: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { - ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = - new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); - oauth2Client.setDefaultClientRegistrationId("okta"); - return WebClient.builder() - .filter(oauth2Client) - .build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { - val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) - oauth2Client.setDefaultClientRegistrationId("okta") - return WebClient.builder() - .filter(oauth2Client) - .build() -} ----- -==== - -[WARNING] -It is recommended to be cautious with this feature since all HTTP requests will receive the access token. diff --git a/docs/modules/ROOT/pages/reactive/oauth2/client/authorized-clients.adoc b/docs/modules/ROOT/pages/reactive/oauth2/client/authorized-clients.adoc new file mode 100644 index 00000000000..ef42bab6a1f --- /dev/null +++ b/docs/modules/ROOT/pages/reactive/oauth2/client/authorized-clients.adoc @@ -0,0 +1,250 @@ +[[oauth2Client-additional-features]] += Authorized Clients + + +[[oauth2Client-registered-authorized-client]] +== Resolving an Authorized Client + +The `@RegisteredOAuth2AuthorizedClient` annotation provides the capability of resolving a method parameter to an argument value of type `OAuth2AuthorizedClient`. +This is a convenient alternative compared to accessing the `OAuth2AuthorizedClient` using the `ReactiveOAuth2AuthorizedClientManager` or `ReactiveOAuth2AuthorizedClientService`. + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @GetMapping("/") + public Mono index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { + return Mono.just(authorizedClient.getAccessToken()) + ... + .thenReturn("index"); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + @GetMapping("/") + fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): Mono { + return Mono.just(authorizedClient.accessToken) + ... + .thenReturn("index") + } +} +---- +==== + +The `@RegisteredOAuth2AuthorizedClient` annotation is handled by `OAuth2AuthorizedClientArgumentResolver`, which directly uses a <> and therefore inherits it's capabilities. + + +[[oauth2Client-webclient-webflux]] +== WebClient integration for Reactive Environments + +The OAuth 2.0 Client support integrates with `WebClient` using an `ExchangeFilterFunction`. + +The `ServerOAuth2AuthorizedClientExchangeFilterFunction` provides a simple mechanism for requesting protected resources by using an `OAuth2AuthorizedClient` and including the associated `OAuth2AccessToken` as a Bearer Token. +It directly uses an <> and therefore inherits the following capabilities: + +* An `OAuth2AccessToken` will be requested if the client has not yet been authorized. +** `authorization_code` - triggers the Authorization Request redirect to initiate the flow +** `client_credentials` - the access token is obtained directly from the Token Endpoint +** `password` - the access token is obtained directly from the Token Endpoint +* If the `OAuth2AccessToken` is expired, it will be refreshed (or renewed) if a `ReactiveOAuth2AuthorizedClientProvider` is available to perform the authorization + +The following code shows an example of how to configure `WebClient` with OAuth 2.0 Client support: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + return WebClient.builder() + .filter(oauth2Client) + .build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { + val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + return WebClient.builder() + .filter(oauth2Client) + .build() +} +---- +==== + +=== Providing the Authorized Client + +The `ServerOAuth2AuthorizedClientExchangeFilterFunction` determines the client to use (for a request) by resolving the `OAuth2AuthorizedClient` from the `ClientRequest.attributes()` (request attributes). + +The following code shows how to set an `OAuth2AuthorizedClient` as a request attribute: + +==== +.Java +[source,java,role="primary"] +---- +@GetMapping("/") +public Mono index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { + String resourceUri = ... + + return webClient + .get() + .uri(resourceUri) + .attributes(oauth2AuthorizedClient(authorizedClient)) <1> + .retrieve() + .bodyToMono(String.class) + ... + .thenReturn("index"); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@GetMapping("/") +fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): Mono { + val resourceUri: String = ... + + return webClient + .get() + .uri(resourceUri) + .attributes(oauth2AuthorizedClient(authorizedClient)) <1> + .retrieve() + .bodyToMono() + ... + .thenReturn("index") +} +---- +==== + +<1> `oauth2AuthorizedClient()` is a `static` method in `ServerOAuth2AuthorizedClientExchangeFilterFunction`. + +The following code shows how to set the `ClientRegistration.getRegistrationId()` as a request attribute: + +==== +.Java +[source,java,role="primary"] +---- +@GetMapping("/") +public Mono index() { + String resourceUri = ... + + return webClient + .get() + .uri(resourceUri) + .attributes(clientRegistrationId("okta")) <1> + .retrieve() + .bodyToMono(String.class) + ... + .thenReturn("index"); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@GetMapping("/") +fun index(): Mono { + val resourceUri: String = ... + + return webClient + .get() + .uri(resourceUri) + .attributes(clientRegistrationId("okta")) <1> + .retrieve() + .bodyToMono() + ... + .thenReturn("index") +} +---- +==== +<1> `clientRegistrationId()` is a `static` method in `ServerOAuth2AuthorizedClientExchangeFilterFunction`. + + +=== Defaulting the Authorized Client + +If neither `OAuth2AuthorizedClient` or `ClientRegistration.getRegistrationId()` is provided as a request attribute, the `ServerOAuth2AuthorizedClientExchangeFilterFunction` can determine the _default_ client to use depending on it's configuration. + +If `setDefaultOAuth2AuthorizedClient(true)` is configured and the user has authenticated using `ServerHttpSecurity.oauth2Login()`, the `OAuth2AccessToken` associated with the current `OAuth2AuthenticationToken` is used. + +The following code shows the specific configuration: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + oauth2Client.setDefaultOAuth2AuthorizedClient(true); + return WebClient.builder() + .filter(oauth2Client) + .build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { + val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + oauth2Client.setDefaultOAuth2AuthorizedClient(true) + return WebClient.builder() + .filter(oauth2Client) + .build() +} +---- +==== + +[WARNING] +It is recommended to be cautious with this feature since all HTTP requests will receive the access token. + +Alternatively, if `setDefaultClientRegistrationId("okta")` is configured with a valid `ClientRegistration`, the `OAuth2AccessToken` associated with the `OAuth2AuthorizedClient` is used. + +The following code shows the specific configuration: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + oauth2Client.setDefaultClientRegistrationId("okta"); + return WebClient.builder() + .filter(oauth2Client) + .build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { + val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + oauth2Client.setDefaultClientRegistrationId("okta") + return WebClient.builder() + .filter(oauth2Client) + .build() +} +---- +==== + +[WARNING] +It is recommended to be cautious with this feature since all HTTP requests will receive the access token. diff --git a/docs/modules/ROOT/pages/reactive/oauth2/client/client-authentication.adoc b/docs/modules/ROOT/pages/reactive/oauth2/client/client-authentication.adoc new file mode 100644 index 00000000000..93bedb5394a --- /dev/null +++ b/docs/modules/ROOT/pages/reactive/oauth2/client/client-authentication.adoc @@ -0,0 +1,151 @@ +[[oauth2Client-client-auth-support]] += Client Authentication Support + + +[[oauth2Client-jwt-bearer-auth]] +== JWT Bearer + +[NOTE] +Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] Client Authentication. + +The default implementation for JWT Bearer Client Authentication is `NimbusJwtClientAuthenticationParametersConverter`, +which is a `Converter` that customizes the Token Request parameters by adding +a signed JSON Web Token (JWS) in the `client_assertion` parameter. + +The `java.security.PrivateKey` or `javax.crypto.SecretKey` used for signing the JWS +is supplied by the `com.nimbusds.jose.jwk.JWK` resolver associated with `NimbusJwtClientAuthenticationParametersConverter`. + + +=== Authenticate using `private_key_jwt` + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-authentication-method: private_key_jwt + authorization-grant-type: authorization_code + ... +---- + +The following example shows how to configure `WebClientReactiveAuthorizationCodeTokenResponseClient`: + +==== +.Java +[source,java,role="primary"] +---- +Function jwkResolver = (clientRegistration) -> { + if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { + // Assuming RSA key type + RSAPublicKey publicKey = ... + RSAPrivateKey privateKey = ... + return new RSAKey.Builder(publicKey) + .privateKey(privateKey) + .keyID(UUID.randomUUID().toString()) + .build(); + } + return null; +}; + +WebClientReactiveAuthorizationCodeTokenResponseClient tokenResponseClient = + new WebClientReactiveAuthorizationCodeTokenResponseClient(); +tokenResponseClient.addParametersConverter( + new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val jwkResolver: Function = + Function { clientRegistration -> + if (clientRegistration.clientAuthenticationMethod.equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { + // Assuming RSA key type + var publicKey: RSAPublicKey = ... + var privateKey: RSAPrivateKey = ... + RSAKey.Builder(publicKey) + .privateKey(privateKey) + .keyID(UUID.randomUUID().toString()) + .build() + } + null + } + +val tokenResponseClient = WebClientReactiveAuthorizationCodeTokenResponseClient() +tokenResponseClient.addParametersConverter( + NimbusJwtClientAuthenticationParametersConverter(jwkResolver) +) +---- +==== + + +=== Authenticate using `client_secret_jwt` + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + client-authentication-method: client_secret_jwt + authorization-grant-type: client_credentials + ... +---- + +The following example shows how to configure `WebClientReactiveClientCredentialsTokenResponseClient`: + +==== +.Java +[source,java,role="primary"] +---- +Function jwkResolver = (clientRegistration) -> { + if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_JWT)) { + SecretKeySpec secretKey = new SecretKeySpec( + clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), + "HmacSHA256"); + return new OctetSequenceKey.Builder(secretKey) + .keyID(UUID.randomUUID().toString()) + .build(); + } + return null; +}; + +WebClientReactiveClientCredentialsTokenResponseClient tokenResponseClient = + new WebClientReactiveClientCredentialsTokenResponseClient(); +tokenResponseClient.addParametersConverter( + new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val jwkResolver = Function { clientRegistration: ClientRegistration -> + if (clientRegistration.clientAuthenticationMethod == ClientAuthenticationMethod.CLIENT_SECRET_JWT) { + val secretKey = SecretKeySpec( + clientRegistration.clientSecret.toByteArray(StandardCharsets.UTF_8), + "HmacSHA256" + ) + OctetSequenceKey.Builder(secretKey) + .keyID(UUID.randomUUID().toString()) + .build() + } + null +} + +val tokenResponseClient = WebClientReactiveClientCredentialsTokenResponseClient() +tokenResponseClient.addParametersConverter( + NimbusJwtClientAuthenticationParametersConverter(jwkResolver) +) +---- +==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/client/core.adoc b/docs/modules/ROOT/pages/reactive/oauth2/client/core.adoc new file mode 100644 index 00000000000..95ce3fd7c6a --- /dev/null +++ b/docs/modules/ROOT/pages/reactive/oauth2/client/core.adoc @@ -0,0 +1,429 @@ +[[oauth2Client-core-interface-class]] += Core Interfaces / Classes + + +[[oauth2Client-client-registration]] +== ClientRegistration + +`ClientRegistration` is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. + +A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details. + +`ClientRegistration` and its properties are defined as follows: + +[source,java] +---- +public final class ClientRegistration { + private String registrationId; <1> + private String clientId; <2> + private String clientSecret; <3> + private ClientAuthenticationMethod clientAuthenticationMethod; <4> + private AuthorizationGrantType authorizationGrantType; <5> + private String redirectUri; <6> + private Set scopes; <7> + private ProviderDetails providerDetails; + private String clientName; <8> + + public class ProviderDetails { + private String authorizationUri; <9> + private String tokenUri; <10> + private UserInfoEndpoint userInfoEndpoint; + private String jwkSetUri; <11> + private String issuerUri; <12> + private Map configurationMetadata; <13> + + public class UserInfoEndpoint { + private String uri; <14> + private AuthenticationMethod authenticationMethod; <15> + private String userNameAttributeName; <16> + + } + } +} +---- +<1> `registrationId`: The ID that uniquely identifies the `ClientRegistration`. +<2> `clientId`: The client identifier. +<3> `clientSecret`: The client secret. +<4> `clientAuthenticationMethod`: The method used to authenticate the Client with the Provider. +The supported values are *client_secret_basic*, *client_secret_post*, *private_key_jwt*, *client_secret_jwt* and *none* https://tools.ietf.org/html/rfc6749#section-2.1[(public clients)]. +<5> `authorizationGrantType`: The OAuth 2.0 Authorization Framework defines four https://tools.ietf.org/html/rfc6749#section-1.3[Authorization Grant] types. + The supported values are `authorization_code`, `client_credentials`, `password`, as well as, extension grant type `urn:ietf:params:oauth:grant-type:jwt-bearer`. +<6> `redirectUri`: The client's registered redirect URI that the _Authorization Server_ redirects the end-user's user-agent + to after the end-user has authenticated and authorized access to the client. +<7> `scopes`: The scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile. +<8> `clientName`: A descriptive name used for the client. +The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page. +<9> `authorizationUri`: The Authorization Endpoint URI for the Authorization Server. +<10> `tokenUri`: The Token Endpoint URI for the Authorization Server. +<11> `jwkSetUri`: The URI used to retrieve the https://tools.ietf.org/html/rfc7517[JSON Web Key (JWK)] Set from the Authorization Server, + which contains the cryptographic key(s) used to verify the https://tools.ietf.org/html/rfc7515[JSON Web Signature (JWS)] of the ID Token and optionally the UserInfo Response. +<12> `issuerUri`: Returns the issuer identifier uri for the OpenID Connect 1.0 provider or the OAuth 2.0 Authorization Server. +<13> `configurationMetadata`: The https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[OpenID Provider Configuration Information]. + This information will only be available if the Spring Boot 2.x property `spring.security.oauth2.client.provider.[providerId].issuerUri` is configured. +<14> `(userInfoEndpoint)uri`: The UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user. +<15> `(userInfoEndpoint)authenticationMethod`: The authentication method used when sending the access token to the UserInfo Endpoint. +The supported values are *header*, *form* and *query*. +<16> `userNameAttributeName`: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user. + +A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint]. + +`ClientRegistrations` provides convenience methods for configuring a `ClientRegistration` in this way, as can be seen in the following example: + +==== +.Java +[source,java,role="primary"] +---- +ClientRegistration clientRegistration = + ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build(); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build() +---- +==== + +The above code will query in series `https://idp.example.com/issuer/.well-known/openid-configuration`, and then `https://idp.example.com/.well-known/openid-configuration/issuer`, and finally `https://idp.example.com/.well-known/oauth-authorization-server/issuer`, stopping at the first to return a 200 response. + +As an alternative, you can use `ClientRegistrations.fromOidcIssuerLocation()` to only query the OpenID Connect Provider's Configuration endpoint. + +[[oauth2Client-client-registration-repo]] +== ReactiveClientRegistrationRepository + +The `ReactiveClientRegistrationRepository` serves as a repository for OAuth 2.0 / OpenID Connect 1.0 `ClientRegistration`(s). + +[NOTE] +Client registration information is ultimately stored and owned by the associated Authorization Server. +This repository provides the ability to retrieve a sub-set of the primary client registration information, which is stored with the Authorization Server. + +Spring Boot 2.x auto-configuration binds each of the properties under `spring.security.oauth2.client.registration._[registrationId]_` to an instance of `ClientRegistration` and then composes each of the `ClientRegistration` instance(s) within a `ReactiveClientRegistrationRepository`. + +[NOTE] +The default implementation of `ReactiveClientRegistrationRepository` is `InMemoryReactiveClientRegistrationRepository`. + +The auto-configuration also registers the `ReactiveClientRegistrationRepository` as a `@Bean` in the `ApplicationContext` so that it is available for dependency-injection, if needed by the application. + +The following listing shows an example: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @Autowired + private ReactiveClientRegistrationRepository clientRegistrationRepository; + + @GetMapping("/") + public Mono index() { + return this.clientRegistrationRepository.findByRegistrationId("okta") + ... + .thenReturn("index"); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + + @Autowired + private lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository + + @GetMapping("/") + fun index(): Mono { + return this.clientRegistrationRepository.findByRegistrationId("okta") + ... + .thenReturn("index") + } +} +---- +==== + +[[oauth2Client-authorized-client]] +== OAuth2AuthorizedClient + +`OAuth2AuthorizedClient` is a representation of an Authorized Client. +A client is considered to be authorized when the end-user (Resource Owner) has granted authorization to the client to access its protected resources. + +`OAuth2AuthorizedClient` serves the purpose of associating an `OAuth2AccessToken` (and optional `OAuth2RefreshToken`) to a `ClientRegistration` (client) and resource owner, who is the `Principal` end-user that granted the authorization. + + +[[oauth2Client-authorized-repo-service]] +== ServerOAuth2AuthorizedClientRepository / ReactiveOAuth2AuthorizedClientService + +`ServerOAuth2AuthorizedClientRepository` is responsible for persisting `OAuth2AuthorizedClient`(s) between web requests. +Whereas, the primary role of `ReactiveOAuth2AuthorizedClientService` is to manage `OAuth2AuthorizedClient`(s) at the application-level. + +From a developer perspective, the `ServerOAuth2AuthorizedClientRepository` or `ReactiveOAuth2AuthorizedClientService` provides the capability to lookup an `OAuth2AccessToken` associated with a client so that it may be used to initiate a protected resource request. + +The following listing shows an example: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @Autowired + private ReactiveOAuth2AuthorizedClientService authorizedClientService; + + @GetMapping("/") + public Mono index(Authentication authentication) { + return this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()) + .map(OAuth2AuthorizedClient::getAccessToken) + ... + .thenReturn("index"); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + + @Autowired + private lateinit var authorizedClientService: ReactiveOAuth2AuthorizedClientService + + @GetMapping("/") + fun index(authentication: Authentication): Mono { + return this.authorizedClientService.loadAuthorizedClient("okta", authentication.name) + .map { it.accessToken } + ... + .thenReturn("index") + } +} +---- +==== + +[NOTE] +Spring Boot 2.x auto-configuration registers an `ServerOAuth2AuthorizedClientRepository` and/or `ReactiveOAuth2AuthorizedClientService` `@Bean` in the `ApplicationContext`. +However, the application may choose to override and register a custom `ServerOAuth2AuthorizedClientRepository` or `ReactiveOAuth2AuthorizedClientService` `@Bean`. + +The default implementation of `ReactiveOAuth2AuthorizedClientService` is `InMemoryReactiveOAuth2AuthorizedClientService`, which stores `OAuth2AuthorizedClient`(s) in-memory. + +Alternatively, the R2DBC implementation `R2dbcReactiveOAuth2AuthorizedClientService` may be configured for persisting `OAuth2AuthorizedClient`(s) in a database. + +[NOTE] +`R2dbcReactiveOAuth2AuthorizedClientService` depends on the table definition described in xref:servlet/appendix/database-schema.adoc#dbschema-oauth2-client[ OAuth 2.0 Client Schema]. + + +[[oauth2Client-authorized-manager-provider]] +== ReactiveOAuth2AuthorizedClientManager / ReactiveOAuth2AuthorizedClientProvider + +The `ReactiveOAuth2AuthorizedClientManager` is responsible for the overall management of `OAuth2AuthorizedClient`(s). + +The primary responsibilities include: + +* Authorizing (or re-authorizing) an OAuth 2.0 Client, using a `ReactiveOAuth2AuthorizedClientProvider`. +* Delegating the persistence of an `OAuth2AuthorizedClient`, typically using a `ReactiveOAuth2AuthorizedClientService` or `ServerOAuth2AuthorizedClientRepository`. +* Delegating to a `ReactiveOAuth2AuthorizationSuccessHandler` when an OAuth 2.0 Client has been successfully authorized (or re-authorized). +* Delegating to a `ReactiveOAuth2AuthorizationFailureHandler` when an OAuth 2.0 Client fails to authorize (or re-authorize). + +A `ReactiveOAuth2AuthorizedClientProvider` implements a strategy for authorizing (or re-authorizing) an OAuth 2.0 Client. +Implementations will typically implement an authorization grant type, eg. `authorization_code`, `client_credentials`, etc. + +The default implementation of `ReactiveOAuth2AuthorizedClientManager` is `DefaultReactiveOAuth2AuthorizedClientManager`, which is associated with a `ReactiveOAuth2AuthorizedClientProvider` that may support multiple authorization grant types using a delegation-based composite. +The `ReactiveOAuth2AuthorizedClientProviderBuilder` may be used to configure and build the delegation-based composite. + +The following code shows an example of how to configure and build a `ReactiveOAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build(); + + DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build() + val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== + +When an authorization attempt succeeds, the `DefaultReactiveOAuth2AuthorizedClientManager` will delegate to the `ReactiveOAuth2AuthorizationSuccessHandler`, which (by default) will save the `OAuth2AuthorizedClient` via the `ServerOAuth2AuthorizedClientRepository`. +In the case of a re-authorization failure, eg. a refresh token is no longer valid, the previously saved `OAuth2AuthorizedClient` will be removed from the `ServerOAuth2AuthorizedClientRepository` via the `RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler`. +The default behaviour may be customized via `setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler)` and `setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler)`. + +The `DefaultReactiveOAuth2AuthorizedClientManager` is also associated with a `contextAttributesMapper` of type `Function>>`, which is responsible for mapping attribute(s) from the `OAuth2AuthorizeRequest` to a `Map` of attributes to be associated to the `OAuth2AuthorizationContext`. +This can be useful when you need to supply a `ReactiveOAuth2AuthorizedClientProvider` with required (supported) attribute(s), eg. the `PasswordReactiveOAuth2AuthorizedClientProvider` requires the resource owner's `username` and `password` to be available in `OAuth2AuthorizationContext.getAttributes()`. + +The following code shows an example of the `contextAttributesMapper`: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build(); + + DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters, + // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()); + + return authorizedClientManager; +} + +private Function>> contextAttributesMapper() { + return authorizeRequest -> { + Map contextAttributes = Collections.emptyMap(); + ServerWebExchange exchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName()); + ServerHttpRequest request = exchange.getRequest(); + String username = request.getQueryParams().getFirst(OAuth2ParameterNames.USERNAME); + String password = request.getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD); + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = new HashMap<>(); + + // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username); + contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password); + } + return Mono.just(contextAttributes); + }; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build() + val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + + // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters, + // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()) + return authorizedClientManager +} + +private fun contextAttributesMapper(): Function>> { + return Function { authorizeRequest -> + var contextAttributes: MutableMap = mutableMapOf() + val exchange: ServerWebExchange = authorizeRequest.getAttribute(ServerWebExchange::class.java.name)!! + val request: ServerHttpRequest = exchange.request + val username: String? = request.queryParams.getFirst(OAuth2ParameterNames.USERNAME) + val password: String? = request.queryParams.getFirst(OAuth2ParameterNames.PASSWORD) + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = hashMapOf() + + // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username!! + contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password!! + } + Mono.just(contextAttributes) + } +} +---- +==== + +The `DefaultReactiveOAuth2AuthorizedClientManager` is designed to be used *_within_* the context of a `ServerWebExchange`. +When operating *_outside_* of a `ServerWebExchange` context, use `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager` instead. + +A _service application_ is a common use case for when to use an `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager`. +Service applications often run in the background, without any user interaction, and typically run under a system-level account instead of a user account. +An OAuth 2.0 Client configured with the `client_credentials` grant type can be considered a type of service application. + +The following code shows an example of how to configure an `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager` that provides support for the `client_credentials` grant type: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ReactiveOAuth2AuthorizedClientService authorizedClientService) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build(); + + AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientService); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientService: ReactiveOAuth2AuthorizedClientService): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build() + val authorizedClientManager = AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientService) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/client/index.adoc b/docs/modules/ROOT/pages/reactive/oauth2/client/index.adoc new file mode 100644 index 00000000000..b04019a5a4f --- /dev/null +++ b/docs/modules/ROOT/pages/reactive/oauth2/client/index.adoc @@ -0,0 +1,123 @@ +[[webflux-oauth2-client]] += OAuth 2.0 Client +:page-section-summary-toc: 1 + +The OAuth 2.0 Client features provide support for the Client role as defined in the https://tools.ietf.org/html/rfc6749#section-1.1[OAuth 2.0 Authorization Framework]. + +At a high-level, the core features available are: + +.Authorization Grant support +* https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] +* https://tools.ietf.org/html/rfc6749#section-6[Refresh Token] +* https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] +* https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] +* https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[JWT Bearer] + +.Client Authentication support +* https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] + +.HTTP Client support +* <> (for requesting protected resources) + +The `ServerHttpSecurity.oauth2Client()` DSL provides a number of configuration options for customizing the core components used by OAuth 2.0 Client. + +The following code shows the complete configuration options provided by the `ServerHttpSecurity.oauth2Client()` DSL: + +.OAuth2 Client Configuration Options +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2ClientSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .oauth2Client(oauth2 -> oauth2 + .clientRegistrationRepository(this.clientRegistrationRepository()) + .authorizedClientRepository(this.authorizedClientRepository()) + .authorizationRequestRepository(this.authorizationRequestRepository()) + .authenticationConverter(this.authenticationConverter()) + .authenticationManager(this.authenticationManager()) + ); + + return http.build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2ClientSecurityConfig { + + @Bean + fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Client { + clientRegistrationRepository = clientRegistrationRepository() + authorizedClientRepository = authorizedClientRepository() + authorizationRequestRepository = authorizedRequestRepository() + authenticationConverter = authenticationConverter() + authenticationManager = authenticationManager() + } + } + + return http.build() + } +} +---- +==== + +The `ReactiveOAuth2AuthorizedClientManager` is responsible for managing the authorization (or re-authorization) of an OAuth 2.0 Client, in collaboration with one or more `ReactiveOAuth2AuthorizedClientProvider`(s). + +The following code shows an example of how to register a `ReactiveOAuth2AuthorizedClientManager` `@Bean` and associate it with a `ReactiveOAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build(); + + DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build() + val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/index.adoc b/docs/modules/ROOT/pages/reactive/oauth2/index.adoc index af06df5136b..592bc9fbab7 100644 --- a/docs/modules/ROOT/pages/reactive/oauth2/index.adoc +++ b/docs/modules/ROOT/pages/reactive/oauth2/index.adoc @@ -3,6 +3,6 @@ Spring Security provides OAuth2 and WebFlux integration for reactive applications. -* xref:reactive/oauth2/login.adoc[OAuth2 Log In] - Authenticating with an OAuth2 or OpenID Connect 1.0 Provider -* xref:reactive/oauth2/oauth2-client.adoc[OAuth2 Client] - Making requests to an OAuth2 Resource Server +* xref:reactive/oauth2/login/index.adoc[OAuth2 Log In] - Authenticating with an OAuth2 or OpenID Connect 1.0 Provider +* xref:reactive/oauth2/client/index.adoc[OAuth2 Client] - Making requests to an OAuth2 Resource Server * xref:reactive/oauth2/resource-server/index.adoc[OAuth2 Resource Server] - Protecting a REST endpoint using OAuth2 diff --git a/docs/modules/ROOT/pages/reactive/oauth2/login.adoc b/docs/modules/ROOT/pages/reactive/oauth2/login.adoc deleted file mode 100644 index a16160c0ff7..00000000000 --- a/docs/modules/ROOT/pages/reactive/oauth2/login.adoc +++ /dev/null @@ -1,245 +0,0 @@ -[[webflux-oauth2-login]] -= OAuth 2.0 Login - -The OAuth 2.0 Login feature provides an application with the capability to have users log in to the application by using their existing account at an OAuth 2.0 Provider (e.g. -GitHub) or OpenID Connect 1.0 Provider (such as Google). -OAuth 2.0 Login implements the use cases: "Login with Google" or "Login with GitHub". - -NOTE: OAuth 2.0 Login is implemented by using the *Authorization Code Grant*, as specified in the https://tools.ietf.org/html/rfc6749#section-4.1[OAuth 2.0 Authorization Framework] and https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth[OpenID Connect Core 1.0]. - -[[webflux-oauth2-login-sample]] -== Spring Boot 2.0 Sample - -Spring Boot 2.0 brings full auto-configuration capabilities for OAuth 2.0 Login. - -This section shows how to configure the {gh-samples-url}/reactive/webflux/java/oauth2/login[*OAuth 2.0 Login WebFlux sample*] using _Google_ as the _Authentication Provider_ and covers the following topics: - -* <> -* <> -* <> -* <> - - -[[webflux-oauth2-login-sample-setup]] -=== Initial setup - -To use Google's OAuth 2.0 authentication system for login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials. - -NOTE: https://developers.google.com/identity/protocols/OpenIDConnect[Google's OAuth 2.0 implementation] for authentication conforms to the https://openid.net/connect/[OpenID Connect 1.0] specification and is https://openid.net/certification/[OpenID Certified]. - -Follow the instructions on the https://developers.google.com/identity/protocols/OpenIDConnect[OpenID Connect] page, starting in the section, "Setting up OAuth 2.0". - -After completing the "Obtain OAuth 2.0 credentials" instructions, you should have a new OAuth Client with credentials consisting of a Client ID and a Client Secret. - -[[webflux-oauth2-login-sample-redirect]] -=== Setting the redirect URI - -The redirect URI is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with Google and have granted access to the OAuth Client _(<>)_ on the Consent page. - -In the "Set a redirect URI" sub-section, ensure that the *Authorized redirect URIs* field is set to `http://localhost:8080/login/oauth2/code/google`. - -TIP: The default redirect URI template is `+{baseUrl}/login/oauth2/code/{registrationId}+`. -The *_registrationId_* is a unique identifier for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration]. -For our example, the `registrationId` is `google`. - -IMPORTANT: If the OAuth Client is running behind a proxy server, it is recommended to check xref:features/exploits/http.adoc#http-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured. -Also, see the supported xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. - -[[webflux-oauth2-login-sample-config]] -=== Configure `application.yml` - -Now that you have a new OAuth Client with Google, you need to configure the application to use the OAuth Client for the _authentication flow_. -To do so: - -. Go to `application.yml` and set the following configuration: -+ -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: <1> - google: <2> - client-id: google-client-id - client-secret: google-client-secret ----- -+ -.OAuth Client properties -==== -<1> `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties. -<2> Following the base property prefix is the ID for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration], such as google. -==== - -. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. - - -[[webflux-oauth2-login-sample-start]] -=== Boot up the application - -Launch the Spring Boot 2.0 sample and go to `http://localhost:8080`. -You are then redirected to the default _auto-generated_ login page, which displays a link for Google. - -Click on the Google link, and you are then redirected to Google for authentication. - -After authenticating with your Google account credentials, the next page presented to you is the Consent screen. -The Consent screen asks you to either allow or deny access to the OAuth Client you created earlier. -Click *Allow* to authorize the OAuth Client to access your email address and basic profile information. - -At this point, the OAuth Client retrieves your email address and basic profile information from the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session. - -[[webflux-oauth2-login-openid-provider-configuration]] -== Using OpenID Provider Configuration - -For well known providers, Spring Security provides the necessary defaults for the OAuth Authorization Provider's configuration. -If you are working with your own Authorization Provider that supports https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[OpenID Provider Configuration] or https://tools.ietf.org/html/rfc8414#section-3[Authorization Server Metadata], the https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse[OpenID Provider Configuration Response]'s `issuer-uri` can be used to configure the application. - -[source,yml] ----- -spring: - security: - oauth2: - client: - provider: - keycloak: - issuer-uri: https://idp.example.com/auth/realms/demo - registration: - keycloak: - client-id: spring-security - client-secret: 6cea952f-10d0-4d00-ac79-cc865820dc2c ----- - -The `issuer-uri` instructs Spring Security to query in series the endpoints `https://idp.example.com/auth/realms/demo/.well-known/openid-configuration`, `https://idp.example.com/.well-known/openid-configuration/auth/realms/demo`, or `https://idp.example.com/.well-known/oauth-authorization-server/auth/realms/demo` to discover the configuration. - -[NOTE] -Spring Security will query the endpoints one at a time, stopping at the first that gives a 200 response. - -The `client-id` and `client-secret` are linked to the provider because `keycloak` is used for both the provider and the registration. - - -[[webflux-oauth2-login-explicit]] -== Explicit OAuth2 Login Configuration - -A minimal OAuth2 Login configuration is shown below: - -.Minimal OAuth2 Login -==== -.Java -[source,java,role="primary"] ----- -@Bean -ReactiveClientRegistrationRepository clientRegistrations() { - ClientRegistration clientRegistration = ClientRegistrations - .fromIssuerLocation("https://idp.example.com/auth/realms/demo") - .clientId("spring-security") - .clientSecret("6cea952f-10d0-4d00-ac79-cc865820dc2c") - .build(); - return new InMemoryReactiveClientRegistrationRepository(clientRegistration); -} - -@Bean -SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http - // ... - .oauth2Login(withDefaults()); - return http.build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun clientRegistrations(): ReactiveClientRegistrationRepository { - val clientRegistration: ClientRegistration = ClientRegistrations - .fromIssuerLocation("https://idp.example.com/auth/realms/demo") - .clientId("spring-security") - .clientSecret("6cea952f-10d0-4d00-ac79-cc865820dc2c") - .build() - return InMemoryReactiveClientRegistrationRepository(clientRegistration) -} - -@Bean -fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { - return http { - oauth2Login { } - } -} ----- -==== - -Additional configuration options can be seen below: - -.Advanced OAuth2 Login -==== -.Java -[source,java,role="primary"] ----- -@Bean -SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http - // ... - .oauth2Login(oauth2 -> oauth2 - .authenticationConverter(converter) - .authenticationManager(manager) - .authorizedClientRepository(authorizedClients) - .clientRegistrationRepository(clientRegistrations) - ); - return http.build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { - return http { - oauth2Login { - authenticationConverter = converter - authenticationManager = manager - authorizedClientRepository = authorizedClients - clientRegistrationRepository = clientRegistration - } - } -} ----- -==== - -You may register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the default configuration, as shown in the following example: - -.GrantedAuthoritiesMapper Bean -==== -.Java -[source,java,role="primary"] ----- -@Bean -public GrantedAuthoritiesMapper userAuthoritiesMapper() { - ... -} - -@Bean -SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http - // ... - .oauth2Login(withDefaults()); - return http.build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun userAuthoritiesMapper(): GrantedAuthoritiesMapper { - // ... -} - -@Bean -fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { - return http { - oauth2Login { } - } -} ----- -==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/login/advanced.adoc b/docs/modules/ROOT/pages/reactive/oauth2/login/advanced.adoc new file mode 100644 index 00000000000..1b73b2c9a4d --- /dev/null +++ b/docs/modules/ROOT/pages/reactive/oauth2/login/advanced.adoc @@ -0,0 +1,759 @@ +[[webflux-oauth2-login-advanced]] += Advanced Configuration + +The OAuth 2.0 Authorization Framework defines the https://tools.ietf.org/html/rfc6749#section-3[Protocol Endpoints] as follows: + +The authorization process utilizes two authorization server endpoints (HTTP resources): + +* Authorization Endpoint: Used by the client to obtain authorization from the resource owner via user-agent redirection. +* Token Endpoint: Used by the client to exchange an authorization grant for an access token, typically with client authentication. + +As well as one client endpoint: + +* Redirection Endpoint: Used by the authorization server to return responses containing authorization credentials to the client via the resource owner user-agent. + +The OpenID Connect Core 1.0 specification defines the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] as follows: + +The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns claims about the authenticated end-user. +To obtain the requested claims about the end-user, the client makes a request to the UserInfo Endpoint by using an access token obtained through OpenID Connect Authentication. +These claims are normally represented by a JSON object that contains a collection of name-value pairs for the claims. + +`ServerHttpSecurity.oauth2Login()` provides a number of configuration options for customizing OAuth 2.0 Login. + +The following code shows the complete configuration options available for the `oauth2Login()` DSL: + +.OAuth2 Login Configuration Options +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .oauth2Login(oauth2 -> oauth2 + .authenticationConverter(this.authenticationConverter()) + .authenticationMatcher(this.authenticationMatcher()) + .authenticationManager(this.authenticationManager()) + .authenticationSuccessHandler(this.authenticationSuccessHandler()) + .authenticationFailureHandler(this.authenticationFailureHandler()) + .clientRegistrationRepository(this.clientRegistrationRepository()) + .authorizedClientRepository(this.authorizedClientRepository()) + .authorizedClientService(this.authorizedClientService()) + .authorizationRequestResolver(this.authorizationRequestResolver()) + .authorizationRequestRepository(this.authorizationRequestRepository()) + .securityContextRepository(this.securityContextRepository()) + ); + + return http.build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { + authenticationConverter = authenticationConverter() + authenticationMatcher = authenticationMatcher() + authenticationManager = authenticationManager() + authenticationSuccessHandler = authenticationSuccessHandler() + authenticationFailureHandler = authenticationFailureHandler() + clientRegistrationRepository = clientRegistrationRepository() + authorizedClientRepository = authorizedClientRepository() + authorizedClientService = authorizedClientService() + authorizationRequestResolver = authorizationRequestResolver() + authorizationRequestRepository = authorizationRequestRepository() + securityContextRepository = securityContextRepository() + } + } + + return http.build() + } +} +---- +==== + +The following sections go into more detail on each of the configuration options available: + +* <> +* <> +* <> +* <> +* <> + + +[[webflux-oauth2-login-advanced-login-page]] +== OAuth 2.0 Login Page + +By default, the OAuth 2.0 Login Page is auto-generated by the `LoginPageGeneratingWebFilter`. +The default login page shows each configured OAuth Client with its `ClientRegistration.clientName` as a link, which is capable of initiating the Authorization Request (or OAuth 2.0 Login). + +[NOTE] +In order for `LoginPageGeneratingWebFilter` to show links for configured OAuth Clients, the registered `ReactiveClientRegistrationRepository` needs to also implement `Iterable`. +See `InMemoryReactiveClientRegistrationRepository` for reference. + +The link's destination for each OAuth Client defaults to the following: + +`+"/oauth2/authorization/{registrationId}"+` + +The following line shows an example: + +[source,html] +---- +Google +---- + +To override the default login page, configure the `exceptionHandling().authenticationEntryPoint()` and (optionally) `oauth2Login().authorizationRequestResolver()`. + +The following listing shows an example: + +.OAuth2 Login Page Configuration +==== +.Java +[source,java,role="primary",subs="-attributes"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .exceptionHandling(exceptionHandling -> exceptionHandling + .authenticationEntryPoint(new RedirectServerAuthenticationEntryPoint("/login/oauth2")) + ) + .oauth2Login(oauth2 -> oauth2 + .authorizationRequestResolver(this.authorizationRequestResolver()) + ); + + return http.build(); + } + + private ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver() { + ServerWebExchangeMatcher authorizationRequestMatcher = + new PathPatternParserServerWebExchangeMatcher( + "/login/oauth2/authorization/{registrationId}"); + + return new DefaultServerOAuth2AuthorizationRequestResolver( + this.clientRegistrationRepository(), authorizationRequestMatcher); + } + + ... +} +---- + +.Kotlin +[source,kotlin,role="secondary",subs="-attributes"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + exceptionHandling { + authenticationEntryPoint = RedirectServerAuthenticationEntryPoint("/login/oauth2") + } + oauth2Login { + authorizationRequestResolver = authorizationRequestResolver() + } + } + + return http.build() + } + + private fun authorizationRequestResolver(): ServerOAuth2AuthorizationRequestResolver { + val authorizationRequestMatcher: ServerWebExchangeMatcher = PathPatternParserServerWebExchangeMatcher( + "/login/oauth2/authorization/{registrationId}" + ) + + return DefaultServerOAuth2AuthorizationRequestResolver( + clientRegistrationRepository(), authorizationRequestMatcher + ) + } + + ... +} +---- +==== + +[IMPORTANT] +You need to provide a `@Controller` with a `@RequestMapping("/login/oauth2")` that is capable of rendering the custom login page. + +[TIP] +==== +As noted earlier, configuring `oauth2Login().authorizationRequestResolver()` is optional. +However, if you choose to customize it, ensure the link to each OAuth Client matches the pattern provided through the `ServerWebExchangeMatcher`. + +The following line shows an example: + +[source,html] +---- +Google +---- +==== + + +[[webflux-oauth2-login-advanced-redirection-endpoint]] +== Redirection Endpoint + +The Redirection Endpoint is used by the Authorization Server for returning the Authorization Response (which contains the authorization credentials) to the client via the Resource Owner user-agent. + +[TIP] +OAuth 2.0 Login leverages the Authorization Code Grant. +Therefore, the authorization credential is the authorization code. + +The default Authorization Response redirection endpoint is `+/login/oauth2/code/{registrationId}+`. + +If you would like to customize the Authorization Response redirection endpoint, configure it as shown in the following example: + +.Redirection Endpoint Configuration +==== +.Java +[source,java,role="primary",subs="-attributes"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .oauth2Login(oauth2 -> oauth2 + .authenticationMatcher(new PathPatternParserServerWebExchangeMatcher("/login/oauth2/callback/{registrationId}")) + ); + + return http.build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary",subs="-attributes"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { + authenticationMatcher = PathPatternParserServerWebExchangeMatcher("/login/oauth2/callback/{registrationId}") + } + } + + return http.build() + } +} +---- +==== + +[IMPORTANT] +==== +You also need to ensure the `ClientRegistration.redirectUri` matches the custom Authorization Response redirection endpoint. + +The following listing shows an example: + +.Java +[source,java,role="primary",subs="-attributes"] +---- +return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}") + .build(); +---- + +.Kotlin +[source,kotlin,role="secondary",subs="-attributes"] +---- +return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}") + .build() +---- +==== + + +[[webflux-oauth2-login-advanced-userinfo-endpoint]] +== UserInfo Endpoint + +The UserInfo Endpoint includes a number of configuration options, as described in the following sub-sections: + +* <> +* <> +* <> + + +[[webflux-oauth2-login-advanced-map-authorities]] +=== Mapping User Authorities + +After the user successfully authenticates with the OAuth 2.0 Provider, the `OAuth2User.getAuthorities()` (or `OidcUser.getAuthorities()`) may be mapped to a new set of `GrantedAuthority` instances, which will be supplied to `OAuth2AuthenticationToken` when completing the authentication. + +[TIP] +`OAuth2AuthenticationToken.getAuthorities()` is used for authorizing requests, such as in `hasRole('USER')` or `hasRole('ADMIN')`. + +There are a couple of options to choose from when mapping user authorities: + +* <> +* <> + + +[[webflux-oauth2-login-advanced-map-authorities-grantedauthoritiesmapper]] +==== Using a GrantedAuthoritiesMapper + +Register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the configuration, as shown in the following example: + +.Granted Authorities Mapper Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public GrantedAuthoritiesMapper userAuthoritiesMapper() { + return (authorities) -> { + Set mappedAuthorities = new HashSet<>(); + + authorities.forEach(authority -> { + if (OidcUserAuthority.class.isInstance(authority)) { + OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority; + + OidcIdToken idToken = oidcUserAuthority.getIdToken(); + OidcUserInfo userInfo = oidcUserAuthority.getUserInfo(); + + // Map the claims found in idToken and/or userInfo + // to one or more GrantedAuthority's and add it to mappedAuthorities + + } else if (OAuth2UserAuthority.class.isInstance(authority)) { + OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority; + + Map userAttributes = oauth2UserAuthority.getAttributes(); + + // Map the attributes found in userAttributes + // to one or more GrantedAuthority's and add it to mappedAuthorities + + } + }); + + return mappedAuthorities; + }; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { } + } + + return http.build() + } + + @Bean + fun userAuthoritiesMapper(): GrantedAuthoritiesMapper = GrantedAuthoritiesMapper { authorities: Collection -> + val mappedAuthorities = emptySet() + + authorities.forEach { authority -> + if (authority is OidcUserAuthority) { + val idToken = authority.idToken + val userInfo = authority.userInfo + // Map the claims found in idToken and/or userInfo + // to one or more GrantedAuthority's and add it to mappedAuthorities + } else if (authority is OAuth2UserAuthority) { + val userAttributes = authority.attributes + // Map the attributes found in userAttributes + // to one or more GrantedAuthority's and add it to mappedAuthorities + } + } + + mappedAuthorities + } +} +---- +==== + +[[webflux-oauth2-login-advanced-map-authorities-reactiveoauth2userservice]] +==== Delegation-based strategy with ReactiveOAuth2UserService + +This strategy is advanced compared to using a `GrantedAuthoritiesMapper`, however, it's also more flexible as it gives you access to the `OAuth2UserRequest` and `OAuth2User` (when using an OAuth 2.0 UserService) or `OidcUserRequest` and `OidcUser` (when using an OpenID Connect 1.0 UserService). + +The `OAuth2UserRequest` (and `OidcUserRequest`) provides you access to the associated `OAuth2AccessToken`, which is very useful in the cases where the _delegator_ needs to fetch authority information from a protected resource before it can map the custom authorities for the user. + +The following example shows how to implement and configure a delegation-based strategy using an OpenID Connect 1.0 UserService: + +.ReactiveOAuth2UserService Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveOAuth2UserService oidcUserService() { + final OidcReactiveOAuth2UserService delegate = new OidcReactiveOAuth2UserService(); + + return (userRequest) -> { + // Delegate to the default implementation for loading a user + return delegate.loadUser(userRequest) + .flatMap((oidcUser) -> { + OAuth2AccessToken accessToken = userRequest.getAccessToken(); + Set mappedAuthorities = new HashSet<>(); + + // TODO + // 1) Fetch the authority information from the protected resource using accessToken + // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities + + // 3) Create a copy of oidcUser but use the mappedAuthorities instead + oidcUser = new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo()); + + return Mono.just(oidcUser); + }); + }; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { } + } + + return http.build() + } + + @Bean + fun oidcUserService(): ReactiveOAuth2UserService { + val delegate = OidcReactiveOAuth2UserService() + + return ReactiveOAuth2UserService { userRequest -> + // Delegate to the default implementation for loading a user + delegate.loadUser(userRequest) + .flatMap { oidcUser -> + val accessToken = userRequest.accessToken + val mappedAuthorities = mutableSetOf() + + // TODO + // 1) Fetch the authority information from the protected resource using accessToken + // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities + // 3) Create a copy of oidcUser but use the mappedAuthorities instead + val mappedOidcUser = DefaultOidcUser(mappedAuthorities, oidcUser.idToken, oidcUser.userInfo) + + Mono.just(mappedOidcUser) + } + } + } +} +---- +==== + + +[[webflux-oauth2-login-advanced-oauth2-user-service]] +=== OAuth 2.0 UserService + +`DefaultReactiveOAuth2UserService` is an implementation of a `ReactiveOAuth2UserService` that supports standard OAuth 2.0 Provider's. + +[NOTE] +`ReactiveOAuth2UserService` obtains the user attributes of the end-user (the resource owner) from the UserInfo Endpoint (by using the access token granted to the client during the authorization flow) and returns an `AuthenticatedPrincipal` in the form of an `OAuth2User`. + +`DefaultReactiveOAuth2UserService` uses a `WebClient` when requesting the user attributes at the UserInfo Endpoint. + +If you need to customize the pre-processing of the UserInfo Request and/or the post-handling of the UserInfo Response, you will need to provide `DefaultReactiveOAuth2UserService.setWebClient()` with a custom configured `WebClient`. + +Whether you customize `DefaultReactiveOAuth2UserService` or provide your own implementation of `ReactiveOAuth2UserService`, you'll need to configure it as shown in the following example: + +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveOAuth2UserService oauth2UserService() { + ... + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { } + } + + return http.build() + } + + @Bean + fun oauth2UserService(): ReactiveOAuth2UserService { + // ... + } +} +---- +==== + + +[[webflux-oauth2-login-advanced-oidc-user-service]] +=== OpenID Connect 1.0 UserService + +`OidcReactiveOAuth2UserService` is an implementation of a `ReactiveOAuth2UserService` that supports OpenID Connect 1.0 Provider's. + +The `OidcReactiveOAuth2UserService` leverages the `DefaultReactiveOAuth2UserService` when requesting the user attributes at the UserInfo Endpoint. + +If you need to customize the pre-processing of the UserInfo Request and/or the post-handling of the UserInfo Response, you will need to provide `OidcReactiveOAuth2UserService.setOauth2UserService()` with a custom configured `ReactiveOAuth2UserService`. + +Whether you customize `OidcReactiveOAuth2UserService` or provide your own implementation of `ReactiveOAuth2UserService` for OpenID Connect 1.0 Provider's, you'll need to configure it as shown in the following example: + +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveOAuth2UserService oidcUserService() { + ... + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { } + } + + return http.build() + } + + @Bean + fun oidcUserService(): ReactiveOAuth2UserService { + // ... + } +} +---- +==== + + +[[webflux-oauth2-login-advanced-idtoken-verify]] +== ID Token Signature Verification + +OpenID Connect 1.0 Authentication introduces the https://openid.net/specs/openid-connect-core-1_0.html#IDToken[ID Token], which is a security token that contains Claims about the Authentication of an End-User by an Authorization Server when used by a Client. + +The ID Token is represented as a https://tools.ietf.org/html/rfc7519[JSON Web Token] (JWT) and MUST be signed using https://tools.ietf.org/html/rfc7515[JSON Web Signature] (JWS). + +The `ReactiveOidcIdTokenDecoderFactory` provides a `ReactiveJwtDecoder` used for `OidcIdToken` signature verification. The default algorithm is `RS256` but may be different when assigned during client registration. +For these cases, a resolver may be configured to return the expected JWS algorithm assigned for a specific client. + +The JWS algorithm resolver is a `Function` that accepts a `ClientRegistration` and returns the expected `JwsAlgorithm` for the client, eg. `SignatureAlgorithm.RS256` or `MacAlgorithm.HS256` + +The following code shows how to configure the `OidcIdTokenDecoderFactory` `@Bean` to default to `MacAlgorithm.HS256` for all `ClientRegistration`: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public ReactiveJwtDecoderFactory idTokenDecoderFactory() { + ReactiveOidcIdTokenDecoderFactory idTokenDecoderFactory = new ReactiveOidcIdTokenDecoderFactory(); + idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> MacAlgorithm.HS256); + return idTokenDecoderFactory; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun idTokenDecoderFactory(): ReactiveJwtDecoderFactory { + val idTokenDecoderFactory = ReactiveOidcIdTokenDecoderFactory() + idTokenDecoderFactory.setJwsAlgorithmResolver { MacAlgorithm.HS256 } + return idTokenDecoderFactory +} +---- +==== + +[NOTE] +For MAC based algorithms such as `HS256`, `HS384` or `HS512`, the `client-secret` corresponding to the `client-id` is used as the symmetric key for signature verification. + +[TIP] +If more than one `ClientRegistration` is configured for OpenID Connect 1.0 Authentication, the JWS algorithm resolver may evaluate the provided `ClientRegistration` to determine which algorithm to return. + + +[[webflux-oauth2-login-advanced-oidc-logout]] +== OpenID Connect 1.0 Logout + +OpenID Connect Session Management 1.0 allows the ability to log out the End-User at the Provider using the Client. +One of the strategies available is https://openid.net/specs/openid-connect-session-1_0.html#RPLogout[RP-Initiated Logout]. + +If the OpenID Provider supports both Session Management and https://openid.net/specs/openid-connect-discovery-1_0.html[Discovery], the client may obtain the `end_session_endpoint` `URL` from the OpenID Provider's https://openid.net/specs/openid-connect-session-1_0.html#OPMetadata[Discovery Metadata]. +This can be achieved by configuring the `ClientRegistration` with the `issuer-uri`, as in the following example: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + ... + provider: + okta: + issuer-uri: https://dev-1234.oktapreview.com +---- + +...and the `OidcClientInitiatedServerLogoutSuccessHandler`, which implements RP-Initiated Logout, may be configured as follows: + +==== +.Java +[source,java,role="primary",subs="-attributes"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Autowired + private ReactiveClientRegistrationRepository clientRegistrationRepository; + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()) + .logout(logout -> logout + .logoutSuccessHandler(oidcLogoutSuccessHandler()) + ); + + return http.build(); + } + + private ServerLogoutSuccessHandler oidcLogoutSuccessHandler() { + OidcClientInitiatedServerLogoutSuccessHandler oidcLogoutSuccessHandler = + new OidcClientInitiatedServerLogoutSuccessHandler(this.clientRegistrationRepository); + + // Sets the location that the End-User's User Agent will be redirected to + // after the logout has been performed at the Provider + oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}"); + + return oidcLogoutSuccessHandler; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary",subs="-attributes"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Autowired + private lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + logout { + logoutSuccessHandler = oidcLogoutSuccessHandler() + } + } + + return http.build() + } + + private fun oidcLogoutSuccessHandler(): ServerLogoutSuccessHandler { + val oidcLogoutSuccessHandler = OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository) + + // Sets the location that the End-User's User Agent will be redirected to + // after the logout has been performed at the Provider + oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}") + return oidcLogoutSuccessHandler + } +} +---- +==== + +NOTE: `OidcClientInitiatedServerLogoutSuccessHandler` supports the `+{baseUrl}+` placeholder. +If used, the application's base URL, like `https://app.example.org`, will replace it at request time. diff --git a/docs/modules/ROOT/pages/reactive/oauth2/login/core.adoc b/docs/modules/ROOT/pages/reactive/oauth2/login/core.adoc new file mode 100644 index 00000000000..8c831f099e3 --- /dev/null +++ b/docs/modules/ROOT/pages/reactive/oauth2/login/core.adoc @@ -0,0 +1,553 @@ += Core Configuration + +[[webflux-oauth2-login-sample]] +== Spring Boot 2.x Sample + +Spring Boot 2.x brings full auto-configuration capabilities for OAuth 2.0 Login. + +This section shows how to configure the {gh-samples-url}/boot/oauth2login-webflux[*OAuth 2.0 Login WebFlux sample*] by using _Google_ as the _Authentication Provider_ and covers the following topics: + +* <> +* <> +* <> +* <> + + +[[webflux-oauth2-login-sample-setup]] +=== Initial Setup + +To use Google's OAuth 2.0 authentication system for login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials. + +[NOTE] +==== +https://developers.google.com/identity/protocols/OpenIDConnect[Google's OAuth 2.0 implementation] for authentication conforms to the https://openid.net/connect/[OpenID Connect 1.0] specification and is https://openid.net/certification/[OpenID Certified]. +==== + +Follow the instructions on the https://developers.google.com/identity/protocols/OpenIDConnect[OpenID Connect] page, starting in the "`Setting up OAuth 2.0`" section. + +After completing the "`Obtain OAuth 2.0 credentials`" instructions, you should have a new OAuth Client with credentials that consist of a Client ID and a Client Secret. + + +[[webflux-oauth2-login-sample-redirect]] +=== Setting the Redirect URI + +The redirect URI is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with Google and have been granted access to the OAuth Client (<>) on the consent page. + +In the "`Set a redirect URI`" sub-section, ensure that the *Authorized redirect URIs* field is set to `http://localhost:8080/login/oauth2/code/google`. + +[TIP] +==== +The default redirect URI template is `+{baseUrl}/login/oauth2/code/{registrationId}+`. +The *_registrationId_* is a unique identifier for the xref:reactive/oauth2/client/core.adoc#oauth2Client-client-registration[ClientRegistration]. +For our example, the `registrationId` is `google`. +==== + +[IMPORTANT] +==== +If the OAuth Client is running behind a proxy server, it is recommended to check xref:features/exploits/http.adoc#http-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured. +Also, see the supported xref:reactive/oauth2/client/authorization-grants.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. +==== + +[[webflux-oauth2-login-sample-config]] +=== Configure `application.yml` + +Now that you have a new OAuth Client with Google, you need to configure the application to use the OAuth Client for the _authentication flow_. +To do so: + +. Go to `application.yml` and set the following configuration: ++ +.OAuth Client properties +==== +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: <1> + google: <2> + client-id: google-client-id + client-secret: google-client-secret +---- + +<1> `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties. +<2> Following the base property prefix is the ID for the xref:reactive/oauth2/client/core.adoc#oauth2Client-client-registration[`ClientRegistration`], such as google. +==== + +. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. + + +[[webflux-oauth2-login-sample-start]] +=== Boot the Application + +Launch the Spring Boot 2.x sample and go to `http://localhost:8080`. +You are then redirected to the default _auto-generated_ login page, which displays a link for Google. + +Click on the Google link, and you are then redirected to Google for authentication. + +After authenticating with your Google account credentials, the next page presented to you is the Consent screen. +The Consent screen asks you to either allow or deny access to the OAuth Client you created earlier. +Click *Allow* to authorize the OAuth Client to access your email address and basic profile information. + +At this point, the OAuth Client retrieves your email address and basic profile information from the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session. + + +[[oauth2login-boot-property-mappings]] +== Spring Boot 2.x Property Mappings + +The following table outlines the mapping of the Spring Boot 2.x OAuth Client properties to the xref:reactive/oauth2/client/core.adoc#oauth2Client-client-registration[ClientRegistration] properties. + +|=== +|Spring Boot 2.x |ClientRegistration + +|`spring.security.oauth2.client.registration._[registrationId]_` +|`registrationId` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-id` +|`clientId` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-secret` +|`clientSecret` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-authentication-method` +|`clientAuthenticationMethod` + +|`spring.security.oauth2.client.registration._[registrationId]_.authorization-grant-type` +|`authorizationGrantType` + +|`spring.security.oauth2.client.registration._[registrationId]_.redirect-uri` +|`redirectUri` + +|`spring.security.oauth2.client.registration._[registrationId]_.scope` +|`scopes` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-name` +|`clientName` + +|`spring.security.oauth2.client.provider._[providerId]_.authorization-uri` +|`providerDetails.authorizationUri` + +|`spring.security.oauth2.client.provider._[providerId]_.token-uri` +|`providerDetails.tokenUri` + +|`spring.security.oauth2.client.provider._[providerId]_.jwk-set-uri` +|`providerDetails.jwkSetUri` + +|`spring.security.oauth2.client.provider._[providerId]_.issuer-uri` +|`providerDetails.issuerUri` + +|`spring.security.oauth2.client.provider._[providerId]_.user-info-uri` +|`providerDetails.userInfoEndpoint.uri` + +|`spring.security.oauth2.client.provider._[providerId]_.user-info-authentication-method` +|`providerDetails.userInfoEndpoint.authenticationMethod` + +|`spring.security.oauth2.client.provider._[providerId]_.user-name-attribute` +|`providerDetails.userInfoEndpoint.userNameAttributeName` +|=== + +[TIP] +A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint], by specifying the `spring.security.oauth2.client.provider._[providerId]_.issuer-uri` property. + + +[[webflux-oauth2-login-common-oauth2-provider]] +== CommonOAuth2Provider + +`CommonOAuth2Provider` pre-defines a set of default client properties for a number of well known providers: Google, GitHub, Facebook, and Okta. + +For example, the `authorization-uri`, `token-uri`, and `user-info-uri` do not change often for a Provider. +Therefore, it makes sense to provide default values in order to reduce the required configuration. + +As demonstrated previously, when we <>, only the `client-id` and `client-secret` properties are required. + +The following listing shows an example: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + google: + client-id: google-client-id + client-secret: google-client-secret +---- + +[TIP] +The auto-defaulting of client properties works seamlessly here because the `registrationId` (`google`) matches the `GOOGLE` `enum` (case-insensitive) in `CommonOAuth2Provider`. + +For cases where you may want to specify a different `registrationId`, such as `google-login`, you can still leverage auto-defaulting of client properties by configuring the `provider` property. + +The following listing shows an example: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + google-login: <1> + provider: google <2> + client-id: google-client-id + client-secret: google-client-secret +---- +<1> The `registrationId` is set to `google-login`. +<2> The `provider` property is set to `google`, which will leverage the auto-defaulting of client properties set in `CommonOAuth2Provider.GOOGLE.getBuilder()`. + + +[[webflux-oauth2-login-custom-provider-properties]] +== Configuring Custom Provider Properties + +There are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain). + +For example, an OAuth Client registered with Okta is assigned to a specific sub-domain and have their own protocol endpoints. + +For these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: `spring.security.oauth2.client.provider._[providerId]_`. + +The following listing shows an example: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + provider: + okta: <1> + authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize + token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token + user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo + user-name-attribute: sub + jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys +---- + +<1> The base property (`spring.security.oauth2.client.provider.okta`) allows for custom configuration of protocol endpoint locations. + + +[[webflux-oauth2-login-override-boot-autoconfig]] +== Overriding Spring Boot 2.x Auto-configuration + +The Spring Boot 2.x auto-configuration class for OAuth Client support is `ReactiveOAuth2ClientAutoConfiguration`. + +It performs the following tasks: + +* Registers a `ReactiveClientRegistrationRepository` `@Bean` composed of `ClientRegistration`(s) from the configured OAuth Client properties. +* Registers a `SecurityWebFilterChain` `@Bean` and enables OAuth 2.0 Login through `serverHttpSecurity.oauth2Login()`. + +If you need to override the auto-configuration based on your specific requirements, you may do so in the following ways: + +* <> +* <> +* <> + + +[[webflux-oauth2-login-register-reactiveclientregistrationrepository-bean]] +=== Register a ReactiveClientRegistrationRepository @Bean + +The following example shows how to register a `ReactiveClientRegistrationRepository` `@Bean`: + +==== +.Java +[source,java,role="primary",attrs="-attributes"] +---- +@Configuration +public class OAuth2LoginConfig { + + @Bean + public ReactiveClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration()); + } + + private ClientRegistration googleClientRegistration() { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary",attrs="-attributes"] +---- +@Configuration +class OAuth2LoginConfig { + + @Bean + fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { + return InMemoryReactiveClientRegistrationRepository(googleClientRegistration()) + } + + private fun googleClientRegistration(): ClientRegistration { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build() + } +} +---- +==== + + +[[webflux-oauth2-login-register-securitywebfilterchain-bean]] +=== Register a SecurityWebFilterChain @Bean + +The following example shows how to register a `SecurityWebFilterChain` `@Bean` with `@EnableWebFluxSecurity` and enable OAuth 2.0 login through `serverHttpSecurity.oauth2Login()`: + +.OAuth2 Login Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()); + + return http.build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + } + + return http.build() + } +} +---- +==== + + +[[webflux-oauth2-login-completely-override-autoconfiguration]] +=== Completely Override the Auto-configuration + +The following example shows how to completely override the auto-configuration by registering a `ReactiveClientRegistrationRepository` `@Bean` and a `SecurityWebFilterChain` `@Bean`. + +.Overriding the auto-configuration +==== +.Java +[source,java,role="primary",attrs="-attributes"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration()); + } + + private ClientRegistration googleClientRegistration() { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary",attrs="-attributes"] +---- +@EnableWebFluxSecurity +class OAuth2LoginConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + } + + return http.build() + } + + @Bean + fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { + return InMemoryReactiveClientRegistrationRepository(googleClientRegistration()) + } + + private fun googleClientRegistration(): ClientRegistration { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build() + } +} +---- +==== + + +[[webflux-oauth2-login-javaconfig-wo-boot]] +== Java Configuration without Spring Boot 2.x + +If you are not able to use Spring Boot 2.x and would like to configure one of the pre-defined providers in `CommonOAuth2Provider` (for example, Google), apply the following configuration: + +.OAuth2 Login Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration()); + } + + @Bean + public ReactiveOAuth2AuthorizedClientService authorizedClientService( + ReactiveClientRegistrationRepository clientRegistrationRepository) { + return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository); + } + + @Bean + public ServerOAuth2AuthorizedClientRepository authorizedClientRepository( + ReactiveOAuth2AuthorizedClientService authorizedClientService) { + return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService); + } + + private ClientRegistration googleClientRegistration() { + return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + } + + return http.build() + } + + @Bean + fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { + return InMemoryReactiveClientRegistrationRepository(googleClientRegistration()) + } + + @Bean + fun authorizedClientService( + clientRegistrationRepository: ReactiveClientRegistrationRepository + ): ReactiveOAuth2AuthorizedClientService { + return InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository) + } + + @Bean + fun authorizedClientRepository( + authorizedClientService: ReactiveOAuth2AuthorizedClientService + ): ServerOAuth2AuthorizedClientRepository { + return AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService) + } + + private fun googleClientRegistration(): ClientRegistration { + return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .build() + } +} +---- +==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/login/index.adoc b/docs/modules/ROOT/pages/reactive/oauth2/login/index.adoc new file mode 100644 index 00000000000..5c16c18fc49 --- /dev/null +++ b/docs/modules/ROOT/pages/reactive/oauth2/login/index.adoc @@ -0,0 +1,11 @@ +[[webflux-oauth2-login]] += OAuth 2.0 Login +:page-section-summary-toc: 1 + +The OAuth 2.0 Login feature provides an application with the ability to have users log in to the application by using their existing account at an OAuth 2.0 Provider (such as GitHub) or OpenID Connect 1.0 Provider (such as Google). +OAuth 2.0 Login implements the "Login with Google" or "Login with GitHub" use cases. + +[NOTE] +==== +OAuth 2.0 Login is implemented by using the *Authorization Code Grant*, as specified in the https://tools.ietf.org/html/rfc6749#section-4.1[OAuth 2.0 Authorization Framework] and https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth[OpenID Connect Core 1.0]. +==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/bearer-tokens.adoc b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/bearer-tokens.adoc index 30a4c8fd07b..cd6c295fa0a 100644 --- a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/bearer-tokens.adoc +++ b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/bearer-tokens.adoc @@ -4,10 +4,10 @@ == Bearer Token Resolution By default, Resource Server looks for a bearer token in the `Authorization` header. -This, however, can be customized. +However, you can verify this token. For example, you may have a need to read the bearer token from a custom header. -To achieve this, you can wire an instance of `ServerBearerTokenAuthenticationConverter` into the DSL, as you can see in the following example: +To do so, you can wire an instance of `ServerBearerTokenAuthenticationConverter` into the DSL: .Custom Bearer Token Header ==== @@ -37,8 +37,8 @@ return http { == Bearer Token Propagation -Now that you're in possession of a bearer token, it might be handy to pass that to downstream services. -This is quite simple with `{security-api-url}org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.html[ServerBearerExchangeFilterFunction]`, which you can see in the following example: +Now that you have a bearer token, you can pass that to downstream services. +This is possible with `{security-api-url}org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.html[ServerBearerExchangeFilterFunction]`: ==== .Java @@ -64,10 +64,8 @@ fun rest(): WebClient { ---- ==== -When the above `WebClient` is used to perform requests, Spring Security will look up the current `Authentication` and extract any `{security-api-url}org/springframework/security/oauth2/core/AbstractOAuth2Token.html[AbstractOAuth2Token]` credential. -Then, it will propagate that token in the `Authorization` header. - -For example: +When the `WebClient` shown in the preceding example performs requests, Spring Security looks up the current `Authentication` and extract any `{security-api-url}org/springframework/security/oauth2/core/AbstractOAuth2Token.html[AbstractOAuth2Token]` credential. +Then, it propagates that token in the `Authorization` header -- for example: ==== .Java @@ -89,9 +87,9 @@ this.rest.get() ---- ==== -Will invoke the `https://other-service.example.com/endpoint`, adding the bearer token `Authorization` header for you. +The prececing example invokes the `https://other-service.example.com/endpoint`, adding the bearer token `Authorization` header for you. -In places where you need to override this behavior, it's a simple matter of supplying the header yourself, like so: +In places where you need to override this behavior, you can supply the header yourself: ==== .Java @@ -115,8 +113,9 @@ rest.get() ---- ==== -In this case, the filter will fall back and simply forward the request onto the rest of the web filter chain. +In this case, the filter falls back and forwards the request onto the rest of the web filter chain. [NOTE] +==== Unlike the https://docs.spring.io/spring-security/site/docs/current-SNAPSHOT/api/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.html[OAuth 2.0 Client filter function], this filter function makes no attempt to renew the token, should it be expired. -To obtain this level of support, please use the OAuth 2.0 Client filter. +==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/index.adoc b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/index.adoc index 7d22aa4a6f4..56fec650c32 100644 --- a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/index.adoc +++ b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/index.adoc @@ -1,15 +1,15 @@ [[webflux-oauth2-resource-server]] = OAuth 2.0 Resource Server -Spring Security supports protecting endpoints using two forms of OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens]: +Spring Security supports protecting endpoints by offering two forms of OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens]: * https://tools.ietf.org/html/rfc7519[JWT] * Opaque Tokens This is handy in circumstances where an application has delegated its authority management to an https://tools.ietf.org/html/rfc6749[authorization server] (for example, Okta or Ping Identity). -This authorization server can be consulted by resource servers to authorize requests. +Resource serves can consult this authorization server to authorize requests. [NOTE] ==== -A complete working example for {gh-samples-url}/reactive/webflux/java/oauth2/resource-server[*JWTs*] is available in the {gh-samples-url}[Spring Security repository]. +A complete working example for {gh-samples-url}/reactive/webflux/java/oauth2/resource-server[JWT] is available in the {gh-samples-url}[Spring Security repository]. ==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/jwt.adoc b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/jwt.adoc index ffac9a718d2..ed511ed0479 100644 --- a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/jwt.adoc +++ b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/jwt.adoc @@ -4,18 +4,19 @@ == Minimal Dependencies for JWT Most Resource Server support is collected into `spring-security-oauth2-resource-server`. -However, the support for decoding and verifying JWTs is in `spring-security-oauth2-jose`, meaning that both are necessary in order to have a working resource server that supports JWT-encoded Bearer Tokens. +However, the support for decoding and verifying JWTs is in `spring-security-oauth2-jose`, meaning that both are necessary to have a working resource server that supports JWT-encoded Bearer Tokens. [[webflux-oauth2resourceserver-jwt-minimalconfiguration]] == Minimal Configuration for JWTs When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server consists of two basic steps. -First, include the needed dependencies and second, indicate the location of the authorization server. +First, include the needed dependencies. Second, indicate the location of the authorization server. === Specifying the Authorization Server -In a Spring Boot application, to specify which authorization server to use, simply do: +In a Spring Boot application, you need to specify which authorization server to use: +==== [source,yml] ---- spring: @@ -25,65 +26,72 @@ spring: jwt: issuer-uri: https://idp.example.com/issuer ---- +==== -Where `https://idp.example.com/issuer` is the value contained in the `iss` claim for JWT tokens that the authorization server will issue. -Resource Server will use this property to further self-configure, discover the authorization server's public keys, and subsequently validate incoming JWTs. +Where `https://idp.example.com/issuer` is the value contained in the `iss` claim for JWT tokens that the authorization server issues. +This resource server uses this property to further self-configure, discover the authorization server's public keys, and subsequently validate incoming JWTs. [NOTE] +==== To use the `issuer-uri` property, it must also be true that one of `https://idp.example.com/issuer/.well-known/openid-configuration`, `https://idp.example.com/.well-known/openid-configuration/issuer`, or `https://idp.example.com/.well-known/oauth-authorization-server/issuer` is a supported endpoint for the authorization server. This endpoint is referred to as a https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Provider Configuration] endpoint or a https://tools.ietf.org/html/rfc8414#section-3[Authorization Server Metadata] endpoint. - -And that's it! +==== === Startup Expectations -When this property and these dependencies are used, Resource Server will automatically configure itself to validate JWT-encoded Bearer Tokens. +When this property and these dependencies are used, Resource Server automatically configures itself to validate JWT-encoded Bearer Tokens. It achieves this through a deterministic startup process: -1. Hit the Provider Configuration or Authorization Server Metadata endpoint, processing the response for the `jwks_url` property -2. Configure the validation strategy to query `jwks_url` for valid public keys -3. Configure the validation strategy to validate each JWTs `iss` claim against `https://idp.example.com`. +. Hit the Provider Configuration or Authorization Server Metadata endpoint, processing the response for the `jwks_url` property. +. Configure the validation strategy to query `jwks_url` for valid public keys. +. Configure the validation strategy to validate each JWT's `iss` claim against `https://idp.example.com`. -A consequence of this process is that the authorization server must be up and receiving requests in order for Resource Server to successfully start up. +A consequence of this process is that the authorization server must be receiving requests in order for Resource Server to successfully start up. [NOTE] -If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup will fail. +==== +If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup fails. +==== === Runtime Expectations -Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header: +Once the application is started up, Resource Server tries to process any request that contains an `Authorization: Bearer` header: +==== [source,html] ---- GET / HTTP/1.1 Authorization: Bearer some-token-value # Resource Server will process this ---- +==== -So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification. +So long as this scheme is indicated, Resource Server tries to process the request according to the Bearer Token specification. -Given a well-formed JWT, Resource Server will: +Given a well-formed JWT, Resource Server: -1. Validate its signature against a public key obtained from the `jwks_url` endpoint during startup and matched against the JWTs header -2. Validate the JWTs `exp` and `nbf` timestamps and the JWTs `iss` claim, and -3. Map each scope to an authority with the prefix `SCOPE_`. +. Validates its signature against a public key obtained from the `jwks_url` endpoint during startup and matched against the JWTs header. +. Validates the JWTs `exp` and `nbf` timestamps and the JWTs `iss` claim. +. Maps each scope to an authority with the prefix `SCOPE_`. [NOTE] -As the authorization server makes available new keys, Spring Security will automatically rotate the keys used to validate the JWT tokens. +==== +As the authorization server makes available new keys, Spring Security automatically rotates the keys used to validate the JWT tokens. +==== -The resulting `Authentication#getPrincipal`, by default, is a Spring Security `Jwt` object, and `Authentication#getName` maps to the JWT's `sub` property, if one is present. +By default, the resulting `Authentication#getPrincipal` is a Spring Security `Jwt` object, and `Authentication#getName` maps to the JWT's `sub` property, if one is present. From here, consider jumping to: -<> - -<> +* <> +* <> [[webflux-oauth2resourceserver-jwt-jwkseturi]] === Specifying the Authorization Server JWK Set Uri Directly -If the authorization server doesn't support any configuration endpoints, or if Resource Server must be able to start up independently from the authorization server, then the `jwk-set-uri` can be supplied as well: +If the authorization server does not support any configuration endpoints, or if Resource Server must be able to start up independently from the authorization server, you can supply `jwk-set-uri` as well: +==== [source,yaml] ---- spring: @@ -94,22 +102,27 @@ spring: issuer-uri: https://idp.example.com jwk-set-uri: https://idp.example.com/.well-known/jwks.json ---- +==== [NOTE] -The JWK Set uri is not standardized, but can typically be found in the authorization server's documentation +==== +The JWK Set uri is not standardized, but you can typically find it in the authorization server's documentation. +==== -Consequently, Resource Server will not ping the authorization server at startup. +Consequently, Resource Server does not ping the authorization server at startup. We still specify the `issuer-uri` so that Resource Server still validates the `iss` claim on incoming JWTs. [NOTE] -This property can also be supplied directly on the <>. +==== +You can supply this property directly on the <>. +==== [[webflux-oauth2resourceserver-jwt-sansboot]] === Overriding or Replacing Boot Auto Configuration -There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf. +Spring Boot generates two `@Bean` objects on Resource Server's behalf. -The first is a `SecurityWebFilterChain` that configures the app as a resource server. When including `spring-security-oauth2-jose`, this `SecurityWebFilterChain` looks like: +The first bean is a `SecurityWebFilterChain` that configures the application as a resource server. When including `spring-security-oauth2-jose`, this `SecurityWebFilterChain` looks like: .Resource Server SecurityWebFilterChain ==== @@ -144,9 +157,9 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain ---- ==== -If the application doesn't expose a `SecurityWebFilterChain` bean, then Spring Boot will expose the above default one. +If the application does not expose a `SecurityWebFilterChain` bean, Spring Boot exposes the default one (shown in the preceding listing). -Replacing this is as simple as exposing the bean within the application: +To replace it, expose the `@Bean` within the application: .Replacing SecurityWebFilterChain ==== @@ -185,9 +198,9 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain ---- ==== -The above requires the scope of `message:read` for any URL that starts with `/messages/`. +The preceding configuration requires the scope of `message:read` for any URL that starts with `/messages/`. -Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration. +Methods on the `oauth2ResourceServer` DSL also override or replace auto configuration. For example, the second `@Bean` Spring Boot creates is a `ReactiveJwtDecoder`, which decodes `String` tokens into validated instances of `Jwt`: @@ -213,15 +226,17 @@ fun jwtDecoder(): ReactiveJwtDecoder { ==== [NOTE] -Calling `{security-api-url}org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.html#fromIssuerLocation-java.lang.String-[ReactiveJwtDecoders#fromIssuerLocation]` is what invokes the Provider Configuration or Authorization Server Metadata endpoint in order to derive the JWK Set Uri. -If the application doesn't expose a `ReactiveJwtDecoder` bean, then Spring Boot will expose the above default one. +==== +Calling `{security-api-url}org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.html#fromIssuerLocation-java.lang.String-[ReactiveJwtDecoders#fromIssuerLocation]` invokes the Provider Configuration or Authorization Server Metadata endpoint to derive the JWK Set URI. +If the application does not expose a `ReactiveJwtDecoder` bean, Spring Boot exposes the above default one. +==== -And its configuration can be overridden using `jwkSetUri()` or replaced using `decoder()`. +Its configuration can be overridden by using `jwkSetUri()` or replaced by using `decoder()`. [[webflux-oauth2resourceserver-jwt-jwkseturi-dsl]] ==== Using `jwkSetUri()` -An authorization server's JWK Set Uri can be configured <> or it can be supplied in the DSL: +You can configure an authorization server's JWK Set URI <> or supply it in the DSL: ==== .Java @@ -266,7 +281,7 @@ Using `jwkSetUri()` takes precedence over any configuration property. [[webflux-oauth2resourceserver-jwt-decoder-dsl]] ==== Using `decoder()` -More powerful than `jwkSetUri()` is `decoder()`, which will completely replace any Boot auto configuration of `JwtDecoder`: +`decoder()` is more powerful than `jwkSetUri()`, because it completely replaces any Spring Boot auto-configuration of `JwtDecoder`: ==== .Java @@ -306,12 +321,12 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain ---- ==== -This is handy when deeper configuration, like <>, is necessary. +This is handy when you need deeper configuration, such as <>. [[webflux-oauth2resourceserver-decoder-bean]] ==== Exposing a `ReactiveJwtDecoder` `@Bean` -Or, exposing a `ReactiveJwtDecoder` `@Bean` has the same effect as `decoder()`: +Alternately, exposing a `ReactiveJwtDecoder` `@Bean` has the same effect as `decoder()`: ==== .Java @@ -336,15 +351,16 @@ fun jwtDecoder(): ReactiveJwtDecoder { [[webflux-oauth2resourceserver-jwt-decoder-algorithm]] == Configuring Trusted Algorithms -By default, `NimbusReactiveJwtDecoder`, and hence Resource Server, will only trust and verify tokens using `RS256`. +By default, `NimbusReactiveJwtDecoder`, and hence Resource Server, trust and verify only tokens that use `RS256`. -You can customize this via <> or <>. +You can customize this behavior with <> or by using <>. [[webflux-oauth2resourceserver-jwt-boot-algorithm]] -=== Via Spring Boot +=== Customizing Trusted Algorithms with Spring Boot The simplest way to set the algorithm is as a property: +==== [source,yaml] ---- spring: @@ -355,9 +371,10 @@ spring: jws-algorithm: RS512 jwk-set-uri: https://idp.example.org/.well-known/jwks.json ---- +==== [[webflux-oauth2resourceserver-jwt-decoder-builder]] -=== Using a Builder +=== Customizing Trusted Algorithms by Using a Builder For greater power, though, we can use a builder that ships with `NimbusReactiveJwtDecoder`: @@ -383,7 +400,7 @@ fun jwtDecoder(): ReactiveJwtDecoder { ---- ==== -Calling `jwsAlgorithm` more than once will configure `NimbusReactiveJwtDecoder` to trust more than one algorithm, like so: +Calling `jwsAlgorithm` more than once configures `NimbusReactiveJwtDecoder` to trust more than one algorithm: ==== .Java @@ -407,7 +424,7 @@ fun jwtDecoder(): ReactiveJwtDecoder { ---- ==== -Or, you can call `jwsAlgorithms`: +Alternately, you can call `jwsAlgorithms`: ==== .Java @@ -442,14 +459,14 @@ fun jwtDecoder(): ReactiveJwtDecoder { === Trusting a Single Asymmetric Key Simpler than backing a Resource Server with a JWK Set endpoint is to hard-code an RSA public key. -The public key can be provided via <> or by <>. +The public key can be provided with <> or by <>. [[webflux-oauth2resourceserver-jwt-decoder-public-key-boot]] ==== Via Spring Boot -Specifying a key via Spring Boot is quite simple. -The key's location can be specified like so: +You can specify a key with Spring Boot: +==== [source,yaml] ---- spring: @@ -459,8 +476,9 @@ spring: jwt: public-key-location: classpath:my-key.pub ---- +==== -Or, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`: +Alternately, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`: .BeanFactoryPostProcessor ==== @@ -490,12 +508,14 @@ fun conversionServiceCustomizer(): BeanFactoryPostProcessor { Specify your key's location: +==== [source,yaml] ---- key.location: hfds://my-key.pub ---- +==== -And then autowire the value: +Then autowire the value: ==== .Java @@ -516,7 +536,7 @@ val key: RSAPublicKey? = null [[webflux-oauth2resourceserver-jwt-decoder-public-key-builder]] ==== Using a Builder -To wire an `RSAPublicKey` directly, you can simply use the appropriate `NimbusReactiveJwtDecoder` builder, like so: +To wire an `RSAPublicKey` directly, use the appropriate `NimbusReactiveJwtDecoder` builder: ==== .Java @@ -541,8 +561,8 @@ fun jwtDecoder(): ReactiveJwtDecoder { [[webflux-oauth2resourceserver-jwt-decoder-secret-key]] === Trusting a Single Symmetric Key -Using a single symmetric key is also simple. -You can simply load in your `SecretKey` and use the appropriate `NimbusReactiveJwtDecoder` builder, like so: +You can also use a single symmetric key. +You can load in your `SecretKey` and use the appropriate `NimbusReactiveJwtDecoder` builder: ==== .Java @@ -567,13 +587,18 @@ fun jwtDecoder(): ReactiveJwtDecoder { [[webflux-oauth2resourceserver-jwt-authorization]] === Configuring Authorization -A JWT that is issued from an OAuth 2.0 Authorization Server will typically either have a `scope` or `scp` attribute, indicating the scopes (or authorities) it's been granted, for example: +A JWT that is issued from an OAuth 2.0 Authorization Server typically has either a `scope` or an `scp` attribute, indicating the scopes (or authorities) it has been granted -- for example: -`{ ..., "scope" : "messages contacts"}` +==== +[source,json] +---- +{ ..., "scope" : "messages contacts"} +---- +==== -When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string "SCOPE_". +When this is the case, Resource Server tries to coerce these scopes into a list of granted authorities, prefixing each scope with the string, `SCOPE_`. -This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix: +This means that, to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix: ==== .Java @@ -611,7 +636,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain ---- ==== -Or similarly with method security: +You can do something similar with method security: ==== .Java @@ -633,8 +658,8 @@ fun getMessages(): Flux { } ==== Extracting Authorities Manually However, there are a number of circumstances where this default is insufficient. -For example, some authorization servers don't use the `scope` attribute, but instead have their own custom attribute. -Or, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities. +For example, some authorization servers do not use the `scope` attribute. Instead, they have their own custom attribute. +At other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities. To this end, the DSL exposes `jwtAuthenticationConverter()`: @@ -690,10 +715,10 @@ fun grantedAuthoritiesExtractor(): Converter>, indicating the authorization server's issuer uri, Resource Server will default to verifying the `iss` claim as well as the `exp` and `nbf` timestamp claims. +Using <>, indicating the authorization server's issuer URI, Resource Server defaults to verifying the `iss` claim as well as the `exp` and `nbf` timestamp claims. -In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances. +In circumstances where you need to customize validation needs, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances. [[webflux-oauth2resourceserver-jwt-validation-clockskew]] ==== Customizing Timestamp Validation -JWT's typically have a window of validity, with the start of the window indicated in the `nbf` claim and the end indicated in the `exp` claim. +JWT instances typically have a window of validity, with the start of the window indicated in the `nbf` claim and the end indicated in the `exp` claim. -However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another. -This can cause some implementation heartburn as the number of collaborating servers increases in a distributed system. +However, every server can experience clock drift, which can cause tokens to appear to be expired to one server but not to another. +This can cause some implementation heartburn, as the number of collaborating servers increases in a distributed system. -Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and it can be configured with a `clockSkew` to alleviate the above problem: +Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and you can configure it with a `clockSkew` to alleviate the clock drift problem: ==== .Java @@ -805,12 +830,14 @@ fun jwtDecoder(): ReactiveJwtDecoder { ==== [NOTE] +==== By default, Resource Server configures a clock skew of 60 seconds. +==== [[webflux-oauth2resourceserver-validation-custom]] ==== Configuring a Custom Validator -Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API: +You can Add a check for the `aud` claim with the `OAuth2TokenValidator` API: ==== .Java @@ -845,7 +872,7 @@ class AudienceValidator : OAuth2TokenValidator { ---- ==== -Then, to add into a resource server, it's a matter of specifying the `ReactiveJwtDecoder` instance: +Then, to add into a resource server, you can specifying the `ReactiveJwtDecoder` instance: ==== .Java diff --git a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/multitenancy.adoc b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/multitenancy.adoc index 9138926b797..ac900d5674e 100644 --- a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/multitenancy.adoc +++ b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/multitenancy.adoc @@ -5,17 +5,17 @@ A resource server is considered multi-tenant when there are multiple strategies for verifying a bearer token, keyed by some tenant identifier. -For example, your resource server may accept bearer tokens from two different authorization servers. -Or, your authorization server may represent a multiplicity of issuers. +For example, your resource server can accept bearer tokens from two different authorization servers. +Alternately, your authorization server can represent a multiplicity of issuers. -In each case, there are two things that need to be done and trade-offs associated with how you choose to do them: +In each case, two things need to be done and trade-offs are associated with how you choose to do them: -1. Resolve the tenant -2. Propagate the tenant +. Resolve the tenant. +. Propagate the tenant. === Resolving the Tenant By Claim -One way to differentiate tenants is by the issuer claim. Since the issuer claim accompanies signed JWTs, this can be done with the `JwtIssuerReactiveAuthenticationManagerResolver`, like so: +One way to differentiate tenants is by the issuer claim. Since the issuer claim accompanies signed JWTs, you can do so with the `JwtIssuerReactiveAuthenticationManagerResolver`: ==== .Java @@ -55,8 +55,8 @@ This allows for an application startup that is independent from those authorizat ==== Dynamic Tenants -Of course, you may not want to restart the application each time a new tenant is added. -In this case, you can configure the `JwtIssuerReactiveAuthenticationManagerResolver` with a repository of `ReactiveAuthenticationManager` instances, which you can edit at runtime, like so: +You may not want to restart the application each time a new tenant is added. +In this case, you can configure the `JwtIssuerReactiveAuthenticationManagerResolver` with a repository of `ReactiveAuthenticationManager` instances, which you can edit at runtime: ==== .Java @@ -110,8 +110,11 @@ return http { ---- ==== -In this case, you construct `JwtIssuerReactiveAuthenticationManagerResolver` with a strategy for obtaining the `ReactiveAuthenticationManager` given the issuer. -This approach allows us to add and remove elements from the repository (shown as a `Map` in the snippet) at runtime. +In this case, you construct `JwtIssuerReactiveAuthenticationManagerResolver` with a strategy for obtaining the `ReactiveAuthenticationManager` given to the issuer. +This approach lets us add and remove elements from the repository (shown as a `Map` in the preceding snippet) at runtime. -NOTE: It would be unsafe to simply take any issuer and construct an `ReactiveAuthenticationManager` from it. -The issuer should be one that the code can verify from a trusted source like an allowed list of issuers. +[NOTE] +==== +It would be unsafe to simply take any issuer and construct an `ReactiveAuthenticationManager` from it. +The issuer should be one that the code can verify from a trusted source, such as an allowed list of issuers. +==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/opaque-token.adoc b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/opaque-token.adoc index 70b6bd5133c..a30f200d702 100644 --- a/docs/modules/ROOT/pages/reactive/oauth2/resource-server/opaque-token.adoc +++ b/docs/modules/ROOT/pages/reactive/oauth2/resource-server/opaque-token.adoc @@ -2,25 +2,28 @@ [[webflux-oauth2resourceserver-opaque-minimaldependencies]] == Minimal Dependencies for Introspection -As described in xref:servlet/oauth2/resource-server/jwt.adoc#oauth2resourceserver-jwt-minimaldependencies[Minimal Dependencies for JWT] most of Resource Server support is collected in `spring-security-oauth2-resource-server`. -However unless a custom <> is provided, the Resource Server will fallback to ReactiveOpaqueTokenIntrospector. -Meaning that both `spring-security-oauth2-resource-server` and `oauth2-oidc-sdk` are necessary in order to have a working minimal Resource Server that supports opaque Bearer Tokens. -Please refer to `spring-security-oauth2-resource-server` in order to determin the correct version for `oauth2-oidc-sdk`. +As described in xref:servlet/oauth2/resource-server/jwt.adoc#oauth2resourceserver-jwt-minimaldependencies[Minimal Dependencies for JWT], most Resource Server support is collected in `spring-security-oauth2-resource-server`. +However, unless you provide a custom <>, the Resource Server falls back to `ReactiveOpaqueTokenIntrospector`. +This means that both `spring-security-oauth2-resource-server` and `oauth2-oidc-sdk` are necessary to have a working minimal Resource Server that supports opaque Bearer Tokens. +See `spring-security-oauth2-resource-server` in order to determine the correct version for `oauth2-oidc-sdk`. [[webflux-oauth2resourceserver-opaque-minimalconfiguration]] == Minimal Configuration for Introspection -Typically, an opaque token can be verified via an https://tools.ietf.org/html/rfc7662[OAuth 2.0 Introspection Endpoint], hosted by the authorization server. +Typically, you can verify an opaque token with an https://tools.ietf.org/html/rfc7662[OAuth 2.0 Introspection Endpoint], hosted by the authorization server. This can be handy when revocation is a requirement. -When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server that uses introspection consists of two basic steps. -First, include the needed dependencies and second, indicate the introspection endpoint details. +When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server that uses introspection consists of two steps: + +. Include the needed dependencies. +. Indicate the introspection endpoint details. [[webflux-oauth2resourceserver-opaque-introspectionuri]] === Specifying the Authorization Server -To specify where the introspection endpoint is, simply do: +You can specify where the introspection endpoint is: +==== [source,yaml] ---- security: @@ -31,55 +34,57 @@ security: client-id: client client-secret: secret ---- +==== Where `https://idp.example.com/introspect` is the introspection endpoint hosted by your authorization server and `client-id` and `client-secret` are the credentials needed to hit that endpoint. -Resource Server will use these properties to further self-configure and subsequently validate incoming JWTs. +Resource Server uses these properties to further self-configure and subsequently validate incoming JWTs. [NOTE] -When using introspection, the authorization server's word is the law. +==== If the authorization server responses that the token is valid, then it is. - -And that's it! +==== === Startup Expectations -When this property and these dependencies are used, Resource Server will automatically configure itself to validate Opaque Bearer Tokens. +When this property and these dependencies are used, Resource Server automatically configures itself to validate Opaque Bearer Tokens. -This startup process is quite a bit simpler than for JWTs since no endpoints need to be discovered and no additional validation rules get added. +This startup process is quite a bit simpler than for JWTs, since no endpoints need to be discovered and no additional validation rules get added. === Runtime Expectations -Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header: +Once the application has started, Resource Server tries to process any request containing an `Authorization: Bearer` header: +==== [source,http] ---- GET / HTTP/1.1 Authorization: Bearer some-token-value # Resource Server will process this ---- +==== -So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification. +So long as this scheme is indicated, Resource Server tries to process the request according to the Bearer Token specification. -Given an Opaque Token, Resource Server will +Given an Opaque Token, Resource Server: -1. Query the provided introspection endpoint using the provided credentials and the token -2. Inspect the response for an `{ 'active' : true }` attribute -3. Map each scope to an authority with the prefix `SCOPE_` +. Queries the provided introspection endpoint by using the provided credentials and the token. +. Inspects the response for an `{ 'active' : true }` attribute. +. Maps each scope to an authority with a prefix of `SCOPE_`. -The resulting `Authentication#getPrincipal`, by default, is a Spring Security `{security-api-url}org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.html[OAuth2AuthenticatedPrincipal]` object, and `Authentication#getName` maps to the token's `sub` property, if one is present. +By default, the resulting `Authentication#getPrincipal` is a Spring Security `{security-api-url}org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.html[OAuth2AuthenticatedPrincipal]` object, and `Authentication#getName` maps to the token's `sub` property, if one is present. From here, you may want to jump to: -* <> -* <> -* <> +* <> +* <> +* <> [[webflux-oauth2resourceserver-opaque-attributes]] -== Looking Up Attributes Post-Authentication +== Looking Up Attributes After Authentication Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`. -This means that it's available in `@Controller` methods when using `@EnableWebFlux` in your configuration: +This means that it is available in `@Controller` methods when you use `@EnableWebFlux` in your configuration: ==== .Java @@ -123,11 +128,11 @@ fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): Mono< ---- ==== -=== Looking Up Attributes Via SpEL +=== Looking Up Attributes with SpEL -Of course, this also means that attributes can be accessed via SpEL. +You can access attributes with the Spring Expression Language (SpEL). -For example, if using `@EnableReactiveMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do: +For example, if you use `@EnableReactiveMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do: ==== .Java @@ -152,10 +157,10 @@ fun forFoosEyesOnly(): Mono { [[webflux-oauth2resourceserver-opaque-sansboot]] == Overriding or Replacing Boot Auto Configuration -There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf. +Spring Boot generates two `@Bean` instances for Resource Server. -The first is a `SecurityWebFilterChain` that configures the app as a resource server. -When use Opaque Token, this `SecurityWebFilterChain` looks like: +The first is a `SecurityWebFilterChain` that configures the application as a resource server. +When you use an Opaque Token, this `SecurityWebFilterChain` looks like: ==== .Java @@ -189,9 +194,9 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain ---- ==== -If the application doesn't expose a `SecurityWebFilterChain` bean, then Spring Boot will expose the above default one. +If the application does not expose a `SecurityWebFilterChain` bean, Spring Boot exposes the default bean (shown in the preceding listing). -Replacing this is as simple as exposing the bean within the application: +You can replace it by exposing the bean within the application: .Replacing SecurityWebFilterChain ==== @@ -237,9 +242,9 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain ---- ==== -The above requires the scope of `message:read` for any URL that starts with `/messages/`. +The preceding example requires the scope of `message:read` for any URL that starts with `/messages/`. -Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration. +Methods on the `oauth2ResourceServer` DSL also override or replace auto configuration. For example, the second `@Bean` Spring Boot creates is a `ReactiveOpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`: @@ -263,14 +268,14 @@ fun introspector(): ReactiveOpaqueTokenIntrospector { ---- ==== -If the application doesn't expose a `ReactiveOpaqueTokenIntrospector` bean, then Spring Boot will expose the above default one. +If the application does not expose a `ReactiveOpaqueTokenIntrospector` bean, Spring Boot exposes the default one (shown in the preceding listing). -And its configuration can be overridden using `introspectionUri()` and `introspectionClientCredentials()` or replaced using `introspector()`. +You can override its configuration by using `introspectionUri()` and `introspectionClientCredentials()` or replace it by using `introspector()`. [[webflux-oauth2resourceserver-opaque-introspectionuri-dsl]] === Using `introspectionUri()` -An authorization server's Introspection Uri can be configured <> or it can be supplied in the DSL: +You can configure an authorization server's Introspection URI <>, or you can supply in the DSL: ==== .Java @@ -320,7 +325,7 @@ Using `introspectionUri()` takes precedence over any configuration property. [[webflux-oauth2resourceserver-opaque-introspector-dsl]] === Using `introspector()` -More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of `ReactiveOpaqueTokenIntrospector`: +`introspector()` is more powerful than `introspectionUri()`. It completely replaces any Boot auto-configuration of `ReactiveOpaqueTokenIntrospector`: ==== .Java @@ -363,7 +368,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain ---- ==== -This is handy when deeper configuration, like <>or <> is necessary. +This is handy when deeper configuration, such as <>or <>, is necessary. [[webflux-oauth2resourceserver-opaque-introspector-bean]] === Exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` @@ -393,13 +398,18 @@ fun introspector(): ReactiveOpaqueTokenIntrospector { [[webflux-oauth2resourceserver-opaque-authorization]] == Configuring Authorization -An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it's been granted, for example: +An OAuth 2.0 Introspection endpoint typically returns a `scope` attribute, indicating the scopes (or authorities) it has been granted -- for example: -`{ ..., "scope" : "messages contacts"}` +==== +[source,json] +---- +{ ..., "scope" : "messages contacts"} +---- +==== -When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string "SCOPE_". +When this is the case, Resource Server tries to coerce these scopes into a list of granted authorities, prefixing each scope with a string: `SCOPE_`. -This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix: +This means that, to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix: ==== .Java @@ -440,7 +450,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain ---- ==== -Or similarly with method security: +You can do something similar with method security: ==== .Java @@ -461,9 +471,9 @@ fun getMessages(): Flux { } [[webflux-oauth2resourceserver-opaque-authorization-extraction]] === Extracting Authorities Manually -By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances. +By default, Opaque Token support extracts the scope claim from an introspection response and parses it into individual `GrantedAuthority` instances. -For example, if the introspection response were: +Consider the following example: [source,json] ---- @@ -473,9 +483,9 @@ For example, if the introspection response were: } ---- -Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`. +If the introspection response were as the preceding example shows, Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`. -This can, of course, be customized using a custom `ReactiveOpaqueTokenIntrospector` that takes a look at the attribute set and converts in its own way: +You can customize behavior by using a custom `ReactiveOpaqueTokenIntrospector` that looks at the attribute set and converts in its own way: ==== .Java @@ -522,7 +532,7 @@ class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector ---- ==== -Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`: +Thereafter, you can configure this custom introspector by exposing it as a `@Bean`: ==== .Java @@ -548,12 +558,13 @@ fun introspector(): ReactiveOpaqueTokenIntrospector { == Using Introspection with JWTs A common question is whether or not introspection is compatible with JWTs. -Spring Security's Opaque Token support has been designed to not care about the format of the token -- it will gladly pass any token to the introspection endpoint provided. +Spring Security's Opaque Token support has been designed to not care about the format of the token. It gladly passes any token to the provided introspection endpoint. -So, let's say that you've got a requirement that requires you to check with the authorization server on each request, in case the JWT has been revoked. +So, suppose you need to check with the authorization server on each request, in case the JWT has been revoked. -Even though you are using the JWT format for the token, your validation method is introspection, meaning you'd want to do: +Even though you are using the JWT format for the token, your validation method is introspection, meaning you would want to do: +==== [source,yaml] ---- spring: @@ -565,14 +576,15 @@ spring: client-id: client client-secret: secret ---- +==== In this case, the resulting `Authentication` would be `BearerTokenAuthentication`. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint. -But, let's say that, oddly enough, the introspection endpoint only returns whether or not the token is active. +However, suppose that, for whatever reason, the introspection endpoint returns only whether or not the token is active. Now what? -In this case, you can create a custom `ReactiveOpaqueTokenIntrospector` that still hits the endpoint, but then updates the returned principal to have the JWTs claims as the attributes: +In this case, you can create a custom `ReactiveOpaqueTokenIntrospector` that still hits the endpoint but then updates the returned principal to have the JWTs claims as the attributes: ==== .Java @@ -626,7 +638,7 @@ class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector { ---- ==== -Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`: +Thereafter, you can configure this custom introspector by exposing it as a `@Bean`: ==== .Java @@ -651,16 +663,16 @@ fun introspector(): ReactiveOpaqueTokenIntrospector { [[webflux-oauth2resourceserver-opaque-userinfo]] == Calling a `/userinfo` Endpoint -Generally speaking, a Resource Server doesn't care about the underlying user, but instead about the authorities that have been granted. +Generally speaking, a Resource Server does not care about the underlying user but, instead, cares about the authorities that have been granted. That said, at times it can be valuable to tie the authorization statement back to a user. -If an application is also using `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, then this is quite simple with a custom `OpaqueTokenIntrospector`. -This implementation below does three things: +If an application also uses `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, you can do so with a custom `OpaqueTokenIntrospector`. +The implementation in the next listing does three things: -* Delegates to the introspection endpoint, to affirm the token's validity -* Looks up the appropriate client registration associated with the `/userinfo` endpoint -* Invokes and returns the response from the `/userinfo` endpoint +* Delegates to the introspection endpoint, to affirm the token's validity. +* Looks up the appropriate client registration associated with the `/userinfo` endpoint. +* Invokes and returns the response from the `/userinfo` endpoint. ==== .Java diff --git a/docs/modules/ROOT/pages/reactive/test/method.adoc b/docs/modules/ROOT/pages/reactive/test/method.adoc index 2c51dd24baa..348384273ce 100644 --- a/docs/modules/ROOT/pages/reactive/test/method.adoc +++ b/docs/modules/ROOT/pages/reactive/test/method.adoc @@ -1,8 +1,8 @@ [[test-erms]] = Testing Method Security -For example, we can test our example from xref:reactive/authorization/method.adoc#jc-erms[EnableReactiveMethodSecurity] using the same setup and annotations we did in xref:servlet/test/method.adoc#test-method[Testing Method Security]. -Here is a minimal sample of what we can do: +For example, we can test our example from xref:reactive/authorization/method.adoc#jc-erms[EnableReactiveMethodSecurity] by using the same setup and annotations that we used in xref:servlet/test/method.adoc#test-method[Testing Method Security]. +The following minimal sample shows what we can do: ==== .Java diff --git a/docs/modules/ROOT/pages/reactive/test/web/authentication.adoc b/docs/modules/ROOT/pages/reactive/test/web/authentication.adoc index 897356789c7..cee14a72aaa 100644 --- a/docs/modules/ROOT/pages/reactive/test/web/authentication.adoc +++ b/docs/modules/ROOT/pages/reactive/test/web/authentication.adoc @@ -1,7 +1,6 @@ = Testing Authentication -After xref:reactive/test/web/setup.adoc[applying the Spring Security support to `WebTestClient`] we can use either annotations or `mutateWith` support. -For example: +After xref:reactive/test/web/setup.adoc[applying the Spring Security support to `WebTestClient`], we can use either annotations or `mutateWith` support -- for example: ==== .Java diff --git a/docs/modules/ROOT/pages/reactive/test/web/csrf.adoc b/docs/modules/ROOT/pages/reactive/test/web/csrf.adoc index da3b917c35b..2b9b56f7033 100644 --- a/docs/modules/ROOT/pages/reactive/test/web/csrf.adoc +++ b/docs/modules/ROOT/pages/reactive/test/web/csrf.adoc @@ -1,7 +1,6 @@ = Testing with CSRF -Spring Security also provides support for CSRF testing with `WebTestClient`. -For example: +Spring Security also provides support for CSRF testing with `WebTestClient` -- for example: ==== .Java diff --git a/docs/modules/ROOT/pages/reactive/test/web/oauth2.adoc b/docs/modules/ROOT/pages/reactive/test/web/oauth2.adoc index cdabd0f0387..91994fbf25f 100644 --- a/docs/modules/ROOT/pages/reactive/test/web/oauth2.adoc +++ b/docs/modules/ROOT/pages/reactive/test/web/oauth2.adoc @@ -3,7 +3,7 @@ When it comes to OAuth 2.0, xref:reactive/test/method.adoc#test-erms[the same principles covered earlier still apply]: Ultimately, it depends on what your method under test is expecting to be in the `SecurityContextHolder`. -For example, for a controller that looks like this: +Consider the following example of a controller: ==== .Java @@ -25,9 +25,9 @@ fun foo(user: Principal): Mono { ---- ==== -There's nothing OAuth2-specific about it, so you will likely be able to simply xref:reactive/test/method.adoc#test-erms[use `@WithMockUser`] and be fine. +Nothing about it is OAuth2-specific, so you can xref:reactive/test/method.adoc#test-erms[use `@WithMockUser`] and be fine. -But, in cases where your controllers are bound to some aspect of Spring Security's OAuth 2.0 support, like the following: +However, consider a case where your controller is bound to some aspect of Spring Security's OAuth 2.0 support: ==== .Java @@ -49,15 +49,15 @@ fun foo(@AuthenticationPrincipal user: OidcUser): Mono { ---- ==== -then Spring Security's test support can come in handy. +In that case, Spring Security's test support is handy. [[webflux-testing-oidc-login]] == Testing OIDC Login -Testing the method above with `WebTestClient` would require simulating some kind of grant flow with an authorization server. -Certainly this would be a daunting task, which is why Spring Security ships with support for removing this boilerplate. +Testing the method shown in the <> with `WebTestClient` requires simulating some kind of grant flow with an authorization server. +This is a daunting task, which is why Spring Security ships with support for removing this boilerplate. -For example, we can tell Spring Security to include a default `OidcUser` using the `SecurityMockServerConfigurers#mockOidcLogin` method, like so: +For example, we can tell Spring Security to include a default `OidcUser` by using the `SecurityMockServerConfigurers#oidcLogin` method: ==== .Java @@ -77,9 +77,9 @@ client ---- ==== -What this will do is configure the associated `MockServerRequest` with an `OidcUser` that includes a simple `OidcIdToken`, `OidcUserInfo`, and `Collection` of granted authorities. +That line configures the associated `MockServerRequest` with an `OidcUser` that includes a simple `OidcIdToken`, an `OidcUserInfo`, and a `Collection` of granted authorities. -Specifically, it will include an `OidcIdToken` with a `sub` claim set to `user`: +Specifically, it includes an `OidcIdToken` with a `sub` claim set to `user`: ==== .Java @@ -95,7 +95,7 @@ assertThat(user.idToken.getClaim("sub")).isEqualTo("user") ---- ==== -an `OidcUserInfo` with no claims set: +It also includes an `OidcUserInfo` with no claims set: ==== .Java @@ -111,7 +111,7 @@ assertThat(user.userInfo.claims).isEmpty() ---- ==== -and a `Collection` of authorities with just one authority, `SCOPE_read`: +It also includes a `Collection` of authorities with just one authority, `SCOPE_read`: ==== .Java @@ -129,9 +129,9 @@ assertThat(user.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read" ---- ==== -Spring Security does the necessary work to make sure that the `OidcUser` instance is available for xref:servlet/integrations/mvc.adoc#mvc-authentication-principal[the `@AuthenticationPrincipal` annotation]. +Spring Security makes sure that the `OidcUser` instance is available forxref:servlet/integrations/mvc.adoc#mvc-authentication-principal[the `@AuthenticationPrincipal` annotation]. -Further, it also links that `OidcUser` to a simple instance of `OAuth2AuthorizedClient` that it deposits into a mock `ServerOAuth2AuthorizedClientRepository`. +Further, it also links the `OidcUser` to a simple instance of `OAuth2AuthorizedClient` that it deposits into a mock `ServerOAuth2AuthorizedClientRepository`. This can be handy if your tests <>.. [[webflux-testing-oidc-login-authorities]] @@ -139,7 +139,7 @@ This can be handy if your tests < { ---- ==== -In that case, you'd want to specify that claim with the `idToken()` method: +In that case, you can specify that claim with the `idToken()` method: ==== .Java @@ -217,22 +217,22 @@ client ---- ==== -since `OidcUser` collects its claims from `OidcIdToken`. +That works because `OidcUser` collects its claims from `OidcIdToken`. [[webflux-testing-oidc-login-user]] === Additional Configurations -There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects: +There are additional methods, too, for further configuring the authentication, depending on what data your controller expects: -* `userInfo(OidcUserInfo.Builder)` - For configuring the `OidcUserInfo` instance -* `clientRegistration(ClientRegistration)` - For configuring the associated `OAuth2AuthorizedClient` with a given `ClientRegistration` -* `oidcUser(OidcUser)` - For configuring the complete `OidcUser` instance +* `userInfo(OidcUserInfo.Builder)`: Configures the `OidcUserInfo` instance +* `clientRegistration(ClientRegistration)`: Configures the associated `OAuth2AuthorizedClient` with a given `ClientRegistration` +* `oidcUser(OidcUser)`: Configures the complete `OidcUser` instance That last one is handy if you: -1. Have your own implementation of `OidcUser`, or -2. Need to change the name attribute +* Have your own implementation of `OidcUser` or +* Need to change the name attribute -For example, let's say that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim. +For example, suppose that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim. In that case, you can configure an `OidcUser` by hand: ==== @@ -267,10 +267,10 @@ client [[webflux-testing-oauth2-login]] == Testing OAuth 2.0 Login -As with <>, testing OAuth 2.0 Login presents a similar challenge of mocking a grant flow. -And because of that, Spring Security also has test support for non-OIDC use cases. +As with <>, testing OAuth 2.0 Login presents a similar challenge: mocking a grant flow. +Because of that, Spring Security also has test support for non-OIDC use cases. -Let's say that we've got a controller that gets the logged-in user as an `OAuth2User`: +Suppose that we have a controller that gets the logged-in user as an `OAuth2User`: ==== .Java @@ -292,7 +292,7 @@ fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): Mono { ---- ==== -In that case, we can tell Spring Security to include a default `OAuth2User` using the `SecurityMockServerConfigurers#mockOAuth2Login` method, like so: +In that case, we can tell Spring Security to include a default `OAuth2User` by using the `SecurityMockServerConfigurers#oauth2User` method: ==== .Java @@ -312,9 +312,9 @@ client ---- ==== -What this will do is configure the associated `MockServerRequest` with an `OAuth2User` that includes a simple `Map` of attributes and `Collection` of granted authorities. +The preceding example configures the associated `MockServerRequest` with an `OAuth2User` that includes a simple `Map` of attributes and a `Collection` of granted authorities. -Specifically, it will include a `Map` with a key/value pair of `sub`/`user`: +Specifically, it includes a `Map` with a key/value pair of `sub`/`user`: ==== .Java @@ -330,7 +330,7 @@ assertThat(user.getAttribute("sub")).isEqualTo("user") ---- ==== -and a `Collection` of authorities with just one authority, `SCOPE_read`: +It also includes a `Collection` of authorities with just one authority, `SCOPE_read`: ==== .Java @@ -358,7 +358,7 @@ This can be handy if your tests < { ---- ==== -In that case, you'd want to specify that attribute with the `attributes()` method: +In that case, you can specify that attribute with the `attributes()` method: ==== .Java @@ -439,16 +439,16 @@ client [[webflux-testing-oauth2-login-user]] === Additional Configurations -There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects: +There are additional methods, too, for further configuring the authentication, depending on what data your controller expects: -* `clientRegistration(ClientRegistration)` - For configuring the associated `OAuth2AuthorizedClient` with a given `ClientRegistration` -* `oauth2User(OAuth2User)` - For configuring the complete `OAuth2User` instance +* `clientRegistration(ClientRegistration)`: Configures the associated `OAuth2AuthorizedClient` with a given `ClientRegistration` +* `oauth2User(OAuth2User)`: Configures the complete `OAuth2User` instance That last one is handy if you: -1. Have your own implementation of `OAuth2User`, or -2. Need to change the name attribute +* Have your own implementation of `OAuth2User` or +* Need to change the name attribute -For example, let's say that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim. +For example, suppose that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim. In that case, you can configure an `OAuth2User` by hand: ==== @@ -484,7 +484,7 @@ client == Testing OAuth 2.0 Clients Independent of how your user authenticates, you may have other tokens and client registrations that are in play for the request you are testing. -For example, your controller may be relying on the client credentials grant to get a token that isn't associated with the user at all: +For example, your controller may rely on the client credentials grant to get a token that is not associated with the user at all: ==== .Java @@ -516,8 +516,8 @@ fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2Auth ---- ==== -Simulating this handshake with the authorization server could be cumbersome. -Instead, you can use `SecurityMockServerConfigurers#mockOAuth2Client` to add a `OAuth2AuthorizedClient` into a mock `ServerOAuth2AuthorizedClientRepository`: +Simulating this handshake with the authorization server can be cumbersome. +Instead, you can use `SecurityMockServerConfigurers#oauth2Client` to add a `OAuth2AuthorizedClient` to a mock `ServerOAuth2AuthorizedClientRepository`: ==== .Java @@ -537,9 +537,9 @@ client ---- ==== -What this will do is create an `OAuth2AuthorizedClient` that has a simple `ClientRegistration`, `OAuth2AccessToken`, and resource owner name. +This creates an `OAuth2AuthorizedClient` that has a simple `ClientRegistration`, a `OAuth2AccessToken`, and a resource owner name. -Specifically, it will include a `ClientRegistration` with a client id of "test-client" and client secret of "test-secret": +Specifically, it includes a `ClientRegistration` with a client ID of `test-client` and a client secret of `test-secret`: ==== .Java @@ -557,7 +557,7 @@ assertThat(authorizedClient.clientRegistration.clientSecret).isEqualTo("test-sec ---- ==== -a resource owner name of "user": +It also includes a resource owner name of `user`: ==== .Java @@ -573,7 +573,7 @@ assertThat(authorizedClient.principalName).isEqualTo("user") ---- ==== -and an `OAuth2AccessToken` with just one scope, `read`: +It also includes an `OAuth2AccessToken` with one scope, `read`: ==== .Java @@ -591,13 +591,13 @@ assertThat(authorizedClient.accessToken.scopes).containsExactly("read") ---- ==== -The client can then be retrieved as normal using `@RegisteredOAuth2AuthorizedClient` in a controller method. +You can then retrieve the client as usual by using `@RegisteredOAuth2AuthorizedClient` in a controller method. [[webflux-testing-oauth2-client-scopes]] === Configuring Scopes In many circumstances, the OAuth 2.0 access token comes with a set of scopes. -If your controller inspects these, say like so: +Consider the following example of how a controller can inspect the scopes: ==== .Java @@ -637,7 +637,7 @@ fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2Auth ---- ==== -then you can configure the scope using the `accessToken()` method: +Given a controller that inspects scopes, you can configure the scope by using the `accessToken()` method: ==== .Java @@ -664,15 +664,15 @@ client [[webflux-testing-oauth2-client-registration]] === Additional Configurations -There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects: +You can also use additional methods to further configure the authentication depending on what data your controller expects: -* `principalName(String)` - For configuring the resource owner name -* `clientRegistration(Consumer)` - For configuring the associated `ClientRegistration` -* `clientRegistration(ClientRegistration)` - For configuring the complete `ClientRegistration` +* `principalName(String)`; Configures the resource owner name +* `clientRegistration(Consumer)`: Configures the associated `ClientRegistration` +* `clientRegistration(ClientRegistration)`: Configures the complete `ClientRegistration` That last one is handy if you want to use a real `ClientRegistration` -For example, let's say that you are wanting to use one of your app's `ClientRegistration` definitions, as specified in your `application.yml`. +For example, suppose that you want to use one of your application's `ClientRegistration` definitions, as specified in your `application.yml`. In that case, your test can autowire the `ReactiveClientRegistrationRepository` and look up the one your test needs: @@ -711,16 +711,16 @@ client [[webflux-testing-jwt]] == Testing JWT Authentication -In order to make an authorized request on a resource server, you need a bearer token. -If your resource server is configured for JWTs, then this would mean that the bearer token needs to be signed and then encoded according to the JWT specification. -All of this can be quite daunting, especially when this isn't the focus of your test. +To make an authorized request on a resource server, you need a bearer token. +If your resource server is configured for JWTs, the bearer token needs to be signed and then encoded according to the JWT specification. +All of this can be quite daunting, especially when this is not the focus of your test. -Fortunately, there are a number of simple ways that you can overcome this difficulty and allow your tests to focus on authorization and not on representing bearer tokens. -We'll look at two of them now: +Fortunately, there are a number of simple ways in which you can overcome this difficulty and let your tests focus on authorization and not on representing bearer tokens. +We look at two of them in the next two subsections. === `mockJwt() WebTestClientConfigurer` -The first way is via a `WebTestClientConfigurer`. +The first way is with a `WebTestClientConfigurer`. The simplest of these would be to use the `SecurityMockServerConfigurers#mockJwt` method like the following: ==== @@ -739,7 +739,7 @@ client ---- ==== -What this will do is create a mock `Jwt`, passing it correctly through any authentication APIs so that it's available for your authorization mechanisms to verify. +This example creates a mock `Jwt` and passes it through any authentication APIs so that it is available for your authorization mechanisms to verify. By default, the `JWT` that it creates has the following characteristics: @@ -754,7 +754,7 @@ By default, the `JWT` that it creates has the following characteristics: } ---- -And the resulting `Jwt`, were it tested, would pass in the following way: +The resulting `Jwt`, were it tested, would pass in the following way: ==== .Java @@ -774,9 +774,9 @@ assertThat(jwt.subject).isEqualTo("sub") ---- ==== -These values can, of course be configured. +Note that you configure these values. -Any headers or claims can be configured with their corresponding methods: +You can also configure any headers or claims with their corresponding methods: ==== .Java @@ -840,7 +840,7 @@ client ---- ==== -Or, if you have a custom `Jwt` to `Collection` converter, you can also use that to derive the authorities: +Alternatively, if you have a custom `Jwt` to `Collection` converter, you can also use that to derive the authorities: ==== .Java @@ -860,7 +860,7 @@ client ---- ==== -You can also specify a complete `Jwt`, for which `{security-api-url}org/springframework/security/oauth2/jwt/Jwt.Builder.html[Jwt.Builder]` comes quite handy: +You can also specify a complete `Jwt`, for which `{security-api-url}org/springframework/security/oauth2/jwt/Jwt.Builder.html[Jwt.Builder]` is quite handy: ==== .Java @@ -892,10 +892,10 @@ client ---- ==== -=== `authentication()` `WebTestClientConfigurer` +=== `authentication()` and `WebTestClientConfigurer` The second way is by using the `authentication()` `Mutator`. -Essentially, you can instantiate your own `JwtAuthenticationToken` and provide it in your test, like so: +You can instantiate your own `JwtAuthenticationToken` and provide it in your test: ==== .Java @@ -929,7 +929,7 @@ client ---- ==== -Note that as an alternative to these, you can also mock the `ReactiveJwtDecoder` bean itself with a `@MockBean` annotation. +Note that, as an alternative to these, you can also mock the `ReactiveJwtDecoder` bean itself with a `@MockBean` annotation. [[webflux-testing-opaque-token]] == Testing Opaque Token Authentication @@ -937,7 +937,7 @@ Note that as an alternative to these, you can also mock the `ReactiveJwtDecoder` Similar to <>, opaque tokens require an authorization server in order to verify their validity, which can make testing more difficult. To help with that, Spring Security has test support for opaque tokens. -Let's say that we've got a controller that retrieves the authentication as a `BearerTokenAuthentication`: +Suppose you have a controller that retrieves the authentication as a `BearerTokenAuthentication`: ==== .Java @@ -959,7 +959,7 @@ fun foo(authentication: BearerTokenAuthentication): Mono { ---- ==== -In that case, we can tell Spring Security to include a default `BearerTokenAuthentication` using the `SecurityMockServerConfigurers#mockOpaqueToken` method, like so: +In that case, you can tell Spring Security to include a default `BearerTokenAuthentication` by using the `SecurityMockServerConfigurers#opaqueToken` method: ==== .Java @@ -979,9 +979,9 @@ client ---- ==== -What this will do is configure the associated `MockHttpServletRequest` with a `BearerTokenAuthentication` that includes a simple `OAuth2AuthenticatedPrincipal`, `Map` of attributes, and `Collection` of granted authorities. +This example configures the associated `MockHttpServletRequest` with a `BearerTokenAuthentication` that includes a simple `OAuth2AuthenticatedPrincipal`, a `Map` of attributes, and a `Collection` of granted authorities. -Specifically, it will include a `Map` with a key/value pair of `sub`/`user`: +Specifically, it includes a `Map` with a key/value pair of `sub`/`user`: ==== .Java @@ -997,7 +997,7 @@ assertThat(token.tokenAttributes["sub"] as String?).isEqualTo("user") ---- ==== -and a `Collection` of authorities with just one authority, `SCOPE_read`: +It also includes a `Collection` of authorities with just one authority, `SCOPE_read`: ==== .Java @@ -1049,10 +1049,10 @@ client [[webflux-testing-opaque-token-attributes]] === Configuring Claims -And while granted authorities are quite common across all of Spring Security, we also have attributes in the case of OAuth 2.0. +While granted authorities are quite common across all of Spring Security, we also have attributes in the case of OAuth 2.0. -Let's say, for example, that you've got a `user_id` attribute that indicates the user's id in your system. -You might access it like so in a controller: +Suppose, for example, that you have a `user_id` attribute that indicates the user's ID in your system. +You might access it as follows in a controller: ==== .Java @@ -1076,7 +1076,7 @@ fun foo(authentication: BearerTokenAuthentication): Mono { ---- ==== -In that case, you'd want to specify that attribute with the `attributes()` method: +In that case, you can specify that attribute with the `attributes()` method: ==== .Java @@ -1103,15 +1103,15 @@ client [[webflux-testing-opaque-token-principal]] === Additional Configurations -There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects. +You can also use additional methods to further configure the authentication, depending on what data your controller expects. -One such is `principal(OAuth2AuthenticatedPrincipal)`, which you can use to configure the complete `OAuth2AuthenticatedPrincipal` instance that underlies the `BearerTokenAuthentication` +One such method is `principal(OAuth2AuthenticatedPrincipal)`, which you can use to configure the complete `OAuth2AuthenticatedPrincipal` instance that underlies the `BearerTokenAuthentication`. -It's handy if you: -1. Have your own implementation of `OAuth2AuthenticatedPrincipal`, or -2. Want to specify a different principal name +It is handy if you: +* Have your own implementation of `OAuth2AuthenticatedPrincipal` or +* Want to specify a different principal name -For example, let's say that your authorization server sends the principal name in the `user_name` attribute instead of the `sub` attribute. +For example, suppose that your authorization server sends the principal name in the `user_name` attribute instead of the `sub` attribute. In that case, you can configure an `OAuth2AuthenticatedPrincipal` by hand: ==== @@ -1145,4 +1145,4 @@ client ---- ==== -Note that as an alternative to using `mockOpaqueToken()` test support, you can also mock the `OpaqueTokenIntrospector` bean itself with a `@MockBean` annotation. +Note that, as an alternative to using `mockOpaqueToken()` test support, you can also mock the `OpaqueTokenIntrospector` bean itself with a `@MockBean` annotation. diff --git a/docs/modules/ROOT/pages/servlet/appendix/database-schema.adoc b/docs/modules/ROOT/pages/servlet/appendix/database-schema.adoc index f6cf413b681..83bccb0daec 100644 --- a/docs/modules/ROOT/pages/servlet/appendix/database-schema.adoc +++ b/docs/modules/ROOT/pages/servlet/appendix/database-schema.adoc @@ -1,7 +1,7 @@ [[appendix-schema]] = Security Database Schema -There are various database schema used by the framework and this appendix provides a single reference point to them all. -You only need to provide the tables for the areas of functionality you require. +The framework uses various database schema. This appendix provides a single reference point to them all. +You need only provide the tables for the areas of functionality you require. DDL statements are given for the HSQLDB database. You can use these as a guideline for defining the schema for the database you are using. @@ -9,8 +9,9 @@ You can use these as a guideline for defining the schema for the database you ar == User Schema The standard JDBC implementation of the `UserDetailsService` (`JdbcDaoImpl`) requires tables to load the password, account status (enabled or disabled) and a list of authorities (roles) for the user. -You will need to adjust this schema to match the database dialect you are using. +You can use these as a guideline for defining the schema for the database you use. +==== [source] ---- @@ -27,8 +28,13 @@ create table authorities ( ); create unique index ix_auth_username on authorities (username,authority); ---- +==== === For Oracle database + +The following listing shows the Oracle variant of the schema creation commands: + +==== [source] ---- CREATE TABLE USERS ( @@ -45,12 +51,14 @@ CREATE TABLE AUTHORITIES ( ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_UNIQUE UNIQUE (USERNAME, AUTHORITY); ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME) REFERENCES USERS (USERNAME) ENABLE; ---- +==== === Group Authorities Spring Security 2.0 introduced support for group authorities in `JdbcDaoImpl`. The table structure if groups are enabled is as follows. -You will need to adjust this schema to match the database dialect you are using. +You need to adjust the following schema to match the database dialect you use: +==== [source] ---- @@ -72,16 +80,18 @@ create table group_members ( constraint fk_group_members_group foreign key(group_id) references groups(id) ); ---- +==== -Remember that these tables are only required if you are using the provided JDBC `UserDetailsService` implementation. -If you write your own or choose to implement `AuthenticationProvider` without a `UserDetailsService`, then you have complete freedom over how you store the data, as long as the interface contract is satisfied. +Remember that these tables are required only if you us the provided JDBC `UserDetailsService` implementation. +If you write your own or choose to implement `AuthenticationProvider` without a `UserDetailsService`, you have complete freedom over how you store the data, as long as the interface contract is satisfied. == Persistent Login (Remember-Me) Schema -This table is used to store data used by the more secure xref:servlet/authentication/rememberme.adoc#remember-me-persistent-token[persistent token] remember-me implementation. -If you are using `JdbcTokenRepositoryImpl` either directly or through the namespace, then you will need this table. -Remember to adjust this schema to match the database dialect you are using. +This table is used to store the data used by the more secure <> remember-me implementation. +If you use `JdbcTokenRepositoryImpl` either directly or through the namespace, you need this table. +Remember to adjust this schema to match the database dialect you use: +==== [source] ---- @@ -93,21 +103,22 @@ create table persistent_logins ( ); ---- +==== [[dbschema-acl]] == ACL Schema -There are four tables used by the Spring Security xref:servlet/authorization/acls.adoc#domain-acls[ACL] implementation. +The Spring Security xref:servlet/authorization/acls.adoc#domain-acls[ACL] implementation uses four tables. -. `acl_sid` stores the security identities recognised by the ACL system. -These can be unique principals or authorities which may apply to multiple principals. -. `acl_class` defines the domain object types to which ACLs apply. +* `acl_sid` stores the security identities recognised by the ACL system. +These can be unique principals or authorities, which may apply to multiple principals. +* `acl_class` defines the domain object types to which ACLs apply. The `class` column stores the Java class name of the object. -. `acl_object_identity` stores the object identity definitions of specific domain objects. -. `acl_entry` stores the ACL permissions which apply to a specific object identity and security identity. +* `acl_object_identity` stores the object identity definitions of specific domain objects. +* `acl_entry` stores the ACL permissions, each of which applies to a specific object identity and security identity. -It is assumed that the database will auto-generate the primary keys for each of the identities. +We assume that the database auto-generates the primary keys for each of the identities. The `JdbcMutableAclService` has to be able to retrieve these when it has created a new row in the `acl_sid` or `acl_class` tables. -It has two properties which define the SQL needed to retrieve these values `classIdentityQuery` and `sidIdentityQuery`. +It has two properties that define the SQL needed to retrieve these values `classIdentityQuery` and `sidIdentityQuery`. Both of these default to `call identity()` The ACL artifact JAR contains files for creating the ACL schema in HyperSQL (HSQLDB), PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, and Oracle Database. @@ -116,9 +127,9 @@ These schemas are also demonstrated in the following sections. === HyperSQL The default schema works with the embedded HSQLDB database that is used in unit tests within the framework. +==== [source,ddl] ---- - create table acl_sid( id bigint generated by default as identity(start with 100) not null primary key, principal boolean not null, @@ -159,8 +170,16 @@ create table acl_entry( constraint foreign_fk_5 foreign key(sid) references acl_sid(id) ); ---- +==== === PostgreSQL + +For PostgreSQL, you have to set the `classIdentityQuery` and `sidIdentityQuery` properties of `JdbcMutableAclService` to the following values, respectively: + +* `select currval(pg_get_serial_sequence('acl_class', 'id'))` +* `select currval(pg_get_serial_sequence('acl_sid', 'id'))` + +==== [source,ddl] ---- create table acl_sid( @@ -203,13 +222,11 @@ create table acl_entry( constraint foreign_fk_5 foreign key(sid) references acl_sid(id) ); ---- - -You will have to set the `classIdentityQuery` and `sidIdentityQuery` properties of `JdbcMutableAclService` to the following values, respectively: - -* `select currval(pg_get_serial_sequence('acl_class', 'id'))` -* `select currval(pg_get_serial_sequence('acl_sid', 'id'))` +==== === MySQL and MariaDB + +==== [source,ddl] ---- CREATE TABLE acl_sid ( @@ -252,8 +269,11 @@ CREATE TABLE acl_entry ( CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id) ) ENGINE=InnoDB; ---- +==== === Microsoft SQL Server + +==== [source,ddl] ---- CREATE TABLE acl_sid ( @@ -296,8 +316,11 @@ CREATE TABLE acl_entry ( CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id) ); ---- +==== === Oracle Database + +==== [source,ddl] ---- CREATE TABLE ACL_SID ( @@ -363,13 +386,14 @@ BEGIN SELECT ACL_ENTRY_SQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; ---- - +==== [[dbschema-oauth2-client]] == OAuth 2.0 Client Schema -The JDBC implementation of xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-authorized-repo-service[ OAuth2AuthorizedClientService] (`JdbcOAuth2AuthorizedClientService`) requires a table for persisting `OAuth2AuthorizedClient`(s). -You will need to adjust this schema to match the database dialect you are using. +The JDBC implementation of xref:servlet/oauth2/client/core.adoc#oauth2Client-authorized-repo-service[ `OAuth2AuthorizedClientService`] (`JdbcOAuth2AuthorizedClientService`) requires a table for persisting `OAuth2AuthorizedClient` instances. +You will need to adjust this schema to match the database dialect you use. +==== [source,ddl] ---- CREATE TABLE oauth2_authorized_client ( @@ -386,3 +410,4 @@ CREATE TABLE oauth2_authorized_client ( PRIMARY KEY (client_registration_id, principal_name) ); ---- +==== diff --git a/docs/modules/ROOT/pages/servlet/appendix/faq.adoc b/docs/modules/ROOT/pages/servlet/appendix/faq.adoc index 87dcff45642..328707bcc6c 100644 --- a/docs/modules/ROOT/pages/servlet/appendix/faq.adoc +++ b/docs/modules/ROOT/pages/servlet/appendix/faq.adoc @@ -1,6 +1,8 @@ [[appendix-faq]] = Spring Security FAQ +This FAQ has the following sections: + * <> * <> * <> @@ -9,57 +11,59 @@ [[appendix-faq-general-questions]] == General Questions -. <> -. <> -. <> -. <> +This FAQ answers the following general questions: + +* <> +* <> +* <> +* <> [[appendix-faq-other-concerns]] -=== Will Spring Security take care of all my application security requirements? +=== Can Spring Security take care of all my application security requirements? -Spring Security provides you with a very flexible framework for your authentication and authorization requirements, but there are many other considerations for building a secure application that are outside its scope. -Web applications are vulnerable to all kinds of attacks which you should be familiar with, preferably before you start development so you can design and code with them in mind from the beginning. -Check out the https://www.owasp.org/[OWASP web site] for information on the major issues facing web application developers and the countermeasures you can use against them. +Spring Security provides you with a flexible framework for your authentication and authorization requirements, but there are many other considerations for building a secure application that are outside its scope. +Web applications are vulnerable to all kinds of attacks with which you should be familiar, preferably before you start development so that you can design and code with them in mind from the beginning. +Check out the https://www.owasp.org/[OWASP web site] for information on the major issues that face web application developers and the countermeasures you can use against them. [[appendix-faq-web-xml]] -=== Why not just use web.xml security? +=== Why Not Use web.xml Security? -Let's assume you're developing an enterprise application based on Spring. -There are four security concerns you typically need to address: authentication, web request security, service layer security (i.e. your methods that implement business logic), and domain object instance security (i.e. different domain objects have different permissions). With these typical requirements in mind: +Suppose you are developing an enterprise application based on Spring. +You typically need to address four security concerns : authentication, web request security, service layer security (your methods that implement business logic), and domain object instance security (different domain objects can have different permissions). With these typical requirements in mind, we have the following considerations: -. __Authentication__: The servlet specification provides an approach to authentication. -However, you will need to configure the container to perform authentication which typically requires editing of container-specific "realm" settings. -This makes a non-portable configuration, and if you need to write an actual Java class to implement the container's authentication interface, it becomes even more non-portable. -With Spring Security you achieve complete portability - right down to the WAR level. +* _Authentication_: The servlet specification provides an approach to authentication. +However, you need to configure the container to perform authentication, which typically requires editing of container-specific "`realm`" settings. +This makes a non-portable configuration. Also, if you need to write an actual Java class to implement the container's authentication interface, it becomes even more non-portable. +With Spring Security, you achieve complete portability -- right down to the WAR level. Also, Spring Security offers a choice of production-proven authentication providers and mechanisms, meaning you can switch your authentication approaches at deployment time. This is particularly valuable for software vendors writing products that need to work in an unknown target environment. -. __Web request security:__ The servlet specification provides an approach to secure your request URIs. -However, these URIs can only be expressed in the servlet specification's own limited URI path format. +* _Web request security:_ The servlet specification provides an approach to secure your request URIs. +However, these URIs can be expressed only in the servlet specification's own limited URI path format. Spring Security provides a far more comprehensive approach. -For instance, you can use Ant paths or regular expressions, you can consider parts of the URI other than simply the requested page (e.g. -you can consider HTTP GET parameters) and you can implement your own runtime source of configuration data. -This means your web request security can be dynamically changed during the actual execution of your webapp. +For instance, you can use Ant paths or regular expressions, you can consider parts of the URI other than simply the requested page (for example, +you can consider HTTP GET parameters), and you can implement your own runtime source of configuration data. +This means that you can dynamically change your web request security during the actual execution of your web application. -. __Service layer and domain object security:__ The absence of support in the servlet specification for services layer security or domain object instance security represent serious limitations for multi-tiered applications. -Typically developers either ignore these requirements, or implement security logic within their MVC controller code (or even worse, inside the views). There are serious disadvantages with this approach: +* _Service layer and domain object security:_ The absence of support in the servlet specification for services layer security or domain object instance security represents serious limitations for multi-tiered applications. +Typically, developers either ignore these requirements or implement security logic within their MVC controller code (or, even worse, inside the views). There are serious disadvantages with this approach: -.. __Separation of concerns:__ Authorization is a crosscutting concern and should be implemented as such. -MVC controllers or views implementing authorization code makes it more difficult to test both the controller and authorization logic, more difficult to debug, and will often lead to code duplication. +** _Separation of concerns:_ Authorization is a crosscutting concern and should be implemented as such. +MVC controllers or views that implement authorization code makes it more difficult to test both the controller and the authorization logic, is more difficult to debug, and often leads to code duplication. -.. __Support for rich clients and web services:__ If an additional client type must ultimately be supported, any authorization code embedded within the web layer is non-reusable. -It should be considered that Spring remoting exporters only export service layer beans (not MVC controllers). As such authorization logic needs to be located in the services layer to support a multitude of client types. +** _Support for rich clients and web services:_ If an additional client type must ultimately be supported, any authorization code embedded within the web layer is non-reusable. +It should be considered that Spring remoting exporters export only service layer beans (not MVC controllers). As a result, authorization logic needs to be located in the services layer to support a multitude of client types. -.. __Layering issues:__ An MVC controller or view is simply the incorrect architectural layer to implement authorization decisions concerning services layer methods or domain object instances. -Whilst the Principal may be passed to the services layer to enable it to make the authorization decision, doing so would introduce an additional argument on every services layer method. -A more elegant approach is to use a ThreadLocal to hold the Principal, although this would likely increase development time to a point where it would become more economical (on a cost-benefit basis) to simply use a dedicated security framework. +** _Layering issues:_ An MVC controller or view is the incorrect architectural layer in which to implement authorization decisions concerning services layer methods or domain object instances. +While the principal may be passed to the services layer to enable it to make the authorization decision, doing so would introduce an additional argument on every services layer method. +A more elegant approach is to use a `ThreadLocal` to hold the principal, although this would likely increase development time to a point where it would become more economical (on a cost-benefit basis) to use a dedicated security framework. -.. __Authorisation code quality:__ It is often said of web frameworks that they "make it easier to do the right things, and harder to do the wrong things". Security frameworks are the same, because they are designed in an abstract manner for a wide range of purposes. -Writing your own authorization code from scratch does not provide the "design check" a framework would offer, and in-house authorization code will typically lack the improvements that emerge from widespread deployment, peer review and new versions. +** _Authorisation code quality:_ It is often said of web frameworks that they "`make it easier to do the right things, and harder to do the wrong things`". Security frameworks are the same, because they are designed in an abstract manner for a wide range of purposes. +Writing your own authorization code from scratch does not provide the "`design check`" a framework would offer, and in-house authorization code typically lacks the improvements that emerge from widespread deployment, peer review, and new versions. -For simple applications, servlet specification security may just be enough. +For simple applications, servlet specification security may be enough. Although when considered within the context of web container portability, configuration requirements, limited web request security flexibility, and non-existent services layer and domain object instance security, it becomes clear why developers often look to alternative solutions. @@ -67,76 +71,78 @@ Although when considered within the context of web container portability, config === What Java and Spring Framework versions are required? Spring Security 3.0 and 3.1 require at least JDK 1.5 and also require Spring 3.0.3 as a minimum. -Ideally you should be using the latest release versions to avoid problems. +Ideally, you should use the latest release versions to avoid problems. Spring Security 2.0.x requires a minimum JDK version of 1.4 and is built against Spring 2.0.x. -It should also be compatible with applications using Spring 2.5.x. +It should also be compatible with applications that use Spring 2.5.x. [[appendix-faq-start-simple]] -=== I'm new to Spring Security and I need to build an application that supports CAS single sign-on over HTTPS, while allowing Basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). I've copied some configuration files I found but it doesn't work. -What could be wrong? +==== I have a complex scenario. What could be wrong? + +(This answer address complex scenarios in general by dealing with a particular scenario.) -Or substitute an alternative complex scenario... +Suppose you are new to Spring Security and need to build an application that supports CAS single sign-on over HTTPS while allowing basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). You have copied some configuration files but have found that it does not work. What could be wrong? -Realistically, you need an understanding of the technologies you are intending to use before you can successfully build applications with them. +You need an understanding of the technologies you intend to use before you can successfully build applications with them. Security is complicated. -Setting up a simple configuration using a login form and some hard-coded users using Spring Security's namespace is reasonably straightforward. +Setting up a simple configuration by using a login form and some hard-coded users with Spring Security's namespace is reasonably straightforward. Moving to using a backed JDBC database is also easy enough. -But if you try and jump straight to a complicated deployment scenario like this you will almost certainly be frustrated. -There is a big jump in the learning curve required to set up systems like CAS, configure LDAP servers and install SSL certificates properly. +However, if you try to jump straight to a complicated deployment scenario like this scenario, you are almost certain to be frustrated. +There is a big jump in the learning curve required to set up systems such as CAS, configure LDAP servers, and install SSL certificates properly. So you need to take things one step at a time. -From a Spring Security perspective, the first thing you should do is follow the "Getting Started" guide on the web site. +From a Spring Security perspective, the first thing you should do is follow the "`Getting Started`" guide on the web site. This will take you through a series of steps to get up and running and get some idea of how the framework operates. -If you are using other technologies which you aren't familiar with then you should do some research and try to make sure you can use them in isolation before combining them in a complex system. +If you use other technologies with which you are not familiar, you should do some research and try to make sure you can use them in isolation before combining them in a complex system. [[appendix-faq-common-problems]] == Common Problems -. Authentication -.. <> -.. <> -.. <> -.. <> -.. <> -.. <> -. Session Management -.. <> -.. <> -.. <> -.. <> -.. <> -. Miscellaneous -.. <> -.. <> -.. <> -.. <> -.. <> +This section addresses the most common problems that people encounter when using Spring Security: + +* Authentication +** <> +** <> +** <> +** <> +** <> +** <> +* Session Management +** <> +** <> +** <> +** <> +** <> +* Miscellaneous +** <> +** <> +** <> +** <> +** <> [[appendix-faq-bad-credentials]] -=== When I try to log in, I get an error message that says "Bad Credentials". What's wrong? +=== When I try to log in, I get an error message that says, "`Bad Credentials`". What is wrong? This means that authentication has failed. -It doesn't say why, as it is good practice to avoid giving details which might help an attacker guess account names or passwords. +It does not say why, as it is good practice to avoid giving details that might help an attacker guess account names or passwords. -This also means that if you ask this question in the forum, you will not get an answer unless you provide additional information. -As with any issue you should check the output from the debug log, note any exception stacktraces and related messages. -Step through the code in a debugger to see where the authentication fails and why. -Write a test case which exercises your authentication configuration outside of the application. -More often than not, the failure is due to a difference in the password data stored in a database and that entered by the user. -If you are using hashed passwords, make sure the value stored in your database is __exactly__ the same as the value produced by the `PasswordEncoder` configured in your application. +This also means that, if you ask this question online, you should not expect an answer unless you provide additional information. +As with any issue, you should check the output from the debug log and note any exception stacktraces and related messages. +You should step through the code in a debugger to see where the authentication fails and why. +You should also write a test case which exercises your authentication configuration outside of the application. +If you use hashed passwords, make sure the value stored in your database is _exactly_ the same as the value produced by the `PasswordEncoder` configured in your application. [[appendix-faq-login-loop]] -=== My application goes into an "endless loop" when I try to login, what's going on? +=== My application goes into an "`endless loop`" when I try to login. What is going on? -A common user problem with infinite loop and redirecting to the login page is caused by accidentally configuring the login page as a "secured" resource. -Make sure your configuration allows anonymous access to the login page, either by excluding it from the security filter chain or marking it as requiring ROLE_ANONYMOUS. +A common user problem with infinite loop and redirecting to the login page is caused by accidentally configuring the login page as a "`secured`" resource. +Make sure your configuration allows anonymous access to the login page, either by excluding it from the security filter chain or marking it as requiring `ROLE_ANONYMOUS`. -If your AccessDecisionManager includes an AuthenticatedVoter, you can use the attribute "IS_AUTHENTICATED_ANONYMOUSLY". This is automatically available if you are using the standard namespace configuration setup. +If your `AccessDecisionManager` includes an `AuthenticatedVoter`, you can use the `IS_AUTHENTICATED_ANONYMOUSLY` attribute. This is automatically available if you use the standard namespace configuration setup. -From Spring Security 2.0.1 onwards, when you are using namespace-based configuration, a check will be made on loading the application context and a warning message logged if your login page appears to be protected. +From Spring Security 2.0.1 onwards, when you use namespace-based configuration, a check is made on loading the application context and a warning message logged if your login page appears to be protected. [[appendix-faq-anon-access-denied]] @@ -144,56 +150,56 @@ From Spring Security 2.0.1 onwards, when you are using namespace-based configura This is a debug level message which occurs the first time an anonymous user attempts to access a protected resource. +==== [source] ---- - DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point org.springframework.security.AccessDeniedException: Access is denied at org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68) at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262) - ---- +==== It is normal and shouldn't be anything to worry about. [[appendix-faq-cached-secure-page]] -=== Why can I still see a secured page even after I've logged out of my application? +=== Why can I still see a secured page even after I have logged out of my application? -The most common reason for this is that your browser has cached the page and you are seeing a copy which is being retrieved from the browsers cache. -Verify this by checking whether the browser is actually sending the request (check your server access logs, the debug log or use a suitable browser debugging plugin such as "Tamper Data" for Firefox). This has nothing to do with Spring Security and you should configure your application or server to set the appropriate `Cache-Control` response headers. +The most common reason for this is that your browser has cached the page and you are seeing a copy that is being retrieved from the browsers cache. +Verify this by checking whether the browser is actually sending the request (check your server access logs and the debug log or use a suitable browser debugging plugin, such as "`Tamper Data`" for Firefox). This has nothing to do with Spring Security, and you should configure your application or server to set the appropriate `Cache-Control` response headers. Note that SSL requests are never cached. [[auth-exception-credentials-not-found]] -=== I get an exception with the message "An Authentication object was not found in the SecurityContext". What's wrong? +=== I get an exception with a message of "An Authentication object was not found in the SecurityContext". What is wrong? -This is a another debug level message which occurs the first time an anonymous user attempts to access a protected resource, but when you do not have an `AnonymousAuthenticationFilter` in your filter chain configuration. +The following listing shows another debug-level message that occurs the first time an anonymous user attempts to access a protected resource. However, this listing shows what happens when you do not have an `AnonymousAuthenticationFilter` in your filter chain configuration: +==== [source] ---- - DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342) at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254) ---- +==== -It is normal and shouldn't be anything to worry about. +It is normal and is not something to worry about. [[appendix-faq-ldap-authentication]] -=== I can't get LDAP authentication to work. -What's wrong with my configuration? +=== I can't get LDAP authentication to work. What's wrong with my configuration? -Note that the permissions for an LDAP directory often do not allow you to read the password for a user. -Hence it is often not possible to use the <> where Spring Security compares the stored password with the one submitted by the user. -The most common approach is to use LDAP "bind", which is one of the operations supported by https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol[the LDAP protocol]. With this approach, Spring Security validates the password by attempting to authenticate to the directory as the user. +Note that the permissions for an LDAP directory often do not let you read the password for a user. +Hence, it is often not possible to use the <> where Spring Security compares the stored password with the one submitted by the user. +The most common approach is to use LDAP "`bind`", which is one of the operations supported by https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol[the LDAP protocol]. With this approach, Spring Security validates the password by trying to authenticate to the directory as the user. The most common problem with LDAP authentication is a lack of knowledge of the directory server tree structure and configuration. -This will be different in different companies, so you have to find it out yourself. -Before adding a Spring Security LDAP configuration to an application, it's a good idea to write a simple test using standard Java LDAP code (without Spring Security involved), and make sure you can get that to work first. +This differs from one company to another, so you have to find it out yourself. +Before adding a Spring Security LDAP configuration to an application, you should write a simple test by using standard Java LDAP code (without Spring Security involved) and make sure you can get that to work first. For example, to authenticate a user, you could use the following code: ==== @@ -234,120 +240,128 @@ fun ldapAuthenticationIsSuccessful() { === Session Management -Session management issues are a common source of forum questions. +Session management issues are a common source of questions. If you are developing Java web applications, you should understand how the session is maintained between the servlet container and the user's browser. -You should also understand the difference between secure and non-secure cookies and the implications of using HTTP/HTTPS and switching between the two. +You should also understand the difference between secure and non-secure cookies and the implications of using HTTP and HTTPS and switching between the two. Spring Security has nothing to do with maintaining the session or providing session identifiers. This is entirely handled by the servlet container. [[appendix-faq-concurrent-session-same-browser]] -=== I'm using Spring Security's concurrent session control to prevent users from logging in more than once at a time. -When I open another browser window after logging in, it doesn't stop me from logging in again. -Why can I log in more than once? +=== I am using Spring Security's concurrent session control to prevent users from logging in more than once at the same time. When I open another browser window after logging in, it does not stop me from logging in again. Why can I log in more than once? Browsers generally maintain a single session per browser instance. You cannot have two separate sessions at once. So if you log in again in another window or tab you are just reauthenticating in the same session. -The server doesn't know anything about tabs, windows or browser instances. -All it sees are HTTP requests and it ties those to a particular session according to the value of the JSESSIONID cookie that they contain. -When a user authenticates during a session, Spring Security's concurrent session control checks the number of __other authenticated sessions__ that they have. -If they are already authenticated with the same session, then re-authenticating will have no effect. +So, if you log in again in another window or tab, you are reauthenticating in the same session. +The server does not know anything about tabs, windows, or browser instances. +All it sees are HTTP requests, and it ties those to a particular session according to the value of the `JSESSIONID` cookie that they contain. +When a user authenticates during a session, Spring Security's concurrent session control checks the number of _other authenticated sessions_ that they have. +If they are already authenticated with the same session, re-authenticating has no effect. [[appendix-faq-new-session-on-authentication]] -=== Why does the session Id change when I authenticate through Spring Security? +=== Why does the session ID change when I authenticate through Spring Security? With the default configuration, Spring Security changes the session ID when the user authenticates. -If you're using a Servlet 3.1 or newer container, the session ID is simply changed. -If you're using an older container, Spring Security invalidates the existing session, creates a new session, and transfers the session data to the new session. -Changing the session identifier in this manner prevents"session-fixation" attacks. +If you us a Servlet 3.1 or newer container, the session ID is simply changed. +If you use an older container, Spring Security invalidates the existing session, creates a new session, and transfers the session data to the new session. +Changing the session identifier in this manner prevents "`session-fixation`" attacks. You can find more about this online and in the reference manual. [[appendix-faq-tomcat-https-session]] -=== I'm using Tomcat (or some other servlet container) and have enabled HTTPS for my login page, switching back to HTTP afterwards. +=== I use Tomcat (or some other servlet container) and have enabled HTTPS for my login page, switching back to HTTP afterwards. It does not work. I end up back at the login page after authenticating. It doesn't work - I just end up back at the login page after authenticating. -This happens because sessions created under HTTPS, for which the session cookie is marked as "secure", cannot subsequently be used under HTTP. The browser will not send the cookie back to the server and any session state will be lost (including the security context information). Starting a session in HTTP first should work as the session cookie won't be marked as secure. +This happens because sessions created under HTTPS, for which the session cookie is marked as "`secure`", cannot subsequently be used under HTTP. The browser does not send the cookie back to the server, and any session state (including the security context information) is lost. Starting a session in HTTP first should work, as the session cookie is not marked as secure. However, Spring Security's https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-session-fixation[Session Fixation Protection] can interfere with this because it results in a new session ID cookie being sent back to the user's browser, usually with the secure flag. -To get around this, you can disable session fixation protection, but in newer Servlet containers you can also configure session cookies to never use the secure flag. -Note that switching between HTTP and HTTPS is not a good idea in general, as any application which uses HTTP at all is vulnerable to man-in-the-middle attacks. +To get around this, you can disable session fixation protection. However, in newer Servlet containers, you can also configure session cookies to never use the secure flag. + + +[IMPORTANT] +==== +Switching between HTTP and HTTPS is not a good idea in general, as any application that uses HTTP at all is vulnerable to man-in-the-middle attacks. To be truly secure, the user should begin accessing your site in HTTPS and continue using it until they log out. Even clicking on an HTTPS link from a page accessed over HTTP is potentially risky. If you need more convincing, check out a tool like https://github.com/moxie0/sslstrip/[sslstrip]. +==== -=== I'm not switching between HTTP and HTTPS but my session is still getting lost +=== I am not switching between HTTP and HTTPS, but my session is still lost. What happened? -Sessions are maintained either by exchanging a session cookie or by adding a `jsessionid` parameter to URLs (this happens automatically if you are using JSTL to output URLs, or if you call `HttpServletResponse.encodeUrl` on URLs (before a redirect, for example). If clients have cookies disabled, and you are not rewriting URLs to include the `jsessionid`, then the session will be lost. +Sessions are maintained either by exchanging a session cookie or by adding a `jsessionid` parameter to URLs (this happens automatically if you use JSTL to output URLs or if you call `HttpServletResponse.encodeUrl` on URLs (before a redirect, for example). If clients have cookies disabled and you are not rewriting URLs to include the `jsessionid`, the session is lost. Note that the use of cookies is preferred for security reasons, as it does not expose the session information in the URL. [[appendix-faq-session-listener-missing]] -=== I'm trying to use the concurrent session-control support but it won't let me log back in, even if I'm sure I've logged out and haven't exceeded the allowed sessions. +=== I am trying to use the concurrent session-control support, but it does not let me log back in, even if I am sure I have logged out and have not exceeded the allowed sessions. What is wrong? -Make sure you have added the listener to your web.xml file. +Make sure you have added the listener to your `web.xml` file. It is essential to make sure that the Spring Security session registry is notified when a session is destroyed. -Without it, the session information will not be removed from the registry. - +Without it, the session information is not removed from the registry. +The following example adds a listener in a `web.xml` file: +==== [source,xml] ---- org.springframework.security.web.session.HttpSessionEventPublisher ---- +==== [[appendix-faq-unwanted-session-creation]] -=== Spring Security is creating a session somewhere, even though I've configured it not to, by setting the create-session attribute to never. +=== Spring Security creates a session somewhere, even though I have configured it not to, by setting the create-session attribute to never. What is wrong? -This usually means that the user's application is creating a session somewhere, but that they aren't aware of it. -The most common culprit is a JSP. Many people aren't aware that JSPs create sessions by default. -To prevent a JSP from creating a session, add the directive `<%@ page session="false" %>` to the top of the page. +This usually means that the user's application is creating a session somewhere but that they are not aware of it. +The most common culprit is a JSP. Many people are not aware that JSPs create sessions by default. +To prevent a JSP from creating a session, add the `<%@ page session="false" %>` directive to the top of the page. -If you are having trouble working out where a session is being created, you can add some debugging code to track down the location(s). One way to do this would be to add a `javax.servlet.http.HttpSessionListener` to your application, which calls `Thread.dumpStack()` in the `sessionCreated` method. +If you have trouble working out where a session is being created, you can add some debugging code to track down the location(s). One way to do this is to add a `javax.servlet.http.HttpSessionListener`, which calls `Thread.dumpStack()` in the `sessionCreated` method, to your application. [[appendix-faq-forbidden-csrf]] -=== I get a 403 Forbidden when performing a POST +=== I get a 403 Forbidden when performing a POST. What is wrong? -If an HTTP 403 Forbidden is returned for HTTP POST, but works for HTTP GET then the issue is most likely related to https://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#csrf[CSRF]. Either provide the CSRF Token or disable CSRF protection (not recommended). +If an HTTP 403 Forbidden error is returned for HTTP POST but it works for HTTP GET, the issue is most likely related to https://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#csrf[CSRF]. Either provide the CSRF Token or disable CSRF protection (the latter is not recommended). [[appendix-faq-no-security-on-forward]] -=== I'm forwarding a request to another URL using the RequestDispatcher, but my security constraints aren't being applied. +=== I am forwarding a request to another URL by using the RequestDispatcher, but my security constraints are not being applied. -Filters are not applied by default to forwards or includes. -If you really want the security filters to be applied to forwards and/or includes, then you have to configure these explicitly in your web.xml using the element, a child element of . +By default, filters are not applied to forwards or includes. +If you really want the security filters to be applied to forwards or includes, you have to configure these explicitly in your `web.xml` file by using the `` element, which is a child element of the `` element. [[appendix-faq-method-security-in-web-context]] -=== I have added Spring Security's element to my application context but if I add security annotations to my Spring MVC controller beans (Struts actions etc.) then they don't seem to have an effect. +=== I have added Spring Security's element to my application context, but, if I add security annotations to my Spring MVC controller beans (Struts actions etc.), they do not seem to have an effect. Why not? -In a Spring web application, the application context which holds the Spring MVC beans for the dispatcher servlet is often separate from the main application context. -It is often defined in a file called `myapp-servlet.xml`, where "myapp" is the name assigned to the Spring `DispatcherServlet` in `web.xml`. An application can have multiple ``DispatcherServlet``s, each with its own isolated application context. -The beans in these "child" contexts are not visible to the rest of the application. -The"parent" application context is loaded by the `ContextLoaderListener` you define in your `web.xml` and is visible to all the child contexts. -This parent context is usually where you define your security configuration, including the `` element). As a result any security constraints applied to methods in these web beans will not be enforced, since the beans cannot be seen from the `DispatcherServlet` context. -You need to either move the `` declaration to the web context or moved the beans you want secured into the main application context. +In a Spring web application, the application context that holds the Spring MVC beans for the dispatcher servlet is often separate from the main application context. +It is often defined in a file called `myapp-servlet.xml`, where `myapp` is the name assigned to the Spring `DispatcherServlet` in the `web.xml` file. An application can have multiple `DispatcherServlet` instances, each with its own isolated application context. +The beans in these "`child`" contexts are not visible to the rest of the application. +The "`parent`" application context is loaded by the `ContextLoaderListener` you define in your `web.xml` file and is visible to all the child contexts. +This parent context is usually where you define your security configuration, including the `` element. As a result, any security constraints applied to methods in these web beans are not enforced, since the beans cannot be seen from the `DispatcherServlet` context. +You need to either move the `` declaration to the web context or move the beans you want secured into the main application context. -Generally we would recommend applying method security at the service layer rather than on individual web controllers. +Generally, we recommend applying method security at the service layer rather than on individual web controllers. [[appendix-faq-no-filters-no-context]] -=== I have a user who has definitely been authenticated, but when I try to access the SecurityContextHolder during some requests, the Authentication is null. +=== I have a user who has definitely been authenticated, but, when I try to access the SecurityContextHolder during some requests, the Authentication is null. Why can I not see the user information? Why can't I see the user information? -If you have excluded the request from the security filter chain using the attribute `filters='none'` in the `` element that matches the URL pattern, then the `SecurityContextHolder` will not be populated for that request. +If you have excluded the request from the security filter chain by using the `filters='none'` attribute in the `` element that matches the URL pattern, the `SecurityContextHolder` is not populated for that request. Check the debug log to see whether the request is passing through the filter chain. -(You are reading the debug log, right?). +(You are reading the debug log, right?) [[appendix-faq-method-security-with-taglib]] -=== The authorize JSP Tag doesn't respect my method security annotations when using the URL attribute. +=== The authorize JSP Tag does not respect my method security annotations when using the URL attribute. Why not? -Method security will not hide links when using the `url` attribute in `` because we cannot readily reverse engineer what URL is mapped to what controller endpoint as controllers can rely on headers, current user, etc to determine what method to invoke. +Method security does not hide links when using the `url` attribute in ``, because we cannot readily reverse engineer what URL is mapped to what controller endpoint. We are limited because controllers can rely on headers, the current user, and other details to determine what method to invoke. [[appendix-faq-architecture]] == Spring Security Architecture Questions +This section addresses common Spring Security architecture questions: + . <> . <> . <> @@ -360,8 +374,7 @@ Method security will not hide links when using the `url` attribute in `> that lists the first-level dependencies for each Spring Security module, with some information on whether they are optional and when they are required. +If you build your project with Maven, adding the appropriate Spring Security modules as dependencies to your `pom.xml` file automatically pulls in the core jars that the framework requires. +Any that are marked as "`optional`" in the Spring Security `pom.xml` files have to be added to your own `pom.xml` file if you need them. [[appendix-faq-apacheds-deps]] === What dependencies are needed to run an embedded ApacheDS LDAP server? -If you are using Maven, you need to add the following to your pom dependencies: +If you use Maven, you need to add the following to your `pom.xml` file dependencies: +==== [source] ---- @@ -424,6 +438,7 @@ If you are using Maven, you need to add the following to your pom dependencies: ---- +==== The other required jars should be pulled in transitively. @@ -431,16 +446,18 @@ The other required jars should be pulled in transitively. === What is a UserDetailsService and do I need one? `UserDetailsService` is a DAO interface for loading data that is specific to a user account. -It has no other function other to load that data for use by other components within the framework. +It has no function other than to load that data for use by other components within the framework. It is not responsible for authenticating the user. -Authenticating a user with a username/password combination is most commonly performed by the `DaoAuthenticationProvider`, which is injected with a `UserDetailsService` to allow it to load the password (and other data) for a user in order to compare it with the submitted value. -Note that if you are using LDAP, <>. +Authenticating a user with a username and password combination is most commonly performed by the `DaoAuthenticationProvider`, which is injected with a `UserDetailsService` to let it to load the password (and other data) for a user, to compare it with the submitted value. +Note that, if you use LDAP, <>. -If you want to customize the authentication process then you should implement `AuthenticationProvider` yourself. -See this https://spring.io/blog/2010/08/02/spring-security-in-google-app-engine/[ blog article] for an example integrating Spring Security authentication with Google App Engine. +If you want to customize the authentication process, you should implement `AuthenticationProvider` yourself. +See this https://spring.io/blog/2010/08/02/spring-security-in-google-app-engine/[ blog article] for an example that integrate Spring Security authentication with Google App Engine. [[appendix-faq-howto]] -== Common "Howto" Requests +== Common "How to" Questions + +This section addresses the most common "How to" (or "How do I") questions about Spring Security: . <> . <> @@ -453,28 +470,26 @@ See this https://spring.io/blog/2010/08/02/spring-security-in-google-app-engine/ [[appendix-faq-extra-login-fields]] -=== I need to login in with more information than just the username. -How do I add support for extra login fields (e.g. -a company name)? +=== I need to login in with more information than just the username. How do I add support for extra login fields (such as a company name)? -This question comes up repeatedly in the Spring Security forum so you will find more information there by searching the archives (or through google). +This question comes up repeatedly, so you can find more information by searching online. -The submitted login information is processed by an instance of `UsernamePasswordAuthenticationFilter`. You will need to customize this class to handle the extra data field(s). One option is to use your own customized authentication token class (rather than the standard `UsernamePasswordAuthenticationToken`), another is simply to concatenate the extra fields with the username (for example, using a ":" as the separator) and pass them in the username property of `UsernamePasswordAuthenticationToken`. +The submitted login information is processed by an instance of `UsernamePasswordAuthenticationFilter`. You need to customize this class to handle the extra data fields. One option is to use your own customized authentication token class (rather than the standard `UsernamePasswordAuthenticationToken`). Another option is to concatenate the extra fields with the username (for example, by using a `:` character as the separator) and pass them in the username property of `UsernamePasswordAuthenticationToken`. -You will also need to customize the actual authentication process. -If you are using a custom authentication token class, for example, you will have to write an `AuthenticationProvider` to handle it (or extend the standard `DaoAuthenticationProvider`). If you have concatenated the fields, you can implement your own `UserDetailsService` which splits them up and loads the appropriate user data for authentication. +You also need to customize the actual authentication process. +If you use a custom authentication token class, for example, you will have to write an `AuthenticationProvider` (or extend the standard `DaoAuthenticationProvider`) to handle it. If you have concatenated the fields, you can implement your own `UserDetailsService` to split them up and load the appropriate user data for authentication. [[appendix-faq-matching-url-fragments]] -=== How do I apply different intercept-url constraints where only the fragment value of the requested URLs differs (e.g./foo#bar and /foo#blah? +=== How do I apply different intercept-url constraints where only the fragment value of the requested URLs differs (such as /thing1#thing2 and /thing1#thing3? -You can't do this, since the fragment is not transmitted from the browser to the server. -The URLs above are identical from the server's perspective. +You cannot do this, since the fragment is not transmitted from the browser to the server. +From the server's perspective, the URLs are identical. This is a common question from GWT users. [[appendix-faq-request-details-in-user-service]] === How do I access the user's IP Address (or other web-request data) in a UserDetailsService? -Obviously you can't (without resorting to something like thread-local variables) since the only information supplied to the interface is the username. +You cannot (without resorting to something like thread-local variables), since the only information supplied to the interface is the username. Instead of implementing `UserDetailsService`, you should implement `AuthenticationProvider` directly and extract the information from the supplied `Authentication` token. In a standard web setup, the `getDetails()` method on the `Authentication` object will return an instance of `WebAuthenticationDetails`. If you need additional information, you can inject a custom `AuthenticationDetailsSource` into the authentication filter you are using. @@ -484,37 +499,37 @@ If you are using the namespace, for example with the `` element, the [[appendix-faq-access-session-from-user-service]] === How do I access the HttpSession from a UserDetailsService? -You can't, since the `UserDetailsService` has no awareness of the servlet API. If you want to store custom user data, then you should customize the `UserDetails` object which is returned. -This can then be accessed at any point, via the thread-local `SecurityContextHolder`. A call to `SecurityContextHolder.getContext().getAuthentication().getPrincipal()` will return this custom object. +You cannot, since the `UserDetailsService` has no awareness of the servlet API. If you want to store custom user data, you should customize the `UserDetails` object that is returned. +This can then be accessed at any point, through the thread-local `SecurityContextHolder`. A call to `SecurityContextHolder.getContext().getAuthentication().getPrincipal()` returns this custom object. -If you really need to access the session, then it must be done by customizing the web tier. +If you really need to access the session, you must do so by by customizing the web tier. [[appendix-faq-password-in-user-service]] === How do I access the user's password in a UserDetailsService? -You can't (and shouldn't). You are probably misunderstanding its purpose. -See "<>" above. +You cannot (and should not, even if you find a way to do so). You are probably misunderstanding its purpose. +See "<>", earlier in the FAQ. [[appendix-faq-dynamic-url-metadata]] -=== How do I define the secured URLs within an application dynamically? +=== How do I dynamically define the secured URLs within an application? -People often ask about how to store the mapping between secured URLs and security metadata attributes in a database, rather than in the application context. +People often ask about how to store the mapping between secured URLs and security metadata attributes in a database rather than in the application context. The first thing you should ask yourself is if you really need to do this. -If an application requires securing, then it also requires that the security be tested thoroughly based on a defined policy. +If an application needs to be secure, it also requires that the security be tested thoroughly based on a defined policy. It may require auditing and acceptance testing before being rolled out into a production environment. -A security-conscious organization should be aware that the benefits of their diligent testing process could be wiped out instantly by allowing the security settings to be modified at runtime by changing a row or two in a configuration database. -If you have taken this into account (perhaps using multiple layers of security within your application) then Spring Security allows you to fully customize the source of security metadata. +A security-conscious organization should be aware that the benefits of their diligent testing process could be wiped out instantly by letting the security settings be modified at runtime by changing a row or two in a configuration database. +If you have taken this into account (perhaps by using multiple layers of security within your application), Spring Security lets you fully customize the source of security metadata. You can make it fully dynamic if you choose. -Both method and web security are protected by subclasses of `AbstractSecurityInterceptor` which is configured with a `SecurityMetadataSource` from which it obtains the metadata for a particular method or filter invocation. -For web security, the interceptor class is `FilterSecurityInterceptor` and it uses the marker interface `FilterInvocationSecurityMetadataSource`. The "secured object" type it operates on is a `FilterInvocation`. The default implementation which is used (both in the namespace `` and when configuring the interceptor explicitly, stores the list of URL patterns and their corresponding list of "configuration attributes" (instances of `ConfigAttribute`) in an in-memory map. +Both method and web security are protected by subclasses of `AbstractSecurityInterceptor`, which is configured with a `SecurityMetadataSource` from which it obtains the metadata for a particular method or filter invocation. +For web security, the interceptor class is `FilterSecurityInterceptor`, and it uses the `FilterInvocationSecurityMetadataSource` marker interface. The "`secured object`" type it operates on is a `FilterInvocation`. The default implementation (which is used both in the namespace `` and when configuring the interceptor explicitly) stores the list of URL patterns and their corresponding list of "`configuration attributes`" (instances of `ConfigAttribute`) in an in-memory map. -To load the data from an alternative source, you must be using an explicitly declared security filter chain (typically Spring Security's `FilterChainProxy`) in order to customize the `FilterSecurityInterceptor` bean. -You can't use the namespace. -You would then implement `FilterInvocationSecurityMetadataSource` to load the data as you please for a particular `FilterInvocation` footnote:[The `FilterInvocation` object contains the `HttpServletRequest`, so you can obtain the URL or any other relevant information on which to base your decision on what the list of returned attributes will contain.]. A very basic outline would look something like this: +To load the data from an alternative source, you must use an explicitly declared security filter chain (typically Spring Security's `FilterChainProxy`) to customize the `FilterSecurityInterceptor` bean. +You cannot use the namespace. +You would then implement `FilterInvocationSecurityMetadataSource` to load the data as you please for a particular `FilterInvocation`. The `FilterInvocation` object contains the `HttpServletRequest`, so you can obtain the URL or any other relevant information on which to base your decision, based on what the list of returned attributes contains. A basic outline would look something like the following example: ==== .Java @@ -577,35 +592,35 @@ For more information, look at the code for `DefaultFilterInvocationSecurityMetad [[appendix-faq-ldap-authorities]] === How do I authenticate against LDAP but load user roles from a database? -The `LdapAuthenticationProvider` bean (which handles normal LDAP authentication in Spring Security) is configured with two separate strategy interfaces, one which performs the authentication and one which loads the user authorities, called `LdapAuthenticator` and `LdapAuthoritiesPopulator` respectively. -The `DefaultLdapAuthoritiesPopulator` loads the user authorities from the LDAP directory and has various configuration parameters to allow you to specify how these should be retrieved. +The `LdapAuthenticationProvider` bean (which handles normal LDAP authentication in Spring Security) is configured with two separate strategy interfaces, one that performs the authentication and one that loads the user authorities, called `LdapAuthenticator` and `LdapAuthoritiesPopulator`, respectively. +The `DefaultLdapAuthoritiesPopulator` loads the user authorities from the LDAP directory and has various configuration parameters to let you specify how these should be retrieved. -To use JDBC instead, you can implement the interface yourself, using whatever SQL is appropriate for your schema: +To use JDBC instead, you can implement the interface yourself, by using whatever SQL is appropriate for your schema: ==== .Java [source,java,role="primary"] ---- - public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator { - @Autowired - JdbcTemplate template; - - List getGrantedAuthorities(DirContextOperations userData, String username) { - return template.query("select role from roles where username = ?", - new String[] {username}, - new RowMapper() { - /** - * We're assuming here that you're using the standard convention of using the role - * prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter. - */ - @Override - public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException { - return new SimpleGrantedAuthority("ROLE_" + rs.getString(1)); - } - }); - } - } +public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator { + @Autowired + JdbcTemplate template; + + List getGrantedAuthorities(DirContextOperations userData, String username) { + return template.query("select role from roles where username = ?", + new String[] {username}, + new RowMapper() { + /** + * We're assuming here that you're using the standard convention of using the role + * prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter. + */ + @Override + public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException { + return new SimpleGrantedAuthority("ROLE_" + rs.getString(1)); + } + }); + } +} ---- @@ -631,27 +646,25 @@ class MyAuthoritiesPopulator : LdapAuthoritiesPopulator { ---- ==== -You would then add a bean of this type to your application context and inject it into the `LdapAuthenticationProvider`. This is covered in the section on configuring LDAP using explicit Spring beans in the LDAP chapter of the reference manual. -Note that you can't use the namespace for configuration in this case. -You should also consult the Javadoc for the relevant classes and interfaces. +You would then add a bean of this type to your application context and inject it into the `LdapAuthenticationProvider`. This is covered in the section on configuring LDAP by using explicit Spring beans in the LDAP chapter of the reference manual. +Note that you cannot use the namespace for configuration in this case. +You should also consult the security-api-url[Javadoc] for the relevant classes and interfaces. [[appendix-faq-namespace-post-processor]] -=== I want to modify the property of a bean that is created by the namespace, but there is nothing in the schema to support it. -What can I do short of abandoning namespace use? +=== I want to modify the property of a bean that is created by the namespace, but there is nothing in the schema to support it. What can I do short of abandoning namespace use? -The namespace functionality is intentionally limited, so it doesn't cover everything that you can do with plain beans. -If you want to do something simple, like modify a bean, or inject a different dependency, you can do this by adding a `BeanPostProcessor` to your configuration. -More information can be found in the https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#beans-factory-extension-bpp[Spring Reference Manual]. In order to do this, you need to know a bit about which beans are created, so you should also read the blog article in the above question on <>. +The namespace functionality is intentionally limited, so it does not cover everything that you can do with plain beans. +If you want to do something simple, such as modifying a bean or injecting a different dependency, you can do so by adding a `BeanPostProcessor` to your configuration. +You can find more information in the https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#beans-factory-extension-bpp[Spring Reference Manual]. To do so, you need to know a bit about which beans are created, so you should also read the blog article mentioned in the earlier question on <>. -Normally, you would add the functionality you require to the `postProcessBeforeInitialization` method of `BeanPostProcessor`. Let's say that you want to customize the `AuthenticationDetailsSource` used by the `UsernamePasswordAuthenticationFilter`, (created by the `form-login` element). You want to extract a particular header called `CUSTOM_HEADER` from the request and make use of it while authenticating the user. -The processor class would look like this: +Normally, you would add the functionality you require to the `postProcessBeforeInitialization` method of `BeanPostProcessor`. Suppose that you want to customize the `AuthenticationDetailsSource` used by the `UsernamePasswordAuthenticationFilter` (created by the `form-login` element). You want to extract a particular header called `CUSTOM_HEADER` from the request and use it while authenticating the user. +The processor class would look like the following listing: ==== .Java [source,java,role="primary"] ---- - public class CustomBeanPostProcessor implements BeanPostProcessor { public Object postProcessAfterInitialization(Object bean, String name) { @@ -671,7 +684,6 @@ public class CustomBeanPostProcessor implements BeanPostProcessor { return bean; } } - ---- .Kotlin @@ -695,4 +707,4 @@ class CustomBeanPostProcessor : BeanPostProcessor { ==== You would then register this bean in your application context. -Spring will automatically invoke it on the beans defined in the application context. +Spring automatically invoke it on the beans defined in the application context. diff --git a/docs/modules/ROOT/pages/servlet/appendix/index.adoc b/docs/modules/ROOT/pages/servlet/appendix/index.adoc index 3fecd174b47..9c84348fea4 100644 --- a/docs/modules/ROOT/pages/servlet/appendix/index.adoc +++ b/docs/modules/ROOT/pages/servlet/appendix/index.adoc @@ -4,5 +4,5 @@ This is an appendix for Servlet based Spring Security. It has the following sections: * xref:servlet/appendix/database-schema.adoc[Database Schemas] -* xref:servlet/appendix/namespace.adoc[XML Namespace] +* xref:servlet/appendix/namespace/index.adoc[XML Namespace] * xref:servlet/appendix/faq.adoc[FAQ] diff --git a/docs/modules/ROOT/pages/servlet/appendix/namespace/authentication-manager.adoc b/docs/modules/ROOT/pages/servlet/appendix/namespace/authentication-manager.adoc new file mode 100644 index 00000000000..5452a2b7994 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/appendix/namespace/authentication-manager.adoc @@ -0,0 +1,292 @@ +[[nsa-authentication]] += Authentication Services +Before Spring Security 3.0, an `AuthenticationManager` was automatically registered internally. +Now you must register one explicitly using the `` element. +This creates an instance of Spring Security's `ProviderManager` class, which needs to be configured with a list of one or more `AuthenticationProvider` instances. +These can either be created using syntax elements provided by the namespace, or they can be standard bean definitions, marked for addition to the list using the `authentication-provider` element. + + +[[nsa-authentication-manager]] +== +Every Spring Security application which uses the namespace must have include this element somewhere. +It is responsible for registering the `AuthenticationManager` which provides authentication services to the application. +All elements which create `AuthenticationProvider` instances should be children of this element. + + +[[nsa-authentication-manager-attributes]] +=== Attributes + + +[[nsa-authentication-manager-alias]] +* **alias** +This attribute allows you to define an alias name for the internal instance for use in your own configuration. + + +[[nsa-authentication-manager-erase-credentials]] +* **erase-credentials** +If set to true, the AuthenticationManager will attempt to clear any credentials data in the returned Authentication object, once the user has been authenticated. +Literally it maps to the `eraseCredentialsAfterAuthentication` property of the xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`ProviderManager`]. + + +[[nsa-authentication-manager-id]] +* **id** +This attribute allows you to define an id for the internal instance for use in your own configuration. +It is the same as the alias element, but provides a more consistent experience with elements that use the id attribute. + + +[[nsa-authentication-manager-children]] +=== Child Elements of + + +* <> +* xref:servlet/appendix/namespace/ldap.adoc#nsa-ldap-authentication-provider[ldap-authentication-provider] + + + +[[nsa-authentication-provider]] +== +Unless used with a `ref` attribute, this element is shorthand for configuring a `DaoAuthenticationProvider`. +`DaoAuthenticationProvider` loads user information from a `UserDetailsService` and compares the username/password combination with the values supplied at login. +The `UserDetailsService` instance can be defined either by using an available namespace element (`jdbc-user-service` or by using the `user-service-ref` attribute to point to a bean defined elsewhere in the application context). + + + +[[nsa-authentication-provider-parents]] +=== Parent Elements of + + +* <> + + + +[[nsa-authentication-provider-attributes]] +=== Attributes + + +[[nsa-authentication-provider-ref]] +* **ref** +Defines a reference to a Spring bean that implements `AuthenticationProvider`. + +If you have written your own `AuthenticationProvider` implementation (or want to configure one of Spring Security's own implementations as a traditional bean for some reason, then you can use the following syntax to add it to the internal list of `ProviderManager`: + +[source,xml] +---- + + + + + + +---- + + + + +[[nsa-authentication-provider-user-service-ref]] +* **user-service-ref** +A reference to a bean that implements UserDetailsService that may be created using the standard bean element or the custom user-service element. + + +[[nsa-authentication-provider-children]] +=== Child Elements of + + +* <> +* xref:servlet/appendix/namespace/ldap.adoc#nsa-ldap-user-service[ldap-user-service] +* <> +* <> + + + +[[nsa-jdbc-user-service]] +== +Causes creation of a JDBC-based UserDetailsService. + + +[[nsa-jdbc-user-service-attributes]] +=== Attributes + + +[[nsa-jdbc-user-service-authorities-by-username-query]] +* **authorities-by-username-query** +An SQL statement to query for a user's granted authorities given a username. + +The default is + +[source] +---- +select username, authority from authorities where username = ? +---- + + + + +[[nsa-jdbc-user-service-cache-ref]] +* **cache-ref** +Defines a reference to a cache for use with a UserDetailsService. + + +[[nsa-jdbc-user-service-data-source-ref]] +* **data-source-ref** +The bean ID of the DataSource which provides the required tables. + + +[[nsa-jdbc-user-service-group-authorities-by-username-query]] +* **group-authorities-by-username-query** +An SQL statement to query user's group authorities given a username. +The default is + ++ + +[source] +---- +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 +---- + + + + +[[nsa-jdbc-user-service-id]] +* **id** +A bean identifier, used for referring to the bean elsewhere in the context. + + +[[nsa-jdbc-user-service-role-prefix]] +* **role-prefix** +A non-empty string prefix that will be added to role strings loaded from persistent storage (default is "ROLE_"). +Use the value "none" for no prefix in cases where the default is non-empty. + + +[[nsa-jdbc-user-service-users-by-username-query]] +* **users-by-username-query** +An SQL statement to query a username, password, and enabled status given a username. +The default is + ++ + +[source] +---- +select username, password, enabled from users where username = ? +---- + + + + +[[nsa-password-encoder]] +== +Authentication providers can optionally be configured to use a password encoder as described in the xref:features/authentication/password-storage.adoc#authentication-password-storage[Password Storage]. +This will result in the bean being injected with the appropriate `PasswordEncoder` instance. + + +[[nsa-password-encoder-parents]] +=== Parent Elements of + + +* <> +* xref:servlet/appendix/namespace/authentication-manager.adoc#nsa-password-compare[password-compare] + + + +[[nsa-password-encoder-attributes]] +=== Attributes + + +[[nsa-password-encoder-hash]] +* **hash** +Defines the hashing algorithm used on user passwords. +We recommend strongly against using MD4, as it is a very weak hashing algorithm. + + +[[nsa-password-encoder-ref]] +* **ref** +Defines a reference to a Spring bean that implements `PasswordEncoder`. + + +[[nsa-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. + + +[[nsa-user-service-attributes]] +=== Attributes + + +[[nsa-user-service-id]] +* **id** +A bean identifier, used for referring to the bean elsewhere in the context. + + +[[nsa-user-service-properties]] +* **properties** +The location of a Properties file where each line is in the format of + ++ + +[source] +---- +username=password,grantedAuthority[,grantedAuthority][,enabled|disabled] +---- + + + + +[[nsa-user-service-children]] +=== Child Elements of + + +* <> + + + +[[nsa-user]] +== +Represents a user in the application. + + +[[nsa-user-parents]] +=== Parent Elements of + + +* <> + + + +[[nsa-user-attributes]] +=== Attributes + + +[[nsa-user-authorities]] +* **authorities** +One of more authorities granted to the user. +Separate authorities with a comma (but no space). +For example, "ROLE_USER,ROLE_ADMINISTRATOR" + + +[[nsa-user-disabled]] +* **disabled** +Can be set to "true" to mark an account as disabled and unusable. + + +[[nsa-user-locked]] +* **locked** +Can be set to "true" to mark an account as locked and unusable. + + +[[nsa-user-name]] +* **name** +The username assigned to the user. + + +[[nsa-user-password]] +* **password** +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. diff --git a/docs/modules/ROOT/pages/servlet/appendix/namespace.adoc b/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc similarity index 61% rename from docs/modules/ROOT/pages/servlet/appendix/namespace.adoc rename to docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc index a6518b4ed13..eb81c2734c2 100644 --- a/docs/modules/ROOT/pages/servlet/appendix/namespace.adoc +++ b/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc @@ -1,22 +1,14 @@ -[[appendix-namespace]] -= The Security Namespace -This appendix provides a reference to the elements available in the security namespace and information on the underlying beans they create (a knowledge of the individual classes and how they work together is assumed - you can find more information in the project Javadoc and elsewhere in this document). -If you haven't used the namespace before, please read the xref:servlet/configuration/xml-namespace.adoc#ns-config[introductory chapter] on namespace configuration, as this is intended as a supplement to the information there. -Using a good quality XML editor while editing a configuration based on the schema is recommended as this will provide contextual information on which elements and attributes are available as well as comments explaining their purpose. -The namespace is written in https://relaxng.org/[RELAX NG] Compact format and later converted into an XSD schema. -If you are familiar with this format, you may wish to examine the https://raw.githubusercontent.com/spring-projects/spring-security/main/config/src/main/resources/org/springframework/security/config/spring-security-4.1.rnc[schema file] directly. - [[nsa-web]] -== Web Application Security += Web Application Security [[nsa-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. [[nsa-http]] -=== +== If you use an `` element within your application, a `FilterChainProxy` bean named "springSecurityFilterChain" is created and the configuration within the element is used to build a filter chain within `FilterChainProxy`. As of Spring Security 3.1, additional `http` elements can be used to add extra filter chains footnote:[See the pass:specialcharacters,macros[xref:servlet/configuration/xml-namespace.adoc#ns-web-xml[introductory chapter]] for how to set up the mapping from your `web.xml` ]. @@ -34,7 +26,7 @@ These are fixed and cannot be replaced with alternatives. [[nsa-http-attributes]] -==== Attributes +=== Attributes The attributes on the `` element control some of the properties on the core filters. @@ -151,7 +143,7 @@ The default value is true. [[nsa-http-children]] -==== Child Elements of +=== Child Elements of * <> * <> * <> @@ -177,18 +169,18 @@ The default value is true. [[nsa-access-denied-handler]] -=== -This element allows you to set the `errorPage` property for the default `AccessDeniedHandler` used by the `ExceptionTranslationFilter`, using the <> attribute, or to supply your own implementation using the<> attribute. +== +This element allows you to set the `errorPage` property for the default `AccessDeniedHandler` used by the `ExceptionTranslationFilter`, using the <> attribute, or to supply your own implementation using the <> attribute. This is discussed in more detail in the section on the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[ExceptionTranslationFilter]. [[nsa-access-denied-handler-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-access-denied-handler-attributes]] -==== Attributes +=== Attributes [[nsa-access-denied-handler-error-page]] @@ -202,12 +194,12 @@ Defines a reference to a Spring bean of type `AccessDeniedHandler`. [[nsa-cors]] -=== +== This element allows for configuring a `CorsFilter`. If no `CorsFilter` or `CorsConfigurationSource` is specified and Spring MVC is on the classpath, a `HandlerMappingIntrospector` is used as the `CorsConfigurationSource`. [[nsa-cors-attributes]] -==== Attributes +=== Attributes The attributes on the `` element control the headers element. [[nsa-cors-ref]] @@ -219,12 +211,12 @@ Optional attribute that specifies the bean name of a `CorsFilter`. Optional attribute that specifies the bean name of a `CorsConfigurationSource` to be injected into a `CorsFilter` created by the XML namespace. [[nsa-cors-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-headers]] -=== +== This element allows for configuring additional (security) headers to be send with the response. It enables easy configuration for several headers and also allows for setting custom headers through the <> element. Additional information, can be found in the xref:features/exploits/headers.adoc#headers[Security Headers] section of the reference. @@ -246,9 +238,12 @@ This allows HTTPS websites to resist impersonation by attackers using mis-issued https://www.w3.org/TR/CSP2/[Content Security Policy (CSP)] is a mechanism that web applications can leverage to mitigate content injection vulnerabilities, such as cross-site scripting (XSS). ** `Referrer-Policy` - Can be set using the <> element, https://www.w3.org/TR/referrer-policy/[Referrer-Policy] is a mechanism that web applications can leverage to manage the referrer field, which contains the last page the user was on. ** `Feature-Policy` - Can be set using the <> element, https://wicg.github.io/feature-policy/[Feature-Policy] is a mechanism that allows web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser. +** `Cross-Origin-Opener-Policy` - Can be set using the <> element, https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy[Cross-Origin-Opener-Policy] is a mechanism that allows you to ensure a top-level document does not share a browsing context group with cross-origin documents. +** `Cross-Origin-Embedder-Policy` - Can be set using the <> element, https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy[Cross-Origin-Embedder-Policy] is a mechanism that prevents a document from loading any cross-origin resources that don't explicitly grant the document permission. +** `Cross-Origin-Resource-Policy` - Can be set using the <> element, https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy[Cross-Origin-Resource-Policy] is a mechanism that conveys a desire that the browser blocks no-cors cross-origin/cross-site requests to the given resource. [[nsa-headers-attributes]] -==== Attributes +=== Attributes The attributes on the `` element control the headers element. @@ -264,19 +259,22 @@ The default is false (the headers are enabled). [[nsa-headers-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-headers-children]] -==== Child Elements of +=== Child Elements of * <> * <> * <> +* <> +* <> +* <> * <> * <> * <> @@ -289,12 +287,12 @@ The default is false (the headers are enabled). [[nsa-cache-control]] -=== +== Adds `Cache-Control`, `Pragma`, and `Expires` headers to ensure that the browser does not cache your secured pages. [[nsa-cache-control-attributes]] -==== Attributes +=== Attributes [[nsa-cache-control-disabled]] * **disabled** @@ -303,7 +301,7 @@ Default false. [[nsa-cache-control-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -311,13 +309,13 @@ Default false. [[nsa-hsts]] -=== +== When enabled adds the https://tools.ietf.org/html/rfc6797[Strict-Transport-Security] header to the response for any secure request. This allows the server to instruct browsers to automatically use HTTPS for future requests. [[nsa-hsts-attributes]] -==== Attributes +=== Attributes [[nsa-hsts-disabled]] * **disabled** @@ -347,20 +345,20 @@ Specifies if preload should be included. Default false. [[nsa-hsts-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-hpkp]] -=== +== When enabled adds the https://tools.ietf.org/html/rfc7469[Public Key Pinning Extension for HTTP] header to the response for any secure request. This allows HTTPS websites to resist impersonation by attackers using mis-issued or otherwise fraudulent certificates. [[nsa-hpkp-attributes]] -==== Attributes +=== Attributes [[nsa-hpkp-disabled]] * **disabled** @@ -391,28 +389,28 @@ Specifies the URI to which the browser should report pin validation failures. [[nsa-hpkp-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-pins]] -=== +== The list of pins [[nsa-pins-children]] -==== Child Elements of +=== Child Elements of * <> [[nsa-pin]] -=== +== A pin is specified using the base64-encoded SPKI fingerprint as value and the cryptographic hash algorithm as attribute [[nsa-pin-attributes]] -==== Attributes +=== Attributes [[nsa-pin-algorithm]] * **algorithm** @@ -421,19 +419,19 @@ Default is SHA256. [[nsa-pin-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-content-security-policy]] -=== +== When enabled adds the https://www.w3.org/TR/CSP2/[Content Security Policy (CSP)] header to the response. CSP is a mechanism that web applications can leverage to mitigate content injection vulnerabilities, such as cross-site scripting (XSS). [[nsa-content-security-policy-attributes]] -==== Attributes +=== Attributes [[nsa-content-security-policy-policy-directives]] * **policy-directives** @@ -445,18 +443,18 @@ Set to true, to enable the Content-Security-Policy-Report-Only header for report Defaults to false. [[nsa-content-security-policy-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-referrer-policy]] -=== +== When enabled adds the https://www.w3.org/TR/referrer-policy/[Referrer Policy] header to the response. [[nsa-referrer-policy-attributes]] -==== Attributes +=== Attributes [[nsa-referrer-policy-policy]] * **policy** @@ -464,37 +462,37 @@ The policy for the Referrer-Policy header. Default "no-referrer". [[nsa-referrer-policy-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-feature-policy]] -=== +== When enabled adds the https://wicg.github.io/feature-policy/[Feature Policy] header to the response. [[nsa-feature-policy-attributes]] -==== Attributes +=== Attributes [[nsa-feature-policy-policy-directives]] * **policy-directives** The security policy directive(s) for the Feature-Policy header. [[nsa-feature-policy-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-frame-options]] -=== +== When enabled adds the https://tools.ietf.org/html/draft-ietf-websec-x-frame-options[X-Frame-Options header] to the response, this allows newer browsers to do some security checks and prevent https://en.wikipedia.org/wiki/Clickjacking[clickjacking] attacks. [[nsa-frame-options-attributes]] -==== Attributes +=== Attributes [[nsa-frame-options-disabled]] * **disabled** @@ -515,34 +513,34 @@ On the other hand, if you specify SAMEORIGIN, you can still use the page in a fr [[nsa-frame-options-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-permissions-policy]] -=== +== Adds the https://w3c.github.io/webappsec-permissions-policy/[Permissions-Policy header] to the response. [[nsa-permissions-policy-attributes]] -==== Attributes +=== Attributes [[nsa-permissions-policy-policy]] * **policy** The policy value to write for the `Permissions-Policy` header [[nsa-permissions-policy-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-xss-protection]] -=== +== Adds the https://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx[X-XSS-Protection header] to the response to assist in protecting against https://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent[reflected / Type-1 Cross-Site Scripting (XSS)] attacks. This is in no-way a full protection to XSS attacks! [[nsa-xss-protection-attributes]] -==== Attributes +=== Attributes [[nsa-xss-protection-disabled]] @@ -564,20 +562,20 @@ Note that there are sometimes ways of bypassing this mode which can often times [[nsa-xss-protection-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-content-type-options]] -=== +== Add the X-Content-Type-Options header with the value of nosniff to the response. This https://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx[disables MIME-sniffing] for IE8+ and Chrome extensions. [[nsa-content-type-options-attributes]] -==== Attributes +=== Attributes [[nsa-content-type-options-disabled]] * **disabled** @@ -585,7 +583,67 @@ Specifies if Content Type Options should be disabled. Default false. [[nsa-content-type-options-parents]] -==== Parent Elements of +=== Parent Elements of + + +* <> + + + +[[nsa-cross-origin-embedder-policy]] +==== +When enabled adds the https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy[Cross-Origin-Embedder-Policy] header to the response. + + +[[nsa-cross-origin-embedder-policy-attributes]] +===== Attributes + +[[nsa-cross-origin-embedder-policy-policy]] +* **policy** +The policy for the `Cross-Origin-Embedder-Policy` header. + +[[nsa-cross-origin-embedder-policy-parents]] +===== Parent Elements of + + +* <> + + + +[[nsa-cross-origin-opener-policy]] +==== +When enabled adds the https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy[Cross-Origin-Opener-Policy] header to the response. + + +[[nsa-cross-origin-opener-policy-attributes]] +===== Attributes + +[[nsa-cross-origin-opener-policy-policy]] +* **policy** +The policy for the `Cross-Origin-Opener-Policy` header. + +[[nsa-cross-origin-opener-policy-parents]] +===== Parent Elements of + + +* <> + + + +[[nsa-cross-origin-resource-policy]] +==== +When enabled adds the https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy[Cross-Origin-Resource-Policy] header to the response. + + +[[nsa-cross-origin-resource-policy-attributes]] +===== Attributes + +[[nsa-cross-origin-resource-policy-policy]] +* **policy** +The policy for the `Cross-Origin-Resource-Policy` header. + +[[nsa-cross-origin-resource-policy-parents]] +===== Parent Elements of * <> @@ -593,12 +651,12 @@ Default false. [[nsa-header]] -===
+==
Add additional headers to the response, both the name and value need to be specified. [[nsa-header-attributes]] -==== Attributes +=== Attributes [[nsa-header-name]] @@ -617,7 +675,7 @@ Reference to a custom implementation of the `HeaderWriter` interface. [[nsa-header-parents]] -==== Parent Elements of
+=== Parent Elements of
* <> @@ -625,13 +683,13 @@ Reference to a custom implementation of the `HeaderWriter` interface. [[nsa-anonymous]] -=== +== Adds an `AnonymousAuthenticationFilter` to the stack and an `AnonymousAuthenticationProvider`. Required if you are using the `IS_AUTHENTICATED_ANONYMOUSLY` attribute. [[nsa-anonymous-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -639,7 +697,7 @@ Required if you are using the `IS_AUTHENTICATED_ANONYMOUSLY` attribute. [[nsa-anonymous-attributes]] -==== Attributes +=== Attributes [[nsa-anonymous-enabled]] @@ -671,14 +729,14 @@ if unset, defaults to `anonymousUser`. [[nsa-csrf]] -=== +== This element will add https://en.wikipedia.org/wiki/Cross-site_request_forgery[Cross Site Request Forger (CSRF)] protection to the application. It also updates the default RequestCache to only replay "GET" requests upon successful authentication. Additional information can be found in the xref:features/exploits/csrf.adoc#csrf[Cross Site Request Forgery (CSRF)] section of the reference. [[nsa-csrf-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -686,7 +744,7 @@ Additional information can be found in the xref:features/exploits/csrf.adoc#csrf [[nsa-csrf-attributes]] -==== Attributes +=== Attributes [[nsa-csrf-disabled]] * **disabled** @@ -707,14 +765,14 @@ Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS". [[nsa-custom-filter]] -=== +== This element is used to add a filter to the filter chain. -It doesn't create any additional beans but is used to select a bean of type `javax.servlet.Filter` which is already defined in the application context and add that at a particular position in the filter chain maintained by Spring Security. +It doesn't create any additional beans but is used to select a bean of type `jakarta.servlet.Filter` which is already defined in the application context and add that at a particular position in the filter chain maintained by Spring Security. Full details can be found in the xref:servlet/configuration/xml-namespace.adoc#ns-custom-filters[ namespace chapter]. [[nsa-custom-filter-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -722,7 +780,7 @@ Full details can be found in the xref:servlet/configuration/xml-namespace.adoc#n [[nsa-custom-filter-attributes]] -==== Attributes +=== Attributes [[nsa-custom-filter-after]] @@ -749,24 +807,24 @@ Defines a reference to a Spring bean that implements `Filter`. [[nsa-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. [[nsa-expression-handler-parents]] -==== Parent Elements of +=== Parent Elements of -* <> +* xref:servlet/appendix/namespace/method-security.adoc#nsa-global-method-security[global-method-security] * <> -* <> -* <> +* xref:servlet/appendix/namespace/method-security.adoc#nsa-method-security[method-security] +* xref:servlet/appendix/namespace/websocket.adoc#nsa-websocket-message-broker[websocket-message-broker] [[nsa-expression-handler-attributes]] -==== Attributes +=== Attributes [[nsa-expression-handler-ref]] @@ -775,7 +833,7 @@ Defines a reference to a Spring bean that implements `SecurityExpressionHandler` [[nsa-form-login]] -=== +== Used to add an `UsernamePasswordAuthenticationFilter` to the filter stack and an `LoginUrlAuthenticationEntryPoint` to the application context to provide authentication on demand. This will always take precedence over other namespace-created entry points. If no attributes are supplied, a login page will be generated automatically at the URL "/login" footnote:[ @@ -785,7 +843,7 @@ The class `DefaultLoginPageGeneratingFilter` is responsible for rendering the lo [[nsa-form-login-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -793,7 +851,7 @@ The class `DefaultLoginPageGeneratingFilter` is responsible for rendering the lo [[nsa-form-login-attributes]] -==== Attributes +=== Attributes [[nsa-form-login-always-use-default-target]] @@ -870,17 +928,17 @@ Maps a `ForwardAuthenticationFailureHandler` to `authenticationFailureHandler` p [[nsa-oauth2-login]] -=== -The xref:servlet/oauth2/oauth2-login.adoc#oauth2login[OAuth 2.0 Login] feature configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider. +== +The xref:servlet/oauth2/login/index.adoc#oauth2login[OAuth 2.0 Login] feature configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider. [[nsa-oauth2-login-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-oauth2-login-attributes]] -==== Attributes +=== Attributes [[nsa-oauth2-login-client-registration-repository-ref]] @@ -954,17 +1012,17 @@ Reference to the `JwtDecoderFactory` used by `OidcAuthorizationCodeAuthenticatio [[nsa-oauth2-client]] -=== -Configures xref:servlet/oauth2/oauth2-client.adoc#oauth2client[OAuth 2.0 Client] support. +== +Configures xref:servlet/oauth2/client/index.adoc#oauth2client[OAuth 2.0 Client] support. [[nsa-oauth2-client-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-oauth2-client-attributes]] -==== Attributes +=== Attributes [[nsa-oauth2-client-client-registration-repository-ref]] @@ -983,24 +1041,24 @@ Reference to the `OAuth2AuthorizedClientService`. [[nsa-oauth2-client-children]] -==== Child Elements of +=== Child Elements of * <> [[nsa-authorization-code-grant]] -=== -Configures xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-auth-grant-support[OAuth 2.0 Authorization Code Grant]. +== +Configures xref:servlet/oauth2/client/authorization-grants.adoc#oauth2Client-auth-grant-support[OAuth 2.0 Authorization Code Grant]. [[nsa-authorization-code-grant-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-authorization-code-grant-attributes]] -==== Attributes +=== Attributes [[nsa-authorization-code-grant-authorization-request-repository-ref]] @@ -1019,30 +1077,30 @@ Reference to the `OAuth2AccessTokenResponseClient`. [[nsa-client-registrations]] -=== -A container element for client(s) registered (xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration]) with an OAuth 2.0 or OpenID Connect 1.0 Provider. +== +A container element for client(s) registered (xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[ClientRegistration]) with an OAuth 2.0 or OpenID Connect 1.0 Provider. [[nsa-client-registrations-children]] -==== Child Elements of +=== Child Elements of * <> * <> [[nsa-client-registration]] -=== +== Represents a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. [[nsa-client-registration-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-client-registration-attributes]] -==== Attributes +=== Attributes [[nsa-client-registration-registration-id]] @@ -1093,18 +1151,18 @@ A reference to the associated provider. May reference a `` element or [[nsa-provider]] -=== +== The configuration information for an OAuth 2.0 or OpenID Connect 1.0 Provider. [[nsa-provider-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-provider-attributes]] -==== Attributes +=== Attributes [[nsa-provider-provider-id]] @@ -1148,23 +1206,23 @@ The URI used to retrieve the https://tools.ietf.org/html/rfc7517[JSON Web Key (J The URI used to initially configure a `ClientRegistration` using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint]. [[nsa-oauth2-resource-server]] -=== +== Adds a `BearerTokenAuthenticationFilter`, `BearerTokenAuthenticationEntryPoint`, and `BearerTokenAccessDeniedHandler` to the configuration. In addition, either `` or `` must be specified. [[nsa-oauth2-resource-server-parents]] -==== Parents Elements of +=== Parents Elements of * <> [[nsa-oauth2-resource-server-children]] -==== Child Elements of +=== Child Elements of * <> * <> [[nsa-oauth2-resource-server-attributes]] -==== Attributes +=== Attributes [[nsa-oauth2-resource-server-authentication-manager-resolver-ref]] * **authentication-manager-resolver-ref** @@ -1179,18 +1237,18 @@ Reference to a `BearerTokenResolver` which will retrieve the bearer token from t Reference to a `AuthenticationEntryPoint` which will handle unauthorized requests [[nsa-jwt]] -=== +== Represents an OAuth 2.0 Resource Server that will authorize JWTs [[nsa-jwt-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-jwt-attributes]] -==== Attributes +=== Attributes [[nsa-jwt-jwt-authentication-converter-ref]] * **jwt-authentication-converter-ref** @@ -1205,16 +1263,16 @@ Reference to a `JwtDecoder`. This is a larger component that overrides `jwk-set- The JWK Set Uri used to load signing verification keys from an OAuth 2.0 Authorization Server [[nsa-opaque-token]] -=== +== Represents an OAuth 2.0 Resource Server that will authorize opaque tokens [[nsa-opaque-token-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-opaque-token-attributes]] -==== Attributes +=== Attributes [[nsa-opaque-token-introspector-ref]] * **introspector-ref** @@ -1233,13 +1291,13 @@ The Client Id to use for client authentication against the provided `introspecti The Client Secret to use for client authentication against the provided `introspection-uri`. [[nsa-http-basic]] -=== +== Adds a `BasicAuthenticationFilter` and `BasicAuthenticationEntryPoint` to the configuration. The latter will only be used as the configuration entry point if form-based login is not enabled. [[nsa-http-basic-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1247,7 +1305,7 @@ The latter will only be used as the configuration entry point if form-based logi [[nsa-http-basic-attributes]] -==== Attributes +=== Attributes [[nsa-http-basic-authentication-details-source-ref]] @@ -1261,13 +1319,13 @@ Sets the `AuthenticationEntryPoint` which is used by the `BasicAuthenticationFil [[nsa-http-firewall]] -=== Element +== Element This is a top-level element which can be used to inject a custom implementation of `HttpFirewall` into the `FilterChainProxy` created by the namespace. The default implementation should be suitable for most applications. [[nsa-http-firewall-attributes]] -==== Attributes +=== Attributes [[nsa-http-firewall-ref]] @@ -1276,7 +1334,7 @@ Defines a reference to a Spring bean that implements `HttpFirewall`. [[nsa-intercept-url]] -=== +== This element is used to define the set of URL patterns that the application is interested in and to configure how they should be handled. It is used to construct the `FilterInvocationSecurityMetadataSource` used by the `FilterSecurityInterceptor`. It is also responsible for configuring a `ChannelProcessingFilter` if particular URLs need to be accessed by HTTPS, for example. @@ -1285,7 +1343,7 @@ So the most specific patterns should come first and the most general should come [[nsa-intercept-url-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1294,7 +1352,7 @@ So the most specific patterns should come first and the most general should come [[nsa-intercept-url-attributes]] -==== Attributes +=== Attributes [[nsa-intercept-url-access]] @@ -1341,12 +1399,12 @@ NOTE: This property is invalid for < +== Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication. [[nsa-jee-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1354,7 +1412,7 @@ Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integ [[nsa-jee-attributes]] -==== Attributes +=== Attributes [[nsa-jee-mappable-roles]] @@ -1368,13 +1426,13 @@ A reference to a user-service (or UserDetailsService bean) Id [[nsa-logout]] -=== +== Adds a `LogoutFilter` to the filter stack. This is configured with a `SecurityContextLogoutHandler`. [[nsa-logout-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1382,7 +1440,7 @@ This is configured with a `SecurityContextLogoutHandler`. [[nsa-logout-attributes]] -==== Attributes +=== Attributes [[nsa-logout-delete-cookies]] @@ -1419,7 +1477,7 @@ May be used to supply an instance of `LogoutSuccessHandler` which will be invoke [[nsa-openid-login]] -=== +== Similar to `` and has the same attributes. The default value for `login-processing-url` is "/login/openid". An `OpenIDAuthenticationFilter` and `OpenIDAuthenticationProvider` will be registered. @@ -1428,7 +1486,7 @@ Again, this can be specified by `id`, using the `user-service-ref` attribute, or [[nsa-openid-login-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1436,7 +1494,7 @@ Again, this can be specified by `id`, using the `user-service-ref` attribute, or [[nsa-openid-login-attributes]] -==== Attributes +=== Attributes [[nsa-openid-login-always-use-default-target]] @@ -1514,13 +1572,13 @@ Defaults to "username". [[nsa-openid-login-children]] -==== Child Elements of +=== Child Elements of * <> [[nsa-attribute-exchange]] -=== +== The `attribute-exchange` element defines the list of attributes which should be requested from the identity provider. An example can be found in the xref:servlet/authentication/openid.adoc#servlet-openid[OpenID Support] section of the namespace configuration chapter. More than one can be used, in which case each must have an `identifier-match` attribute, containing a regular expression which is matched against the supplied OpenID identifier. @@ -1528,7 +1586,7 @@ This allows different attribute lists to be fetched from different providers (Go [[nsa-attribute-exchange-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1536,7 +1594,7 @@ This allows different attribute lists to be fetched from different providers (Go [[nsa-attribute-exchange-attributes]] -==== Attributes +=== Attributes [[nsa-attribute-exchange-identifier-match]] @@ -1545,7 +1603,7 @@ A regular expression which will be compared against the claimed identity, when d [[nsa-attribute-exchange-children]] -==== Child Elements of +=== Child Elements of * <> @@ -1553,12 +1611,12 @@ A regular expression which will be compared against the claimed identity, when d [[nsa-openid-attribute]] -=== +== Attributes used when making an OpenID AX https://openid.net/specs/openid-attribute-exchange-1_0.html#fetch_request[ Fetch Request] [[nsa-openid-attribute-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1566,7 +1624,7 @@ Attributes used when making an OpenID AX https://openid.net/specs/openid-attribu [[nsa-openid-attribute-attributes]] -==== Attributes +=== Attributes [[nsa-openid-attribute-count]] @@ -1595,23 +1653,23 @@ For example, https://axschema.org/contact/email. See your OP's documentation for valid attribute types. [[nsa-password-management]] -=== +== This element configures password management. [[nsa-password-management-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-password-management-attributes]] -==== Attributes +=== Attributes [[nsa-password-management-change-password-page]] * **change-password-page** The change password page. Defaults to "/change-password". [[nsa-port-mappings]] -=== +== By default, an instance of `PortMapperImpl` will be added to the configuration for use in redirecting to secure and insecure URLs. This element can optionally be used to override the default mappings which that class defines. Each child `` element defines a pair of HTTP:HTTPS ports. @@ -1620,7 +1678,7 @@ An example of overriding these can be found in xref:servlet/exploits/http.adoc#s [[nsa-port-mappings-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1628,7 +1686,7 @@ An example of overriding these can be found in xref:servlet/exploits/http.adoc#s [[nsa-port-mappings-children]] -==== Child Elements of +=== Child Elements of * <> @@ -1636,12 +1694,12 @@ An example of overriding these can be found in xref:servlet/exploits/http.adoc#s [[nsa-port-mapping]] -=== +== Provides a method to map http ports to https ports when forcing a redirect. [[nsa-port-mapping-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1649,7 +1707,7 @@ Provides a method to map http ports to https ports when forcing a redirect. [[nsa-port-mapping-attributes]] -==== Attributes +=== Attributes [[nsa-port-mapping-http]] @@ -1663,13 +1721,13 @@ The https port to use. [[nsa-remember-me]] -=== +== Adds the `RememberMeAuthenticationFilter` to the stack. This in turn will be configured with either a `TokenBasedRememberMeServices`, a `PersistentTokenBasedRememberMeServices` or a user-specified bean implementing `RememberMeServices` depending on the attribute settings. [[nsa-remember-me-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1677,7 +1735,7 @@ This in turn will be configured with either a `TokenBasedRememberMeServices`, a [[nsa-remember-me-attributes]] -==== Attributes +=== Attributes [[nsa-remember-me-authentication-success-handler-ref]] @@ -1757,17 +1815,17 @@ If there are multiple instances, you can specify a bean `id` explicitly using th [[nsa-request-cache]] -=== Element +== Element Sets the `RequestCache` instance which will be used by the `ExceptionTranslationFilter` to store request information before invoking an `AuthenticationEntryPoint`. [[nsa-request-cache-parents]] -==== Parent Elements of +=== Parent Elements of * <> [[nsa-request-cache-attributes]] -==== Attributes +=== Attributes [[nsa-request-cache-ref]] @@ -1776,12 +1834,12 @@ Defines a reference to a Spring bean that is a `RequestCache`. [[nsa-session-management]] -=== +== Session-management related functionality is implemented by the addition of a `SessionManagementFilter` to the filter stack. [[nsa-session-management-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1789,7 +1847,7 @@ Session-management related functionality is implemented by the addition of a `Se [[nsa-session-management-attributes]] -==== Attributes +=== Attributes [[nsa-session-management-invalid-session-url]] @@ -1831,7 +1889,7 @@ See the Javadoc for this class for more details. [[nsa-session-management-children]] -==== Child Elements of +=== Child Elements of * <> @@ -1839,7 +1897,7 @@ See the Javadoc for this class for more details. [[nsa-concurrency-control]] -=== +== Adds support for concurrent session control, allowing limits to be placed on the number of active sessions a user can have. A `ConcurrentSessionFilter` will be created, and a `ConcurrentSessionControlAuthenticationStrategy` will be used with the `SessionManagementFilter`. If a `form-login` element has been declared, the strategy object will also be injected into the created authentication filter. @@ -1847,7 +1905,7 @@ An instance of `SessionRegistry` (a `SessionRegistryImpl` instance unless the us [[nsa-concurrency-control-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1855,7 +1913,7 @@ An instance of `SessionRegistry` (a `SessionRegistryImpl` instance unless the us [[nsa-concurrency-control-attributes]] -==== Attributes +=== Attributes [[nsa-concurrency-control-error-if-maximum-exceeded]] @@ -1893,7 +1951,7 @@ The other concurrent session control beans will be wired up to use it. [[nsa-x509]] -=== +== Adds support for X.509 authentication. An `X509AuthenticationFilter` will be added to the stack and an `Http403ForbiddenEntryPoint` bean will be created. The latter will only be used if no other authentication mechanisms are in use (its only functionality is to return an HTTP 403 error code). @@ -1901,7 +1959,7 @@ A `PreAuthenticatedAuthenticationProvider` will also be created which delegates [[nsa-x509-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1909,7 +1967,7 @@ A `PreAuthenticatedAuthenticationProvider` will also be created which delegates [[nsa-x509-attributes]] -==== Attributes +=== Attributes [[nsa-x509-authentication-details-source-ref]] @@ -1929,12 +1987,12 @@ If not set, an attempt will be made to locate a suitable instance automatically [[nsa-filter-chain-map]] -=== +== Used to explicitly configure a FilterChainProxy instance with a FilterChainMap [[nsa-filter-chain-map-attributes]] -==== Attributes +=== Attributes [[nsa-filter-chain-map-request-matcher]] @@ -1944,7 +2002,7 @@ Currently the options are 'ant' (for ant path patterns), 'regex' for regular exp [[nsa-filter-chain-map-children]] -==== Child Elements of +=== Child Elements of * <> @@ -1952,13 +2010,13 @@ Currently the options are 'ant' (for ant path patterns), 'regex' for regular exp [[nsa-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. [[nsa-filter-chain-parents]] -==== Parent Elements of +=== Parent Elements of * <> @@ -1966,7 +2024,7 @@ When multiple filter-chain elements are assembled in a list in order to configur [[nsa-filter-chain-attributes]] -==== Attributes +=== Attributes [[nsa-filter-chain-filters]] @@ -1986,7 +2044,7 @@ A reference to a `RequestMatcher` that will be used to determine if any `Filter` [[nsa-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 element. The intercept-url elements used should only contain pattern, method and access attributes. @@ -1994,7 +2052,7 @@ Any others will result in a configuration error. [[nsa-filter-security-metadata-source-attributes]] -==== Attributes +=== Attributes [[nsa-filter-security-metadata-source-id]] @@ -2017,1011 +2075,7 @@ If the expression evaluates to 'true', access will be granted. [[nsa-filter-security-metadata-source-children]] -==== Child Elements of +=== Child Elements of * <> - -[[nsa-websocket-security]] -== WebSocket Security - -Spring Security 4.0+ provides support for authorizing messages. -One concrete example of where this is useful is to provide authorization in WebSocket based applications. - -[[nsa-websocket-message-broker]] -=== - -The websocket-message-broker element has two different modes. -If the <> is not specified, then it will do the following things: - -* Ensure that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver. -This allows the use of `@AuthenticationPrincipal` to resolve the principal of the current `Authentication` -* Ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel. -This populates the SecurityContextHolder with the user that is found in the Message -* Ensures that a ChannelSecurityInterceptor is registered with the clientInboundChannel. -This allows authorization rules to be specified for a message. -* Ensures that a CsrfChannelInterceptor is registered with the clientInboundChannel. -This ensures that only requests from the original domain are enabled. -* Ensures that a CsrfTokenHandshakeInterceptor is registered with WebSocketHttpRequestHandler, TransportHandlingSockJsService, or DefaultSockJsService. -This ensures that the expected CsrfToken from the HttpServletRequest is copied into the WebSocket Session attributes. - -If additional control is necessary, the id can be specified and a ChannelSecurityInterceptor will be assigned to the specified id. -All the wiring with Spring's messaging infrastructure can then be done manually. -This is more cumbersome, but provides greater control over the configuration. - - -[[nsa-websocket-message-broker-attributes]] -==== Attributes - -[[nsa-websocket-message-broker-id]] -* **id** A bean identifier, used for referring to the ChannelSecurityInterceptor bean elsewhere in the context. -If specified, Spring Security requires explicit configuration within Spring Messaging. -If not specified, Spring Security will automatically integrate with the messaging infrastructure as described in <> - -[[nsa-websocket-message-broker-same-origin-disabled]] -* **same-origin-disabled** 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. - -[[nsa-websocket-message-broker-children]] -==== Child Elements of - - -* <> -* <> - -[[nsa-intercept-message]] -=== - -Defines an authorization rule for a message. - - -[[nsa-intercept-message-parents]] -==== Parent Elements of - - -* <> - - -[[nsa-intercept-message-attributes]] -==== Attributes - -[[nsa-intercept-message-pattern]] -* **pattern** An ant based pattern that matches on the Message destination. -For example, "/**" matches any Message with a destination; "/admin/**" matches any Message that has a destination that starts with "/admin/**". - -[[nsa-intercept-message-type]] -* **type** 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). - -[[nsa-intercept-message-access]] -* **access** The expression used to secure the Message. -For example, "denyAll" will deny access to all of the matching Messages; "permitAll" will grant access to all of the matching Messages; "hasRole('ADMIN') requires the current user to have the role 'ROLE_ADMIN' for the matching Messages. - -[[nsa-authentication]] -== Authentication Services -Before Spring Security 3.0, an `AuthenticationManager` was automatically registered internally. -Now you must register one explicitly using the `` element. -This creates an instance of Spring Security's `ProviderManager` class, which needs to be configured with a list of one or more `AuthenticationProvider` instances. -These can either be created using syntax elements provided by the namespace, or they can be standard bean definitions, marked for addition to the list using the `authentication-provider` element. - - -[[nsa-authentication-manager]] -=== -Every Spring Security application which uses the namespace must have include this element somewhere. -It is responsible for registering the `AuthenticationManager` which provides authentication services to the application. -All elements which create `AuthenticationProvider` instances should be children of this element. - - -[[nsa-authentication-manager-attributes]] -==== Attributes - - -[[nsa-authentication-manager-alias]] -* **alias** -This attribute allows you to define an alias name for the internal instance for use in your own configuration. - - -[[nsa-authentication-manager-erase-credentials]] -* **erase-credentials** -If set to true, the AuthenticationManager will attempt to clear any credentials data in the returned Authentication object, once the user has been authenticated. -Literally it maps to the `eraseCredentialsAfterAuthentication` property of the xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`ProviderManager`]. - - -[[nsa-authentication-manager-id]] -* **id** -This attribute allows you to define an id for the internal instance for use in your own configuration. -It is the same as the alias element, but provides a more consistent experience with elements that use the id attribute. - - -[[nsa-authentication-manager-children]] -==== Child Elements of - - -* <> -* <> - - - -[[nsa-authentication-provider]] -=== -Unless used with a `ref` attribute, this element is shorthand for configuring a `DaoAuthenticationProvider`. -`DaoAuthenticationProvider` loads user information from a `UserDetailsService` and compares the username/password combination with the values supplied at login. -The `UserDetailsService` instance can be defined either by using an available namespace element (`jdbc-user-service` or by using the `user-service-ref` attribute to point to a bean defined elsewhere in the application context). - - - -[[nsa-authentication-provider-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-authentication-provider-attributes]] -==== Attributes - - -[[nsa-authentication-provider-ref]] -* **ref** -Defines a reference to a Spring bean that implements `AuthenticationProvider`. - -If you have written your own `AuthenticationProvider` implementation (or want to configure one of Spring Security's own implementations as a traditional bean for some reason, then you can use the following syntax to add it to the internal list of `ProviderManager`: - -[source,xml] ----- - - - - - - ----- - - - - -[[nsa-authentication-provider-user-service-ref]] -* **user-service-ref** -A reference to a bean that implements UserDetailsService that may be created using the standard bean element or the custom user-service element. - - -[[nsa-authentication-provider-children]] -==== Child Elements of - - -* <> -* <> -* <> -* <> - - - -[[nsa-jdbc-user-service]] -=== -Causes creation of a JDBC-based UserDetailsService. - - -[[nsa-jdbc-user-service-attributes]] -==== Attributes - - -[[nsa-jdbc-user-service-authorities-by-username-query]] -* **authorities-by-username-query** -An SQL statement to query for a user's granted authorities given a username. - -The default is - -[source] ----- -select username, authority from authorities where username = ? ----- - - - - -[[nsa-jdbc-user-service-cache-ref]] -* **cache-ref** -Defines a reference to a cache for use with a UserDetailsService. - - -[[nsa-jdbc-user-service-data-source-ref]] -* **data-source-ref** -The bean ID of the DataSource which provides the required tables. - - -[[nsa-jdbc-user-service-group-authorities-by-username-query]] -* **group-authorities-by-username-query** -An SQL statement to query user's group authorities given a username. -The default is - -+ - -[source] ----- -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 ----- - - - - -[[nsa-jdbc-user-service-id]] -* **id** -A bean identifier, used for referring to the bean elsewhere in the context. - - -[[nsa-jdbc-user-service-role-prefix]] -* **role-prefix** -A non-empty string prefix that will be added to role strings loaded from persistent storage (default is "ROLE_"). -Use the value "none" for no prefix in cases where the default is non-empty. - - -[[nsa-jdbc-user-service-users-by-username-query]] -* **users-by-username-query** -An SQL statement to query a username, password, and enabled status given a username. -The default is - -+ - -[source] ----- -select username, password, enabled from users where username = ? ----- - - - - -[[nsa-password-encoder]] -=== -Authentication providers can optionally be configured to use a password encoder as described in the xref:features/authentication/password-storage.adoc#authentication-password-storage[Password Storage]. -This will result in the bean being injected with the appropriate `PasswordEncoder` instance. - - -[[nsa-password-encoder-parents]] -==== Parent Elements of - - -* <> -* <> - - - -[[nsa-password-encoder-attributes]] -==== Attributes - - -[[nsa-password-encoder-hash]] -* **hash** -Defines the hashing algorithm used on user passwords. -We recommend strongly against using MD4, as it is a very weak hashing algorithm. - - -[[nsa-password-encoder-ref]] -* **ref** -Defines a reference to a Spring bean that implements `PasswordEncoder`. - - -[[nsa-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. - - -[[nsa-user-service-attributes]] -==== Attributes - - -[[nsa-user-service-id]] -* **id** -A bean identifier, used for referring to the bean elsewhere in the context. - - -[[nsa-user-service-properties]] -* **properties** -The location of a Properties file where each line is in the format of - -+ - -[source] ----- -username=password,grantedAuthority[,grantedAuthority][,enabled|disabled] ----- - - - - -[[nsa-user-service-children]] -==== Child Elements of - - -* <> - - - -[[nsa-user]] -=== -Represents a user in the application. - - -[[nsa-user-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-user-attributes]] -==== Attributes - - -[[nsa-user-authorities]] -* **authorities** -One of more authorities granted to the user. -Separate authorities with a comma (but no space). -For example, "ROLE_USER,ROLE_ADMINISTRATOR" - - -[[nsa-user-disabled]] -* **disabled** -Can be set to "true" to mark an account as disabled and unusable. - - -[[nsa-user-locked]] -* **locked** -Can be set to "true" to mark an account as locked and unusable. - - -[[nsa-user-name]] -* **name** -The username assigned to the user. - - -[[nsa-user-password]] -* **password** -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. - - - -== Method Security - -[[nsa-method-security]] -=== -This element is the primary means of adding support for securing methods on Spring Security beans. -Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts. - -[[nsa-method-security-attributes]] -==== attributes - -[[nsa-method-security-pre-post-enabled]] -* **pre-post-enabled** -Enables Spring Security's pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) for this application context. -Defaults to "true". - -[[nsa-method-security-secured-enabled]] -* **secured-enabled** -Enables Spring Security's @Secured annotation for this application context. -Defaults to "false". - -[[nsa-method-security-jsr250-enabled]] -* **jsr250-enabled** -Enables JSR-250 authorization annotations (@RolesAllowed, @PermitAll, @DenyAll) for this application context. -Defaults to "false". - -[[nsa-method-security-proxy-target-class]] -* **proxy-target-class** -If true, class based proxying will be used instead of interface based proxying. -Defaults to "false". - -[[nsa-method-security-children]] -==== Child Elements of - -* <> - -[[nsa-global-method-security]] -=== -This element is the primary means of adding support for securing methods on Spring Security beans. -Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts as child elements, using AspectJ syntax. - - -[[nsa-global-method-security-attributes]] -==== Attributes - - -[[nsa-global-method-security-access-decision-manager-ref]] -* **access-decision-manager-ref** -Method security uses the same `AccessDecisionManager` configuration as web security, but this can be overridden using this attribute. -By default an AffirmativeBased implementation is used for with a RoleVoter and an AuthenticatedVoter. - - -[[nsa-global-method-security-authentication-manager-ref]] -* **authentication-manager-ref** -A reference to an `AuthenticationManager` that should be used for method security. - - -[[nsa-global-method-security-jsr250-annotations]] -* **jsr250-annotations** -Specifies whether JSR-250 style attributes are to be used (for example "RolesAllowed"). -This will require the javax.annotation.security classes on the classpath. -Setting this to true also adds a `Jsr250Voter` to the `AccessDecisionManager`, so you need to make sure you do this if you are using a custom implementation and want to use these annotations. - - -[[nsa-global-method-security-metadata-source-ref]] -* **metadata-source-ref** -An external `MethodSecurityMetadataSource` instance can be supplied which will take priority over other sources (such as the default annotations). - - -[[nsa-global-method-security-mode]] -* **mode** -This attribute can be set to "aspectj" to specify that AspectJ should be used instead of the default Spring AOP. -Secured methods must be woven with the `AnnotationSecurityAspect` from the `spring-security-aspects` module. - -It is important to note that AspectJ follows Java's rule that annotations on interfaces are not inherited. -This means that methods that define the Security annotations on the interface will not be secured. -Instead, you must place the Security annotation on the class when using AspectJ. - - -[[nsa-global-method-security-order]] -* **order** -Allows the advice "order" to be set for the method security interceptor. - - -[[nsa-global-method-security-pre-post-annotations]] -* **pre-post-annotations** -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". - - -[[nsa-global-method-security-proxy-target-class]] -* **proxy-target-class** -If true, class based proxying will be used instead of interface based proxying. - - -[[nsa-global-method-security-run-as-manager-ref]] -* **run-as-manager-ref** -A reference to an optional `RunAsManager` implementation which will be used by the configured `MethodSecurityInterceptor` - - -[[nsa-global-method-security-secured-annotations]] -* **secured-annotations** -Specifies whether the use of Spring Security's @Secured annotations should be enabled for this application context. -Defaults to "disabled". - - -[[nsa-global-method-security-children]] -==== Child Elements of - - -* <> -* <> -* <> -* <> - - - -[[nsa-after-invocation-provider]] -=== -This element can be used to decorate an `AfterInvocationProvider` for use by the security interceptor maintained by the `` namespace. -You can define zero or more of these within the `global-method-security` element, each with a `ref` attribute pointing to an `AfterInvocationProvider` bean instance within your application context. - - -[[nsa-after-invocation-provider-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-after-invocation-provider-attributes]] -==== Attributes - - -[[nsa-after-invocation-provider-ref]] -* **ref** -Defines a reference to a Spring bean that implements `AfterInvocationProvider`. - - -[[nsa-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 replaced entirely. -Only applies if these annotations are enabled. - - -[[nsa-pre-post-annotation-handling-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-pre-post-annotation-handling-children]] -==== Child Elements of - - -* <> -* <> -* <> - - - -[[nsa-invocation-attribute-factory]] -=== -Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods. - - -[[nsa-invocation-attribute-factory-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-invocation-attribute-factory-attributes]] -==== Attributes - - -[[nsa-invocation-attribute-factory-ref]] -* **ref** -Defines a reference to a Spring bean Id. - - -[[nsa-post-invocation-advice]] -=== -Customizes the `PostInvocationAdviceProvider` with the ref as the `PostInvocationAuthorizationAdvice` for the element. - - -[[nsa-post-invocation-advice-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-post-invocation-advice-attributes]] -==== Attributes - - -[[nsa-post-invocation-advice-ref]] -* **ref** -Defines a reference to a Spring bean Id. - - -[[nsa-pre-invocation-advice]] -=== -Customizes the `PreInvocationAuthorizationAdviceVoter` with the ref as the `PreInvocationAuthorizationAdviceVoter` for the element. - - -[[nsa-pre-invocation-advice-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-pre-invocation-advice-attributes]] -==== Attributes - - -[[nsa-pre-invocation-advice-ref]] -* **ref** -Defines a reference to a Spring bean Id. - - -[[nsa-protect-pointcut]] -=== Securing Methods using -`` -Rather than defining security attributes on an individual method or class basis using the `@Secured` annotation, you can define cross-cutting security constraints across whole sets of methods and interfaces in your service layer using the `` element. -You can find an example in the xref:servlet/authorization/method-security.adoc#ns-protect-pointcut[namespace introduction]. - - -[[nsa-protect-pointcut-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-protect-pointcut-attributes]] -==== Attributes - - -[[nsa-protect-pointcut-access]] -* **access** -Access configuration attributes list that applies to all methods matching the pointcut, e.g. -"ROLE_A,ROLE_B" - - -[[nsa-protect-pointcut-expression]] -* **expression** -An AspectJ expression, including the `execution` keyword. -For example, `execution(int com.foo.TargetObject.countLength(String))`. - - -[[nsa-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 - - -[[nsa-intercept-methods-attributes]] -==== Attributes - - -[[nsa-intercept-methods-access-decision-manager-ref]] -* **access-decision-manager-ref** -Optional AccessDecisionManager bean ID to be used by the created method security interceptor. - - -[[nsa-intercept-methods-children]] -==== Child Elements of - - -* <> - - - -[[nsa-method-security-metadata-source]] -=== -Creates a MethodSecurityMetadataSource instance - - -[[nsa-method-security-metadata-source-attributes]] -==== Attributes - - -[[nsa-method-security-metadata-source-id]] -* **id** -A bean identifier, used for referring to the bean elsewhere in the context. - - -[[nsa-method-security-metadata-source-use-expressions]] -* **use-expressions** -Enables the use of expressions in the 'access' attributes in elements rather than the traditional list of configuration attributes. -Defaults to 'false'. -If enabled, each attribute should contain a single Boolean expression. -If the expression evaluates to 'true', access will be granted. - - -[[nsa-method-security-metadata-source-children]] -==== Child Elements of - - -* <> - - - -[[nsa-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". - - -[[nsa-protect-parents]] -==== Parent Elements of - - -* <> -* <> - - - -[[nsa-protect-attributes]] -==== Attributes - - -[[nsa-protect-access]] -* **access** -Access configuration attributes list that applies to the method, e.g. -"ROLE_A,ROLE_B". - - -[[nsa-protect-method]] -* **method** -A method name - - -[[nsa-ldap]] -== LDAP Namespace Options -LDAP is covered in some details in xref:servlet/authentication/passwords/ldap.adoc#servlet-authentication-ldap[its own chapter]. -We will expand on that here with some explanation of how the namespace options map to Spring beans. -The LDAP implementation uses Spring LDAP extensively, so some familiarity with that project's API may be useful. - - -[[nsa-ldap-server]] -=== Defining the LDAP Server using the -`` Element -This element sets up a Spring LDAP `ContextSource` for use by the other LDAP beans, defining the location of the LDAP server and other information (such as a username and password, if it doesn't allow anonymous access) for connecting to it. -It can also be used to create an embedded server for testing. -Details of the syntax for both options are covered in the xref:servlet/authentication/passwords/ldap.adoc#servlet-authentication-ldap[LDAP chapter]. -The actual `ContextSource` implementation is `DefaultSpringSecurityContextSource` which extends Spring LDAP's `LdapContextSource` class. -The `manager-dn` and `manager-password` attributes map to the latter's `userDn` and `password` properties respectively. - -If you only have one server defined in your application context, the other LDAP namespace-defined beans will use it automatically. -Otherwise, you can give the element an "id" attribute and refer to it from other namespace beans using the `server-ref` attribute. -This is actually the bean `id` of the `ContextSource` instance, if you want to use it in other traditional Spring beans. - - -[[nsa-ldap-server-attributes]] -==== Attributes - -[[nsa-ldap-server-mode]] -* **mode** -Explicitly specifies which embedded ldap server should use. Values are `apacheds` and `unboundid`. By default, it will depends if the library is available in the classpath. - -[[nsa-ldap-server-id]] -* **id** -A bean identifier, used for referring to the bean elsewhere in the context. - - -[[nsa-ldap-server-ldif]] -* **ldif** -Explicitly specifies an ldif file resource to load into an embedded LDAP server. -The ldif should be a Spring resource pattern (i.e. classpath:init.ldif). -The default is classpath*:*.ldif - - -[[nsa-ldap-server-manager-dn]] -* **manager-dn** -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. - - -[[nsa-ldap-server-manager-password]] -* **manager-password** -The password for the manager DN. -This is required if the manager-dn is specified. - - -[[nsa-ldap-server-port]] -* **port** -Specifies an IP port number. -Used to configure an embedded LDAP server, for example. -The default value is 33389. - - -[[nsa-ldap-server-root]] -* **root** -Optional root suffix for the embedded LDAP server. -Default is "dc=springframework,dc=org" - - -[[nsa-ldap-server-url]] -* **url** -Specifies the ldap server URL when not using the embedded LDAP server. - - -[[nsa-ldap-authentication-provider]] -=== -This element is shorthand for the creation of an `LdapAuthenticationProvider` instance. -By default this will be configured with a `BindAuthenticator` instance and a `DefaultAuthoritiesPopulator`. -As with all namespace authentication providers, it must be included as a child of the `authentication-provider` element. - - -[[nsa-ldap-authentication-provider-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-ldap-authentication-provider-attributes]] -==== Attributes - - -[[nsa-ldap-authentication-provider-group-role-attribute]] -* **group-role-attribute** -The LDAP attribute name which contains the role name which will be used within Spring Security. -Maps to the ``DefaultLdapAuthoritiesPopulator``'s `groupRoleAttribute` property. -Defaults to "cn". - - -[[nsa-ldap-authentication-provider-group-search-base]] -* **group-search-base** -Search base for group membership searches. -Maps to the ``DefaultLdapAuthoritiesPopulator``'s `groupSearchBase` constructor argument. -Defaults to "" (searching from the root). - - -[[nsa-ldap-authentication-provider-group-search-filter]] -* **group-search-filter** -Group search filter. -Maps to the ``DefaultLdapAuthoritiesPopulator``'s `groupSearchFilter` property. -Defaults to `+(uniqueMember={0})+`. -The substituted parameter is the DN of the user. - - -[[nsa-ldap-authentication-provider-role-prefix]] -* **role-prefix** -A non-empty string prefix that will be added to role strings loaded from persistent. -Maps to the ``DefaultLdapAuthoritiesPopulator``'s `rolePrefix` property. -Defaults to "ROLE_". -Use the value "none" for no prefix in cases where the default is non-empty. - - -[[nsa-ldap-authentication-provider-server-ref]] -* **server-ref** -The optional server to use. -If omitted, and a default LDAP server is registered (using with no Id), that server will be used. - - -[[nsa-ldap-authentication-provider-user-context-mapper-ref]] -* **user-context-mapper-ref** -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 - - -[[nsa-ldap-authentication-provider-user-details-class]] -* **user-details-class** -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 - - -[[nsa-ldap-authentication-provider-user-dn-pattern]] -* **user-dn-pattern** -If your users are at a fixed location in the directory (i.e. you can work out the DN directly from the username without doing a directory search), you can use this attribute to map directly to the DN. -It maps directly to the `userDnPatterns` property of `AbstractLdapAuthenticator`. -The value is 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. - - -[[nsa-ldap-authentication-provider-user-search-base]] -* **user-search-base** -Search base for user searches. -Defaults to "". -Only used with a 'user-search-filter'. - -+ - -If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. -The `BindAuthenticator` will be configured with a `FilterBasedLdapUserSearch` and the attribute values map directly to the first two arguments of that bean's constructor. -If these attributes aren't set and no `user-dn-pattern` has been supplied as an alternative, then the default search values of `+user-search-filter="(uid={0})"+` and `user-search-base=""` will be used. - - -[[nsa-ldap-authentication-provider-user-search-filter]] -* **user-search-filter** -The LDAP filter used to search for users (optional). -For example `+(uid={0})+`. -The substituted parameter is the user's login name. - -+ - -If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. -The `BindAuthenticator` will be configured with a `FilterBasedLdapUserSearch` and the attribute values map directly to the first two arguments of that bean's constructor. -If these attributes aren't set and no `user-dn-pattern` has been supplied as an alternative, then the default search values of `+user-search-filter="(uid={0})"+` and `user-search-base=""` will be used. - - -[[nsa-ldap-authentication-provider-children]] -==== Child Elements of - - -* <> - - - -[[nsa-password-compare]] -=== -This is used as child element to `` and switches the authentication strategy from `BindAuthenticator` to `PasswordComparisonAuthenticator`. - - -[[nsa-password-compare-parents]] -==== Parent Elements of - - -* <> - - - -[[nsa-password-compare-attributes]] -==== Attributes - - -[[nsa-password-compare-hash]] -* **hash** -Defines the hashing algorithm used on user passwords. -We recommend strongly against using MD4, as it is a very weak hashing algorithm. - - -[[nsa-password-compare-password-attribute]] -* **password-attribute** -The attribute in the directory which contains the user password. -Defaults to "userPassword". - - -[[nsa-password-compare-children]] -==== Child Elements of - - -* <> - - - -[[nsa-ldap-user-service]] -=== -This element configures an LDAP `UserDetailsService`. -The class used is `LdapUserDetailsService` which is a combination of a `FilterBasedLdapUserSearch` and a `DefaultLdapAuthoritiesPopulator`. -The attributes it supports have the same usage as in ``. - - -[[nsa-ldap-user-service-attributes]] -==== Attributes - - -[[nsa-ldap-user-service-cache-ref]] -* **cache-ref** -Defines a reference to a cache for use with a UserDetailsService. - - -[[nsa-ldap-user-service-group-role-attribute]] -* **group-role-attribute** -The LDAP attribute name which contains the role name which will be used within Spring Security. -Defaults to "cn". - - -[[nsa-ldap-user-service-group-search-base]] -* **group-search-base** -Search base for group membership searches. -Defaults to "" (searching from the root). - - -[[nsa-ldap-user-service-group-search-filter]] -* **group-search-filter** -Group search filter. -Defaults to `+(uniqueMember={0})+`. -The substituted parameter is the DN of the user. - - -[[nsa-ldap-user-service-id]] -* **id** -A bean identifier, used for referring to the bean elsewhere in the context. - - -[[nsa-ldap-user-service-role-prefix]] -* **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. - - -[[nsa-ldap-user-service-server-ref]] -* **server-ref** -The optional server to use. -If omitted, and a default LDAP server is registered (using with no Id), that server will be used. - - -[[nsa-ldap-user-service-user-context-mapper-ref]] -* **user-context-mapper-ref** -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 - - -[[nsa-ldap-user-service-user-details-class]] -* **user-details-class** -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 - - -[[nsa-ldap-user-service-user-search-base]] -* **user-search-base** -Search base for user searches. -Defaults to "". -Only used with a 'user-search-filter'. - - -[[nsa-ldap-user-service-user-search-filter]] -* **user-search-filter** -The LDAP filter used to search for users (optional). -For example `+(uid={0})+`. -The substituted parameter is the user's login name. diff --git a/docs/modules/ROOT/pages/servlet/appendix/namespace/index.adoc b/docs/modules/ROOT/pages/servlet/appendix/namespace/index.adoc new file mode 100644 index 00000000000..4f36c2c2cb3 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/appendix/namespace/index.adoc @@ -0,0 +1,9 @@ +[[appendix-namespace]] += The Security Namespace +:page-section-summary-toc: 1 + +This appendix provides a reference to the elements available in the security namespace and information on the underlying beans they create (a knowledge of the individual classes and how they work together is assumed - you can find more information in the project Javadoc and elsewhere in this document). +If you haven't used the namespace before, please read the xref:servlet/configuration/xml-namespace.adoc#ns-config[introductory chapter] on namespace configuration, as this is intended as a supplement to the information there. +Using a good quality XML editor while editing a configuration based on the schema is recommended as this will provide contextual information on which elements and attributes are available as well as comments explaining their purpose. +The namespace is written in https://relaxng.org/[RELAX NG] Compact format and later converted into an XSD schema. +If you are familiar with this format, you may wish to examine the https://raw.githubusercontent.com/spring-projects/spring-security/main/config/src/main/resources/org/springframework/security/config/spring-security-5.6.rnc[schema file] directly. diff --git a/docs/modules/ROOT/pages/servlet/appendix/namespace/ldap.adoc b/docs/modules/ROOT/pages/servlet/appendix/namespace/ldap.adoc new file mode 100644 index 00000000000..f3c07e6d767 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/appendix/namespace/ldap.adoc @@ -0,0 +1,291 @@ +[[nsa-ldap]] += LDAP Namespace Options +LDAP is covered in some details in xref:servlet/authentication/passwords/ldap.adoc#servlet-authentication-ldap[its own chapter]. +We will expand on that here with some explanation of how the namespace options map to Spring beans. +The LDAP implementation uses Spring LDAP extensively, so some familiarity with that project's API may be useful. + + +[[nsa-ldap-server]] +== Defining the LDAP Server using the +`` Element +This element sets up a Spring LDAP `ContextSource` for use by the other LDAP beans, defining the location of the LDAP server and other information (such as a username and password, if it doesn't allow anonymous access) for connecting to it. +It can also be used to create an embedded server for testing. +Details of the syntax for both options are covered in the xref:servlet/authentication/passwords/ldap.adoc#servlet-authentication-ldap[LDAP chapter]. +The actual `ContextSource` implementation is `DefaultSpringSecurityContextSource` which extends Spring LDAP's `LdapContextSource` class. +The `manager-dn` and `manager-password` attributes map to the latter's `userDn` and `password` properties respectively. + +If you only have one server defined in your application context, the other LDAP namespace-defined beans will use it automatically. +Otherwise, you can give the element an "id" attribute and refer to it from other namespace beans using the `server-ref` attribute. +This is actually the bean `id` of the `ContextSource` instance, if you want to use it in other traditional Spring beans. + + +[[nsa-ldap-server-attributes]] +=== Attributes + +[[nsa-ldap-server-mode]] +* **mode** +Explicitly specifies which embedded ldap server should use. Values are `apacheds` and `unboundid`. By default, it will depends if the library is available in the classpath. + +[[nsa-ldap-server-id]] +* **id** +A bean identifier, used for referring to the bean elsewhere in the context. + + +[[nsa-ldap-server-ldif]] +* **ldif** +Explicitly specifies an ldif file resource to load into an embedded LDAP server. +The ldif should be a Spring resource pattern (i.e. classpath:init.ldif). +The default is classpath*:*.ldif + + +[[nsa-ldap-server-manager-dn]] +* **manager-dn** +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. + + +[[nsa-ldap-server-manager-password]] +* **manager-password** +The password for the manager DN. +This is required if the manager-dn is specified. + + +[[nsa-ldap-server-port]] +* **port** +Specifies an IP port number. +Used to configure an embedded LDAP server, for example. +The default value is 33389. + + +[[nsa-ldap-server-root]] +* **root** +Optional root suffix for the embedded LDAP server. +Default is "dc=springframework,dc=org" + + +[[nsa-ldap-server-url]] +* **url** +Specifies the ldap server URL when not using the embedded LDAP server. + + +[[nsa-ldap-authentication-provider]] +== +This element is shorthand for the creation of an `LdapAuthenticationProvider` instance. +By default this will be configured with a `BindAuthenticator` instance and a `DefaultAuthoritiesPopulator`. +As with all namespace authentication providers, it must be included as a child of the `authentication-provider` element. + + +[[nsa-ldap-authentication-provider-parents]] +=== Parent Elements of + + +* xref:servlet/appendix/namespace/authentication-manager.adoc#nsa-authentication-manager[authentication-manager] + + + +[[nsa-ldap-authentication-provider-attributes]] +=== Attributes + + +[[nsa-ldap-authentication-provider-group-role-attribute]] +* **group-role-attribute** +The LDAP attribute name which contains the role name which will be used within Spring Security. +Maps to the ``DefaultLdapAuthoritiesPopulator``'s `groupRoleAttribute` property. +Defaults to "cn". + + +[[nsa-ldap-authentication-provider-group-search-base]] +* **group-search-base** +Search base for group membership searches. +Maps to the ``DefaultLdapAuthoritiesPopulator``'s `groupSearchBase` constructor argument. +Defaults to "" (searching from the root). + + +[[nsa-ldap-authentication-provider-group-search-filter]] +* **group-search-filter** +Group search filter. +Maps to the ``DefaultLdapAuthoritiesPopulator``'s `groupSearchFilter` property. +Defaults to `+(uniqueMember={0})+`. +The substituted parameter is the DN of the user. + + +[[nsa-ldap-authentication-provider-role-prefix]] +* **role-prefix** +A non-empty string prefix that will be added to role strings loaded from persistent. +Maps to the ``DefaultLdapAuthoritiesPopulator``'s `rolePrefix` property. +Defaults to "ROLE_". +Use the value "none" for no prefix in cases where the default is non-empty. + + +[[nsa-ldap-authentication-provider-server-ref]] +* **server-ref** +The optional server to use. +If omitted, and a default LDAP server is registered (using with no Id), that server will be used. + + +[[nsa-ldap-authentication-provider-user-context-mapper-ref]] +* **user-context-mapper-ref** +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 + + +[[nsa-ldap-authentication-provider-user-details-class]] +* **user-details-class** +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 + + +[[nsa-ldap-authentication-provider-user-dn-pattern]] +* **user-dn-pattern** +If your users are at a fixed location in the directory (i.e. you can work out the DN directly from the username without doing a directory search), you can use this attribute to map directly to the DN. +It maps directly to the `userDnPatterns` property of `AbstractLdapAuthenticator`. +The value is 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. + + +[[nsa-ldap-authentication-provider-user-search-base]] +* **user-search-base** +Search base for user searches. +Defaults to "". +Only used with a 'user-search-filter'. + ++ + +If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. +The `BindAuthenticator` will be configured with a `FilterBasedLdapUserSearch` and the attribute values map directly to the first two arguments of that bean's constructor. +If these attributes aren't set and no `user-dn-pattern` has been supplied as an alternative, then the default search values of `+user-search-filter="(uid={0})"+` and `user-search-base=""` will be used. + + +[[nsa-ldap-authentication-provider-user-search-filter]] +* **user-search-filter** +The LDAP filter used to search for users (optional). +For example `+(uid={0})+`. +The substituted parameter is the user's login name. + ++ + +If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. +The `BindAuthenticator` will be configured with a `FilterBasedLdapUserSearch` and the attribute values map directly to the first two arguments of that bean's constructor. +If these attributes aren't set and no `user-dn-pattern` has been supplied as an alternative, then the default search values of `+user-search-filter="(uid={0})"+` and `user-search-base=""` will be used. + + +[[nsa-ldap-authentication-provider-children]] +=== Child Elements of + + +* <> + + + +[[nsa-password-compare]] +== +This is used as child element to `` and switches the authentication strategy from `BindAuthenticator` to `PasswordComparisonAuthenticator`. + + +[[nsa-password-compare-parents]] +=== Parent Elements of + + +* <> + + + +[[nsa-password-compare-attributes]] +=== Attributes + + +[[nsa-password-compare-hash]] +* **hash** +Defines the hashing algorithm used on user passwords. +We recommend strongly against using MD4, as it is a very weak hashing algorithm. + + +[[nsa-password-compare-password-attribute]] +* **password-attribute** +The attribute in the directory which contains the user password. +Defaults to "userPassword". + + +[[nsa-password-compare-children]] +=== Child Elements of + + +* xref:servlet/appendix/namespace/authentication-manager.adoc#nsa-password-encoder[password-encoder] + + + +[[nsa-ldap-user-service]] +== +This element configures an LDAP `UserDetailsService`. +The class used is `LdapUserDetailsService` which is a combination of a `FilterBasedLdapUserSearch` and a `DefaultLdapAuthoritiesPopulator`. +The attributes it supports have the same usage as in ``. + + +[[nsa-ldap-user-service-attributes]] +=== Attributes + + +[[nsa-ldap-user-service-cache-ref]] +* **cache-ref** +Defines a reference to a cache for use with a UserDetailsService. + + +[[nsa-ldap-user-service-group-role-attribute]] +* **group-role-attribute** +The LDAP attribute name which contains the role name which will be used within Spring Security. +Defaults to "cn". + + +[[nsa-ldap-user-service-group-search-base]] +* **group-search-base** +Search base for group membership searches. +Defaults to "" (searching from the root). + + +[[nsa-ldap-user-service-group-search-filter]] +* **group-search-filter** +Group search filter. +Defaults to `+(uniqueMember={0})+`. +The substituted parameter is the DN of the user. + + +[[nsa-ldap-user-service-id]] +* **id** +A bean identifier, used for referring to the bean elsewhere in the context. + + +[[nsa-ldap-user-service-role-prefix]] +* **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. + + +[[nsa-ldap-user-service-server-ref]] +* **server-ref** +The optional server to use. +If omitted, and a default LDAP server is registered (using with no Id), that server will be used. + + +[[nsa-ldap-user-service-user-context-mapper-ref]] +* **user-context-mapper-ref** +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 + + +[[nsa-ldap-user-service-user-details-class]] +* **user-details-class** +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 + + +[[nsa-ldap-user-service-user-search-base]] +* **user-search-base** +Search base for user searches. +Defaults to "". +Only used with a 'user-search-filter'. + + +[[nsa-ldap-user-service-user-search-filter]] +* **user-search-filter** +The LDAP filter used to search for users (optional). +For example `+(uid={0})+`. +The substituted parameter is the user's login name. diff --git a/docs/modules/ROOT/pages/servlet/appendix/namespace/method-security.adoc b/docs/modules/ROOT/pages/servlet/appendix/namespace/method-security.adoc new file mode 100644 index 00000000000..3d50d5507cb --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/appendix/namespace/method-security.adoc @@ -0,0 +1,340 @@ += Method Security + +[[nsa-method-security]] +== +This element is the primary means of adding support for securing methods on Spring Security beans. +Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts. + +[[nsa-method-security-attributes]] +=== attributes + +[[nsa-method-security-pre-post-enabled]] +* **pre-post-enabled** +Enables Spring Security's pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) for this application context. +Defaults to "true". + +[[nsa-method-security-secured-enabled]] +* **secured-enabled** +Enables Spring Security's @Secured annotation for this application context. +Defaults to "false". + +[[nsa-method-security-jsr250-enabled]] +* **jsr250-enabled** +Enables JSR-250 authorization annotations (@RolesAllowed, @PermitAll, @DenyAll) for this application context. +Defaults to "false". + +[[nsa-method-security-proxy-target-class]] +* **proxy-target-class** +If true, class based proxying will be used instead of interface based proxying. +Defaults to "false". + +[[nsa-method-security-children]] +=== Child Elements of + +* xref:servlet/appendix/namespace/http.adoc#nsa-expression-handler[expression-handler] + +[[nsa-global-method-security]] +== +This element is the primary means of adding support for securing methods on Spring Security beans. +Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts as child elements, using AspectJ syntax. + + +[[nsa-global-method-security-attributes]] +=== Attributes + + +[[nsa-global-method-security-access-decision-manager-ref]] +* **access-decision-manager-ref** +Method security uses the same `AccessDecisionManager` configuration as web security, but this can be overridden using this attribute. +By default an AffirmativeBased implementation is used for with a RoleVoter and an AuthenticatedVoter. + + +[[nsa-global-method-security-authentication-manager-ref]] +* **authentication-manager-ref** +A reference to an `AuthenticationManager` that should be used for method security. + + +[[nsa-global-method-security-jsr250-annotations]] +* **jsr250-annotations** +Specifies whether JSR-250 style attributes are to be used (for example "RolesAllowed"). +This will require the javax.annotation.security classes on the classpath. +Setting this to true also adds a `Jsr250Voter` to the `AccessDecisionManager`, so you need to make sure you do this if you are using a custom implementation and want to use these annotations. + + +[[nsa-global-method-security-metadata-source-ref]] +* **metadata-source-ref** +An external `MethodSecurityMetadataSource` instance can be supplied which will take priority over other sources (such as the default annotations). + + +[[nsa-global-method-security-mode]] +* **mode** +This attribute can be set to "aspectj" to specify that AspectJ should be used instead of the default Spring AOP. +Secured methods must be woven with the `AnnotationSecurityAspect` from the `spring-security-aspects` module. + +It is important to note that AspectJ follows Java's rule that annotations on interfaces are not inherited. +This means that methods that define the Security annotations on the interface will not be secured. +Instead, you must place the Security annotation on the class when using AspectJ. + + +[[nsa-global-method-security-order]] +* **order** +Allows the advice "order" to be set for the method security interceptor. + + +[[nsa-global-method-security-pre-post-annotations]] +* **pre-post-annotations** +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". + + +[[nsa-global-method-security-proxy-target-class]] +* **proxy-target-class** +If true, class based proxying will be used instead of interface based proxying. + + +[[nsa-global-method-security-run-as-manager-ref]] +* **run-as-manager-ref** +A reference to an optional `RunAsManager` implementation which will be used by the configured `MethodSecurityInterceptor` + + +[[nsa-global-method-security-secured-annotations]] +* **secured-annotations** +Specifies whether the use of Spring Security's @Secured annotations should be enabled for this application context. +Defaults to "disabled". + + +[[nsa-global-method-security-children]] +=== Child Elements of + + +* <> +* xref:servlet/appendix/namespace/http.adoc#nsa-expression-handler[expression-handler] +* <> +* <> + + + +[[nsa-after-invocation-provider]] +== +This element can be used to decorate an `AfterInvocationProvider` for use by the security interceptor maintained by the `` namespace. +You can define zero or more of these within the `global-method-security` element, each with a `ref` attribute pointing to an `AfterInvocationProvider` bean instance within your application context. + + +[[nsa-after-invocation-provider-parents]] +=== Parent Elements of + + +* <> + + + +[[nsa-after-invocation-provider-attributes]] +=== Attributes + + +[[nsa-after-invocation-provider-ref]] +* **ref** +Defines a reference to a Spring bean that implements `AfterInvocationProvider`. + + +[[nsa-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 replaced entirely. +Only applies if these annotations are enabled. + + +[[nsa-pre-post-annotation-handling-parents]] +=== Parent Elements of + + +* <> + + + +[[nsa-pre-post-annotation-handling-children]] +=== Child Elements of + + +* <> +* <> +* <> + + + +[[nsa-invocation-attribute-factory]] +== +Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods. + + +[[nsa-invocation-attribute-factory-parents]] +=== Parent Elements of + + +* <> + + + +[[nsa-invocation-attribute-factory-attributes]] +=== Attributes + + +[[nsa-invocation-attribute-factory-ref]] +* **ref** +Defines a reference to a Spring bean Id. + + +[[nsa-post-invocation-advice]] +== +Customizes the `PostInvocationAdviceProvider` with the ref as the `PostInvocationAuthorizationAdvice` for the element. + + +[[nsa-post-invocation-advice-parents]] +=== Parent Elements of + + +* <> + + + +[[nsa-post-invocation-advice-attributes]] +=== Attributes + + +[[nsa-post-invocation-advice-ref]] +* **ref** +Defines a reference to a Spring bean Id. + + +[[nsa-pre-invocation-advice]] +== +Customizes the `PreInvocationAuthorizationAdviceVoter` with the ref as the `PreInvocationAuthorizationAdviceVoter` for the element. + + +[[nsa-pre-invocation-advice-parents]] +=== Parent Elements of + + +* <> + + + +[[nsa-pre-invocation-advice-attributes]] +=== Attributes + + +[[nsa-pre-invocation-advice-ref]] +* **ref** +Defines a reference to a Spring bean Id. + + +[[nsa-protect-pointcut]] +== Securing Methods using +`` +Rather than defining security attributes on an individual method or class basis using the `@Secured` annotation, you can define cross-cutting security constraints across whole sets of methods and interfaces in your service layer using the `` element. +You can find an example in the xref:servlet/authorization/method-security.adoc#ns-protect-pointcut[namespace introduction]. + + +[[nsa-protect-pointcut-parents]] +=== Parent Elements of + + +* <> + + + +[[nsa-protect-pointcut-attributes]] +=== Attributes + + +[[nsa-protect-pointcut-access]] +* **access** +Access configuration attributes list that applies to all methods matching the pointcut, e.g. +"ROLE_A,ROLE_B" + + +[[nsa-protect-pointcut-expression]] +* **expression** +An AspectJ expression, including the `execution` keyword. +For example, `execution(int com.foo.TargetObject.countLength(String))`. + + +[[nsa-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 + + +[[nsa-intercept-methods-attributes]] +=== Attributes + + +[[nsa-intercept-methods-access-decision-manager-ref]] +* **access-decision-manager-ref** +Optional AccessDecisionManager bean ID to be used by the created method security interceptor. + + +[[nsa-intercept-methods-children]] +=== Child Elements of + + +* <> + + + +[[nsa-method-security-metadata-source]] +== +Creates a MethodSecurityMetadataSource instance + + +[[nsa-method-security-metadata-source-attributes]] +=== Attributes + + +[[nsa-method-security-metadata-source-id]] +* **id** +A bean identifier, used for referring to the bean elsewhere in the context. + + +[[nsa-method-security-metadata-source-use-expressions]] +* **use-expressions** +Enables the use of expressions in the 'access' attributes in elements rather than the traditional list of configuration attributes. +Defaults to 'false'. +If enabled, each attribute should contain a single Boolean expression. +If the expression evaluates to 'true', access will be granted. + + +[[nsa-method-security-metadata-source-children]] +=== Child Elements of + + +* <> + + + +[[nsa-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". + + +[[nsa-protect-parents]] +=== Parent Elements of + + +* <> +* <> + + + +[[nsa-protect-attributes]] +=== Attributes + + +[[nsa-protect-access]] +* **access** +Access configuration attributes list that applies to the method, e.g. +"ROLE_A,ROLE_B". + + +[[nsa-protect-method]] +* **method** +A method name diff --git a/docs/modules/ROOT/pages/servlet/appendix/namespace/websocket.adoc b/docs/modules/ROOT/pages/servlet/appendix/namespace/websocket.adoc new file mode 100644 index 00000000000..fde54bc6426 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/appendix/namespace/websocket.adoc @@ -0,0 +1,74 @@ +[[nsa-websocket-security]] += WebSocket Security + +Spring Security 4.0+ provides support for authorizing messages. +One concrete example of where this is useful is to provide authorization in WebSocket based applications. + +[[nsa-websocket-message-broker]] +== + +The websocket-message-broker element has two different modes. +If the <> is not specified, then it will do the following things: + +* Ensure that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver. +This allows the use of `@AuthenticationPrincipal` to resolve the principal of the current `Authentication` +* Ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel. +This populates the SecurityContextHolder with the user that is found in the Message +* Ensures that a ChannelSecurityInterceptor is registered with the clientInboundChannel. +This allows authorization rules to be specified for a message. +* Ensures that a CsrfChannelInterceptor is registered with the clientInboundChannel. +This ensures that only requests from the original domain are enabled. +* Ensures that a CsrfTokenHandshakeInterceptor is registered with WebSocketHttpRequestHandler, TransportHandlingSockJsService, or DefaultSockJsService. +This ensures that the expected CsrfToken from the HttpServletRequest is copied into the WebSocket Session attributes. + +If additional control is necessary, the id can be specified and a ChannelSecurityInterceptor will be assigned to the specified id. +All the wiring with Spring's messaging infrastructure can then be done manually. +This is more cumbersome, but provides greater control over the configuration. + + +[[nsa-websocket-message-broker-attributes]] +=== Attributes + +[[nsa-websocket-message-broker-id]] +* **id** A bean identifier, used for referring to the ChannelSecurityInterceptor bean elsewhere in the context. +If specified, Spring Security requires explicit configuration within Spring Messaging. +If not specified, Spring Security will automatically integrate with the messaging infrastructure as described in <> + +[[nsa-websocket-message-broker-same-origin-disabled]] +* **same-origin-disabled** 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. + +[[nsa-websocket-message-broker-children]] +=== Child Elements of + + +* xref:servlet/appendix/namespace/http.adoc#nsa-expression-handler[expression-handler] +* <> + +[[nsa-intercept-message]] +== + +Defines an authorization rule for a message. + + +[[nsa-intercept-message-parents]] +=== Parent Elements of + + +* <> + + +[[nsa-intercept-message-attributes]] +=== Attributes + +[[nsa-intercept-message-pattern]] +* **pattern** An ant based pattern that matches on the Message destination. +For example, "/**" matches any Message with a destination; "/admin/**" matches any Message that has a destination that starts with "/admin/**". + +[[nsa-intercept-message-type]] +* **type** 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). + +[[nsa-intercept-message-access]] +* **access** The expression used to secure the Message. +For example, "denyAll" will deny access to all of the matching Messages; "permitAll" will grant access to all of the matching Messages; "hasRole('ADMIN') requires the current user to have the role 'ROLE_ADMIN' for the matching Messages. diff --git a/docs/modules/ROOT/pages/servlet/architecture.adoc b/docs/modules/ROOT/pages/servlet/architecture.adoc index 40b62a1a3c8..26b9a329f97 100644 --- a/docs/modules/ROOT/pages/servlet/architecture.adoc +++ b/docs/modules/ROOT/pages/servlet/architecture.adoc @@ -2,28 +2,28 @@ = Architecture :figures: servlet/architecture -This section discusses Spring Security's high level architecture within Servlet based applications. -We build on this high level understanding within xref:servlet/authentication/index.adoc#servlet-authentication[Authentication], xref:servlet/authorization/index.adoc#servlet-authorization[Authorization], xref:servlet/exploits/index.adoc#servlet-exploits[Protection Against Exploits] sections of the reference. +This section discusses Spring Security's high-level architecture within Servlet based applications. +We build on this high-level understanding within the xref:servlet/authentication/index.adoc#servlet-authentication[Authentication], xref:servlet/authorization/index.adoc#servlet-authorization[Authorization], and xref:servlet/exploits/index.adoc#servlet-exploits[Protection Against Exploits] sections of the reference. // FIXME: Add links to other sections of architecture [[servlet-filters-review]] -== A Review of ``Filter``s +== A Review of Filters -Spring Security's Servlet support is based on Servlet ``Filter``s, so it is helpful to look at the role of ``Filter``s generally first. -The picture below shows the typical layering of the handlers for a single HTTP request. +Spring Security's Servlet support is based on Servlet Filters, so it is helpful to look at the role of Filters generally first. +The following image shows the typical layering of the handlers for a single HTTP request. .FilterChain [[servlet-filterchain-figure]] image::{figures}/filterchain.png[] -The client sends a request to the application, and the container creates a `FilterChain` which contains the ``Filter``s and `Servlet` that should process the `HttpServletRequest` based on the path of the request URI. -In a Spring MVC application the `Servlet` is an instance of {spring-framework-reference-url}web.html#mvc-servlet[`DispatcherServlet`]. -At most one `Servlet` can handle a single `HttpServletRequest` and `HttpServletResponse`. +The client sends a request to the application, and the container creates a `FilterChain`, which contains the `Filter` instances and `Servlet` that should process the `HttpServletRequest`, based on the path of the request URI. +In a Spring MVC application, the `Servlet` is an instance of {spring-framework-reference-url}web.html#mvc-servlet[`DispatcherServlet`]. +At most, one `Servlet` can handle a single `HttpServletRequest` and `HttpServletResponse`. However, more than one `Filter` can be used to: -* Prevent downstream ``Filter``s or the `Servlet` from being invoked. -In this instance the `Filter` will typically write the `HttpServletResponse`. -* Modify the `HttpServletRequest` or `HttpServletResponse` used by the downstream ``Filter``s and `Servlet` +* Prevent downstream `Filter` instances or the `Servlet` from being invoked. +In this case, the `Filter` typically writes the `HttpServletResponse`. +* Modify the `HttpServletRequest` or `HttpServletResponse` used by the downstream `Filter` instances and the `Servlet`. The power of the `Filter` comes from the `FilterChain` that is passed into it. @@ -50,24 +50,23 @@ fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterCh ---- ==== -Since a `Filter` only impacts downstream ``Filter``s and the `Servlet`, the order each `Filter` is invoked is extremely important. - +Since a `Filter` impacts only downstream `Filter` instances and the `Servlet`, the order in which each `Filter` is invoked is extremely important. [[servlet-delegatingfilterproxy]] == DelegatingFilterProxy Spring provides a `Filter` implementation named {spring-framework-api-url}org/springframework/web/filter/DelegatingFilterProxy.html[`DelegatingFilterProxy`] that allows bridging between the Servlet container's lifecycle and Spring's `ApplicationContext`. -The Servlet container allows registering ``Filter``s using its own standards, but it is not aware of Spring defined Beans. -`DelegatingFilterProxy` can be registered via standard Servlet container mechanisms, but delegate all the work to a Spring Bean that implements `Filter`. +The Servlet container allows registering `Filter` instances by using its own standards, but it is not aware of Spring-defined Beans. +You can register `DelegatingFilterProxy` through the standard Servlet container mechanisms but delegate all the work to a Spring Bean that implements `Filter`. -Here is a picture of how `DelegatingFilterProxy` fits into the <>. +Here is a picture of how `DelegatingFilterProxy` fits into the <>. .DelegatingFilterProxy [[servlet-delegatingfilterproxy-figure]] image::{figures}/delegatingfilterproxy.png[] `DelegatingFilterProxy` looks up __Bean Filter~0~__ from the `ApplicationContext` and then invokes __Bean Filter~0~__. -The pseudo code of `DelegatingFilterProxy` can be seen below. +The following listing shows pseudo code of `DelegatingFilterProxy`: .`DelegatingFilterProxy` Pseudo Code ==== @@ -96,9 +95,9 @@ fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterCh ---- ==== -Another benefit of `DelegatingFilterProxy` is that it allows delaying looking `Filter` bean instances. -This is important because the container needs to register the `Filter` instances before the container can startup. -However, Spring typically uses a `ContextLoaderListener` to load the Spring Beans which will not be done until after the `Filter` instances need to be registered. +Another benefit of `DelegatingFilterProxy` is that it allows delaying looking up `Filter` bean instances. +This is important because the container needs to register the `Filter` instances before the container can start up. +However, Spring typically uses a `ContextLoaderListener` to load the Spring Beans, which is not done until after the `Filter` instances need to be registered. [[servlet-filterchainproxy]] == FilterChainProxy @@ -107,6 +106,8 @@ Spring Security's Servlet support is contained within `FilterChainProxy`. `FilterChainProxy` is a special `Filter` provided by Spring Security that allows delegating to many `Filter` instances through <>. Since `FilterChainProxy` is a Bean, it is typically wrapped in a <>. +The following image shows the role of `FilterChainProxy`. + .FilterChainProxy [[servlet-filterchainproxy-figure]] image::{figures}/filterchainproxy.png[] @@ -114,7 +115,9 @@ image::{figures}/filterchainproxy.png[] [[servlet-securityfilterchain]] == SecurityFilterChain -{security-api-url}org/springframework/security/web/SecurityFilterChain.html[`SecurityFilterChain`] is used by <> to determine which Spring Security ``Filter``s should be invoked for this request. +{security-api-url}org/springframework/security/web/SecurityFilterChain.html[`SecurityFilterChain`] is used by <> to determine which Spring Security `Filter` instances should be invoked for the current request. + +The following image shows the role of `SecurityFilterChain`. .SecurityFilterChain [[servlet-securityfilterchain-figure]] @@ -123,80 +126,79 @@ image::{figures}/securityfilterchain.png[] The <> in `SecurityFilterChain` are typically Beans, but they are registered with `FilterChainProxy` instead of <>. `FilterChainProxy` provides a number of advantages to registering directly with the Servlet container or <>. First, it provides a starting point for all of Spring Security's Servlet support. -For that reason, if you are attempting to troubleshoot Spring Security's Servlet support, adding a debug point in `FilterChainProxy` is a great place to start. +For that reason, if you try to troubleshoot Spring Security's Servlet support, adding a debug point in `FilterChainProxy` is a great place to start. -Second, since `FilterChainProxy` is central to Spring Security usage it can perform tasks that are not viewed as optional. +Second, since `FilterChainProxy` is central to Spring Security usage, it can perform tasks that are not viewed as optional. // FIXME: Add a link to SecurityContext For example, it clears out the `SecurityContext` to avoid memory leaks. It also applies Spring Security's xref:servlet/exploits/firewall.adoc#servlet-httpfirewall[`HttpFirewall`] to protect applications against certain types of attacks. In addition, it provides more flexibility in determining when a `SecurityFilterChain` should be invoked. -In a Servlet container, ``Filter``s are invoked based upon the URL alone. +In a Servlet container, `Filter` instances are invoked based upon the URL alone. // FIXME: Link to RequestMatcher -However, `FilterChainProxy` can determine invocation based upon anything in the `HttpServletRequest` by leveraging the `RequestMatcher` interface. +However, `FilterChainProxy` can determine invocation based upon anything in the `HttpServletRequest` by using the `RequestMatcher` interface. -In fact, `FilterChainProxy` can be used to determine which `SecurityFilterChain` should be used. -This allows providing a totally separate configuration for different _slices_ of your application. +The following image shows multiple `SecurityFilterChain` instances: .Multiple SecurityFilterChain [[servlet-multi-securityfilterchain-figure]] image::{figures}/multi-securityfilterchain.png[] -In the <> Figure `FilterChainProxy` decides which `SecurityFilterChain` should be used. -Only the first `SecurityFilterChain` that matches will be invoked. -If a URL of `/api/messages/` is requested, it will first match on ``SecurityFilterChain~0~``'s pattern of `+/api/**+`, so only `SecurityFilterChain~0~` will be invoked even though it also matches on ``SecurityFilterChain~n~``. -If a URL of `/messages/` is requested, it will not match on ``SecurityFilterChain~0~``'s pattern of `+/api/**+`, so `FilterChainProxy` will continue trying each `SecurityFilterChain`. -Assuming that no other, `SecurityFilterChain` instances match `SecurityFilterChain~n~` will be invoked. -// FIXME add link to pattern matching - -Notice that `SecurityFilterChain~0~` has only three security ``Filter``s instances configured. -However, `SecurityFilterChain~n~` has four security ``Filter``s configured. -It is important to note that each `SecurityFilterChain` can be unique and configured in isolation. -In fact, a `SecurityFilterChain` might have zero security ``Filter``s if the application wants Spring Security to ignore certain requests. +In the <> figure, `FilterChainProxy` decides which `SecurityFilterChain` should be used. +Only the first `SecurityFilterChain` that matches is invoked. +If a URL of `/api/messages/` is requested, it first matches on the `SecurityFilterChain~0~` pattern of `+/api/**+`, so only `SecurityFilterChain~0~` is invoked, even though it also matches on ``SecurityFilterChain~n~``. +If a URL of `/messages/` is requested, it does not match on the `SecurityFilterChain~0~` pattern of `+/api/**+`, so `FilterChainProxy` continues trying each `SecurityFilterChain`. +Assuming that no other `SecurityFilterChain` instances match, `SecurityFilterChain~n~` is invoked. +// FIXME: add link to pattern matching + +Notice that `SecurityFilterChain~0~` has only three security `Filter` instances configured. +However, `SecurityFilterChain~n~` has four security `Filter` instanes configured. +It is important to note that each `SecurityFilterChain` can be unique and can be configured in isolation. +In fact, a `SecurityFilterChain` might have zero security `Filter` instances if the application wants Spring Security to ignore certain requests. // FIXME: add link to configuring multiple `SecurityFilterChain` instances [[servlet-security-filters]] == Security Filters The Security Filters are inserted into the <> with the <> API. -The <>s matters. -It is typically not necessary to know the ordering of Spring Security's ``Filter``s. -However, there are times that it is beneficial to know the ordering - -Below is a comprehensive list of Spring Security Filter ordering: - -* ChannelProcessingFilter -* WebAsyncManagerIntegrationFilter -* SecurityContextPersistenceFilter -* HeaderWriterFilter -* CorsFilter -* CsrfFilter -* LogoutFilter -* OAuth2AuthorizationRequestRedirectFilter -* Saml2WebSsoAuthenticationRequestFilter -* X509AuthenticationFilter -* AbstractPreAuthenticatedProcessingFilter -* CasAuthenticationFilter -* OAuth2LoginAuthenticationFilter -* Saml2WebSsoAuthenticationFilter +The <> instances matters. +It is typically not necessary to know the ordering of Spring Security's `Filter` instances. +However, there are times that it is beneficial to know the ordering. + +The following is a comprehensive list of Spring Security Filter ordering: + +* `ChannelProcessingFilter` +* `WebAsyncManagerIntegrationFilter` +* `SecurityContextPersistenceFilter` +* `HeaderWriterFilter` +* `CorsFilter` +* `CsrfFilter` +* `LogoutFilter` +* `OAuth2AuthorizationRequestRedirectFilter` +* `Saml2WebSsoAuthenticationRequestFilter` +* `X509AuthenticationFilter` +* `AbstractPreAuthenticatedProcessingFilter` +* `CasAuthenticationFilter` +* `OAuth2LoginAuthenticationFilter` +* `Saml2WebSsoAuthenticationFilter` * xref:servlet/authentication/passwords/form.adoc#servlet-authentication-usernamepasswordauthenticationfilter[`UsernamePasswordAuthenticationFilter`] -* OpenIDAuthenticationFilter -* DefaultLoginPageGeneratingFilter -* DefaultLogoutPageGeneratingFilter -* ConcurrentSessionFilter +* `OpenIDAuthenticationFilter` +* `DefaultLoginPageGeneratingFilter` +* `DefaultLogoutPageGeneratingFilter` +* `ConcurrentSessionFilter` * xref:servlet/authentication/passwords/digest.adoc#servlet-authentication-digest[`DigestAuthenticationFilter`] -* BearerTokenAuthenticationFilter +* `BearerTokenAuthenticationFilter` * xref:servlet/authentication/passwords/basic.adoc#servlet-authentication-basic[`BasicAuthenticationFilter`] -* RequestCacheAwareFilter -* SecurityContextHolderAwareRequestFilter -* JaasApiIntegrationFilter -* RememberMeAuthenticationFilter -* AnonymousAuthenticationFilter -* OAuth2AuthorizationCodeGrantFilter -* SessionManagementFilter +* `RequestCacheAwareFilter` +* `SecurityContextHolderAwareRequestFilter` +* `JaasApiIntegrationFilter` +* `RememberMeAuthenticationFilter` +* `AnonymousAuthenticationFilter` +* `OAuth2AuthorizationCodeGrantFilter` +* `SessionManagementFilter` * <> * xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] -* SwitchUserFilter +* `SwitchUserFilter` [[servlet-exceptiontranslationfilter]] == Handling Security Exceptions @@ -206,19 +208,21 @@ The {security-api-url}org/springframework/security/web/access/ExceptionTranslati `ExceptionTranslationFilter` is inserted into the <> as one of the <>. +The following image shows the relationship of `ExceptionTranslationFilter` to other components: + image::{figures}/exceptiontranslationfilter.png[] * image:{icondir}/number_1.png[] First, the `ExceptionTranslationFilter` invokes `FilterChain.doFilter(request, response)` to invoke the rest of the application. * image:{icondir}/number_2.png[] If the user is not authenticated or it is an `AuthenticationException`, then __Start Authentication__. -** The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder] is cleared out +** The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder] is cleared out. ** The `HttpServletRequest` is saved in the {security-api-url}org/springframework/security/web/savedrequest/RequestCache.html[`RequestCache`]. When the user successfully authenticates, the `RequestCache` is used to replay the original request. // FIXME: add link to authentication success ** The `AuthenticationEntryPoint` is used to request credentials from the client. For example, it might redirect to a log in page or send a `WWW-Authenticate` header. // FIXME: link to AuthenticationEntryPoint -* image:{icondir}/number_3.png[] Otherwise if it is an `AccessDeniedException`, then __Access Denied__. +* image:{icondir}/number_3.png[] Otherwise, if it is an `AccessDeniedException`, then __Access Denied__. The `AccessDeniedHandler` is invoked to handle access denied. // FIXME: link to AccessDeniedHandler @@ -229,6 +233,7 @@ If the application does not throw an `AccessDeniedException` or an `Authenticati The pseudocode for `ExceptionTranslationFilter` looks something like this: +==== .ExceptionTranslationFilter pseudocode [source,java] ---- @@ -242,7 +247,8 @@ try { } } ---- -<1> You will recall from <> that invoking `FilterChain.doFilter(request, response)` is the equivalent of invoking the rest of the application. -This means that if another part of the application, (i.e. xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] or method security) throws an `AuthenticationException` or `AccessDeniedException` it will be caught and handled here. -<2> If the user is not authenticated or it is an `AuthenticationException`, then __Start Authentication__. +<1> As described in <>, invoking `FilterChain.doFilter(request, response)` is the equivalent of invoking the rest of the application. +This means that if another part of the application, (<> or method security) throws an `AuthenticationException` or `AccessDeniedException` it is caught and handled here. +<2> If the user is not authenticated or it is an `AuthenticationException`, __Start Authentication__. <3> Otherwise, __Access Denied__ +==== diff --git a/docs/modules/ROOT/pages/servlet/authentication/anonymous.adoc b/docs/modules/ROOT/pages/servlet/authentication/anonymous.adoc index d30fd584bf2..f30e304b24a 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/anonymous.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/anonymous.adoc @@ -4,38 +4,37 @@ [[anonymous-overview]] == Overview -It's generally considered good security practice to adopt a "deny-by-default" where you explicitly specify what is allowed and disallow everything else. +It is generally considered good security practice to adopt a "`deny-by-default`" stance, where you explicitly specify what is allowed and disallow everything else. Defining what is accessible to unauthenticated users is a similar situation, particularly for web applications. Many sites require that users must be authenticated for anything other than a few URLs (for example the home and login pages). -In this case it is easiest to define access configuration attributes for these specific URLs rather than have for every secured resource. -Put differently, sometimes it is nice to say `ROLE_SOMETHING` is required by default and only allow certain exceptions to this rule, such as for login, logout and home pages of an application. +In that case, it is easiest to define access configuration attributes for these specific URLs rather than for every secured resource. +Put differently, sometimes it is nice to say `ROLE_SOMETHING` is required by default and allow only certain exceptions to this rule, such as for login, logout, and home pages of an application. You could also omit these pages from the filter chain entirely, thus bypassing the access control checks, but this may be undesirable for other reasons, particularly if the pages behave differently for authenticated users. This is what we mean by anonymous authentication. -Note that there is no real conceptual difference between a user who is "anonymously authenticated" and an unauthenticated user. +Note that there is no real conceptual difference between a user who is "`anonymously authenticated`" and an unauthenticated user. Spring Security's anonymous authentication just gives you a more convenient way to configure your access-control attributes. -Calls to servlet API such as `getCallerPrincipal`, for example, will still return null even though there is actually an anonymous authentication object in the `SecurityContextHolder`. +Calls to servlet API calls, such as `getCallerPrincipal`, still return null, even though there is actually an anonymous authentication object in the `SecurityContextHolder`. There are other situations where anonymous authentication is useful, such as when an auditing interceptor queries the `SecurityContextHolder` to identify which principal was responsible for a given operation. -Classes can be authored more robustly if they know the `SecurityContextHolder` always contains an `Authentication` object, and never `null`. +Classes can be authored more robustly if they know the `SecurityContextHolder` always contains an `Authentication` object and never contains `null`. [[anonymous-config]] == Configuration -Anonymous authentication support is provided automatically when using the HTTP configuration Spring Security 3.0 and can be customized (or disabled) using the `` element. -You don't need to configure the beans described here unless you are using traditional bean configuration. - -Three classes that together provide the anonymous authentication feature. -`AnonymousAuthenticationToken` is an implementation of `Authentication`, and stores the ``GrantedAuthority``s which apply to the anonymous principal. -There is a corresponding `AnonymousAuthenticationProvider`, which is chained into the `ProviderManager` so that ``AnonymousAuthenticationToken``s are accepted. -Finally, there is an `AnonymousAuthenticationFilter`, which is chained after the normal authentication mechanisms and automatically adds an `AnonymousAuthenticationToken` to the `SecurityContextHolder` if there is no existing `Authentication` held there. -The definition of the filter and authentication provider appears as follows: - +Anonymous authentication support is provided automatically when you use the HTTP configuration (introduced inSpring Security 3.0). +You can customize (or disable) it by using the `` element. +You need not configure the beans described here unless you are using traditional bean configuration. +Three classes work together to provide the anonymous authentication feature. +`AnonymousAuthenticationToken` is an implementation of `Authentication` and stores the `GrantedAuthority` instancesthat apply to the anonymous principal. +There is a corresponding `AnonymousAuthenticationProvider`, which is chained into the `ProviderManager` so that `AnonymousAuthenticationToken` instances are accepted. +Finally, an `AnonymousAuthenticationFilter` is chained after the normal authentication mechanisms and automatically adds an `AnonymousAuthenticationToken` to the `SecurityContextHolder` if there is no existing `Authentication` held there. +The filter and authentication provider is defined as follows: +==== [source,xml] ---- - @@ -47,27 +46,29 @@ The definition of the filter and authentication provider appears as follows: ---- +==== -The `key` is shared between the filter and authentication provider, so that tokens created by the former are accepted by the latter footnote:[ +The `key` is shared between the filter and authentication provider, so that tokens created by the former are accepted by the latter + +[NOTE] +==== The use of the `key` property should not be regarded as providing any real security here. It is merely a book-keeping exercise. -If you are sharing a `ProviderManager` which contains an `AnonymousAuthenticationProvider` in a scenario where it is possible for an authenticating client to construct the `Authentication` object (such as with RMI invocations), then a malicious client could submit an `AnonymousAuthenticationToken` which it had created itself (with chosen username and authority list). -If the `key` is guessable or can be found out, then the token would be accepted by the anonymous provider. -This isn't a problem with normal usage but if you are using RMI you would be best to use a customized `ProviderManager` which omits the anonymous provider rather than sharing the one you use for your HTTP authentication mechanisms. -]. -The `userAttribute` is expressed in the form of `usernameInTheAuthenticationToken,grantedAuthority[,grantedAuthority]`. -This is the same syntax as used after the equals sign for the `userMap` property of `InMemoryDaoImpl`. - -As explained earlier, the benefit of anonymous authentication is that all URI patterns can have security applied to them. -For example: +If you share a `ProviderManager` that contains an `AnonymousAuthenticationProvider` in a scenario where it is possible for an authenticating client to construct the `Authentication` object (such as with RMI invocations), then a malicious client could submit an `AnonymousAuthenticationToken` that it had created itself (with the chosen username and authority list). +If the `key` is guessable or can be found out, the token would be accepted by the anonymous provider. +This is not a problem with normal usage. However, if you use RMI, you should use a customized `ProviderManager` that omits the anonymous provider rather than sharing the one you use for your HTTP authentication mechanisms. +==== +The `userAttribute` is expressed in the form of `usernameInTheAuthenticationToken,grantedAuthority[,grantedAuthority]`. +The same syntax is used after the equals sign for the `userMap` property of `InMemoryDaoImpl`. +As explained earlier, the benefit of anonymous authentication is that all URI patterns can have security applied to them, as the following example shows: +==== [source,xml] ---- - @@ -83,23 +84,21 @@ For example: ---- - - - +==== [[anonymous-auth-trust-resolver]] == AuthenticationTrustResolver Rounding out the anonymous authentication discussion is the `AuthenticationTrustResolver` interface, with its corresponding `AuthenticationTrustResolverImpl` implementation. This interface provides an `isAnonymous(Authentication)` method, which allows interested classes to take into account this special type of authentication status. -The `ExceptionTranslationFilter` uses this interface in processing ``AccessDeniedException``s. -If an `AccessDeniedException` is thrown, and the authentication is of an anonymous type, instead of throwing a 403 (forbidden) response, the filter will instead commence the `AuthenticationEntryPoint` so the principal can authenticate properly. -This is a necessary distinction, otherwise principals would always be deemed "authenticated" and never be given an opportunity to login via form, basic, digest or some other normal authentication mechanism. +The `ExceptionTranslationFilter` uses this interface in processing `AccessDeniedException` instances. +If an `AccessDeniedException` is thrown and the authentication is of an anonymous type, instead of throwing a 403 (forbidden) response, the filter, instead, commences the `AuthenticationEntryPoint` so that the principal can authenticate properly. +This is a necessary distinction. Otherwise, principals would always be deemed "`authenticated`" and never be given an opportunity to login through form, basic, digest, or some other normal authentication mechanism. -You will often see the `ROLE_ANONYMOUS` attribute in the above interceptor configuration replaced with `IS_AUTHENTICATED_ANONYMOUSLY`, which is effectively the same thing when defining access controls. -This is an example of the use of the `AuthenticatedVoter` which we will see in the xref:servlet/authorization/architecture.adoc#authz-authenticated-voter[authorization chapter]. +We often see the `ROLE_ANONYMOUS` attribute in the earlier interceptor configuration replaced with `IS_AUTHENTICATED_ANONYMOUSLY`, which is effectively the same thing when defining access controls. +This is an example of the use of the `AuthenticatedVoter`, which we cover in the xref:servlet/authorization/architecture.adoc#authz-authenticated-voter[authorization chapter]. It uses an `AuthenticationTrustResolver` to process this particular configuration attribute and grant access to anonymous users. -The `AuthenticatedVoter` approach is more powerful, since it allows you to differentiate between anonymous, remember-me and fully-authenticated users. -If you don't need this functionality though, then you can stick with `ROLE_ANONYMOUS`, which will be processed by Spring Security's standard `RoleVoter`. +The `AuthenticatedVoter` approach is more powerful, since it lets you differentiate between anonymous, remember-me, and fully authenticated users. +If you do not need this functionality, though, you can stick with `ROLE_ANONYMOUS`, which is processed by Spring Security's standard `RoleVoter`. [[anonymous-auth-mvc-controller]] == Getting Anonymous Authentications with Spring MVC diff --git a/docs/modules/ROOT/pages/servlet/authentication/architecture.adoc b/docs/modules/ROOT/pages/servlet/authentication/architecture.adoc index ea61488c575..a4aa61e4c60 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/architecture.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/architecture.adoc @@ -19,8 +19,6 @@ This also gives a good idea of the high level flow of authentication and how pie [[servlet-authentication-securitycontextholder]] == SecurityContextHolder -Hi {figures} there - At the heart of Spring Security's authentication model is the `SecurityContextHolder`. It contains the <>. @@ -28,9 +26,9 @@ image::{figures}/securitycontextholder.png[] The `SecurityContextHolder` is where Spring Security stores the details of who is xref:features/authentication/index.adoc#authentication[authenticated]. Spring Security does not care how the `SecurityContextHolder` is populated. -If it contains a value, then it is used as the currently authenticated user. +If it contains a value, it is used as the currently authenticated user. -The simplest way to indicate a user is authenticated is to set the `SecurityContextHolder` directly. +The simplest way to indicate a user is authenticated is to set the `SecurityContextHolder` directly: .Setting `SecurityContextHolder` ==== @@ -54,18 +52,18 @@ context.authentication = authentication SecurityContextHolder.setContext(context) // <3> ---- -==== <1> We start by creating an empty `SecurityContext`. -It is important to create a new `SecurityContext` instance instead of using `SecurityContextHolder.getContext().setAuthentication(authentication)` to avoid race conditions across multiple threads. -<2> Next we create a new <> object. +You should create a new `SecurityContext` instance instead of using `SecurityContextHolder.getContext().setAuthentication(authentication)` to avoid race conditions across multiple threads. +<2> Next, we create a new <> object. Spring Security does not care what type of `Authentication` implementation is set on the `SecurityContext`. -Here we use `TestingAuthenticationToken` because it is very simple. +Here, we use `TestingAuthenticationToken`, because it is very simple. A more common production scenario is `UsernamePasswordAuthenticationToken(userDetails, password, authorities)`. <3> Finally, we set the `SecurityContext` on the `SecurityContextHolder`. -Spring Security will use this information for xref:servlet/authorization/index.adoc#servlet-authorization[authorization]. +Spring Security uses this information for xref:servlet/authorization/index.adoc#servlet-authorization[authorization]. +==== -If you wish to obtain information about the authenticated principal, you can do so by accessing the `SecurityContextHolder`. +To obtain information about the authenticated principal, access the `SecurityContextHolder`. .Access Currently Authenticated User ==== @@ -90,21 +88,23 @@ val authorities = authentication.authorities ---- ==== -// FIXME: add links to HttpServletRequest.getRemoteUser() and @CurrentSecurityContext @AuthenticationPrincipal +// FIXME: Add links to and relevant description of HttpServletRequest.getRemoteUser() and @CurrentSecurityContext @AuthenticationPrincipal -By default the `SecurityContextHolder` uses a `ThreadLocal` to store these details, which means that the `SecurityContext` is always available to methods in the same thread, even if the `SecurityContext` is not explicitly passed around as an argument to those methods. -Using a `ThreadLocal` in this way is quite safe if care is taken to clear the thread after the present principal's request is processed. +By default, `SecurityContextHolder` uses a `ThreadLocal` to store these details, which means that the `SecurityContext` is always available to methods in the same thread, even if the `SecurityContext` is not explicitly passed around as an argument to those methods. +Using a `ThreadLocal` in this way is quite safe if you take care to clear the thread after the present principal's request is processed. Spring Security's xref:servlet/architecture.adoc#servlet-filterchainproxy[FilterChainProxy] ensures that the `SecurityContext` is always cleared. -Some applications aren't entirely suitable for using a `ThreadLocal`, because of the specific way they work with threads. +Some applications are not entirely suitable for using a `ThreadLocal`, because of the specific way they work with threads. For example, a Swing client might want all threads in a Java Virtual Machine to use the same security context. -`SecurityContextHolder` can be configured with a strategy on startup to specify how you would like the context to be stored. -For a standalone application you would use the `SecurityContextHolder.MODE_GLOBAL` strategy. +You can configure `SecurityContextHolder` with a strategy on startup to specify how you would like the context to be stored. +For a standalone application, you would use the `SecurityContextHolder.MODE_GLOBAL` strategy. Other applications might want to have threads spawned by the secure thread also assume the same security identity. -This is achieved by using `SecurityContextHolder.MODE_INHERITABLETHREADLOCAL`. +You can achieve this by using `SecurityContextHolder.MODE_INHERITABLETHREADLOCAL`. You can change the mode from the default `SecurityContextHolder.MODE_THREADLOCAL` in two ways. -The first is to set a system property, the second is to call a static method on `SecurityContextHolder`. -Most applications won't need to change from the default, but if you do, take a look at the Javadoc for `SecurityContextHolder` to learn more. +The first is to set a system property. +The second is to call a static method on `SecurityContextHolder`. +Most applications need not change from the default. +However, if you do, take a look at the JavaDoc for `SecurityContextHolder` to learn more. [[servlet-authentication-securitycontext]] == SecurityContext @@ -115,45 +115,46 @@ The `SecurityContext` contains an <> obje [[servlet-authentication-authentication]] == Authentication -The {security-api-url}org/springframework/security/core/Authentication.html[`Authentication`] serves two main purposes within Spring Security: +The {security-api-url}org/springframework/security/core/Authentication.html[`Authentication`] interface serves two main purposes within Spring Security: * An input to <> to provide the credentials a user has provided to authenticate. When used in this scenario, `isAuthenticated()` returns `false`. -* Represents the currently authenticated user. -The current `Authentication` can be obtained from the <>. +* Represent the currently authenticated user. +You can obtain the current `Authentication` from the <>. The `Authentication` contains: -* `principal` - identifies the user. +* `principal`: Identifies the user. When authenticating with a username/password this is often an instance of xref:servlet/authentication/passwords/user-details.adoc#servlet-authentication-userdetails[`UserDetails`]. -* `credentials` - often a password. -In many cases this will be cleared after the user is authenticated to ensure it is not leaked. -* `authorities` - the <> are high level permissions the user is granted. -A few examples are roles or scopes. +* `credentials`: Often a password. +In many cases, this is cleared after the user is authenticated, to ensure that it is not leaked. +* `authorities`: The <> instances are high-level permissions the user is granted. +Two examples are roles and scopes. [[servlet-authentication-granted-authority]] == GrantedAuthority -{security-api-url}org/springframework/security/core/GrantedAuthority.html[``GrantedAuthority``s] are high level permissions the user is granted. A few examples are roles or scopes. +{security-api-url}org/springframework/security/core/GrantedAuthority.html[`GrantedAuthority`] instances are high-level permissions that the user is granted. +Two examples are roles and scopes. -``GrantedAuthority``s can be obtained from the <> method. +You can obtain `GrantedAuthority` instances from the <> method. This method provides a `Collection` of `GrantedAuthority` objects. A `GrantedAuthority` is, not surprisingly, an authority that is granted to the principal. -Such authorities are usually "roles", such as `ROLE_ADMINISTRATOR` or `ROLE_HR_SUPERVISOR`. -These roles are later on configured for web authorization, method authorization and domain object authorization. -Other parts of Spring Security are capable of interpreting these authorities, and expect them to be present. -When using username/password based authentication ``GrantedAuthority``s are usually loaded by the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`]. +Such authorities are usually "`roles`", such as `ROLE_ADMINISTRATOR` or `ROLE_HR_SUPERVISOR`. +These roles are later configured for web authorization, method authorization, and domain object authorization. +Other parts of Spring Security interpret these authorities and expect them to be present. +When using username/password based authentication `GrantedAuthority` instances are usually loaded by the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`]. -Usually the `GrantedAuthority` objects are application-wide permissions. +Usually, the `GrantedAuthority` objects are application-wide permissions. They are not specific to a given domain object. -Thus, you wouldn't likely have a `GrantedAuthority` to represent a permission to `Employee` object number 54, because if there are thousands of such authorities you would quickly run out of memory (or, at the very least, cause the application to take a long time to authenticate a user). -Of course, Spring Security is expressly designed to handle this common requirement, but you'd instead use the project's domain object security capabilities for this purpose. +Thus, you would not likely have a `GrantedAuthority` to represent a permission to `Employee` object number 54, because if there are thousands of such authorities you would quickly run out of memory (or, at the very least, cause the application to take a long time to authenticate a user). +Of course, Spring Security is expressly designed to handle this common requirement, but you should instead use the project's domain object security capabilities for this purpose. [[servlet-authentication-authenticationmanager]] == AuthenticationManager {security-api-url}org/springframework/security/authentication/AuthenticationManager.html[`AuthenticationManager`] is the API that defines how Spring Security's Filters perform xref:features/authentication/index.adoc#authentication[authentication]. -The <> that is returned is then set on the <> by the controller (i.e. xref:servlet/architecture.adoc#servlet-security-filters[Spring Security's ``Filters``s]) that invoked the `AuthenticationManager`. -If you are not integrating with __Spring Security's ``Filters``s__ you can set the `SecurityContextHolder` directly and are not required to use an `AuthenticationManager`. +The <> that is returned is then set on the <> by the controller (that is, by <>) that invoked the `AuthenticationManager`. +If you are not integrating with Spring Security's `Filters` instances, you can set the `SecurityContextHolder` directly and are not required to use an `AuthenticationManager`. While the implementation of `AuthenticationManager` could be anything, the most common implementation is <>. // FIXME: add configuration @@ -162,18 +163,17 @@ While the implementation of `AuthenticationManager` could be anything, the most == ProviderManager {security-api-url}org/springframework/security/authentication/ProviderManager.html[`ProviderManager`] is the most commonly used implementation of <>. -`ProviderManager` delegates to a `List` of <>. -// FIXME: link to AuthenticationProvider +`ProviderManager` delegates to a `List` of <> instances. Each `AuthenticationProvider` has an opportunity to indicate that authentication should be successful, fail, or indicate it cannot make a decision and allow a downstream `AuthenticationProvider` to decide. -If none of the configured ``AuthenticationProvider``s can authenticate, then authentication will fail with a `ProviderNotFoundException` which is a special `AuthenticationException` that indicates the `ProviderManager` was not configured to support the type of `Authentication` that was passed into it. +If none of the configured `AuthenticationProvider` instances can authenticate, authentication fails with a `ProviderNotFoundException`, which is a special `AuthenticationException` that indicates that the `ProviderManager` was not configured to support the type of `Authentication` that was passed into it. image::{figures}/providermanager.png[] In practice each `AuthenticationProvider` knows how to perform a specific type of authentication. For example, one `AuthenticationProvider` might be able to validate a username/password, while another might be able to authenticate a SAML assertion. -This allows each `AuthenticationProvider` to do a very specific type of authentication, while supporting multiple types of authentication and only exposing a single `AuthenticationManager` bean. +This lets each `AuthenticationProvider` do a very specific type of authentication while supporting multiple types of authentication and expose only a single `AuthenticationManager` bean. -`ProviderManager` also allows configuring an optional parent `AuthenticationManager` which is consulted in the event that no `AuthenticationProvider` can perform authentication. +`ProviderManager` also allows configuring an optional parent `AuthenticationManager`, which is consulted in the event that no `AuthenticationProvider` can perform authentication. The parent can be any type of `AuthenticationManager`, but it is often an instance of `ProviderManager`. image::{figures}/providermanager-parent.png[] @@ -184,34 +184,34 @@ This is somewhat common in scenarios where there are multiple xref:servlet/archi image::{figures}/providermanagers-parent.png[] [[servlet-authentication-providermanager-erasing-credentials]] -By default `ProviderManager` will attempt to clear any sensitive credentials information from the `Authentication` object which is returned by a successful authentication request. -This prevents information like passwords being retained longer than necessary in the `HttpSession`. +By default, `ProviderManager` tries to clear any sensitive credentials information from the `Authentication` object that is returned by a successful authentication request. +This prevents information, such as passwords, being retained longer than necessary in the `HttpSession`. -This may cause issues when you are using a cache of user objects, for example, to improve performance in a stateless application. -If the `Authentication` contains a reference to an object in the cache (such as a `UserDetails` instance) and this has its credentials removed, then it will no longer be possible to authenticate against the cached value. -You need to take this into account if you are using a cache. -An obvious solution is to make a copy of the object first, either in the cache implementation or in the `AuthenticationProvider` which creates the returned `Authentication` object. +This may cause issues when you use a cache of user objects, for example, to improve performance in a stateless application. +If the `Authentication` contains a reference to an object in the cache (such as a `UserDetails` instance) and this has its credentials removed, it is no longer possible to authenticate against the cached value. +You need to take this into account if you use a cache. +An obvious solution is to first make a copy of the object, either in the cache implementation or in the `AuthenticationProvider` that creates the returned `Authentication` object. Alternatively, you can disable the `eraseCredentialsAfterAuthentication` property on `ProviderManager`. -See the {security-api-url}org/springframework/security/authentication/ProviderManager.html[Javadoc] for more information. +See the Javadoc for the {security-api-url}org/springframework/security/authentication/ProviderManager.html[Javadoc] class. [[servlet-authentication-authenticationprovider]] == AuthenticationProvider -Multiple {security-api-url}org/springframework/security/authentication/AuthenticationProvider.html[``AuthenticationProvider``s] can be injected into <>. +You can inject multiple {security-api-url}org/springframework/security/authentication/AuthenticationProvider.html[``AuthenticationProvider``s] instances into <>. Each `AuthenticationProvider` performs a specific type of authentication. -For example, xref:servlet/authentication/passwords/dao-authentication-provider.adoc#servlet-authentication-daoauthenticationprovider[`DaoAuthenticationProvider`] supports username/password based authentication while `JwtAuthenticationProvider` supports authenticating a JWT token. +For example, xref:servlet/authentication/passwords/dao-authentication-provider.adoc#servlet-authentication-daoauthenticationprovider[`DaoAuthenticationProvider`] supports username/password-based authentication, while `JwtAuthenticationProvider` supports authenticating a JWT token. [[servlet-authentication-authenticationentrypoint]] == Request Credentials with `AuthenticationEntryPoint` {security-api-url}org/springframework/security/web/AuthenticationEntryPoint.html[`AuthenticationEntryPoint`] is used to send an HTTP response that requests credentials from a client. -Sometimes a client will proactively include credentials such as a username/password to request a resource. -In these cases, Spring Security does not need to provide an HTTP response that requests credentials from the client since they are already included. +Sometimes, a client proactively includes credentials (such as a username and password) to request a resource. +In these cases, Spring Security does not need to provide an HTTP response that requests credentials from the client, since they are already included. -In other cases, a client will make an unauthenticated request to a resource that they are not authorized to access. +In other cases, a client makes an unauthenticated request to a resource that they are not authorized to access. In this case, an implementation of `AuthenticationEntryPoint` is used to request credentials from the client. -The `AuthenticationEntryPoint` implementation might perform a xref:servlet/authentication/passwords/form.adoc#servlet-authentication-form[redirect to a log in page], respond with an xref:servlet/authentication/passwords/basic.adoc#servlet-authentication-basic[WWW-Authenticate] header, etc. +The `AuthenticationEntryPoint` implementation might perform a xref:servlet/authentication/passwords/form.adoc#servlet-authentication-form[redirect to a log in page], respond with an xref:servlet/authentication/passwords/basic.adoc#servlet-authentication-basic[WWW-Authenticate] header, or take other action. @@ -222,7 +222,7 @@ The `AuthenticationEntryPoint` implementation might perform a xref:servlet/authe == AbstractAuthenticationProcessingFilter {security-api-url}org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.html[`AbstractAuthenticationProcessingFilter`] is used as a base `Filter` for authenticating a user's credentials. -Before the credentials can be authenticated, Spring Security typically requests the credentials using <>. +Before the credentials can be authenticated, Spring Security typically requests the credentials by using <>. Next, the `AbstractAuthenticationProcessingFilter` can authenticate any authentication requests that are submitted to it. @@ -234,28 +234,28 @@ For example, xref:servlet/authentication/passwords/form.adoc#servlet-authenticat image:{icondir}/number_2.png[] Next, the <> is passed into the <> to be authenticated. -image:{icondir}/number_3.png[] If authentication fails, then __Failure__ +image:{icondir}/number_3.png[] If authentication fails, then __Failure__. * The <> is cleared out. * `RememberMeServices.loginFail` is invoked. If remember me is not configured, this is a no-op. -// FIXME: link to rememberme +See the {security-api-url}org/springframework/security/web/authentication/rememberme/package-frame.html[`rememberme`] package. * `AuthenticationFailureHandler` is invoked. -// FIXME: link to AuthenticationFailureHandler +See the {security-api-url}org/springframework/security/web/authentication/AuthenticationFailureHandler.html[`AuthenticationFailureHandler`] interface. image:{icondir}/number_4.png[] If authentication is successful, then __Success__. -* `SessionAuthenticationStrategy` is notified of a new log in. -// FIXME: Add link to SessionAuthenticationStrategy +* `SessionAuthenticationStrategy` is notified of a new login. +See the {security-api-url}org/springframework/security/web/authentication/session/SessionAuthenticationStrategy.html[`SessionAuthenticationStrategy`] interface. * The <> is set on the <>. -Later the `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession`. -// FIXME: link securitycontextpersistencefilter +Later, the `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession`. +See the {security-api-url}org/springframework/security/web/context/SecurityContextPersistenceFilter.html[`SecurityContextPersistenceFilter`] class. * `RememberMeServices.loginSuccess` is invoked. If remember me is not configured, this is a no-op. -// FIXME: link to rememberme +See the {security-api-url}org/springframework/security/web/authentication/rememberme/package-frame.html[`rememberme`] package. * `ApplicationEventPublisher` publishes an `InteractiveAuthenticationSuccessEvent`. * `AuthenticationSuccessHandler` is invoked. -// FIXME: link to AuthenticationSuccessHandler +See the {security-api-url}org/springframework/security/web/authentication/AuthenticationSuccessHandler.html[`AuthenticationSuccessHandler`] interface. // daoauthenticationprovider (goes in username/password) diff --git a/docs/modules/ROOT/pages/servlet/authentication/cas.adoc b/docs/modules/ROOT/pages/servlet/authentication/cas.adoc deleted file mode 100644 index 5b6dd7617ed..00000000000 --- a/docs/modules/ROOT/pages/servlet/authentication/cas.adoc +++ /dev/null @@ -1,463 +0,0 @@ -[[servlet-cas]] -= CAS Authentication - -[[cas-overview]] -== Overview -JA-SIG produces an enterprise-wide single sign on system known as CAS. -Unlike other initiatives, JA-SIG's Central Authentication Service is open source, widely used, simple to understand, platform independent, and supports proxy capabilities. -Spring Security fully supports CAS, and provides an easy migration path from single-application deployments of Spring Security through to multiple-application deployments secured by an enterprise-wide CAS server. - -You can learn more about CAS at https://www.apereo.org. -You will also need to visit this site to download the CAS Server files. - -[[cas-how-it-works]] -== How CAS Works -Whilst the CAS web site contains documents that detail the architecture of CAS, we present the general overview again here within the context of Spring Security. -Spring Security 3.x supports CAS 3. -At the time of writing, the CAS server was at version 3.4. - -Somewhere in your enterprise you will need to setup a CAS server. -The CAS server is simply a standard WAR file, so there isn't anything difficult about setting up your server. -Inside the WAR file you will customise the login and other single sign on pages displayed to users. - -When deploying a CAS 3.4 server, you will also need to specify an `AuthenticationHandler` in the `deployerConfigContext.xml` included with CAS. -The `AuthenticationHandler` has a simple method that returns a boolean as to whether a given set of Credentials is valid. -Your `AuthenticationHandler` implementation will need to link into some type of backend authentication repository, such as an LDAP server or database. -CAS itself includes numerous ``AuthenticationHandler``s out of the box to assist with this. -When you download and deploy the server war file, it is set up to successfully authenticate users who enter a password matching their username, which is useful for testing. - -Apart from the CAS server itself, the other key players are of course the secure web applications deployed throughout your enterprise. -These web applications are known as "services". -There are three types of services. -Those that authenticate service tickets, those that can obtain proxy tickets, and those that authenticate proxy tickets. -Authenticating a proxy ticket differs because the list of proxies must be validated and often times a proxy ticket can be reused. - - -[[cas-sequence]] -=== Spring Security and CAS Interaction Sequence -The basic interaction between a web browser, CAS server and a Spring Security-secured service is as follows: - -* The web user is browsing the service's public pages. -CAS or Spring Security is not involved. -* The user eventually requests a page that is either secure or one of the beans it uses is secure. -Spring Security's `ExceptionTranslationFilter` will detect the `AccessDeniedException` or `AuthenticationException`. -* Because the user's `Authentication` object (or lack thereof) caused an `AuthenticationException`, the `ExceptionTranslationFilter` will call the configured `AuthenticationEntryPoint`. -If using CAS, this will be the `CasAuthenticationEntryPoint` class. -* The `CasAuthenticationEntryPoint` will redirect the user's browser to the CAS server. -It will also indicate a `service` parameter, which is the callback URL for the Spring Security service (your application). -For example, the URL to which the browser is redirected might be https://my.company.com/cas/login?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Flogin/cas. -* After the user's browser redirects to CAS, they will be prompted for their username and password. -If the user presents a session cookie which indicates they've previously logged on, they will not be prompted to login again (there is an exception to this procedure, which we'll cover later). -CAS will use the `PasswordHandler` (or `AuthenticationHandler` if using CAS 3.0) discussed above to decide whether the username and password is valid. -* Upon successful login, CAS will redirect the user's browser back to the original service. -It will also include a `ticket` parameter, which is an opaque string representing the "service ticket". -Continuing our earlier example, the URL the browser is redirected to might be https://server3.company.com/webapp/login/cas?ticket=ST-0-ER94xMJmn6pha35CQRoZ. -* Back in the service web application, the `CasAuthenticationFilter` is always listening for requests to `/login/cas` (this is configurable, but we'll use the defaults in this introduction). -The processing filter will construct a `UsernamePasswordAuthenticationToken` representing the service ticket. -The principal will be equal to `CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER`, whilst the credentials will be the service ticket opaque value. -This authentication request will then be handed to the configured `AuthenticationManager`. -* The `AuthenticationManager` implementation will be the `ProviderManager`, which is in turn configured with the `CasAuthenticationProvider`. -The `CasAuthenticationProvider` only responds to ``UsernamePasswordAuthenticationToken``s containing the CAS-specific principal (such as `CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER`) and ``CasAuthenticationToken``s (discussed later). -* `CasAuthenticationProvider` will validate the service ticket using a `TicketValidator` implementation. -This will typically be a `Cas20ServiceTicketValidator` which is one of the classes included in the CAS client library. -In the event the application needs to validate proxy tickets, the `Cas20ProxyTicketValidator` is used. -The `TicketValidator` makes an HTTPS request to the CAS server in order to validate the service ticket. -It may also include a proxy callback URL, which is included in this example: https://my.company.com/cas/proxyValidate?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Flogin/cas&ticket=ST-0-ER94xMJmn6pha35CQRoZ&pgtUrl=https://server3.company.com/webapp/login/cas/proxyreceptor. -* Back on the CAS server, the validation request will be received. -If the presented service ticket matches the service URL the ticket was issued to, CAS will provide an affirmative response in XML indicating the username. -If any proxy was involved in the authentication (discussed below), the list of proxies is also included in the XML response. -* [OPTIONAL] If the request to the CAS validation service included the proxy callback URL (in the `pgtUrl` parameter), CAS will include a `pgtIou` string in the XML response. -This `pgtIou` represents a proxy-granting ticket IOU. -The CAS server will then create its own HTTPS connection back to the `pgtUrl`. -This is to mutually authenticate the CAS server and the claimed service URL. -The HTTPS connection will be used to send a proxy granting ticket to the original web application. -For example, https://server3.company.com/webapp/login/cas/proxyreceptor?pgtIou=PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt&pgtId=PGT-1-si9YkkHLrtACBo64rmsi3v2nf7cpCResXg5MpESZFArbaZiOKH. -* The `Cas20TicketValidator` will parse the XML received from the CAS server. -It will return to the `CasAuthenticationProvider` a `TicketResponse`, which includes the username (mandatory), proxy list (if any were involved), and proxy-granting ticket IOU (if the proxy callback was requested). -* Next `CasAuthenticationProvider` will call a configured `CasProxyDecider`. -The `CasProxyDecider` indicates whether the proxy list in the `TicketResponse` is acceptable to the service. -Several implementations are provided with Spring Security: `RejectProxyTickets`, `AcceptAnyCasProxy` and `NamedCasProxyDecider`. -These names are largely self-explanatory, except `NamedCasProxyDecider` which allows a `List` of trusted proxies to be provided. -* `CasAuthenticationProvider` will next request a `AuthenticationUserDetailsService` to load the `GrantedAuthority` objects that apply to the user contained in the `Assertion`. -* If there were no problems, `CasAuthenticationProvider` constructs a `CasAuthenticationToken` including the details contained in the `TicketResponse` and the ``GrantedAuthority``s. -* Control then returns to `CasAuthenticationFilter`, which places the created `CasAuthenticationToken` in the security context. -* The user's browser is redirected to the original page that caused the `AuthenticationException` (or a custom destination depending on the configuration). - -It's good that you're still here! -Let's now look at how this is configured - -[[cas-client]] -== Configuration of CAS Client -The web application side of CAS is made easy due to Spring Security. -It is assumed you already know the basics of using Spring Security, so these are not covered again below. -We'll assume a namespace based configuration is being used and add in the CAS beans as required. -Each section builds upon the previous section. -A full CAS sample application can be found in the Spring Security xref:samples.adoc#samples[Samples]. - - -[[cas-st]] -=== Service Ticket Authentication -This section describes how to setup Spring Security to authenticate Service Tickets. -Often times this is all a web application requires. -You will need to add a `ServiceProperties` bean to your application context. -This represents your CAS service: - -[source,xml] ----- - - - - ----- - -The `service` must equal a URL that will be monitored by the `CasAuthenticationFilter`. -The `sendRenew` defaults to false, but should be set to true if your application is particularly sensitive. -What this parameter does is tell the CAS login service that a single sign on login is unacceptable. -Instead, the user will need to re-enter their username and password in order to gain access to the service. - -The following beans should be configured to commence the CAS authentication process (assuming you're using a namespace configuration): - -[source,xml] ----- - -... - - - - - - - - - - - ----- - -For CAS to operate, the `ExceptionTranslationFilter` must have its `authenticationEntryPoint` property set to the `CasAuthenticationEntryPoint` bean. -This can easily be done using xref:servlet/appendix/namespace.adoc#nsa-http-entry-point-ref[entry-point-ref] as is done in the example above. -The `CasAuthenticationEntryPoint` must refer to the `ServiceProperties` bean (discussed above), which provides the URL to the enterprise's CAS login server. -This is where the user's browser will be redirected. - -The `CasAuthenticationFilter` has very similar properties to the `UsernamePasswordAuthenticationFilter` (used for form-based logins). -You can use these properties to customize things like behavior for authentication success and failure. - -Next you need to add a `CasAuthenticationProvider` and its collaborators: - -[source,xml,attrs="-attributes"] ----- - - - - - - - - - - - - - - - - - - - - - - -... - ----- - -The `CasAuthenticationProvider` uses a `UserDetailsService` instance to load the authorities for a user, once they have been authenticated by CAS. -We've shown a simple in-memory setup here. -Note that the `CasAuthenticationProvider` does not actually use the password for authentication, but it does use the authorities. - -The beans are all reasonably self-explanatory if you refer back to the <> section. - -This completes the most basic configuration for CAS. -If you haven't made any mistakes, your web application should happily work within the framework of CAS single sign on. -No other parts of Spring Security need to be concerned about the fact CAS handled authentication. -In the following sections we will discuss some (optional) more advanced configurations. - - -[[cas-singlelogout]] -=== Single Logout -The CAS protocol supports Single Logout and can be easily added to your Spring Security configuration. -Below are updates to the Spring Security configuration that handle Single Logout - -[source,xml] ----- - -... - - - - - - - - - - - - - - - - ----- - -The `logout` element logs the user out of the local application, but does not end the session with the CAS server or any other applications that have been logged into. -The `requestSingleLogoutFilter` filter will allow the URL of `/spring_security_cas_logout` to be requested to redirect the application to the configured CAS Server logout URL. -Then the CAS Server will send a Single Logout request to all the services that were signed into. -The `singleLogoutFilter` handles the Single Logout request by looking up the `HttpSession` in a static `Map` and then invalidating it. - -It might be confusing why both the `logout` element and the `singleLogoutFilter` are needed. -It is considered best practice to logout locally first since the `SingleSignOutFilter` just stores the `HttpSession` in a static `Map` in order to call invalidate on it. -With the configuration above, the flow of logout would be: - -* The user requests `/logout` which would log the user out of the local application and send the user to the logout success page. -* The logout success page, `/cas-logout.jsp`, should instruct the user to click a link pointing to `/logout/cas` in order to logout out of all applications. -* When the user clicks the link, the user is redirected to the CAS single logout URL (https://localhost:9443/cas/logout). -* On the CAS Server side, the CAS single logout URL then submits single logout requests to all the CAS Services. -On the CAS Service side, JASIG's `SingleSignOutFilter` processes the logout request by invalidating the original session. - - - -The next step is to add the following to your web.xml - -[source,xml] ----- - -characterEncodingFilter - - org.springframework.web.filter.CharacterEncodingFilter - - - encoding - UTF-8 - - - -characterEncodingFilter -/* - - - - org.jasig.cas.client.session.SingleSignOutHttpSessionListener - - ----- - -When using the SingleSignOutFilter you might encounter some encoding issues. -Therefore it is recommended to add the `CharacterEncodingFilter` to ensure that the character encoding is correct when using the `SingleSignOutFilter`. -Again, refer to JASIG's documentation for details. -The `SingleSignOutHttpSessionListener` ensures that when an `HttpSession` expires, the mapping used for single logout is removed. - - -[[cas-pt-client]] -=== Authenticating to a Stateless Service with CAS -This section describes how to authenticate to a service using CAS. -In other words, this section discusses how to setup a client that uses a service that authenticates with CAS. -The next section describes how to setup a stateless service to Authenticate using CAS. - - -[[cas-pt-client-config]] -==== Configuring CAS to Obtain Proxy Granting Tickets -In order to authenticate to a stateless service, the application needs to obtain a proxy granting ticket (PGT). -This section describes how to configure Spring Security to obtain a PGT building upon thencas-st[Service Ticket Authentication] configuration. - -The first step is to include a `ProxyGrantingTicketStorage` in your Spring Security configuration. -This is used to store PGT's that are obtained by the `CasAuthenticationFilter` so that they can be used to obtain proxy tickets. -An example configuration is shown below - -[source,xml] ----- - - ----- - -The next step is to update the `CasAuthenticationProvider` to be able to obtain proxy tickets. -To do this replace the `Cas20ServiceTicketValidator` with a `Cas20ProxyTicketValidator`. -The `proxyCallbackUrl` should be set to a URL that the application will receive PGT's at. -Last, the configuration should also reference the `ProxyGrantingTicketStorage` so it can use a PGT to obtain proxy tickets. -You can find an example of the configuration changes that should be made below. - -[source,xml] ----- - -... - - - - - - - - ----- - -The last step is to update the `CasAuthenticationFilter` to accept PGT and to store them in the `ProxyGrantingTicketStorage`. -It is important the `proxyReceptorUrl` matches the `proxyCallbackUrl` of the `Cas20ProxyTicketValidator`. -An example configuration is shown below. - -[source,xml] ----- - - - ... - - - - ----- - -[[cas-pt-client-sample]] -==== Calling a Stateless Service Using a Proxy Ticket -Now that Spring Security obtains PGTs, you can use them to create proxy tickets which can be used to authenticate to a stateless service. -The CAS xref:samples.adoc#samples[sample application] contains a working example in the `ProxyTicketSampleServlet`. -Example code can be found below: - -==== -.Java -[source,java,role="primary"] ----- -protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { -// NOTE: The CasAuthenticationToken can also be obtained using -// SecurityContextHolder.getContext().getAuthentication() -final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal(); -// proxyTicket could be reused to make calls to the CAS service even if the -// target url differs -final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl); - -// Make a remote call using the proxy ticket -final String serviceUrl = targetUrl+"?ticket="+URLEncoder.encode(proxyTicket, "UTF-8"); -String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8"); -... -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -protected fun doGet(request: HttpServletRequest, response: HttpServletResponse?) { - // NOTE: The CasAuthenticationToken can also be obtained using - // SecurityContextHolder.getContext().getAuthentication() - val token = request.userPrincipal as CasAuthenticationToken - // proxyTicket could be reused to make calls to the CAS service even if the - // target url differs - val proxyTicket = token.assertion.principal.getProxyTicketFor(targetUrl) - - // Make a remote call using the proxy ticket - val serviceUrl: String = targetUrl + "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8") - val proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8") -} ----- -==== - -[[cas-pt]] -=== Proxy Ticket Authentication -The `CasAuthenticationProvider` distinguishes between stateful and stateless clients. -A stateful client is considered any that submits to the `filterProcessUrl` of the `CasAuthenticationFilter`. -A stateless client is any that presents an authentication request to `CasAuthenticationFilter` on a URL other than the `filterProcessUrl`. - -Because remoting protocols have no way of presenting themselves within the context of an `HttpSession`, it isn't possible to rely on the default practice of storing the security context in the session between requests. -Furthermore, because the CAS server invalidates a ticket after it has been validated by the `TicketValidator`, presenting the same proxy ticket on subsequent requests will not work. - -One obvious option is to not use CAS at all for remoting protocol clients. -However, this would eliminate many of the desirable features of CAS. -As a middle-ground, the `CasAuthenticationProvider` uses a `StatelessTicketCache`. -This is used solely for stateless clients which use a principal equal to `CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER`. -What happens is the `CasAuthenticationProvider` will store the resulting `CasAuthenticationToken` in the `StatelessTicketCache`, keyed on the proxy ticket. -Accordingly, remoting protocol clients can present the same proxy ticket and the `CasAuthenticationProvider` will not need to contact the CAS server for validation (aside from the first request). -Once authenticated, the proxy ticket could be used for URLs other than the original target service. - -This section builds upon the previous sections to accommodate proxy ticket authentication. -The first step is to specify to authenticate all artifacts as shown below. - -[source,xml] ----- - -... - - ----- - -The next step is to specify `serviceProperties` and the `authenticationDetailsSource` for the `CasAuthenticationFilter`. -The `serviceProperties` property instructs the `CasAuthenticationFilter` to attempt to authenticate all artifacts instead of only ones present on the `filterProcessUrl`. -The `ServiceAuthenticationDetailsSource` creates a `ServiceAuthenticationDetails` that ensures the current URL, based upon the `HttpServletRequest`, is used as the service URL when validating the ticket. -The method for generating the service URL can be customized by injecting a custom `AuthenticationDetailsSource` that returns a custom `ServiceAuthenticationDetails`. - -[source,xml] ----- - -... - - - - - - - ----- - -You will also need to update the `CasAuthenticationProvider` to handle proxy tickets. -To do this replace the `Cas20ServiceTicketValidator` with a `Cas20ProxyTicketValidator`. -You will need to configure the `statelessTicketCache` and which proxies you want to accept. -You can find an example of the updates required to accept all proxies below. - -[source,xml] ----- - - -... - - - - - - - - - - - - - - - - - - - - - ----- diff --git a/docs/modules/ROOT/pages/servlet/authentication/events.adoc b/docs/modules/ROOT/pages/servlet/authentication/events.adoc index c016d375744..d31efff6e72 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/events.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/events.adoc @@ -1,10 +1,10 @@ [[servlet-events]] = Authentication Events -For each authentication that succeeds or fails, a `AuthenticationSuccessEvent` or `AbstractAuthenticationFailureEvent` is fired, respectively. +For each authentication that succeeds or fails, a `AuthenticationSuccessEvent` or `AuthenticationFailureEvent`, respectively, is fired. To listen for these events, you must first publish an `AuthenticationEventPublisher`. -Spring Security's `DefaultAuthenticationEventPublisher` will probably do fine: +Spring Security's `DefaultAuthenticationEventPublisher` works fine for this purpose: ==== .Java @@ -28,7 +28,7 @@ fun authenticationEventPublisher ---- ==== -Then, you can use Spring's `@EventListener` support: +Then you can use Spring's `@EventListener` support: ==== .Java @@ -70,7 +70,7 @@ While similar to `AuthenticationSuccessHandler` and `AuthenticationFailureHandle == Adding Exception Mappings -`DefaultAuthenticationEventPublisher` by default will publish an `AbstractAuthenticationFailureEvent` for the following events: +By default, `DefaultAuthenticationEventPublisher` publishes an `AuthenticationFailureEvent` for the following events: |============ | Exception | Event @@ -85,9 +85,9 @@ While similar to `AuthenticationSuccessHandler` and `AuthenticationFailureHandle | `InvalidBearerTokenException` | `AuthenticationFailureBadCredentialsEvent` |============ -The publisher does an exact `Exception` match, which means that sub-classes of these exceptions won't also produce events. +The publisher does an exact `Exception` match, which means that sub-classes of these exceptions do not also produce events. -To that end, you may want to supply additional mappings to the publisher via the `setAdditionalExceptionMappings` method: +To that end, you may want to supply additional mappings to the publisher through the `setAdditionalExceptionMappings` method: ==== .Java @@ -123,7 +123,7 @@ fun authenticationEventPublisher == Default Event -And, you can supply a catch-all event to fire in the case of any `AuthenticationException`: +You can also supply a catch-all event to fire in the case of any `AuthenticationException`: ==== .Java diff --git a/docs/modules/ROOT/pages/servlet/authentication/index.adoc b/docs/modules/ROOT/pages/servlet/authentication/index.adoc index ceb08df6cbc..83ed147bb98 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/index.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/index.adoc @@ -14,9 +14,8 @@ These sections focus on specific ways you may want to authenticate and point bac // FIXME: brief description * xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd[Username and Password] - how to authenticate with a username/password -* xref:servlet/oauth2/oauth2-login.adoc#oauth2login[OAuth 2.0 Login] - OAuth 2.0 Log In with OpenID Connect and non-standard OAuth 2.0 Login (i.e. GitHub) +* xref:servlet/oauth2/login/index.adoc#oauth2login[OAuth 2.0 Login] - OAuth 2.0 Log In with OpenID Connect and non-standard OAuth 2.0 Login (i.e. GitHub) * xref:servlet/saml2/index.adoc#servlet-saml2[SAML 2.0 Login] - SAML 2.0 Log In -* xref:servlet/authentication/cas.adoc#servlet-cas[Central Authentication Server (CAS)] - Central Authentication Server (CAS) Support * xref:servlet/authentication/rememberme.adoc#servlet-rememberme[Remember Me] - how to remember a user past session expiration * xref:servlet/authentication/jaas.adoc#servlet-jaas[JAAS Authentication] - authenticate with JAAS * xref:servlet/authentication/openid.adoc#servlet-openid[OpenID] - OpenID Authentication (not to be confused with OpenID Connect) diff --git a/docs/modules/ROOT/pages/servlet/authentication/jaas.adoc b/docs/modules/ROOT/pages/servlet/authentication/jaas.adoc index 9e241932be3..b38ca45aa44 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/jaas.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/jaas.adoc @@ -1,80 +1,76 @@ [[servlet-jaas]] = Java Authentication and Authorization Service (JAAS) Provider - -== Overview -Spring Security provides a package able to delegate authentication requests to the Java Authentication and Authorization Service (JAAS). -This package is discussed in detail below. +Spring Security provides a package to delegate authentication requests to the Java Authentication and Authorization Service (JAAS). +This section discusses that package. [[jaas-abstractjaasauthenticationprovider]] == AbstractJaasAuthenticationProvider -The `AbstractJaasAuthenticationProvider` is the basis for the provided JAAS `AuthenticationProvider` implementations. +The `AbstractJaasAuthenticationProvider` class is the basis for the provided JAAS `AuthenticationProvider` implementations. Subclasses must implement a method that creates the `LoginContext`. -The `AbstractJaasAuthenticationProvider` has a number of dependencies that can be injected into it that are discussed below. +The `AbstractJaasAuthenticationProvider` has a number of dependencies that can be injected into it, as discussed in the remainder of this section. [[jaas-callbackhandler]] === JAAS CallbackHandler -Most JAAS ``LoginModule``s require a callback of some sort. +Most JAAS `LoginModule` instances require a callback of some sort. These callbacks are usually used to obtain the username and password from the user. -In a Spring Security deployment, Spring Security is responsible for this user interaction (via the authentication mechanism). -Thus, by the time the authentication request is delegated through to JAAS, Spring Security's authentication mechanism will already have fully-populated an `Authentication` object containing all the information required by the JAAS `LoginModule`. - -Therefore, the JAAS package for Spring Security provides two default callback handlers, `JaasNameCallbackHandler` and `JaasPasswordCallbackHandler`. -Each of these callback handlers implement `JaasAuthenticationCallbackHandler`. -In most cases these callback handlers can simply be used without understanding the internal mechanics. +In a Spring Security deployment, Spring Security is responsible for this user interaction (through the authentication mechanism). +Thus, by the time the authentication request is delegated through to JAAS, Spring Security's authentication mechanism has already fully populated an `Authentication` object that contains all the information required by the JAAS `LoginModule`. -For those needing full control over the callback behavior, internally `AbstractJaasAuthenticationProvider` wraps these ``JaasAuthenticationCallbackHandler``s with an `InternalCallbackHandler`. -The `InternalCallbackHandler` is the class that actually implements JAAS normal `CallbackHandler` interface. -Any time that the JAAS `LoginModule` is used, it is passed a list of application context configured ``InternalCallbackHandler``s. -If the `LoginModule` requests a callback against the ``InternalCallbackHandler``s, the callback is in-turn passed to the ``JaasAuthenticationCallbackHandler``s being wrapped. +Therefore, the JAAS package for Spring Security provides two default callback handlers: `JaasNameCallbackHandler` and `JaasPasswordCallbackHandler`. +Each of these callback handlers implements `JaasAuthenticationCallbackHandler`. +In most cases, these callback handlers can be used without understanding the internal mechanics. +For those needing full control over the callback behavior, `AbstractJaasAuthenticationProvider` internally wraps these `JaasAuthenticationCallbackHandler` instances with an `InternalCallbackHandler`. +The `InternalCallbackHandler` is the class that actually implements the JAAS normal `CallbackHandler` interface. +Any time that the JAAS `LoginModule` is used, it is passed a list of application contexts configured `InternalCallbackHandler` instances. +If the `LoginModule` requests a callback against the `InternalCallbackHandler` instances, the callback is, in turn, passed to the `JaasAuthenticationCallbackHandler` instances being wrapped. [[jaas-authoritygranter]] === JAAS AuthorityGranter JAAS works with principals. -Even "roles" are represented as principals in JAAS. +Even "`roles`" are represented as principals in JAAS. Spring Security, on the other hand, works with `Authentication` objects. -Each `Authentication` object contains a single principal, and multiple ``GrantedAuthority``s. +Each `Authentication` object contains a single principal and multiple `GrantedAuthority` instances. To facilitate mapping between these different concepts, Spring Security's JAAS package includes an `AuthorityGranter` interface. -An `AuthorityGranter` is responsible for inspecting a JAAS principal and returning a set of ``String``s, representing the authorities assigned to the principal. -For each returned authority string, the `AbstractJaasAuthenticationProvider` creates a `JaasGrantedAuthority` (which implements Spring Security's `GrantedAuthority` interface) containing the authority string and the JAAS principal that the `AuthorityGranter` was passed. -The `AbstractJaasAuthenticationProvider` obtains the JAAS principals by firstly successfully authenticating the user's credentials using the JAAS `LoginModule`, and then accessing the `LoginContext` it returns. +An `AuthorityGranter` is responsible for inspecting a JAAS principal and returning a set of `String` objects that represent the authorities assigned to the principal. +For each returned authority string, the `AbstractJaasAuthenticationProvider` creates a `JaasGrantedAuthority` (which implements Spring Security's `GrantedAuthority` interface) that contains the authority string and the JAAS principal that the `AuthorityGranter` was passed. +The `AbstractJaasAuthenticationProvider` obtains the JAAS principals by first successfully authenticating the user's credentials by using the JAAS `LoginModule` and then accessing the `LoginContext` it returns. A call to `LoginContext.getSubject().getPrincipals()` is made, with each resulting principal passed to each `AuthorityGranter` defined against the `AbstractJaasAuthenticationProvider.setAuthorityGranters(List)` property. -Spring Security does not include any production ``AuthorityGranter``s given that every JAAS principal has an implementation-specific meaning. +Spring Security does not include any production `AuthorityGranter` instances, given that every JAAS principal has an implementation-specific meaning. However, there is a `TestAuthorityGranter` in the unit tests that demonstrates a simple `AuthorityGranter` implementation. [[jaas-defaultjaasauthenticationprovider]] == DefaultJaasAuthenticationProvider -The `DefaultJaasAuthenticationProvider` allows a JAAS `Configuration` object to be injected into it as a dependency. -It then creates a `LoginContext` using the injected JAAS `Configuration`. -This means that `DefaultJaasAuthenticationProvider` is not bound any particular implementation of `Configuration` as `JaasAuthenticationProvider` is. +The `DefaultJaasAuthenticationProvider` lets a JAAS `Configuration` object be injected into it as a dependency. +It then creates a `LoginContext` by using the injected JAAS `Configuration`. +This means that `DefaultJaasAuthenticationProvider` is not bound to any particular implementation of `Configuration`, as `JaasAuthenticationProvider` is. [[jaas-inmemoryconfiguration]] === InMemoryConfiguration -In order to make it easy to inject a `Configuration` into `DefaultJaasAuthenticationProvider`, a default in-memory implementation named `InMemoryConfiguration` is provided. -The implementation constructor accepts a `Map` where each key represents a login configuration name and the value represents an `Array` of ``AppConfigurationEntry``s. -`InMemoryConfiguration` also supports a default `Array` of `AppConfigurationEntry` objects that will be used if no mapping is found within the provided `Map`. -For details, refer to the class level javadoc of `InMemoryConfiguration`. +To make it easy to inject a `Configuration` into `DefaultJaasAuthenticationProvider`, a default in-memory implementation named `InMemoryConfiguration` is provided. +The implementation constructor accepts a `Map` where each key represents a login configuration name, and the value represents an `Array` of `AppConfigurationEntry` instances. +`InMemoryConfiguration` also supports a default `Array` of `AppConfigurationEntry` objects that is used if no mapping is found within the provided `Map`. +For details, see the {security-api-url}org/springframework/security/authentication/jaas/memory/InMemoryConfiguration.html[Javadoc of `InMemoryConfiguration`]. [[jaas-djap-config]] === DefaultJaasAuthenticationProvider Example Configuration -While the Spring configuration for `InMemoryConfiguration` can be more verbose than the standard JAAS configuration files, using it in conjunction with `DefaultJaasAuthenticationProvider` is more flexible than `JaasAuthenticationProvider` since it not dependant on the default `Configuration` implementation. +While the Spring configuration for `InMemoryConfiguration` can be more verbose than the standard JAAS configuration files, using it in conjunction with `DefaultJaasAuthenticationProvider` is more flexible than `JaasAuthenticationProvider`, since it not dependent on the default `Configuration` implementation. -An example configuration of `DefaultJaasAuthenticationProvider` using `InMemoryConfiguration` is provided below. +The next example provides a configuration of `DefaultJaasAuthenticationProvider` that uses `InMemoryConfiguration`. Note that custom implementations of `Configuration` can easily be injected into `DefaultJaasAuthenticationProvider` as well. - +==== [source,xml] ---- - @@ -110,29 +106,31 @@ class="org.springframework.security.authentication.jaas.DefaultJaasAuthenticatio - ---- - +==== [[jaas-jaasauthenticationprovider]] == JaasAuthenticationProvider -The `JaasAuthenticationProvider` assumes the default `Configuration` is an instance of https://docs.oracle.com/javase/8/docs/jre/api/security/jaas/spec/com/sun/security/auth/login/ConfigFile.html[ ConfigFile]. -This assumption is made in order to attempt to update the `Configuration`. +The `JaasAuthenticationProvider` assumes that the default `Configuration` is an instance of https://docs.oracle.com/javase/8/docs/jre/api/security/jaas/spec/com/sun/security/auth/login/ConfigFile.html[`ConfigFile`]. +This assumption is made in order to try to update the `Configuration`. The `JaasAuthenticationProvider` then uses the default `Configuration` to create the `LoginContext`. -Let's assume we have a JAAS login configuration file, `/WEB-INF/login.conf`, with the following contents: +Assume that we have a JAAS login configuration file, `/WEB-INF/login.conf`, with the following contents: +==== [source,txt] ---- JAASTest { sample.SampleLoginModule required; }; ---- +==== -Like all Spring Security beans, the `JaasAuthenticationProvider` is configured via the application context. +Like all Spring Security beans, the `JaasAuthenticationProvider` is configured through the application context. The following definitions would correspond to the above JAAS login configuration file: +==== [source,xml] ---- @@ -155,16 +153,19 @@ class="org.springframework.security.authentication.jaas.JaasAuthenticationProvid ---- +==== [[jaas-apiprovision]] == Running as a Subject -If configured, the `JaasApiIntegrationFilter` will attempt to run as the `Subject` on the `JaasAuthenticationToken`. +If configured, the `JaasApiIntegrationFilter` tries to run as the `Subject` on the `JaasAuthenticationToken`. This means that the `Subject` can be accessed using: +==== [source,java] ---- Subject subject = Subject.getSubject(AccessController.getContext()); ---- +==== -This integration can easily be configured using the xref:servlet/appendix/namespace.adoc#nsa-http-jaas-api-provision[jaas-api-provision] attribute. +You can configure this integration by using the xref:servlet/appendix/namespace/http.adoc#nsa-http-jaas-api-provision[jaas-api-provision] attribute. This feature is useful when integrating with legacy or external API's that rely on the JAAS Subject being populated. diff --git a/docs/modules/ROOT/pages/servlet/authentication/logout.adoc b/docs/modules/ROOT/pages/servlet/authentication/logout.adoc index 909f1c3d755..e440e20b96c 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/logout.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/logout.adoc @@ -1,16 +1,18 @@ [[jc-logout]] = Handling Logouts +This section covers how to customize the handling of logouts. + [[logout-java-configuration]] == Logout Java/Kotlin Configuration When using the `{security-api-url}org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html[WebSecurityConfigurerAdapter]`, logout capabilities are automatically applied. -The default is that accessing the URL `/logout` will log the user out by: +The default is that accessing the URL `/logout` logs the user out by: - Invalidating the HTTP Session - Cleaning up any RememberMe authentication that was configured - Clearing the `SecurityContextHolder` -- Redirect to `/login?logout` +- Redirecting to `/login?logout` Similar to configuring login capabilities, however, you also have various options to further customize your logout requirements: @@ -53,33 +55,33 @@ override fun configure(http: HttpSecurity) { <1> Provides logout support. This is automatically applied when using `WebSecurityConfigurerAdapter`. -<2> The URL that triggers log out to occur (default is `/logout`). -If CSRF protection is enabled (default), then the request must also be a POST. -For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutUrl-java.lang.String-[Javadoc]. -<3> The URL to redirect to after logout has occurred. +<2> The URL that triggers log out to occur (the default is `/logout`). +If CSRF protection is enabled (the default), the request must also be a POST. +For more information, see {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutUrl-java.lang.String-[`logoutUrl(java.lang.String logoutUrl)`]. +<3> The URL to which to redirect after logout has occurred. The default is `/login?logout`. -For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessUrl-java.lang.String-[Javadoc]. +For more information, see {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessUrl-java.lang.String-[`logoutSuccessUrl(java.lang.String logoutSuccessUrl)`]. <4> Let's you specify a custom `LogoutSuccessHandler`. If this is specified, `logoutSuccessUrl()` is ignored. -For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessHandler-org.springframework.security.web.authentication.logout.LogoutSuccessHandler-[Javadoc]. +For more information, see {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessHandler-org.springframework.security.web.authentication.logout.LogoutSuccessHandler-[`LogoutSuccessHandler`]. <5> Specify whether to invalidate the `HttpSession` at the time of logout. This is *true* by default. Configures the `SecurityContextLogoutHandler` under the covers. -For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#invalidateHttpSession-boolean-[Javadoc]. +For more information, see {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#invalidateHttpSession-boolean-[`invalidateHttpSession(boolean invalidateHttpSession)`]. <6> Adds a `LogoutHandler`. -`SecurityContextLogoutHandler` is added as the last `LogoutHandler` by default. -<7> Allows specifying the names of cookies to be removed on logout success. +By default, `SecurityContextLogoutHandler` is added as the last `LogoutHandler`. +<7> Lets specifying the names of cookies be removed on logout success. This is a shortcut for adding a `CookieClearingLogoutHandler` explicitly. [NOTE] ==== -Logouts can of course also be configured using the XML Namespace notation. -Please see the documentation for the xref:servlet/appendix/namespace.adoc#nsa-logout[ logout element] in the Spring Security XML Namespace section for further details. +Logouts can also be configured by using the XML Namespace notation. +See the documentation for the xref:servlet/appendix/namespace/http.adoc#nsa-logout[ logout element] in the Spring Security XML Namespace section for further details. ==== -Generally, in order to customize logout functionality, you can add +Generally, to customize logout functionality, you can add `{security-api-url}org/springframework/security/web/authentication/logout/LogoutHandler.html[LogoutHandler]` -and/or +or `{security-api-url}org/springframework/security/web/authentication/logout/LogoutSuccessHandler.html[LogoutSuccessHandler]` implementations. For many common scenarios, these handlers are applied under the @@ -88,8 +90,8 @@ covers when using the fluent API. [[ns-logout]] == Logout XML Configuration The `logout` element adds support for logging out by navigating to a particular URL. -The default logout URL is `/logout`, but you can set it to something else using the `logout-url` attribute. -More information on other available attributes may be found in the namespace appendix. +The default logout URL is `/logout`, but you can set it to something else by setting the `logout-url` attribute. +You can find more information on other available attributes in the namespace appendix. [[jc-logout-handler]] == LogoutHandler @@ -97,9 +99,9 @@ More information on other available attributes may be found in the namespace app Generally, `{security-api-url}org/springframework/security/web/authentication/logout/LogoutHandler.html[LogoutHandler]` implementations indicate classes that are able to participate in logout handling. They are expected to be invoked to perform necessary clean-up. -As such they should +As a result, they should not throw exceptions. -Various implementations are provided: +Spring Security provides various implementations: - {security-api-url}org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.html[PersistentTokenBasedRememberMeServices] - {security-api-url}org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.html[TokenBasedRememberMeServices] @@ -108,41 +110,40 @@ Various implementations are provided: - {security-api-url}org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html[SecurityContextLogoutHandler] - {security-api-url}org/springframework/security/web/authentication/logout/HeaderWriterLogoutHandler.html[HeaderWriterLogoutHandler] -Please see xref:servlet/authentication/rememberme.adoc#remember-me-impls[Remember-Me Interfaces and Implementations] for details. +See xref:servlet/authentication/rememberme.adoc#remember-me-impls[Remember-Me Interfaces and Implementations] for details. Instead of providing `LogoutHandler` implementations directly, the fluent API also provides shortcuts that provide the respective `LogoutHandler` implementations under the covers. -E.g. `deleteCookies()` allows specifying the names of one or more cookies to be removed on logout success. +For example, `deleteCookies()` lets you specify the names of one or more cookies to be removed on logout success. This is a shortcut compared to adding a `CookieClearingLogoutHandler`. [[jc-logout-success-handler]] == LogoutSuccessHandler -The `LogoutSuccessHandler` is called after a successful logout by the `LogoutFilter`, to handle e.g. +The `LogoutSuccessHandler` is called after a successful logout by the `LogoutFilter`, to handle (for example) redirection or forwarding to the appropriate destination. Note that the interface is almost the same as the `LogoutHandler` but may raise an exception. -The following implementations are provided: +Spring Security provides the following implementations: - {security-api-url}org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.html[SimpleUrlLogoutSuccessHandler] - HttpStatusReturningLogoutSuccessHandler -As mentioned above, you don't need to specify the `SimpleUrlLogoutSuccessHandler` directly. +As mentioned earlier, you need not specify the `SimpleUrlLogoutSuccessHandler` directly. Instead, the fluent API provides a shortcut by setting the `logoutSuccessUrl()`. -This will setup the `SimpleUrlLogoutSuccessHandler` under the covers. -The provided URL will be redirected to after a logout has occurred. +This sets up the `SimpleUrlLogoutSuccessHandler` under the covers. +The provided URL is redirected to after a logout has occurred. The default is `/login?logout`. The `HttpStatusReturningLogoutSuccessHandler` can be interesting in REST API type scenarios. -Instead of redirecting to a URL upon the successful logout, this `LogoutSuccessHandler` allows you to provide a plain HTTP status code to be returned. -If not configured a status code 200 will be returned by default. +Instead of redirecting to a URL upon the successful logout, this `LogoutSuccessHandler` lets you provide a plain HTTP status code to be returned. +If not configured, a status code 200 is returned by default. [[jc-logout-references]] == Further Logout-Related References - <> -- xref:servlet/test/mockmvc/logout.adoc#test-logout[ Testing Logout] -- xref:servlet/integrations/servlet-api.adoc#servletapi-logout[ HttpServletRequest.logout()] +- xref:servlet/test/mockmvc/logout.adoc#test-logout[Testing Logout] +- xref:servlet/integrations/servlet-api.adoc#servletapi-logout[`HttpServletRequest.logout()`] - xref:servlet/authentication/rememberme.adoc#remember-me-impls[Remember-Me Interfaces and Implementations] -- xref:servlet/exploits/csrf.adoc#servlet-considerations-csrf-logout[ Logging Out] in section CSRF Caveats -- Section xref:servlet/authentication/cas.adoc#cas-singlelogout[ Single Logout] (CAS protocol) -- Documentation for the xref:servlet/appendix/namespace.adoc#nsa-logout[ logout element] in the Spring Security XML Namespace section +- xref:servlet/exploits/csrf.adoc#servlet-considerations-csrf-logout[Logging Out] in section CSRF Caveats +- Documentation for the xref:servlet/appendix/namespace/http.adoc#nsa-logout[logout element] in the Spring Security XML Namespace section diff --git a/docs/modules/ROOT/pages/servlet/authentication/openid.adoc b/docs/modules/ROOT/pages/servlet/authentication/openid.adoc index 8451b82d4d1..28c00fb2574 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/openid.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/openid.adoc @@ -2,10 +2,13 @@ = OpenID Support [NOTE] -The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2. +==== +The OpenID 1.0 and 2.0 protocols have been deprecated. You should migrate to OpenID Connect, which is supported by `spring-security-oauth2`. +==== -The namespace supports https://openid.net/[OpenID] login either instead of, or in addition to normal form-based login, with a simple change: +The namespace supports https://openid.net/[OpenID] login either instead of or in addition to normal form-based login, with a simple change: +==== [source,xml] ---- @@ -13,24 +16,28 @@ The namespace supports https://openid.net/[OpenID] login either instead of, or i ---- +==== You should then register yourself with an OpenID provider (such as myopenid.com), and add the user information to your in-memory ``: +==== [source,xml] ---- ---- +==== -You should be able to login using the `myopenid.com` site to authenticate. -It is also possible to select a specific `UserDetailsService` bean for use OpenID by setting the `user-service-ref` attribute on the `openid-login` element. -Note that we have omitted the password attribute from the above user configuration, since this set of user data is only being used to load the authorities for the user. -A random password will be generated internally, preventing you from accidentally using this user data as an authentication source elsewhere in your configuration. +You should be able to login by using the `myopenid.com` site to authenticate. +You can also select a specific `UserDetailsService` bean for use with OpenID by setting the `user-service-ref` attribute on the `openid-login` element. +Note that we have omitted the password attribute from the above user configuration, since this set of user data is being used only to load the authorities for the user. +A random password is generated internally, preventing you from accidentally using this user data as an authentication source elsewhere in your configuration. == Attribute Exchange -Support for OpenID https://openid.net/specs/openid-attribute-exchange-1_0.html[attribute exchange]. -As an example, the following configuration would attempt to retrieve the email and full name from the OpenID provider, for use by the application: +Spring Security includes support for OpenID https://openid.net/specs/openid-attribute-exchange-1_0.html[attribute exchange]. +As an example, the following configuration tries to retrieve the email and full name from the OpenID provider for use by the application: +==== [source,xml] ---- @@ -40,21 +47,24 @@ As an example, the following configuration would attempt to retrieve the email a ---- +==== -The "type" of each OpenID attribute is a URI, determined by a particular schema, in this case https://axschema.org/[https://axschema.org/]. -If an attribute must be retrieved for successful authentication, the `required` attribute can be set. -The exact schema and attributes supported will depend on your OpenID provider. -The attribute values are returned as part of the authentication process and can be accessed afterwards using the following code: +The "`type`" of each OpenID attribute is a URI, determined by a particular schema -- in this case, https://axschema.org/[https://axschema.org/]. +If an attribute must be retrieved for successful authentication, you can set the `required` attribute. +The exact schema and attributes supported depend on your OpenID provider. +The attribute values are returned as part of the authentication process and can be accessed afterwards by using the following code: +==== [source,java] ---- OpenIDAuthenticationToken token = (OpenIDAuthenticationToken)SecurityContextHolder.getContext().getAuthentication(); List attributes = token.getAttributes(); ---- +==== We can obtain the `OpenIDAuthenticationToken` from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. The `OpenIDAttribute` contains the attribute type and the retrieved value (or values in the case of multi-valued attributes). -You can supply multiple `attribute-exchange` elements, using an `identifier-matcher` attribute on each. -This contains a regular expression which will be matched against the OpenID identifier supplied by the user. +You can supply multiple `attribute-exchange` elements by using an `identifier-matcher` attribute on each element. +This contains a regular expression that is matched against the OpenID identifier supplied by the user. See the OpenID sample application in the codebase for an example configuration, providing different attribute lists for the Google, Yahoo and MyOpenID providers. diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/basic.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/basic.adoc index f83ead53aca..38b071ea687 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/basic.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/basic.adoc @@ -2,60 +2,62 @@ = Basic Authentication :figures: servlet/authentication/unpwd -This section provides details on how Spring Security provides support for https://tools.ietf.org/html/rfc7617[Basic HTTP Authentication] for servlet based applications. +This section provides details on how Spring Security provides support for https://tools.ietf.org/html/rfc7617[Basic HTTP Authentication] for servlet-based applications. // FIXME: describe authenticationentrypoint, authenticationfailurehandler, authenticationsuccesshandler -Let's take a look at how HTTP Basic Authentication works within Spring Security. -First, we see the https://tools.ietf.org/html/rfc7235#section-4.1[WWW-Authenticate] header is sent back to an unauthenticated client. +This section describes how HTTP Basic Authentication works within Spring Security. +First, we see the https://tools.ietf.org/html/rfc7235#section-4.1[WWW-Authenticate] header is sent back to an unauthenticated client: .Sending WWW-Authenticate Header image::{figures}/basicauthenticationentrypoint.png[] -The figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram. +The preceding figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram. image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized. image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`. image:{icondir}/number_3.png[] Since the user is not authenticated, xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__. -The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.html[`BasicAuthenticationEntryPoint`] which sends a WWW-Authenticate header. +The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.html[`BasicAuthenticationEntryPoint`], which sends a WWW-Authenticate header. The `RequestCache` is typically a `NullRequestCache` that does not save the request since the client is capable of replaying the requests it originally requested. -When a client receives the WWW-Authenticate header it knows it should retry with a username and password. -Below is the flow for the username and password being processed. +When a client receives the `WWW-Authenticate` header, it knows it should retry with a username and password. +The following image shows the flow for the username and password being processed: [[servlet-authentication-basicauthenticationfilter]] .Authenticating Username and Password image::{figures}/basicauthenticationfilter.png[] -The figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram. +The preceding figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram. -image:{icondir}/number_1.png[] When the user submits their username and password, the `BasicAuthenticationFilter` creates a `UsernamePasswordAuthenticationToken` which is a type of xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] by extracting the username and password from the `HttpServletRequest`. +image:{icondir}/number_1.png[] When the user submits their username and password, the `BasicAuthenticationFilter` creates a `UsernamePasswordAuthenticationToken`, which is a type of xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] by extracting the username and password from the `HttpServletRequest`. image:{icondir}/number_2.png[] Next, the `UsernamePasswordAuthenticationToken` is passed into the `AuthenticationManager` to be authenticated. The details of what `AuthenticationManager` looks like depend on how the xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-storage[user information is stored]. -image:{icondir}/number_3.png[] If authentication fails, then __Failure__ +image:{icondir}/number_3.png[] If authentication fails, then __Failure__. -* The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder] is cleared out. -* `RememberMeServices.loginFail` is invoked. +. The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder] is cleared out. +. `RememberMeServices.loginFail` is invoked. If remember me is not configured, this is a no-op. -// FIXME: link to rememberme -* `AuthenticationEntryPoint` is invoked to trigger the WWW-Authenticate to be sent again. +See the {security-api-url}org/springframework/security/web/authentication/RememberMeServices.html[`RememberMeServices`] interface in the Javadoc. +. `AuthenticationEntryPoint` is invoked to trigger the WWW-Authenticate to be sent again. +See the {security-api-url}org/springframework/security/web/AuthenticationEntryPoint.html[`AuthenticationEntryPoint`] interface in the Javadoc. image:{icondir}/number_4.png[] If authentication is successful, then __Success__. -* The xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. -* `RememberMeServices.loginSuccess` is invoked. +. The xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. +. `RememberMeServices.loginSuccess` is invoked. If remember me is not configured, this is a no-op. -// FIXME: link to rememberme -* The `BasicAuthenticationFilter` invokes `FilterChain.doFilter(request,response)` to continue with the rest of the application logic. +See the {security-api-url}org/springframework/security/web/authentication/RememberMeServices.html[`RememberMeServices`] interface in the Javadoc. +. The `BasicAuthenticationFilter` invokes `FilterChain.doFilter(request,response)` to continue with the rest of the application logic. +See the {security-api-url}org/springframework/security/web/authentication/www/BasicAuthenticationFilter.html[`BasicAuthenticationFilter`] Class in the Javadoc -Spring Security's HTTP Basic Authentication support in is enabled by default. +By default, Spring Security's HTTP Basic Authentication support is enabled. However, as soon as any servlet based configuration is provided, HTTP Basic must be explicitly provided. -A minimal, explicit configuration can be found below: +The following example shows a minimal, explicit configuration: .Explicit HTTP Basic Configuration ==== diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/dao-authentication-provider.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/dao-authentication-provider.adoc index 18631cb9c44..1366308c7c6 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/dao-authentication-provider.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/dao-authentication-provider.adoc @@ -2,21 +2,21 @@ = DaoAuthenticationProvider :figures: servlet/authentication/unpwd -{security-api-url}org/springframework/security/authentication/dao/DaoAuthenticationProvider.html[`DaoAuthenticationProvider`] is an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[`AuthenticationProvider`] implementation that leverages a xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`] and xref:servlet/authentication/passwords/password-encoder.adoc#servlet-authentication-password-storage[`PasswordEncoder`] to authenticate a username and password. +{security-api-url}org/springframework/security/authentication/dao/DaoAuthenticationProvider.html[`DaoAuthenticationProvider`] is an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[`AuthenticationProvider`] implementation that uses a xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`] and xref:servlet/authentication/passwords/password-encoder.adoc#servlet-authentication-password-storage[`PasswordEncoder`] to authenticate a username and password. -Let's take a look at how `DaoAuthenticationProvider` works within Spring Security. -The figure explains details of how the xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationmanager[`AuthenticationManager`] in figures from xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[Reading the Username & Password] works. +This section examines how `DaoAuthenticationProvider` works within Spring Security. +The following figure explains the workings of the xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationmanager[`AuthenticationManager`] in figures from the xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[Reading the Username & Password] section. .`DaoAuthenticationProvider` Usage image::{figures}/daoauthenticationprovider.png[] -image:{icondir}/number_1.png[] The authentication `Filter` from xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[Reading the Username & Password] passes a `UsernamePasswordAuthenticationToken` to the `AuthenticationManager` which is implemented by xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`ProviderManager`]. +image:{icondir}/number_1.png[] The authentication `Filter` from the xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[Reading the Username & Password] section passes a `UsernamePasswordAuthenticationToken` to the `AuthenticationManager`, which is implemented by xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`ProviderManager`]. image:{icondir}/number_2.png[] The `ProviderManager` is configured to use an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[AuthenticationProvider] of type `DaoAuthenticationProvider`. image:{icondir}/number_3.png[] `DaoAuthenticationProvider` looks up the `UserDetails` from the `UserDetailsService`. -image:{icondir}/number_4.png[] `DaoAuthenticationProvider` then uses the xref:servlet/authentication/passwords/password-encoder.adoc#servlet-authentication-password-storage[`PasswordEncoder`] to validate the password on the `UserDetails` returned in the previous step. +image:{icondir}/number_4.png[] `DaoAuthenticationProvider` uses the xref:servlet/authentication/passwords/password-encoder.adoc#servlet-authentication-password-storage[`PasswordEncoder`] to validate the password on the `UserDetails` returned in the previous step. image:{icondir}/number_5.png[] When authentication is successful, the xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] that is returned is of type `UsernamePasswordAuthenticationToken` and has a principal that is the `UserDetails` returned by the configured `UserDetailsService`. -Ultimately, the returned `UsernamePasswordAuthenticationToken` will be set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] by the authentication `Filter`. +Ultimately, the returned `UsernamePasswordAuthenticationToken` is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] by the authentication `Filter`. diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/digest.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/digest.adoc index 913f175e360..f918bc77455 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/digest.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/digest.adoc @@ -1,26 +1,26 @@ [[servlet-authentication-digest]] = Digest Authentication -This section provides details on how Spring Security provides support for https://tools.ietf.org/html/rfc2617[Digest Authentication] which is provided `DigestAuthenticationFilter`. +This section provides details on how Spring Security provides support for https://tools.ietf.org/html/rfc2617[Digest Authentication], which is provided `DigestAuthenticationFilter`. [WARNING] ==== -You should not use Digest Authentication in modern applications because it is not considered secure. -The most obvious problem is that you must store your passwords in plaintext, encrypted, or an MD5 format. +You should not use Digest Authentication in modern applications, because it is not considered to be secure. +The most obvious problem is that you must store your passwords in plaintext or an encrypted or MD5 format. All of these storage formats are considered insecure. -Instead, you should store credentials using a one way adaptive password hash (i.e. bCrypt, PBKDF2, SCrypt, etc) which is not supported by Digest Authentication. +Instead, you should store credentials by using a one way adaptive password hash (bCrypt, PBKDF2, SCrypt, and others), which is not supported by Digest Authentication. ==== -Digest Authentication attempts to solve many of the weaknesses of xref:servlet/authentication/passwords/basic.adoc#servlet-authentication-basic[Basic authentication], specifically by ensuring credentials are never sent in clear text across the wire. +Digest Authentication tries to solve many of the weaknesses of xref:servlet/authentication/passwords/basic.adoc#servlet-authentication-basic[Basic authentication], specifically by ensuring credentials are never sent in clear text across the wire. Many https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Digest#Browser_compatibility[browsers support Digest Authentication]. The standard governing HTTP Digest Authentication is defined by https://tools.ietf.org/html/rfc2617[RFC 2617], which updates an earlier version of the Digest Authentication standard prescribed by https://tools.ietf.org/html/rfc2069[RFC 2069]. Most user agents implement RFC 2617. Spring Security's Digest Authentication support is compatible with the "`auth`" quality of protection (`qop`) prescribed by RFC 2617, which also provides backward compatibility with RFC 2069. -Digest Authentication was seen as a more attractive option if you need to use unencrypted HTTP (i.e. no TLS/HTTPS) and wish to maximise security of the authentication process. +Digest Authentication was seen as a more attractive option if you need to use unencrypted HTTP (no TLS or HTTPS) and wish to maximize security of the authentication process. However, everyone should use xref:features/exploits/http.adoc#http[HTTPS]. -Central to Digest Authentication is a "nonce". +Central to Digest Authentication is a "`nonce`". This is a value the server generates. Spring Security's nonce adopts the following format: @@ -34,7 +34,8 @@ key: A private key to prevent modification of the nonce token ---- ==== -You will need to ensure you xref:features/authentication/password-storage.adoc#authentication-password-storage-configuration[configure] insecure plain text xref:features/authentication/password-storage.adoc#authentication-password-storage[Password Storage] using `NoOpPasswordEncoder`. +You need to ensure that you xref:features/authentication/password-storage.adoc#authentication-password-storage-configuration[configure] insecure plain text xref:features/authentication/password-storage.adoc#authentication-password-storage[Password Storage] using `NoOpPasswordEncoder`. +(See the {security-api-url}org/springframework/security/crypto/password/NoOpPasswordEncoder.html[`NoOpPasswordEncoder`] class in the Javadoc.) The following provides an example of configuring Digest Authentication with Java Configuration: .Digest Authentication diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/form.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/form.adoc index 941cbb037f3..cde92ebfe7d 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/form.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/form.adoc @@ -2,32 +2,32 @@ = Form Login :figures: servlet/authentication/unpwd -Spring Security provides support for username and password being provided through an html form. +Spring Security provides support for username and password being provided through an HTML form. This section provides details on how form based authentication works within Spring Security. // FIXME: describe authenticationentrypoint, authenticationfailurehandler, authenticationsuccesshandler -Let's take a look at how form based log in works within Spring Security. -First, we see how the user is redirected to the log in form. +This section examines how form-based login works within Spring Security. +First, we see how the user is redirected to the login form: -.Redirecting to the Log In Page +.Redirecting to the Login Page image::{figures}/loginurlauthenticationentrypoint.png[] -The figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram. +The preceding figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram. -image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized. +image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource (`/private`) for which it is not authorized. image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`. -image:{icondir}/number_3.png[] Since the user is not authenticated, xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__ and sends a redirect to the log in page with the configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`]. -In most cases the `AuthenticationEntryPoint` is an instance of {security-api-url}org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html[`LoginUrlAuthenticationEntryPoint`]. +image:{icondir}/number_3.png[] Since the user is not authenticated, xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__ and sends a redirect to the login page with the configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`]. +In most cases, the `AuthenticationEntryPoint` is an instance of {security-api-url}org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html[`LoginUrlAuthenticationEntryPoint`]. -image:{icondir}/number_4.png[] The browser will then request the log in page that it was redirected to. +image:{icondir}/number_4.png[] The browser requests the login page to which it was redirected. -image:{icondir}/number_5.png[] Something within the application, must <>. +image:{icondir}/number_5.png[] Something within the application, must <>. [[servlet-authentication-usernamepasswordauthenticationfilter]] When the username and password are submitted, the `UsernamePasswordAuthenticationFilter` authenticates the username and password. -The `UsernamePasswordAuthenticationFilter` extends xref:servlet/authentication/architecture.adoc#servlet-authentication-abstractprocessingfilter[AbstractAuthenticationProcessingFilter], so this diagram should look pretty similar. +The `UsernamePasswordAuthenticationFilter` extends xref:servlet/authentication/architecture.adoc#servlet-authentication-abstractprocessingfilter[AbstractAuthenticationProcessingFilter], so the following diagram should look pretty similar: .Authenticating Username and Password image::{figures}/usernamepasswordauthenticationfilter.png[] @@ -35,38 +35,38 @@ image::{figures}/usernamepasswordauthenticationfilter.png[] The figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram. -image:{icondir}/number_1.png[] When the user submits their username and password, the `UsernamePasswordAuthenticationFilter` creates a `UsernamePasswordAuthenticationToken` which is a type of xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] by extracting the username and password from the `HttpServletRequest`. +image:{icondir}/number_1.png[] When the user submits their username and password, the `UsernamePasswordAuthenticationFilter` creates a `UsernamePasswordAuthenticationToken`, which is a type of xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`], by extracting the username and password from the `HttpServletRequest` instance. -image:{icondir}/number_2.png[] Next, the `UsernamePasswordAuthenticationToken` is passed into the `AuthenticationManager` to be authenticated. +image:{icondir}/number_2.png[] Next, the `UsernamePasswordAuthenticationToken` is passed into the `AuthenticationManager` instance to be authenticated. The details of what `AuthenticationManager` looks like depend on how the xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-storage[user information is stored]. -image:{icondir}/number_3.png[] If authentication fails, then __Failure__ +image:{icondir}/number_3.png[] If authentication fails, then __Failure__. -* The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder] is cleared out. -* `RememberMeServices.loginFail` is invoked. +. The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder] is cleared out. +. `RememberMeServices.loginFail` is invoked. If remember me is not configured, this is a no-op. -// FIXME: link to rememberme -* `AuthenticationFailureHandler` is invoked. -// FIXME: link to AuthenticationFailureHandler +See the {security-api-url}org/springframework/security/web/authentication/RememberMeServices.html[`RememberMeServices`] interface in the Javadoc. +. `AuthenticationFailureHandler` is invoked. +See the {security-api-url}springframework/security/web/authentication/AuthenticationFailureHandler.html[`AuthenticationFailureHandler`] class in the Javadoc image:{icondir}/number_4.png[] If authentication is successful, then __Success__. -* `SessionAuthenticationStrategy` is notified of a new log in. -// FIXME: Add link to SessionAuthenticationStrategy -* The xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. -// FIXME: link securitycontextpersistencefilter -* `RememberMeServices.loginSuccess` is invoked. +. `SessionAuthenticationStrategy` is notified of a new login. +See the {security-api-url}springframework/security/web/authentication/session/SessionAuthenticationStrategy.html[`SessionAuthenticationStrategy`] interface in the Javadoc. +. The ref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. +See the {security-api-url}springframework/security/web/context/SecurityContextPersistenceFilter.html[`SecurityContextPersistenceFilter`] class in the Javadoc. +. `RememberMeServices.loginSuccess` is invoked. If remember me is not configured, this is a no-op. -// FIXME: link to rememberme -* `ApplicationEventPublisher` publishes an `InteractiveAuthenticationSuccessEvent`. -* The `AuthenticationSuccessHandler` is invoked. Typically this is a `SimpleUrlAuthenticationSuccessHandler` which will redirect to a request saved by xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] when we redirect to the log in page. +See the {security-api-url}springframework/security/web/authentication/RememberMeServices.html[`RememberMeServices`] interface in the Javadoc. +. `ApplicationEventPublisher` publishes an `InteractiveAuthenticationSuccessEvent`. +. The `AuthenticationSuccessHandler` is invoked. Typically, this is a `SimpleUrlAuthenticationSuccessHandler`, which redirects to a request saved by xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] when we redirect to the login page. [[servlet-authentication-form-min]] -Spring Security form log in is enabled by default. -However, as soon as any servlet based configuration is provided, form based log in must be explicitly provided. -A minimal, explicit Java configuration can be found below: +By default, Spring Security form login is enabled. +However, as soon as any servlet-based configuration is provided, form based login must be explicitly provided. +The following example shows a minimal, explicit Java configuration: -.Form Log In +.Form Login ==== .Java [source,java,role="primary"] @@ -99,13 +99,13 @@ fun configure(http: HttpSecurity) { ---- ==== -In this configuration Spring Security will render a default log in page. -Most production applications will require a custom log in form. +In the preceding configuration, Spring Security renders a default login page. +Most production applications require a custom login form. [[servlet-authentication-form-custom]] -The configuration below demonstrates how to provide a custom log in form. +The following configuration demonstrates how to provide a custom login form. -.Custom Log In Form Configuration +.Custom Login Form Configuration ==== .Java [source,java,role="primary"] @@ -148,9 +148,9 @@ fun configure(http: HttpSecurity) { [[servlet-authentication-form-custom-html]] When the login page is specified in the Spring Security configuration, you are responsible for rendering the page. // FIXME: default login page rendered by Spring Security -Below is a https://www.thymeleaf.org/[Thymeleaf] template that produces an HTML login form that complies with a login page of `/login`: +The following https://www.thymeleaf.org/[Thymeleaf] template produces an HTML login form that complies with a login page of `/login`.: -.Log In Form +.Login Form ==== .src/main/resources/templates/login.html [source,xml] @@ -182,19 +182,19 @@ Below is a https://www.thymeleaf.org/[Thymeleaf] template that produces an HTML There are a few key points about the default HTML form: -* The form should perform a `post` to `/login` -* The form will need to include a xref:servlet/exploits/csrf.adoc#servlet-csrf[CSRF Token] which is xref:servlet/exploits/csrf.adoc#servlet-csrf-include-form-auto[automatically included] by Thymeleaf. -* The form should specify the username in a parameter named `username` -* The form should specify the password in a parameter named `password` -* If the HTTP parameter error is found, it indicates the user failed to provide a valid username / password -* If the HTTP parameter logout is found, it indicates the user has logged out successfully +* The form should perform a `post` to `/login`. +* The form needs to include a xref:servlet/exploits/csrf.adoc#servlet-csrf[CSRF Token], which is xref:servlet/exploits/csrf.adoc#servlet-csrf-include-form-auto[automatically included] by Thymeleaf. +* The form should specify the username in a parameter named `username`. +* The form should specify the password in a parameter named `password`. +* If the HTTP parameter named `error` is found, it indicates the user failed to provide a valid username or password. +* If the HTTP parameter named `logout` is found, it indicates the user has logged out successfully. -Many users will not need much more than to customize the log in page. -However, if needed, everything above can be customized with additional configuration. +Many users do not need much more than to customize the login page. +However, if needed, you can customize everything shown earlier with additional configuration. [[servlet-authentication-form-custom-controller]] -If you are using Spring MVC, you will need a controller that maps `GET /login` to the login template we created. -A minimal sample `LoginController` can be seen below: +If you use Spring MVC, you need a controller that maps `GET /login` to the login template we created. +The following example shows a minimal `LoginController`: .LoginController ==== diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/in-memory.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/in-memory.adoc index 62fb993c0d4..2149580331b 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/in-memory.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/in-memory.adoc @@ -3,9 +3,9 @@ Spring Security's `InMemoryUserDetailsManager` implements xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[UserDetailsService] to provide support for username/password based authentication that is stored in memory. `InMemoryUserDetailsManager` provides management of `UserDetails` by implementing the `UserDetailsManager` interface. -`UserDetails` based authentication is used by Spring Security when it is configured to xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[accept a username/password] for authentication. +`UserDetails`-based authentication is used by Spring Security when it is configured to <> for authentication. -In this sample we use xref:features/authentication/password-storage.adoc#authentication-password-storage-boot-cli[Spring Boot CLI] to encode the password of `password` and get the encoded password of `+{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW+`. +In the following sample, we use xref:features/authentication/password-storage.adoc#authentication-password-storage-boot-cli[Spring Boot CLI] to encode a password value of `password` and get the encoded password of `+{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW+`: .InMemoryUserDetailsManager Java Configuration ==== @@ -61,12 +61,11 @@ fun users(): UserDetailsService { ---- ==== -The samples above store the passwords in a secure format, but leave a lot to be desired in terms of getting started experience. +The preceding samples store the passwords in a secure format but leave a lot to be desired in terms of a getting started experience. - -In the sample below we leverage xref:features/authentication/password-storage.adoc#authentication-password-storage-dep-getting-started[User.withDefaultPasswordEncoder] to ensure that the password stored in memory is protected. +In the following sample, we use xref:features/authentication/password-storage.adoc#authentication-password-storage-dep-getting-started[User.withDefaultPasswordEncoder] to ensure that the password stored in memory is protected. However, it does not protect against obtaining the password by decompiling the source code. -For this reason, `User.withDefaultPasswordEncoder` should only be used for "getting started" and is not intended for production. +For this reason, `User.withDefaultPasswordEncoder` should only be used for "`getting started`" and is not intended for production. .InMemoryUserDetailsManager with User.withDefaultPasswordEncoder ==== @@ -113,8 +112,8 @@ fun users(): UserDetailsService { ---- ==== -There is no simple way to use `User.withDefaultPasswordEncoder` with XML based configuration. -For demos or just getting started, you can choose to prefix the password with `+{noop}+` to indicate xref:features/authentication/password-storage.adoc#authentication-password-storage-dpe-format[no encoding should be used]. +There is no simple way to use `User.withDefaultPasswordEncoder` with XML-based configuration. +For demos or just getting started, you can choose to prefix the password with `+{noop}+` to indicate xref:features/authentication/password-storage.adoc#authentication-password-storage-dpe-format[no encoding should be used]: . `+{noop}+` XML Configuration ==== diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/index.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/index.adoc index d461ced251b..eaff4cdb1e6 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/index.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/index.adoc @@ -5,5 +5,5 @@ :icondir: images/icons One of the most common ways to authenticate a user is by validating a username and password. -As such, Spring Security provides comprehensive support for authenticating with a username and password. +Spring Security provides comprehensive support for authenticating with a username and password. diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/input.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/input.adoc index 8be74005707..1f1dca005ba 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/input.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/input.adoc @@ -2,4 +2,4 @@ = Reading the Username & Password :page-section-summary-toc: 1 -Spring Security provides the following built in mechanisms for reading a username and password from the `HttpServletRequest`: +Spring Security provides the following built-in mechanisms for reading a username and password from `HttpServletRequest`: diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/jdbc.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/jdbc.adoc index d4462eaaf8d..44078fb1dcb 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/jdbc.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/jdbc.adoc @@ -1,11 +1,11 @@ [[servlet-authentication-jdbc]] = JDBC Authentication -Spring Security's `JdbcDaoImpl` implements xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[UserDetailsService] to provide support for username/password based authentication that is retrieved using JDBC. +Spring Security's `JdbcDaoImpl` implements xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`] to provide support for username-and-password-based authentication that is retrieved by using JDBC. `JdbcUserDetailsManager` extends `JdbcDaoImpl` to provide management of `UserDetails` through the `UserDetailsManager` interface. -`UserDetails` based authentication is used by Spring Security when it is configured to xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[accept a username/password] for authentication. +`UserDetails`-based authentication is used by Spring Security when it is configured to xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[accept a username/password] for authentication. -In the following sections we will discuss: +In the following sections, we discuss: * The <> used by Spring Security JDBC Authentication * <> @@ -14,15 +14,14 @@ In the following sections we will discuss: [[servlet-authentication-jdbc-schema]] == Default Schema -Spring Security provides default queries for JDBC based authentication. +Spring Security provides default queries for JDBC-based authentication. This section provides the corresponding default schemas used with the default queries. -You will need to adjust the schema to match any customizations to the queries and the database dialect you are using. +You need to adjust the schema to match any customizations to the queries and the database dialect you use. [[servlet-authentication-jdbc-schema-user]] === User Schema `JdbcDaoImpl` requires tables to load the password, account status (enabled or disabled) and a list of authorities (roles) for the user. -The default schema required can be found below. [NOTE] ==== @@ -48,8 +47,7 @@ create unique index ix_auth_username on authorities (username,authority); ---- ==== -Oracle is a popular database choice, but requires a slightly different schema. -You can find the default Oracle Schema for users below. +Oracle is a popular database choice but requires a slightly different schema: .Default User Schema for Oracle Databases ==== @@ -74,8 +72,7 @@ ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME) RE [[servlet-authentication-jdbc-schema-group]] === Group Schema -If your application is leveraging groups, you will need to provide the groups schema. -The default schema for groups can be found below. +If your application uses groups, you need to provide the groups schema: .Default Group Schema ==== @@ -105,7 +102,7 @@ create table group_members ( == Setting up a DataSource Before we configure `JdbcUserDetailsManager`, we must create a `DataSource`. -In our example, we will setup an https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#jdbc-embedded-database-support[embedded DataSource] that is initialized with the <>. +In our example, we set up an https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#jdbc-embedded-database-support[embedded DataSource] that is initialized with the <>. .Embedded Data Source ==== @@ -142,12 +139,12 @@ fun dataSource(): DataSource { ---- ==== -In a production environment, you will want to ensure you setup a connection to an external database. +In a production environment, you want to ensure that you set up a connection to an external database. [[servlet-authentication-jdbc-bean]] == JdbcUserDetailsManager Bean -In this sample we use xref:features/authentication/password-storage.adoc#authentication-password-storage-boot-cli[Spring Boot CLI] to encode the password of `password` and get the encoded password of `+{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW+`. +In this sample, we use xref:features/authentication/password-storage.adoc#authentication-password-storage-boot-cli[Spring Boot CLI] to encode a password value of `password` and get the encoded password of `+{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW+`. See the xref:features/authentication/password-storage.adoc#authentication-password-storage[PasswordEncoder] section for more details about how to store passwords. .JdbcUserDetailsManager diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/ldap.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/ldap.adoc index aa4ad900ff8..a569de96429 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/ldap.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/ldap.adoc @@ -1,25 +1,25 @@ [[servlet-authentication-ldap]] = LDAP Authentication -LDAP is often used by organizations as a central repository for user information and as an authentication service. +LDAP (Lightweight Directory Access Protocol) is often used by organizations as a central repository for user information and as an authentication service. It can also be used to store the role information for application users. -Spring Security's LDAP based authentication is used by Spring Security when it is configured to xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[accept a username/password] for authentication. -However, despite leveraging a username/password for authentication it does not integrate using `UserDetailsService` because in <> the LDAP server does not return the password so the application cannot perform validation of the password. +Spring Security's LDAP-based authentication is used by Spring Security when it is configured to xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[accept a username/password] for authentication. +However, despite using a username and password for authentication, it does not use `UserDetailsService`, because, in <>, the LDAP server does not return the password, so the application cannot perform validation of the password. -There are many different scenarios for how an LDAP server may be configured so Spring Security's LDAP provider is fully configurable. -It uses separate strategy interfaces for authentication and role retrieval and provides default implementations which can be configured to handle a wide range of situations. +There are many different scenarios for how an LDAP server can be configured, so Spring Security's LDAP provider is fully configurable. +It uses separate strategy interfaces for authentication and role retrieval and provides default implementations, which can be configured to handle a wide range of situations. [[servlet-authentication-ldap-prerequisites]] == Prerequisites You should be familiar with LDAP before trying to use it with Spring Security. -The following link provides a good introduction to the concepts involved and a guide to setting up a directory using the free LDAP server OpenLDAP: https://www.zytrax.com/books/ldap/. -Some familiarity with the JNDI APIs used to access LDAP from Java may also be useful. -We don't use any third-party LDAP libraries (Mozilla, JLDAP etc.) in the LDAP provider, but extensive use is made of Spring LDAP, so some familiarity with that project may be useful if you plan on adding your own customizations. +The following link provides a good introduction to the concepts involved and a guide to setting up a directory using the free LDAP server, OpenLDAP: https://www.zytrax.com/books/ldap/. +Some familiarity with the JNDI APIs used to access LDAP from Java can also be useful. +We do not use any third-party LDAP libraries (Mozilla, JLDAP, or others) in the LDAP provider, but extensive use is made of Spring LDAP, so some familiarity with that project may be useful if you plan on adding your own customizations. -When using LDAP authentication, it is important to ensure that you configure LDAP connection pooling properly. -If you are unfamiliar with how to do this, you can refer to the https://docs.oracle.com/javase/jndi/tutorial/ldap/connect/config.html[Java LDAP documentation]. +When using LDAP authentication, you should ensure that you properly configure LDAP connection pooling. +If you are unfamiliar with how to do so, see the https://docs.oracle.com/javase/jndi/tutorial/ldap/connect/config.html[Java LDAP documentation]. // FIXME: @@ -35,16 +35,17 @@ If you are unfamiliar with how to do this, you can refer to the https://docs.ora [[servlet-authentication-ldap-embedded]] == Setting up an Embedded LDAP Server -The first thing you will need to do is to ensure that you have an LDAP Server to point your configuration to. -For simplicity, it often best to start with an embedded LDAP Server. +The first thing you need to do is to ensure that you have an LDAP Server to which to point your configuration. +For simplicity, it is often best to start with an embedded LDAP Server. Spring Security supports using either: * <> * <> -In the samples below, we expose the following as `users.ldif` as a classpath resource to initialize the embedded LDAP server with the users `user` and `admin` both of which have a password of `password`. +In the following samples, we expose `users.ldif` as a classpath resource to initialize the embedded LDAP server with two users, `user` and `admin`, both of which have a password of `password`: .users.ldif +==== [source,ldif] ---- dn: ou=groups,dc=springframework,dc=org @@ -90,11 +91,12 @@ objectclass: groupOfNames cn: admin uniqueMember: uid=admin,ou=people,dc=springframework,dc=org ---- +==== [[servlet-authentication-ldap-unboundid]] === Embedded UnboundID Server -If you wish to use https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID], then specify the following dependencies: +If you wish to use https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID], specify the following dependencies: .UnboundID Dependencies ==== @@ -118,7 +120,7 @@ depenendencies { ---- ==== -You can then configure the Embedded LDAP Server +You can then configure the Embedded LDAP Server: .Embedded LDAP Server Configuration ==== @@ -155,12 +157,12 @@ fun ldapContainer(): UnboundIdContainer { [NOTE] ==== -Spring Security uses ApacheDS 1.x which is no longer maintained. +Spring Security uses ApacheDS 1.x, which is no longer maintained. Unfortunately, ApacheDS 2.x has only released milestone versions with no stable release. Once a stable release of ApacheDS 2.x is available, we will consider updating. ==== -If you wish to use https://directory.apache.org/apacheds/[Apache DS], then specify the following dependencies: +If you wish to use https://directory.apache.org/apacheds/[Apache DS], specify the following dependencies: .ApacheDS Dependencies ==== @@ -191,7 +193,7 @@ depenendencies { ---- ==== -You can then configure the Embedded LDAP Server +You can then configure the Embedded LDAP Server: .Embedded LDAP Server Configuration ==== @@ -226,8 +228,8 @@ fun ldapContainer(): ApacheDSContainer { [[servlet-authentication-ldap-contextsource]] == LDAP ContextSource -Once you have an LDAP Server to point your configuration to, you need configure Spring Security to point to an LDAP server that should be used to authenticate users. -This is done by creating an LDAP `ContextSource`, which is the equivalent of a JDBC `DataSource`. +Once you have an LDAP Server to which to point your configuration, you need to configure Spring Security to point to an LDAP server that should be used to authenticate users. +To do so, create an LDAP `ContextSource` (which is the equivalent of a JDBC `DataSource`): .LDAP Context Source ==== @@ -258,15 +260,15 @@ fun contextSource(container: UnboundIdContainer): ContextSource { [[servlet-authentication-ldap-authentication]] == Authentication -Spring Security's LDAP support does not use the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[UserDetailsService] because LDAP bind authentication does not allow clients to read the password or even a hashed version of the password. -This means there is no way a password to be read and then authenticated by Spring Security. +Spring Security's LDAP support does not use the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[UserDetailsService] because LDAP bind authentication does not let clients read the password or even a hashed version of the password. +This means there is no way for a password to be read and then authenticated by Spring Security. -For this reason, LDAP support is implemented using the `LdapAuthenticator` interface. -The `LdapAuthenticator` is also responsible for retrieving any required user attributes. +For this reason, LDAP support is implemented through the `LdapAuthenticator` interface. +The `LdapAuthenticator` interface is also responsible for retrieving any required user attributes. This is because the permissions on the attributes may depend on the type of authentication being used. -For example, if binding as the user, it may be necessary to read them with the user's own permissions. +For example, if binding as the user, it may be necessary to read the attributes with the user's own permissions. -There are two `LdapAuthenticator` implementations supplied with Spring Security: +Spring Security supplies two `LdapAuthenticator` implementations: * <> * <> @@ -275,11 +277,10 @@ There are two `LdapAuthenticator` implementations supplied with Spring Security: == Using Bind Authentication https://ldap.com/the-ldap-bind-operation/[Bind Authentication] is the most common mechanism for authenticating users with LDAP. -In bind authentication the users credentials (i.e. username/password) are submitted to the LDAP server which authenticates them. -The advantage to using bind authentication is that the user's secrets (i.e. password) do not need to be exposed to clients which helps to protect them from leaking. +In bind authentication, the user's credentials (username and password) are submitted to the LDAP server, which authenticates them. +The advantage to using bind authentication is that the user's secrets (the password) do not need to be exposed to clients, which helps to protect them from leaking. - -An example of bind authentication configuration can be found below. +The following example shows bind authentication configuration: .Bind Authentication ==== @@ -323,9 +324,9 @@ fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthentication ---- ==== -This simple example would obtain the DN for the user by substituting the user login name in the supplied pattern and attempting to bind as that user with the login password. +The preceding simple example would obtain the DN for the user by substituting the user login name in the supplied pattern and attempting to bind as that user with the login password. This is OK if all your users are stored under a single node in the directory. -If instead you wished to configure an LDAP search filter to locate the user, you could use the following: +If, instead, you wish to configure an LDAP search filter to locate the user, you could use the following: .Bind Authentication with Search Filter ==== @@ -377,15 +378,15 @@ fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthentication ---- ==== -If used with the `ContextSource` <>, this would perform a search under the DN `ou=people,dc=springframework,dc=org` using `+(uid={0})+` as a filter. -Again the user login name is substituted for the parameter in the filter name, so it will search for an entry with the `uid` attribute equal to the user name. -If a user search base isn't supplied, the search will be performed from the root. +If used with the `ContextSource` <>, this would perform a search under the DN `ou=people,dc=springframework,dc=org` by using `+(uid={0})+` as a filter. +Again, the user login name is substituted for the parameter in the filter name, so it searchs for an entry with the `uid` attribute equal to the user name. +If a user search base is not supplied, the search is performed from the root. [[servlet-authentication-ldap-pwd]] == Using Password Authentication Password comparison is when the password supplied by the user is compared with the one stored in the repository. -This can either be done by retrieving the value of the password attribute and checking it locally or by performing an LDAP "compare" operation, where the supplied password is passed to the server for comparison and the real password value is never retrieved. +This can either be done by retrieving the value of the password attribute and checking it locally or by performing an LDAP "`compare`" operation, where the supplied password is passed to the server for comparison and the real password value is never retrieved. An LDAP compare cannot be done when the password is properly hashed with a random salt. .Minimal Password Compare Configuration @@ -428,7 +429,7 @@ fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthentication ---- ==== -A more advanced configuration with some customizations can be found below. +The following example shows a more advanced configuration with some customizations: .Password Compare Configuration ==== @@ -481,13 +482,14 @@ fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthentication ---- ==== -<1> Specify the password attribute as `pwd` -<2> Use `BCryptPasswordEncoder` +<1> Specify the password attribute as `pwd`. +<2> Use `BCryptPasswordEncoder`. == LdapAuthoritiesPopulator -Spring Security's `LdapAuthoritiesPopulator` is used to determine what authorites are returned for the user. +Spring Security's `LdapAuthoritiesPopulator` is used to determine what authorities are returned for the user. +The following example shows how configure `LdapAuthoritiesPopulator`: .LdapAuthoritiesPopulator Configuration ==== @@ -537,14 +539,20 @@ fun authenticationProvider(authenticator: LdapAuthenticator, authorities: LdapAu == Active Directory -Active Directory supports its own non-standard authentication options, and the normal usage pattern doesn't fit too cleanly with the standard `LdapAuthenticationProvider`. -Typically authentication is performed using the domain username (in the form `user@domain`), rather than using an LDAP distinguished name. -To make this easier, Spring Security has an authentication provider which is customized for a typical Active Directory setup. +Active Directory supports its own non-standard authentication options, and the normal usage pattern does not fit too cleanly with the standard `LdapAuthenticationProvider`. +Typically, authentication is performed by using the domain username (in the form of `user@domain`), rather than using an LDAP distinguished name. +To make this easier, Spring Security has an authentication provider, which is customized for a typical Active Directory setup. Configuring `ActiveDirectoryLdapAuthenticationProvider` is quite straightforward. -You just need to supply the domain name and an LDAP URL supplying the address of the server footnote:[It is also possible to obtain the server's IP address using a DNS lookup. -This is not currently supported, but hopefully will be in a future version.]. -An example configuration can be seen below: +You need only supply the domain name and an LDAP URL that supplies the address of the server. + +[NOTE] +==== +It is also possible to obtain the server's IP address byusing a DNS lookup. +This is not currently supported, but hopefully will be in a future version. +==== + +The following example configures Active Directory: .Example Active Directory Configuration ==== diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/password-encoder.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/password-encoder.adoc index de20d29004b..1678b8274c8 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/password-encoder.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/password-encoder.adoc @@ -1,5 +1,5 @@ [[servlet-authentication-password-storage]] = PasswordEncoder -Spring Security's servlet support storing passwords securely by integrating with xref:features/authentication/password-storage.adoc#authentication-password-storage[`PasswordEncoder`]. -Customizing the `PasswordEncoder` implementation used by Spring Security can be done by xref:features/authentication/password-storage.adoc#authentication-password-storage-configuration[exposing a `PasswordEncoder` Bean]. +Spring Security's servlet support includes storing passwords securely by integrating with xref:features/authentication/password-storage.adoc#authentication-password-storage[`PasswordEncoder`]. +You can customize the `PasswordEncoder` implementation used by Spring Security by xref:features/authentication/password-storage.adoc#authentication-password-storage-configuration[exposing a `PasswordEncoder` Bean]. diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/storage.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/storage.adoc index 0462818a28d..8bcd1151cff 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/storage.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/storage.adoc @@ -2,7 +2,7 @@ = Storage Mechanisms :page-section-summary-toc: 1 -Each of the supported mechanisms for reading a username and password can leverage any of the supported storage mechanisms: +Each of the supported mechanisms for reading a username and password can use any of the supported storage mechanisms: * Simple Storage with xref:servlet/authentication/passwords/in-memory.adoc#servlet-authentication-inmemory[In-Memory Authentication] * Relational Databases with xref:servlet/authentication/passwords/jdbc.adoc#servlet-authentication-jdbc[JDBC Authentication] diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/user-details-service.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/user-details-service.adoc index d557c040410..50f4d934fd4 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/user-details-service.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/user-details-service.adoc @@ -1,13 +1,16 @@ [[servlet-authentication-userdetailsservice]] = UserDetailsService -{security-api-url}org/springframework/security/core/userdetails/UserDetailsService.html[`UserDetailsService`] is used by xref:servlet/authentication/passwords/dao-authentication-provider.adoc#servlet-authentication-daoauthenticationprovider[`DaoAuthenticationProvider`] for retrieving a username, password, and other attributes for authenticating with a username and password. +{security-api-url}org/springframework/security/core/userdetails/UserDetailsService.html[`UserDetailsService`] is used by xref:servlet/authentication/passwords/dao-authentication-provider.adoc#servlet-authentication-daoauthenticationprovider[`DaoAuthenticationProvider`] for retrieving a username, a password, and other attributes for authenticating with a username and password. Spring Security provides xref:servlet/authentication/passwords/in-memory.adoc#servlet-authentication-inmemory[in-memory] and xref:servlet/authentication/passwords/jdbc.adoc#servlet-authentication-jdbc[JDBC] implementations of `UserDetailsService`. You can define custom authentication by exposing a custom `UserDetailsService` as a bean. -For example, the following will customize authentication assuming that `CustomUserDetailsService` implements `UserDetailsService`: +For example, the following listing customizes authentication, assuming that `CustomUserDetailsService` implements `UserDetailsService`: -NOTE: This is only used if the `AuthenticationManagerBuilder` has not been populated and no `AuthenticationProviderBean` is defined. +[NOTE] +==== +This is only used if the `AuthenticationManagerBuilder` has not been populated and no `AuthenticationProviderBean` is defined. +==== .Custom UserDetailsService Bean ==== diff --git a/docs/modules/ROOT/pages/servlet/authentication/preauth.adoc b/docs/modules/ROOT/pages/servlet/authentication/preauth.adoc index 406c3f871fb..3aaf87093e1 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/preauth.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/preauth.adoc @@ -1,33 +1,29 @@ [[servlet-preauth]] = Pre-Authentication Scenarios There are situations where you want to use Spring Security for authorization, but the user has already been reliably authenticated by some external system prior to accessing the application. -We refer to these situations as "pre-authenticated" scenarios. -Examples include X.509, Siteminder and authentication by the Java EE container in which the application is running. -When using pre-authentication, Spring Security has to +We refer to these situations as "`pre-authenticated`" scenarios. +Examples include X.509, Siteminder, and authentication by the Java EE container in which the application runs. +When using pre-authentication, Spring Security has to: * Identify the user making the request. - * Obtain the authorities for the user. - -The details will depend on the external authentication mechanism. +The details depend on the external authentication mechanism. A user might be identified by their certificate information in the case of X.509, or by an HTTP request header in the case of Siteminder. -If relying on container authentication, the user will be identified by calling the `getUserPrincipal()` method on the incoming HTTP request. -In some cases, the external mechanism may supply role/authority information for the user but in others the authorities must be obtained from a separate source, such as a `UserDetailsService`. - +If relying on container authentication, the user is identified by calling the `getUserPrincipal()` method on the incoming HTTP request. +In some cases, the external mechanism may supply role and authority information for the user. However, in other cases, you must obtain the authorities from a separate source, such as a `UserDetailsService`. == Pre-Authentication Framework Classes -Because most pre-authentication mechanisms follow the same pattern, Spring Security has a set of classes which provide an internal framework for implementing pre-authenticated authentication providers. -This removes duplication and allows new implementations to be added in a structured fashion, without having to write everything from scratch. -You don't need to know about these classes if you want to use something like xref:servlet/authentication/x509.adoc#servlet-x509[X.509 authentication], as it already has a namespace configuration option which is simpler to use and get started with. -If you need to use explicit bean configuration or are planning on writing your own implementation then an understanding of how the provided implementations work will be useful. -You will find classes under the `org.springframework.security.web.authentication.preauth`. -We just provide an outline here so you should consult the Javadoc and source where appropriate. - +Because most pre-authentication mechanisms follow the same pattern, Spring Security has a set of classes that provide an internal framework for implementing pre-authenticated authentication providers. +This removes duplication and lets new implementations be added in a structured fashion, without having to write everything from scratch. +You need not know about these classes if you want to use something like xref:servlet/authentication/x509.adoc#servlet-x509[X.509 authentication], as it already has a namespace configuration option which is simpler to use and get started with. +If you need to use explicit bean configuration or are planning on writing your own implementation, you need an understanding of how the provided implementations work. +You can find the classes under the `org.springframework.security.web.authentication.preauth`. +We provide only an outline here, so you should consult the Javadoc and source where appropriate. === AbstractPreAuthenticatedProcessingFilter -This class will check the current contents of the security context and, if empty, it will attempt to extract user information from the HTTP request and submit it to the `AuthenticationManager`. -Subclasses override the following methods to obtain this information: +This class checks the current contents of the security context and, if it is empty, tries to extract user information from the HTTP request and submit it to the `AuthenticationManager`. +Subclasses override the following methods to obtain this information. .Override AbstractPreAuthenticatedProcessingFilter ==== @@ -49,24 +45,24 @@ protected abstract fun getPreAuthenticatedCredentials(request: HttpServletReques ==== -After calling these, the filter will create a `PreAuthenticatedAuthenticationToken` containing the returned data and submit it for authentication. -By "authentication" here, we really just mean further processing to perhaps load the user's authorities, but the standard Spring Security authentication architecture is followed. +After calling these, the filter creates a `PreAuthenticatedAuthenticationToken` that contains the returned data and submits it for authentication. +By "`authentication`" here, we really just mean further processing to perhaps load the user's authorities, but the standard Spring Security authentication architecture is followed. -Like other Spring Security authentication filters, the pre-authentication filter has an `authenticationDetailsSource` property which by default will create a `WebAuthenticationDetails` object to store additional information such as the session-identifier and originating IP address in the `details` property of the `Authentication` object. +As other Spring Security authentication filters, the pre-authentication filter has an `authenticationDetailsSource` property, which, by default, creates a `WebAuthenticationDetails` object to store additional information, such as the session identifier and the originating IP address in the `details` property of the `Authentication` object. In cases where user role information can be obtained from the pre-authentication mechanism, the data is also stored in this property, with the details implementing the `GrantedAuthoritiesContainer` interface. This enables the authentication provider to read the authorities which were externally allocated to the user. -We'll look at a concrete example next. +We look at a concrete example next. [[j2ee-preauth-details]] ==== J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource -If the filter is configured with an `authenticationDetailsSource` which is an instance of this class, the authority information is obtained by calling the `isUserInRole(String role)` method for each of a pre-determined set of "mappable roles". +If the filter is configured with an `authenticationDetailsSource`, which is an instance of this class, the authority information is obtained by calling the `isUserInRole(String role)` method for each of a pre-determined set of "`mappable roles`". The class gets these from a configured `MappableAttributesRetriever`. Possible implementations include hard-coding a list in the application context and reading the role information from the `` information in a `web.xml` file. The pre-authentication sample application uses the latter approach. -There is an additional stage where the roles (or attributes) are mapped to Spring Security `GrantedAuthority` objects using a configured `Attributes2GrantedAuthoritiesMapper`. -The default will just add the usual `ROLE_` prefix to the names, but it gives you full control over the behaviour. +There is an additional stage where the roles (or attributes) are mapped to Spring Security `GrantedAuthority` objects by using a configured `Attributes2GrantedAuthoritiesMapper`. +The default just adds the usual `ROLE_` prefix to the names, but it gives you full control over the behavior. === PreAuthenticatedAuthenticationProvider @@ -74,45 +70,48 @@ The pre-authenticated provider has little more to do than load the `UserDetails` It does this by delegating to an `AuthenticationUserDetailsService`. The latter is similar to the standard `UserDetailsService` but takes an `Authentication` object rather than just user name: +==== [source,java] ---- public interface AuthenticationUserDetailsService { UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException; } ---- +==== -This interface may have also other uses but with pre-authentication it allows access to the authorities which were packaged in the `Authentication` object, as we saw in the previous section. +This interface may also have other uses, but, with pre-authentication, it allows access to the authorities that were packaged in the `Authentication` object, as we saw in the previous section. The `PreAuthenticatedGrantedAuthoritiesUserDetailsService` class does this. -Alternatively, it may delegate to a standard `UserDetailsService` via the `UserDetailsByNameServiceWrapper` implementation. +Alternatively, it may delegate to a standard `UserDetailsService` through the `UserDetailsByNameServiceWrapper` implementation. === Http403ForbiddenEntryPoint -The xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is responsible for kick-starting the authentication process for an unauthenticated user (when they try to access a protected resource), but in the pre-authenticated case this doesn't apply. -You would only configure the `ExceptionTranslationFilter` with an instance of this class if you aren't using pre-authentication in combination with other authentication mechanisms. -It will be called if the user is rejected by the `AbstractPreAuthenticatedProcessingFilter` resulting in a null authentication. +The xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is responsible for kick-starting the authentication process for an unauthenticated user (when they try to access a protected resource). However, in the pre-authenticated case, this does not apply. +You would only configure the `ExceptionTranslationFilter` with an instance of this class if you do not use pre-authentication in combination with other authentication mechanisms. +It is called if the user is rejected by the `AbstractPreAuthenticatedProcessingFilter`, resulting in a null authentication. It always returns a `403`-forbidden response code if called. == Concrete Implementations X.509 authentication is covered in its xref:servlet/authentication/x509.adoc#servlet-x509[own chapter]. -Here we'll look at some classes which provide support for other pre-authenticated scenarios. +Here, we look at some classes which provide support for other pre-authenticated scenarios. === Request-Header Authentication (Siteminder) An external authentication system may supply information to the application by setting specific headers on the HTTP request. A well-known example of this is Siteminder, which passes the username in a header called `SM_USER`. -This mechanism is supported by the class `RequestHeaderAuthenticationFilter` which simply extracts the username from the header. -It defaults to using the name `SM_USER` as the header name. +This mechanism is supported by the `RequestHeaderAuthenticationFilter` class, which only extracts the username from the header. +It defaults to using a name of `SM_USER` as the header name. See the Javadoc for more details. [TIP] ==== -Note that when using a system like this, the framework performs no authentication checks at all and it is __extremely__ important that the external system is configured properly and protects all access to the application. -If an attacker is able to forge the headers in their original request without this being detected then they could potentially choose any username they wished. +When using a system like this, the framework performs no authentication checks at all, and it is _extremely_ important that the external system is configured properly and protects all access to the application. +If an attacker is able to forge the headers in their original request without this being detected, they could potentially choose any username they wished. ==== ==== Siteminder Example Configuration -A typical configuration using this filter would look like this: +The following example shows a typical configuration that uses this filter: +==== [source,xml] ---- @@ -138,13 +137,14 @@ A typical configuration using this filter would look like this: ---- +==== We've assumed here that the xref:servlet/configuration/xml-namespace.adoc#ns-config[security namespace] is being used for configuration. It's also assumed that you have added a `UserDetailsService` (called "userDetailsService") to your configuration to load the user's roles. === Java EE Container Authentication -The class `J2eePreAuthenticatedProcessingFilter` will extract the username from the `userPrincipal` property of the `HttpServletRequest`. -Use of this filter would usually be combined with the use of Java EE roles as described above in <>. +The `J2eePreAuthenticatedProcessingFilter` class extracts the username from the `userPrincipal` property of the `HttpServletRequest`. +Use of this filter would usually be combined with the use of Java EE roles, as described earlier in <>. -There is a {gh-old-samples-url}/xml/preauth[sample application] in the samples project which uses this approach, so get hold of the code from GitHub and have a look at the application context file if you are interested. +There is a {gh-old-samples-url}/xml/preauth[sample application] that uses this approach in the codebase, so get hold of the code from Github and have a look at the application context file if you are interested. diff --git a/docs/modules/ROOT/pages/servlet/authentication/rememberme.adoc b/docs/modules/ROOT/pages/servlet/authentication/rememberme.adoc index 5e75fc219e4..d6cd44cfe6a 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/rememberme.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/rememberme.adoc @@ -1,23 +1,22 @@ [[servlet-rememberme]] = Remember-Me Authentication - [[remember-me-overview]] -== Overview Remember-me or persistent-login authentication refers to web sites being able to remember the identity of a principal between sessions. This is typically accomplished by sending a cookie to the browser, with the cookie being detected during future sessions and causing automated login to take place. -Spring Security provides the necessary hooks for these operations to take place, and has two concrete remember-me implementations. +Spring Security provides the necessary hooks for these operations to take place and has two concrete remember-me implementations. One uses hashing to preserve the security of cookie-based tokens and the other uses a database or other persistent storage mechanism to store the generated tokens. Note that both implementations require a `UserDetailsService`. -If you are using an authentication provider which doesn't use a `UserDetailsService` (for example, the LDAP provider) then it won't work unless you also have a `UserDetailsService` bean in your application context. +If you use an authentication provider that does not use a `UserDetailsService` (for example, the LDAP provider), it does not work unless you also have a `UserDetailsService` bean in your application context. [[remember-me-hash-token]] == Simple Hash-Based Token Approach This approach uses hashing to achieve a useful remember-me strategy. -In essence a cookie is sent to the browser upon successful interactive authentication, with the cookie being composed as follows: +In essence, a cookie is sent to the browser upon successful interactive authentication, with the cookie being composed as follows: +==== [source,txt] ---- base64(username + ":" + expirationTime + ":" + @@ -28,16 +27,18 @@ password: That matches the one in the retrieved UserDetails expirationTime: The date and time when the remember-me token expires, expressed in milliseconds key: A private key to prevent modification of the remember-me token ---- +==== -As such the remember-me token is valid only for the period specified, and provided that the username, password and key does not change. -Notably, this has a potential security issue in that a captured remember-me token will be usable from any user agent until such time as the token expires. +The remember-me token is valid only for the period specified and only if the username, password, and key do not change. +Notably, this has a potential security issue, in that a captured remember-me token is usable from any user agent until such time as the token expires. This is the same issue as with digest authentication. -If a principal is aware a token has been captured, they can easily change their password and immediately invalidate all remember-me tokens on issue. -If more significant security is needed you should use the approach described in the next section. -Alternatively, remember-me services should simply not be used at all. +If a principal is aware that a token has been captured, they can easily change their password and immediately invalidate all remember-me tokens on issue. +If more significant security is needed, you should use the approach described in the next section. +Alternatively, remember-me services should not be used at all. -If you are familiar with the topics discussed in the chapter on xref:servlet/configuration/xml-namespace.adoc#ns-config[namespace configuration], you can enable remember-me authentication just by adding the `` element: +If you are familiar with the topics discussed in the chapter on xref:servlet/configuration/xml-namespace.adoc#ns-config[namespace configuration], you can enable remember-me authentication by adding the `` element: +==== [source,xml] ---- @@ -45,16 +46,18 @@ If you are familiar with the topics discussed in the chapter on xref:servlet/con ---- +==== -The `UserDetailsService` will normally be selected automatically. +The `UserDetailsService` is normally selected automatically. If you have more than one in your application context, you need to specify which one should be used with the `user-service-ref` attribute, where the value is the name of your `UserDetailsService` bean. [[remember-me-persistent-token]] == Persistent Token Approach -This approach is based on the article https://web.archive.org/web/20180819014446/http://jaspan.com/improved_persistent_login_cookie_best_practice[http://jaspan.com/improved_persistent_login_cookie_best_practice] with some minor modifications footnote:[Essentially, the username is not included in the cookie, to prevent exposing a valid login name unecessarily. -There is a discussion on this in the comments section of this article.]. -To use the this approach with namespace configuration, you would supply a datasource reference: +This approach is based on the article titled http://jaspan.com/improved_persistent_login_cookie_best_practice[http://jaspan.com/improved_persistent_login_cookie_best_practice], with some minor modifications. (Essentially, the username is not included in the cookie, to prevent exposing a valid login name unecessarily. +There is a discussion on this in the comments section of this article.) +To use the this approach with namespace configuration, supply a datasource reference: +==== [source,xml] ---- @@ -62,9 +65,11 @@ To use the this approach with namespace configuration, you would supply a dataso ---- +==== -The database should contain a `persistent_logins` table, created using the following SQL (or equivalent): +The database should contain a `persistent_logins` table, created by using the following SQL (or equivalent): +==== [source,ddl] ---- create table persistent_logins (username varchar(64) not null, @@ -72,14 +77,16 @@ create table persistent_logins (username varchar(64) not null, token varchar(64) not null, last_used timestamp not null) ---- +==== [[remember-me-impls]] == Remember-Me Interfaces and Implementations -Remember-me is used with `UsernamePasswordAuthenticationFilter`, and is implemented via hooks in the `AbstractAuthenticationProcessingFilter` superclass. +Remember-me is used with `UsernamePasswordAuthenticationFilter` and is implemented through hooks in the `AbstractAuthenticationProcessingFilter` superclass. It is also used within `BasicAuthenticationFilter`. -The hooks will invoke a concrete `RememberMeServices` at the appropriate times. -The interface looks like this: +The hooks invoke a concrete `RememberMeServices` at the appropriate times. +The following listing shows the interface: +==== [source,java] ---- Authentication autoLogin(HttpServletRequest request, HttpServletResponse response); @@ -89,24 +96,26 @@ void loginFail(HttpServletRequest request, HttpServletResponse response); void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication); ---- +==== -Please refer to the Javadoc for a fuller discussion on what the methods do, although note at this stage that `AbstractAuthenticationProcessingFilter` only calls the `loginFail()` and `loginSuccess()` methods. +See the Javadoc for {security-api-url}org/springframework/security/web/authentication/RememberMeServices.html[`RememberMeServices`] for a fuller discussion on what the methods do, although note that, at this stage, `AbstractAuthenticationProcessingFilter` calls only the `loginFail()` and `loginSuccess()` methods. The `autoLogin()` method is called by `RememberMeAuthenticationFilter` whenever the `SecurityContextHolder` does not contain an `Authentication`. -This interface therefore provides the underlying remember-me implementation with sufficient notification of authentication-related events, and delegates to the implementation whenever a candidate web request might contain a cookie and wish to be remembered. +This interface, therefore, provides the underlying remember-me implementation with sufficient notification of authentication-related events and delegates to the implementation whenever a candidate web request might contain a cookie and wish to be remembered. This design allows any number of remember-me implementation strategies. -We've seen above that Spring Security provides two implementations. -We'll look at these in turn. + +We have seen earlier that Spring Security provides two implementations. +We look at each of these in turn. === TokenBasedRememberMeServices This implementation supports the simpler approach described in <>. `TokenBasedRememberMeServices` generates a `RememberMeAuthenticationToken`, which is processed by `RememberMeAuthenticationProvider`. A `key` is shared between this authentication provider and the `TokenBasedRememberMeServices`. -In addition, `TokenBasedRememberMeServices` requires A UserDetailsService from which it can retrieve the username and password for signature comparison purposes, and generate the `RememberMeAuthenticationToken` to contain the correct ``GrantedAuthority``s. -Some sort of logout command should be provided by the application that invalidates the cookie if the user requests this. -`TokenBasedRememberMeServices` also implements Spring Security's `LogoutHandler` interface so can be used with `LogoutFilter` to have the cookie cleared automatically. +In addition, `TokenBasedRememberMeServices` requires a `UserDetailsService`, from which it can retrieve the username and password for signature comparison purposes and generate the `RememberMeAuthenticationToken` to contain the correct `GrantedAuthority` instances. +`TokenBasedRememberMeServices` also implements Spring Security's `LogoutHandler` interface so that it can be used with `LogoutFilter` to have the cookie cleared automatically. -The beans required in an application context to enable remember-me services are as follows: +The following beans are required in an application context to enable remember-me services: +==== [source,xml] ---- ---- +==== -Don't forget to add your `RememberMeServices` implementation to your `UsernamePasswordAuthenticationFilter.setRememberMeServices()` property, include the `RememberMeAuthenticationProvider` in your `AuthenticationManager.setProviders()` list, and add `RememberMeAuthenticationFilter` into your `FilterChainProxy` (typically immediately after your `UsernamePasswordAuthenticationFilter`). +Remember to add your `RememberMeServices` implementation to your `UsernamePasswordAuthenticationFilter.setRememberMeServices()` property, include the `RememberMeAuthenticationProvider` in your `AuthenticationManager.setProviders()` list, and add `RememberMeAuthenticationFilter` into your `FilterChainProxy` (typically immediately after your `UsernamePasswordAuthenticationFilter`). === PersistentTokenBasedRememberMeServices -This class can be used in the same way as `TokenBasedRememberMeServices`, but it additionally needs to be configured with a `PersistentTokenRepository` to store the tokens. -There are two standard implementations. +You can use this class in the same way as `TokenBasedRememberMeServices`, but it additionally needs to be configured with a `PersistentTokenRepository` to store the tokens. * `InMemoryTokenRepositoryImpl` which is intended for testing only. * `JdbcTokenRepositoryImpl` which stores the tokens in a database. -The database schema is described above in <>. +See <> for the database schema. diff --git a/docs/modules/ROOT/pages/servlet/authentication/runas.adoc b/docs/modules/ROOT/pages/servlet/authentication/runas.adoc index 258e5a033c7..5d09ce5bddd 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/runas.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/runas.adoc @@ -2,19 +2,19 @@ = Run-As Authentication Replacement [[runas-overview]] -== Overview The `AbstractSecurityInterceptor` is able to temporarily replace the `Authentication` object in the `SecurityContext` and `SecurityContextHolder` during the secure object callback phase. This only occurs if the original `Authentication` object was successfully processed by the `AuthenticationManager` and `AccessDecisionManager`. -The `RunAsManager` will indicate the replacement `Authentication` object, if any, that should be used during the `SecurityInterceptorCallback`. +The `RunAsManager` indicates the replacement `Authentication` object, if any, that should be used during the `SecurityInterceptorCallback`. -By temporarily replacing the `Authentication` object during the secure object callback phase, the secured invocation will be able to call other objects which require different authentication and authorization credentials. -It will also be able to perform any internal security checks for specific `GrantedAuthority` objects. +By temporarily replacing the `Authentication` object during the secure object callback phase, the secured invocation can call other objects that require different authentication and authorization credentials. +It can also perform any internal security checks for specific `GrantedAuthority` objects. Because Spring Security provides a number of helper classes that automatically configure remoting protocols based on the contents of the `SecurityContextHolder`, these run-as replacements are particularly useful when calling remote web services. [[runas-config]] == Configuration -A `RunAsManager` interface is provided by Spring Security: +Spring Security provices a `RunAsManager` interface: +==== [source,java] ---- Authentication buildRunAs(Authentication authentication, Object object, @@ -24,31 +24,31 @@ boolean supports(ConfigAttribute attribute); boolean supports(Class clazz); ---- - +==== The first method returns the `Authentication` object that should replace the existing `Authentication` object for the duration of the method invocation. If the method returns `null`, it indicates no replacement should be made. The second method is used by the `AbstractSecurityInterceptor` as part of its startup validation of configuration attributes. -The `supports(Class)` method is called by a security interceptor implementation to ensure the configured `RunAsManager` supports the type of secure object that the security interceptor will present. +The `supports(Class)` method is called by a security interceptor implementation to ensure that the configured `RunAsManager` supports the type of secure object that the security interceptor presents. -One concrete implementation of a `RunAsManager` is provided with Spring Security. +Spring Security provides one concrete implementation of `RunAsManager`. The `RunAsManagerImpl` class returns a replacement `RunAsUserToken` if any `ConfigAttribute` starts with `RUN_AS_`. -If any such `ConfigAttribute` is found, the replacement `RunAsUserToken` will contain the same principal, credentials and granted authorities as the original `Authentication` object, along with a new `SimpleGrantedAuthority` for each `RUN_AS_` `ConfigAttribute`. -Each new `SimpleGrantedAuthority` will be prefixed with `ROLE_`, followed by the `RUN_AS` `ConfigAttribute`. -For example, a `RUN_AS_SERVER` will result in the replacement `RunAsUserToken` containing a `ROLE_RUN_AS_SERVER` granted authority. +If any such `ConfigAttribute` is found, the replacement `RunAsUserToken` contains the same principal, credentials, and granted authorities as the original `Authentication` object, along with a new `SimpleGrantedAuthority` for each `RUN_AS_` `ConfigAttribute`. +Each new `SimpleGrantedAuthority` is prefixed with `ROLE_`, followed by the `RUN_AS` `ConfigAttribute`. +For example, a `RUN_AS_SERVER` results in the replacement `RunAsUserToken` containing a `ROLE_RUN_AS_SERVER` granted authority. -The replacement `RunAsUserToken` is just like any other `Authentication` object. -It needs to be authenticated by the `AuthenticationManager`, probably via delegation to a suitable `AuthenticationProvider`. +The replacement `RunAsUserToken` is like any other `Authentication` object. +It needs to be authenticated by the `AuthenticationManager`, probably through delegation to a suitable `AuthenticationProvider`. The `RunAsImplAuthenticationProvider` performs such authentication. -It simply accepts as valid any `RunAsUserToken` presented. +It accepts as valid any `RunAsUserToken` presented. To ensure malicious code does not create a `RunAsUserToken` and present it for guaranteed acceptance by the `RunAsImplAuthenticationProvider`, the hash of a key is stored in all generated tokens. The `RunAsManagerImpl` and `RunAsImplAuthenticationProvider` is created in the bean context with the same key: +==== [source,xml] ---- - @@ -59,8 +59,7 @@ The `RunAsManagerImpl` and `RunAsImplAuthenticationProvider` is created in the b ---- +==== - - -By using the same key, each `RunAsUserToken` can be validated it was created by an approved `RunAsManagerImpl`. -The `RunAsUserToken` is immutable after creation for security reasons +By using the same key, each `RunAsUserToken` can be validated because it was created by an approved `RunAsManagerImpl`. +The `RunAsUserToken` is immutable after creation, for security reasons. diff --git a/docs/modules/ROOT/pages/servlet/authentication/session-management.adoc b/docs/modules/ROOT/pages/servlet/authentication/session-management.adoc index 6024d34a1bd..eb77f3cecb3 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/session-management.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/session-management.adoc @@ -1,11 +1,11 @@ [[session-mgmt]] = Session Management -HTTP session related functionality is handled by a combination of the `SessionManagementFilter` and the `SessionAuthenticationStrategy` interface, which the filter delegates to. -Typical usage includes session-fixation protection attack prevention, detection of session timeouts and restrictions on how many sessions an authenticated user may have open concurrently. +HTTP session-related functionality is handled by a combination of the {security-api-url}org/springframework/security/authentication/AuthenticationProvider.html[`SessionManagementFilter`] and the {security-api-url}org/springframework/security/web/authentication/session/SessionAuthenticationStrategy.html[`SessionAuthenticationStrategy`] interface, to which the filter delegates. +Typical usage includes session-fixation protection attack prevention, detection of session timeouts, and restrictions on how many sessions an authenticated user may have open concurrently. == Detecting Timeouts You can configure Spring Security to detect the submission of an invalid session ID and redirect the user to an appropriate URL. -This is achieved through the `session-management` element: +To do so, configure the `session-management` element: ==== .Java @@ -30,9 +30,9 @@ protected void configure(HttpSecurity http) throws Exception{ ---- ==== -Note that if you use this mechanism to detect session timeouts, it may falsely report an error if the user logs out and then logs back in without closing the browser. -This is because the session cookie is not cleared when you invalidate the session and will be resubmitted even if the user has logged out. -You may be able to explicitly delete the JSESSIONID cookie on logging out, for example by using the following syntax in the logout handler: +Note that, if you use this mechanism to detect session timeouts, it may falsely report an error if the user logs out and then logs back in without closing the browser. +This is because the session cookie is not cleared when you invalidate the session and is resubmitted even if the user has logged out. +You may be able to explicitly delete the `JSESSIONID` cookie on logging out -- for example, by using the following syntax in the logout handler: ==== .Java @@ -57,13 +57,15 @@ protected void configure(HttpSecurity http) throws Exception{ ==== -Unfortunately this can't be guaranteed to work with every servlet container, so you will need to test it in your environment +Unfortunately, this cannot be guaranteed to work with every servlet container, so you need to test it in your environment. [NOTE] -==== -If you are running your application behind a proxy, you may also be able to remove the session cookie by configuring the proxy server. -For example, using Apache HTTPD's mod_headers, the following directive would delete the `JSESSIONID` cookie by expiring it in the response to a logout request (assuming the application is deployed under the path `/tutorial`): +===== +If you run your application behind a proxy, you may also be able to remove the session cookie by configuring the proxy server. +For example, by using Apache HTTPD's `mod_headers`, the following directive deletes the `JSESSIONID` cookie by expiring it in the response to a logout request (assuming the application is deployed under the `/tutorial` path): +===== +==== [source,xml] ---- @@ -75,8 +77,8 @@ Header always set Set-Cookie "JSESSIONID=;Path=/tutorial;Expires=Thu, 01 Jan 197 [[ns-concurrent-sessions]] == Concurrent Session Control -If you wish to place constraints on a single user's ability to log in to your application, Spring Security supports this out of the box with the following simple additions. -First, you need to add the following listener to your configuration to keep Spring Security updated about session lifecycle events: +If you wish to place constraints on a single user's ability to log in to your application, Spring Security supports this with the following simple additions. +First, you need to add the following listener to your `web.xml` file to keep Spring Security updated about session lifecycle events: ==== .Java @@ -126,9 +128,8 @@ protected void configure(HttpSecurity http) throws Exception { ---- ==== - -This will prevent a user from logging in multiple times - a second login will cause the first to be invalidated. -Often you would prefer to prevent a second login, in which case you can use +These changes prevent a user from logging in multiple times. A second login causes the first to be invalidated. +Often, you would prefer to prevent a second login. In that case, you can use: ==== .Java @@ -155,48 +156,49 @@ protected void configure(HttpSecurity http) throws Exception { ---- ==== +The second login is then rejected. +By "`rejected`", we mean that the user is sent to the `authentication-failure-url` if form-based login is being used. +If the second authentication takes place through another non-interactive mechanism, such as "`remember-me`", an "`unauthorized`" (401) error is sent to the client. +If, instead, you want to use an error page, you can add the `session-authentication-error-url` attribute to the `session-management` element. -The second login will then be rejected. -By "rejected", we mean that the user will be sent to the `authentication-failure-url` if form-based login is being used. -If the second authentication takes place through another non-interactive mechanism, such as "remember-me", an "unauthorized" (401) error will be sent to the client. -If instead you want to use an error page, you can add the attribute `session-authentication-error-url` to the `session-management` element. - -If you are using a customized authentication filter for form-based login, then you have to configure concurrent session control support explicitly. -More details can be found in the <>. +If you use a customized authentication filter for form-based login, you have to configure concurrent session control support explicitly. +You can find more details in the <>. [[ns-session-fixation]] == Session Fixation Attack Protection -https://en.wikipedia.org/wiki/Session_fixation[Session fixation] attacks are a potential risk where it is possible for a malicious attacker to create a session by accessing a site, then persuade another user to log in with the same session (by sending them a link containing the session identifier as a parameter, for example). -Spring Security protects against this automatically by creating a new session or otherwise changing the session ID when a user logs in. -If you don't require this protection, or it conflicts with some other requirement, you can control the behavior using the `session-fixation-protection` attribute on ``, which has four options +https://en.wikipedia.org/wiki/Session_fixation[Session fixation] attacks are a potential risk where it is possible for a malicious attacker to create a session by accessing a site and then persuade another user to log in with the same session (by sending them a link containing the session identifier as a parameter, for example). +Spring Security automatically protects against this by creating a new session or otherwise changing the session ID when a user logs in. +If you do not require this protection or it conflicts with some other requirement, you can control the behavior setting the `session-fixation-protection` attribute on ``, which has four options -* `none` - Don't do anything. -The original session will be retained. +* `none`: Do nothing. +The original session is retained. -* `newSession` - Create a new "clean" session, without copying the existing session data (Spring Security-related attributes will still be copied). +* `newSession`: Create a new, "`clean`" session, without copying the existing session data (Spring Security-related attributes are still copied). -* `migrateSession` - Create a new session and copy all existing session attributes to the new session. +* `migrateSession`: Create a new session and copy all existing session attributes to the new session. This is the default in Servlet 3.0 or older containers. -* `changeSessionId` - Do not create a new session. +* `changeSessionId`: Do not create a new session. Instead, use the session fixation protection provided by the Servlet container (`HttpServletRequest#changeSessionId()`). -This option is only available in Servlet 3.1 (Java EE 7) and newer containers. -Specifying it in older containers will result in an exception. -This is the default in Servlet 3.1 and newer containers. - +This option is available only in Servlet 3.1 (Java EE 7) and newer containers, where it is the default. +Specifying it in older containers results in an exception. When session fixation protection occurs, it results in a `SessionFixationProtectionEvent` being published in the application context. -If you use `changeSessionId`, this protection will __also__ result in any ``javax.servlet.http.HttpSessionIdListener``s being notified, so use caution if your code listens for both events. +If you use `changeSessionId`, this protection will _also_ result in any `javax.servlet.http.HttpSessionIdListener` instances being notified, so use caution if your code listens for both events. See the <> chapter for additional information. == SessionManagementFilter -The `SessionManagementFilter` checks the contents of the `SecurityContextRepository` against the current contents of the `SecurityContextHolder` to determine whether a user has been authenticated during the current request, typically by a non-interactive authentication mechanism, such as pre-authentication or remember-me footnote:[ -Authentication by mechanisms which perform a redirect after authenticating (such as form-login) will not be detected by `SessionManagementFilter`, as the filter will not be invoked during the authenticating request. +TThe `SessionManagementFilter` checks the contents of the `SecurityContextRepository` against the current contents of the `SecurityContextHolder` to determine whether a user has been authenticated during the current request, typically by a non-interactive authentication mechanism, such as pre-authentication or remember-me + +[NOTE] +==== +Authentication by mechanisms that perform a redirect after authenticating (such as form-login) are not detected by `SessionManagementFilter`, as the filter is not invoked during the authenticating request. Session-management functionality has to be handled separately in these cases. -]. +==== + If the repository contains a security context, the filter does nothing. -If it doesn't, and the thread-local `SecurityContext` contains a (non-anonymous) `Authentication` object, the filter assumes they have been authenticated by a previous filter in the stack. -It will then invoke the configured `SessionAuthenticationStrategy`. +If it does not and the thread-local `SecurityContext` contains a (non-anonymous) `Authentication` object, the filter assumes they have been authenticated by a previous filter in the stack. +It then invokes the configured `SessionAuthenticationStrategy`. If the user is not currently authenticated, the filter will check whether an invalid session ID has been requested (because of a timeout, for example) and will invoke the configured `InvalidSessionStrategy`, if one is set. The most common behaviour is just to redirect to a fixed URL and this is encapsulated in the standard implementation `SimpleRedirectInvalidSessionStrategy`. @@ -204,12 +206,12 @@ The latter is also used when configuring an invalid session URL through the name == SessionAuthenticationStrategy -`SessionAuthenticationStrategy` is used by both `SessionManagementFilter` and `AbstractAuthenticationProcessingFilter`, so if you are using a customized form-login class, for example, you will need to inject it into both of these. -In this case, a typical configuration, combining the namespace and custom beans might look like this: +`SessionAuthenticationStrategy` is used by both `SessionManagementFilter` and `AbstractAuthenticationProcessingFilter`, so, if you are using a customized form-login class, for example, you need to inject it into both of these. +In this case, a typical configuration that combines the namespace and custom beans might look like this: +==== [source,xml] ---- - @@ -223,56 +225,56 @@ In this case, a typical configuration, combining the namespace and custom beans - ---- +==== -Note that the use of the default, `SessionFixationProtectionStrategy` may cause issues if you are storing beans in the session which implement `HttpSessionBindingListener`, including Spring session-scoped beans. -See the Javadoc for this class for more information. +Note that the use of the default, `SessionFixationProtectionStrategy`, may cause issues if you are storing beans in the session that implement `HttpSessionBindingListener`, including Spring session-scoped beans. +See the Javadoc for this Java class for more information. [[concurrent-sessions]] == Concurrency Control -Spring Security is able to prevent a principal from concurrently authenticating to the same application more than a specified number of times. -Many ISVs take advantage of this to enforce licensing, whilst network administrators like this feature because it helps prevent people from sharing login names. -You can, for example, stop user "Batman" from logging onto the web application from two different sessions. +Spring Security can prevent a principal from concurrently authenticating to the same application more than a specified number of times. +Many ISVs take advantage of this to enforce licensing, while network administrators like this feature because it helps prevent people from sharing login names. +You can, for example, stop user `Batman` from logging onto the web application from two different sessions. You can either expire their previous login or you can report an error when they try to log in again, preventing the second login. -Note that if you are using the second approach, a user who has not explicitly logged out (but who has just closed their browser, for example) will not be able to log in again until their original session expires. +Note that, if you use the second approach, a user who has not explicitly logged out (but who has just closed their browser, for example) cannot log in again until their original session expires. +//FIXME: Add a link to the namespace chapter. Concurrency control is supported by the namespace, so please check the earlier namespace chapter for the simplest configuration. -Sometimes you need to customize things though. +Sometimes, though, you need to customize things. The implementation uses a specialized version of `SessionAuthenticationStrategy`, called `ConcurrentSessionControlAuthenticationStrategy`. + [NOTE] ==== - -Previously the concurrent authentication check was made by the `ProviderManager`, which could be injected with a `ConcurrentSessionController`. +Previously, the concurrent authentication check was made by the `ProviderManager`, which could be injected with a `ConcurrentSessionController`. The latter would check if the user was attempting to exceed the number of permitted sessions. However, this approach required that an HTTP session be created in advance, which is undesirable. -In Spring Security 3, the user is first authenticated by the `AuthenticationManager` and once they are successfully authenticated, a session is created and the check is made whether they are allowed to have another session open. - +In Spring Security 3 and later, the user is first authenticated by the `AuthenticationManager` and once they are successfully authenticated, a session is created and the check is made whether they are allowed to have another session open. ==== +To use concurrent session support, you need to add the following to `web.xml`: -To use concurrent session support, you'll need to add the following to `web.xml`: - +==== [source,xml] ---- - org.springframework.security.web.session.HttpSessionEventPublisher ---- +==== +In addition, you need to add the `ConcurrentSessionFilter` to your `FilterChainProxy`. +The `ConcurrentSessionFilter` requires two constructor arguments: +* `sessionRegistry`, which generally points to an instance of `SessionRegistryImpl` +* `sessionInformationExpiredStrategy`, which defines the strategy to apply when a session has expired +The following sample configuration uses the namespace to create the `FilterChainProxy` and other default beans: - -In addition, you will need to add the `ConcurrentSessionFilter` to your `FilterChainProxy`. -The `ConcurrentSessionFilter` requires two constructor arguments, `sessionRegistry`, which generally points to an instance of `SessionRegistryImpl`, and `sessionInformationExpiredStrategy`, which defines the strategy to apply when a session has expired. -A configuration using the namespace to create the `FilterChainProxy` and other default beans might look like this: - +==== [source,xml] ---- - @@ -316,25 +318,24 @@ class="org.springframework.security.web.session.ConcurrentSessionFilter"> - ---- - +==== Adding the listener to `web.xml` causes an `ApplicationEvent` to be published to the Spring `ApplicationContext` every time a `HttpSession` commences or ends. -This is critical, as it allows the `SessionRegistryImpl` to be notified when a session ends. -Without it, a user will never be able to log back in again once they have exceeded their session allowance, even if they log out of another session or it times out. +This is critical, as it lets the `SessionRegistryImpl` be notified when a session ends. +Without it, a user can never log back in again once they have exceeded their session allowance, even if they log out of another session or it times out. [[list-authenticated-principals]] === Querying the SessionRegistry for currently authenticated users and their sessions -Setting up concurrency-control, either through the namespace or using plain beans has the useful side effect of providing you with a reference to the `SessionRegistry` which you can use directly within your application, so even if you don't want to restrict the number of sessions a user may have, it may be worth setting up the infrastructure anyway. -You can set the `maximumSession` property to -1 to allow unlimited sessions. -If you're using the namespace, you can set an alias for the internally-created `SessionRegistry` using the `session-registry-alias` attribute, providing a reference which you can inject into your own beans. +Setting up concurrency control, either through the namespace or using plain beans has the useful side effect of providing you with a reference to the `SessionRegistry` that you can use directly within your application. So, even if you do not want to restrict the number of sessions a user may have, it may be worth setting up the infrastructure anyway. +You can set the `maximumSession` property to `-1` to allow unlimited sessions. +If you use the namespace, you can set an alias for the internally-created `SessionRegistry` by using the `session-registry-alias` attribute, providing a reference that you can inject into your own beans. The `getAllPrincipals()` method supplies you with a list of the currently authenticated users. You can list a user's sessions by calling the `getAllSessions(Object principal, boolean includeExpiredSessions)` method, which returns a list of `SessionInformation` objects. You can also expire a user's session by calling `expireNow()` on a `SessionInformation` instance. -When the user returns to the application, they will be prevented from proceeding. +When the user returns to the application, they are prevented from proceeding. You may find these methods useful in an administration application, for example. -Have a look at the Javadoc for more information. +See the Javadoc for more information about the {security-api-url}org/springframework/security/core/session/SessionRegistry.html[`SessionRegistry`] interface. diff --git a/docs/modules/ROOT/pages/servlet/authentication/x509.adoc b/docs/modules/ROOT/pages/servlet/authentication/x509.adoc index 5dc29b08d15..f7b12cb7ac4 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/x509.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/x509.adoc @@ -1,28 +1,27 @@ [[servlet-x509]] = X.509 Authentication - [[x509-overview]] -== Overview The most common use of X.509 certificate authentication is in verifying the identity of a server when using SSL, most commonly when using HTTPS from a browser. -The browser will automatically check that the certificate presented by a server has been issued (ie digitally signed) by one of a list of trusted certificate authorities which it maintains. +The browser automatically checks that the certificate presented by a server has been issued (digitally signed) by one of a list of trusted certificate authorities that it maintains. -You can also use SSL with "mutual authentication"; the server will then request a valid certificate from the client as part of the SSL handshake. -The server will authenticate the client by checking that its certificate is signed by an acceptable authority. +You can also use SSL with "`mutual authentication`". The server then requests a valid certificate from the client as part of the SSL handshake. +The server authenticates the client by checking that its certificate is signed by an acceptable authority. If a valid certificate has been provided, it can be obtained through the servlet API in an application. -Spring Security X.509 module extracts the certificate using a filter. +The Spring Security X.509 module extracts the certificate by using a filter. It maps the certificate to an application user and loads that user's set of granted authorities for use with the standard Spring Security infrastructure. -You should be familiar with using certificates and setting up client authentication for your servlet container before attempting to use it with Spring Security. -Most of the work is in creating and installing suitable certificates and keys. -For example, if you're using Tomcat then read the instructions here https://tomcat.apache.org/tomcat-9.0-doc/ssl-howto.html[https://tomcat.apache.org/tomcat-9.0-doc/ssl-howto.html]. -It's important that you get this working before trying it out with Spring Security +You can also use SSL with "`mutual authentication`". The server then requests a valid certificate from the client as part of the SSL handshake. +The server authenticates the client by checking that its certificate is signed by an acceptable authority. +For example, if you use Tomcat, you should read the https://tomcat.apache.org/tomcat-9.0-doc/ssl-howto.html[Tomcat SSL instructions]. +You should get this working before trying it out with Spring Security. == Adding X.509 Authentication to Your Web Application Enabling X.509 client authentication is very straightforward. -Just add the `` element to your http security namespace configuration. +To do so, add the `` element to your http security namespace configuration: +==== [source,xml] ---- @@ -30,39 +29,40 @@ Just add the `` element to your http security namespace configuration. ; ---- +==== The element has two optional attributes: * `subject-principal-regex`. The regular expression used to extract a username from the certificate's subject name. -The default value is shown above. -This is the username which will be passed to the `UserDetailsService` to load the authorities for the user. +The default value is shown in the preceding listing. +This is the username that is passed to the `UserDetailsService` to load the authorities for the user. * `user-service-ref`. -This is the bean Id of the `UserDetailsService` to be used with X.509. -It isn't needed if there is only one defined in your application context. +This is the bean ID of the `UserDetailsService` to be used with X.509. +It is not needed if there is only one defined in your application context. The `subject-principal-regex` should contain a single group. -For example the default expression "CN=(.*?)," matches the common name field. -So if the subject name in the certificate is "CN=Jimi Hendrix, OU=...", this will give a user name of "Jimi Hendrix". +For example, the default expression (`CN=(.*?)`) matches the common name field. +So, if the subject name in the certificate is "CN=Jimi Hendrix, OU=...", this gives a user name of "Jimi Hendrix". The matches are case insensitive. -So "emailAddress=(+.*?+)," will match "EMAILADDRESS=jimi@hendrix.org,CN=..." giving a user name "jimi@hendrix.org". -If the client presents a certificate and a valid username is successfully extracted, then there should be a valid `Authentication` object in the security context. -If no certificate is found, or no corresponding user could be found then the security context will remain empty. -This means that you can easily use X.509 authentication with other options such as a form-based login. +So "emailAddress=(+.*?+)," matches "EMAILADDRESS=jimi@hendrix.org,CN=...", giving a user name "jimi@hendrix.org". +If the client presents a certificate and a valid username is successfully extracted, there should be a valid `Authentication` object in the security context. +If no certificate is found or no corresponding user could be found, the security context remains empty. +This means that you can use X.509 authentication with other options, such as a form-based login. [[x509-ssl-config]] == Setting up SSL in Tomcat There are some pre-generated certificates in the {gh-samples-url}/servlet/java-configuration/authentication/x509/server[Spring Security Samples repository]. -You can use these to enable SSL for testing if you don't want to generate your own. -The file `server.jks` contains the server certificate, private key and the issuing certificate authority certificate. +You can use these to enable SSL for testing if you do not want to generate your own. +The `server.jks` file contains the server certificate, the private key, and the issuing authority certificate. There are also some client certificate files for the users from the sample applications. You can install these in your browser to enable SSL client authentication. -To run tomcat with SSL support, drop the `server.jks` file into the tomcat `conf` directory and add the following connector to the `server.xml` file +To run tomcat with SSL support, drop the `server.jks` file into the tomcat `conf` directory and add the following connector to the `server.xml` file: +==== [source,xml] ---- - - ---- +==== -`clientAuth` can also be set to `want` if you still want SSL connections to succeed even if the client doesn't provide a certificate. -Clients which don't present a certificate won't be able to access any objects secured by Spring Security unless you use a non-X.509 authentication mechanism, such as form authentication. +`clientAuth` can also be set to `want` if you still want SSL connections to succeed even if the client does not provide a certificate. +Clients that do not present a certificate cannot access any objects secured by Spring Security unless you use a non-X.509 authentication mechanism, such as form authentication. diff --git a/docs/modules/ROOT/pages/servlet/authorization/acls.adoc b/docs/modules/ROOT/pages/servlet/authorization/acls.adoc index 1735e9000b3..fe700366bfa 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/acls.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/acls.adoc @@ -1,75 +1,73 @@ [[domain-acls]] = Domain Object Security (ACLs) +This section describes how Spring Security provides domain object security with Access Control Lists (ACLs). + [[domain-acls-overview]] -== Overview -Complex applications often will find the need to define access permissions not simply at a web request or method invocation level. -Instead, security decisions need to comprise both who (`Authentication`), where (`MethodInvocation`) and what (`SomeDomainObject`). +Complex applications often need to define access permissions beyond a web request or method invocation level. +Instead, security decisions need to comprise who (`Authentication`), where (`MethodInvocation`), and what (`SomeDomainObject`). In other words, authorization decisions also need to consider the actual domain object instance subject of a method invocation. -Imagine you're designing an application for a pet clinic. -There will be two main groups of users of your Spring-based application: staff of the pet clinic, as well as the pet clinic's customers. -The staff will have access to all of the data, whilst your customers will only be able to see their own customer records. -To make it a little more interesting, your customers can allow other users to see their customer records, such as their "puppy preschool" mentor or president of their local "Pony Club". -Using Spring Security as the foundation, you have several approaches that can be used: +Imagine you are designing an application for a pet clinic. +There are two main groups of users of your Spring-based application: staff of the pet clinic and the pet clinic's customers. +The staff should have access to all of the data, while your customers should be able to see only their own customer records. +To make it a little more interesting, your customers can let other users see their customer records, such as their "`puppy preschool`" mentor or the president of their local "`Pony Club`". +When you use Spring Security as the foundation, you have several possible approaches: * Write your business methods to enforce the security. You could consult a collection within the `Customer` domain object instance to determine which users have access. -By using the `SecurityContextHolder.getContext().getAuthentication()`, you'll be able to access the `Authentication` object. -* Write an `AccessDecisionVoter` to enforce the security from the ``GrantedAuthority[]``s stored in the `Authentication` object. -This would mean your `AuthenticationManager` would need to populate the `Authentication` with custom ``GrantedAuthority[]``s representing each of the `Customer` domain object instances the principal has access to. +By using `SecurityContextHolder.getContext().getAuthentication()`, you can access the `Authentication` object. +* Write an `AccessDecisionVoter` to enforce the security from the `GrantedAuthority[]` instances stored in the `Authentication` object. +This means that your `AuthenticationManager` needs to populate the `Authentication` with custom `GrantedAuthority[]` objects to represent each of the `Customer` domain object instances to which the principal has access. * Write an `AccessDecisionVoter` to enforce the security and open the target `Customer` domain object directly. -This would mean your voter needs access to a DAO that allows it to retrieve the `Customer` object. -It would then access the `Customer` object's collection of approved users and make the appropriate decision. - +This would mean your voter needs access to a DAO that lets it retrieve the `Customer` object. +It can then access the `Customer` object's collection of approved users and make the appropriate decision. Each one of these approaches is perfectly legitimate. However, the first couples your authorization checking to your business code. -The main problems with this include the enhanced difficulty of unit testing and the fact it would be more difficult to reuse the `Customer` authorization logic elsewhere. -Obtaining the ``GrantedAuthority[]``s from the `Authentication` object is also fine, but will not scale to large numbers of ``Customer``s. -If a user might be able to access 5,000 ``Customer``s (unlikely in this case, but imagine if it were a popular vet for a large Pony Club!) the amount of memory consumed and time required to construct the `Authentication` object would be undesirable. +The main problems with this include the enhanced difficulty of unit testing and the fact that it would be more difficult to reuse the `Customer` authorization logic elsewhere. +Obtaining the `GrantedAuthority[]` instances from the `Authentication` object is also fine but will not scale to large numbers of `Customer` objects. +If a user can access 5,000 `Customer` objects (unlikely in this case, but imagine if it were a popular vet for a large Pony Club!) the amount of memory consumed and the time required to construct the `Authentication` object would be undesirable. The final method, opening the `Customer` directly from external code, is probably the best of the three. -It achieves separation of concerns, and doesn't misuse memory or CPU cycles, but it is still inefficient in that both the `AccessDecisionVoter` and the eventual business method itself will perform a call to the DAO responsible for retrieving the `Customer` object. +It achieves separation of concerns and does not misuse memory or CPU cycles, but it is still inefficient in that both the `AccessDecisionVoter` and the eventual business method itself perform a call to the DAO responsible for retrieving the `Customer` object. Two accesses per method invocation is clearly undesirable. -In addition, with every approach listed you'll need to write your own access control list (ACL) persistence and business logic from scratch. - -Fortunately, there is another alternative, which we'll talk about below. +In addition, with every approach listed, you need to write your own access control list (ACL) persistence and business logic from scratch. +Fortunately, there is another alternative, which we discuss later. [[domain-acls-key-concepts]] == Key Concepts Spring Security's ACL services are shipped in the `spring-security-acl-xxx.jar`. -You will need to add this JAR to your classpath to use Spring Security's domain object instance security capabilities. +You need to add this JAR to your classpath to use Spring Security's domain object instance security capabilities. -Spring Security's domain object instance security capabilities centre on the concept of an access control list (ACL). -Every domain object instance in your system has its own ACL, and the ACL records details of who can and can't work with that domain object. -With this in mind, Spring Security delivers three main ACL-related capabilities to your application: +Spring Security's domain object instance security capabilities center on the concept of an access control list (ACL). +Every domain object instance in your system has its own ACL, and the ACL records details of who can and cannot work with that domain object. +With this in mind, Spring Security provides three main ACL-related capabilities to your application: -* A way of efficiently retrieving ACL entries for all of your domain objects (and modifying those ACLs) -* A way of ensuring a given principal is permitted to work with your objects, before methods are called -* A way of ensuring a given principal is permitted to work with your objects (or something they return), after methods are called +* A way to efficiently retrieve ACL entries for all of your domain objects (and modifying those ACLs) +* A way to ensure a given principal is permitted to work with your objects before methods are called +* A way to ensure a given principal is permitted to work with your objects (or something they return) after methods are called As indicated by the first bullet point, one of the main capabilities of the Spring Security ACL module is providing a high-performance way of retrieving ACLs. -This ACL repository capability is extremely important, because every domain object instance in your system might have several access control entries, and each ACL might inherit from other ACLs in a tree-like structure (this is supported out-of-the-box by Spring Security, and is very commonly used). +This ACL repository capability is extremely important, because every domain object instance in your system might have several access control entries, and each ACL might inherit from other ACLs in a tree-like structure (this is supported by Spring Security, and it is very commonly used). Spring Security's ACL capability has been carefully designed to provide high performance retrieval of ACLs, together with pluggable caching, deadlock-minimizing database updates, independence from ORM frameworks (we use JDBC directly), proper encapsulation, and transparent database updating. -Given databases are central to the operation of the ACL module, let's explore the four main tables used by default in the implementation. -The tables are presented below in order of size in a typical Spring Security ACL deployment, with the table with the most rows listed last: - - +Given that databases are central to the operation of the ACL module, we need explore the four main tables used by default in the implementation. +The tables are presented in order of size in a typical Spring Security ACL deployment, with the table with the most rows listed last: -* ACL_SID allows us to uniquely identify any principal or authority in the system ("SID" stands for "security identity"). -The only columns are the ID, a textual representation of the SID, and a flag to indicate whether the textual representation refers to a principal name or a `GrantedAuthority`. +[[acl_tables]] +* `ACL_SID` lets us uniquely identify any principal or authority in the system ("`SID`" stands for "`Security IDentity`"). +The only columns are the ID, a textual representation of the SID, and a flag to indicate whether the textual representation refers to a principal name or a `GrantedAuthority`. Thus, there is a single row for each unique principal or `GrantedAuthority`. -When used in the context of receiving a permission, a SID is generally called a "recipient". +When used in the context of receiving a permission, an SID is generally called a "`recipient`". -* ACL_CLASS allows us to uniquely identify any domain object class in the system. +* `ACL_CLASS` lets us uniquely identify any domain object class in the system. The only columns are the ID and the Java class name. -Thus, there is a single row for each unique Class we wish to store ACL permissions for. +Thus, there is a single row for each unique Class for which we wish to store ACL permissions. -* ACL_OBJECT_IDENTITY stores information for each unique domain object instance in the system. -Columns include the ID, a foreign key to the ACL_CLASS table, a unique identifier so we know which ACL_CLASS instance we're providing information for, the parent, a foreign key to the ACL_SID table to represent the owner of the domain object instance, and whether we allow ACL entries to inherit from any parent ACL. -We have a single row for every domain object instance we're storing ACL permissions for. +* Finally, `ACL_ENTRY` stores the individual permissions assigned to each recipient. +Columns include a foreign key to the ACL_OBJECT_IDENTITY, the recipient (which is a foreign key to ACL_SID), whether we audit or not, and the integer bit mask that represents the actual permission being granted or denied. +We have a single row for every domain object instance for which we store ACL permissions. * Finally, ACL_ENTRY stores the individual permissions assigned to each recipient. Columns include a foreign key to the ACL_OBJECT_IDENTITY, the recipient (i.e. a foreign key to ACL_SID), whether we'll be auditing or not, and the integer bit mask that represents the actual permission being granted or denied. @@ -79,74 +77,71 @@ We have a single row for every recipient that receives a permission to work with As mentioned in the last paragraph, the ACL system uses integer bit masking. -Don't worry, you need not be aware of the finer points of bit shifting to use the ACL system, but suffice to say that we have 32 bits we can switch on or off. -Each of these bits represents a permission, and by default the permissions are read (bit 0), write (bit 1), create (bit 2), delete (bit 3) and administer (bit 4). -It's easy to implement your own `Permission` instance if you wish to use other permissions, and the remainder of the ACL framework will operate without knowledge of your extensions. +However, you need not be aware of the finer points of bit shifting to use the ACL system. +Suffice it to say that we have 32 bits we can switch on or off. +Each of these bits represents a permission. By default, the permissions are read (bit 0), write (bit 1), create (bit 2), delete (bit 3), and administer (bit 4). +You can implement your own `Permission` instance if you wish to use other permissions, and the remainder of the ACL framework operates without knowledge of your extensions. -It is important to understand that the number of domain objects in your system has absolutely no bearing on the fact we've chosen to use integer bit masking. -Whilst you have 32 bits available for permissions, you could have billions of domain object instances (which will mean billions of rows in ACL_OBJECT_IDENTITY and quite probably ACL_ENTRY). -We make this point because we've found sometimes people mistakenly believe they need a bit for each potential domain object, which is not the case. +You should understand that the number of domain objects in your system has absolutely no bearing on the fact that we have chosen to use integer bit masking. +While you have 32 bits available for permissions, you could have billions of domain object instances (which means billions of rows in ACL_OBJECT_IDENTITY and, probably, ACL_ENTRY). +We make this point because we have found that people sometimes mistakenly that believe they need a bit for each potential domain object, which is not the case. -Now that we've provided a basic overview of what the ACL system does, and what it looks like at a table structure, let's explore the key interfaces. -The key interfaces are: +Now that we have provided a basic overview of what the ACL system does, and what it looks like at a table-structure level, we need to explore the key interfaces: -* `Acl`: Every domain object has one and only one `Acl` object, which internally holds the ``AccessControlEntry``s as well as knows the owner of the `Acl`. +* `Acl`: Every domain object has one and only one `Acl` object, which internally holds the `AccessControlEntry` objects and knows the owner of the `Acl`. An Acl does not refer directly to the domain object, but instead to an `ObjectIdentity`. -The `Acl` is stored in the ACL_OBJECT_IDENTITY table. +The `Acl` is stored in the `ACL_OBJECT_IDENTITY` table. -* `AccessControlEntry`: An `Acl` holds multiple ``AccessControlEntry``s, which are often abbreviated as ACEs in the framework. -Each ACE refers to a specific tuple of `Permission`, `Sid` and `Acl`. +* `AccessControlEntry`: An `Acl` holds multiple `AccessControlEntry` objects, which are often abbreviated as ACEs in the framework. +Each ACE refers to a specific tuple of `Permission`, `Sid`, and `Acl`. An ACE can also be granting or non-granting and contain audit settings. -The ACE is stored in the ACL_ENTRY table. +The ACE is stored in the `ACL_ENTRY` table. -* `Permission`: A permission represents a particular immutable bit mask, and offers convenience functions for bit masking and outputting information. +* `Permission`: A permission represents a particular immutable bit mask and offers convenience functions for bit masking and outputting information. The basic permissions presented above (bits 0 through 4) are contained in the `BasePermission` class. -* `Sid`: The ACL module needs to refer to principals and ``GrantedAuthority[]``s. -A level of indirection is provided by the `Sid` interface, which is an abbreviation of "security identity". +* `Sid`: The ACL module needs to refer to principals and `GrantedAuthority[]` instances. +A level of indirection is provided by the `Sid` interface. ("`SID`" is an abbreviation of "`Security IDentity`".) Common classes include `PrincipalSid` (to represent the principal inside an `Authentication` object) and `GrantedAuthoritySid`. -The security identity information is stored in the ACL_SID table. +The security identity information is stored in the `ACL_SID` table. * `ObjectIdentity`: Each domain object is represented internally within the ACL module by an `ObjectIdentity`. The default implementation is called `ObjectIdentityImpl`. * `AclService`: Retrieves the `Acl` applicable for a given `ObjectIdentity`. In the included implementation (`JdbcAclService`), retrieval operations are delegated to a `LookupStrategy`. -The `LookupStrategy` provides a highly optimized strategy for retrieving ACL information, using batched retrievals (`BasicLookupStrategy`) and supporting custom implementations that leverage materialized views, hierarchical queries and similar performance-centric, non-ANSI SQL capabilities. +The `LookupStrategy` provides a highly optimized strategy for retrieving ACL information, using batched retrievals (`BasicLookupStrategy`) and supporting custom implementations that use materialized views, hierarchical queries, and similar performance-centric, non-ANSI SQL capabilities. -* `MutableAclService`: Allows a modified `Acl` to be presented for persistence. -It is not essential to use this interface if you do not wish. +* `MutableAclService`: Lets a modified `Acl` be presented for persistence. +Use of this interface is optional. - - -Please note that our out-of-the-box AclService and related database classes all use ANSI SQL. +Note that our `AclService` and related database classes all use ANSI SQL. This should therefore work with all major databases. -At the time of writing, the system had been successfully tested using Hypersonic SQL, PostgreSQL, Microsoft SQL Server and Oracle. +At the time of writing, the system had been successfully tested with Hypersonic SQL, PostgreSQL, Microsoft SQL Server, and Oracle. Two samples ship with Spring Security that demonstrate the ACL module. The first is the {gh-samples-url}/servlet/xml/java/contacts[Contacts Sample], and the other is the {gh-samples-url}/servlet/xml/java/dms[Document Management System (DMS) Sample]. -We suggest taking a look over these for examples. - +We suggest taking a look at these examples. [[domain-acls-getting-started]] == Getting Started -To get starting using Spring Security's ACL capability, you will need to store your ACL information somewhere. -This necessitates the instantiation of a `DataSource` using Spring. -The `DataSource` is then injected into a `JdbcMutableAclService` and `BasicLookupStrategy` instance. -The latter provides high-performance ACL retrieval capabilities, and the former provides mutator capabilities. -Refer to one of the samples that ship with Spring Security for an example configuration. -You'll also need to populate the database with the four ACL-specific tables listed in the last section (refer to the ACL samples for the appropriate SQL statements). - -Once you've created the required schema and instantiated `JdbcMutableAclService`, you'll next need to ensure your domain model supports interoperability with the Spring Security ACL package. -Hopefully `ObjectIdentityImpl` will prove sufficient, as it provides a large number of ways in which it can be used. -Most people will have domain objects that contain a `public Serializable getId()` method. -If the return type is long, or compatible with long (e.g. an int), you will find you need not give further consideration to `ObjectIdentity` issues. +To get starting with Spring Security's ACL capability, you need to store your ACL information somewhere. +This necessitates the instantiation of a `DataSource` in Spring. +The `DataSource` is then injected into a `JdbcMutableAclService` and a `BasicLookupStrategy` instance. +The former provides mutator capabilities, and the latter provides high-performance ACL retrieval capabilities. +See one of the {gh-samples-url}[samples] that ship with Spring Security for an example configuration. +You also need to populate the database with the <> listed in the previous section (see the ACL samples for the appropriate SQL statements). + +Once you have created the required schema and instantiated `JdbcMutableAclService`, you need to ensure your domain model supports interoperability with the Spring Security ACL package. +Hopefully, `ObjectIdentityImpl` proves sufficient, as it provides a large number of ways in which it can be used. +Most people have domain objects that contain a `public Serializable getId()` method. +If the return type is `long` or compatible with `long` (such as an `int`), you may find that you need not give further consideration to `ObjectIdentity` issues. Many parts of the ACL module rely on long identifiers. -If you're not using long (or an int, byte etc), there is a very good chance you'll need to reimplement a number of classes. -We do not intend to support non-long identifiers in Spring Security's ACL module, as longs are already compatible with all database sequences, the most common identifier data type, and are of sufficient length to accommodate all common usage scenarios. +If you do not use `long` (or an `int`, `byte`, and so on), you probably need to reimplement a number of classes. +We do not intend to support non-long identifiers in Spring Security's ACL module, as longs are already compatible with all database sequences, are the most common identifier data type, and are of sufficient length to accommodate all common usage scenarios. -The following fragment of code shows how to create an `Acl`, or modify an existing `Acl`: +The following fragment of code shows how to create an `Acl` or modify an existing `Acl`: ==== .Java @@ -191,25 +186,24 @@ aclService.updateAcl(acl) ---- ==== - -In the example above, we're retrieving the ACL associated with the "Foo" domain object with identifier number 44. -We're then adding an ACE so that a principal named "Samantha" can "administer" the object. -The code fragment is relatively self-explanatory, except the insertAce method. -The first argument to the insertAce method is determining at what position in the Acl the new entry will be inserted. -In the example above, we're just putting the new ACE at the end of the existing ACEs. +In the preceding example, we retrieve the ACL associated with the `Foo` domain object with identifier number 44. +We then add an ACE so that a principal named "`Samantha`" can "`administer`" the object. +The code fragment is relatively self-explanatory, except for the `insertAce` method. +The first argument to the `insertAce` method determine position in the Acl at which the new entry is inserted. +In the preceding example, we put the new ACE at the end of the existing ACEs. The final argument is a Boolean indicating whether the ACE is granting or denying. -Most of the time it will be granting (true), but if it is denying (false), the permissions are effectively being blocked. +Most of the time it grants (`true`). However, if it denies (`false`), the permissions are effectively being blocked. -Spring Security does not provide any special integration to automatically create, update or delete ACLs as part of your DAO or repository operations. -Instead, you will need to write code like shown above for your individual domain objects. -It's worth considering using AOP on your services layer to automatically integrate the ACL information with your services layer operations. -We've found this quite an effective approach in the past. +Spring Security does not provide any special integration to automatically create, update, or delete ACLs as part of your DAO or repository operations. +Instead, you need to write code similar to that shown in the preceding example for your individual domain objects. +You should consider using AOP on your services layer to automatically integrate the ACL information with your services layer operations. +We have found this approach to be effective. -Once you've used the above techniques to store some ACL information in the database, the next step is to actually use the ACL information as part of authorization decision logic. +Once you have used the techniques described here to store some ACL information in the database, the next step is to actually use the ACL information as part of authorization decision logic. You have a number of choices here. -You could write your own `AccessDecisionVoter` or `AfterInvocationProvider` that respectively fires before or after a method invocation. +You could write your own `AccessDecisionVoter` or `AfterInvocationProvider` that (respectively) fires before or after a method invocation. Such classes would use `AclService` to retrieve the relevant ACL and then call `Acl.isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode)` to decide whether permission is granted or denied. Alternately, you could use our `AclEntryVoter`, `AclEntryAfterInvocationProvider` or `AclEntryAfterInvocationCollectionFilteringProvider` classes. All of these classes provide a declarative-based approach to evaluating ACL information at runtime, freeing you from needing to write any code. -Please refer to the sample applications to learn how to use these classes. +See the https://github.com/spring-projects/spring-security/tree/master/samples[sample applications] to learn how to use these classes. diff --git a/docs/modules/ROOT/pages/servlet/authorization/architecture.adoc b/docs/modules/ROOT/pages/servlet/authorization/architecture.adoc index dd4ad3ee19f..1e2f5353867 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/architecture.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/architecture.adoc @@ -4,40 +4,241 @@ = Authorization Architecture :figures: servlet/authorization +This section describes the Spring Security architecture that applies to authorization. + [[authz-authorities]] == Authorities -xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`], discusses how all `Authentication` implementations store a list of `GrantedAuthority` objects. +xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] discusses how all `Authentication` implementations store a list of `GrantedAuthority` objects. These represent the authorities that have been granted to the principal. -The `GrantedAuthority` objects are inserted into the `Authentication` object by the `AuthenticationManager` and are later read by ``AccessDecisionManager``s when making authorization decisions. +The `GrantedAuthority` objects are inserted into the `Authentication` object by the `AuthenticationManager` and are later read by `AccessDecisionManager` instances when making authorization decisions. -`GrantedAuthority` is an interface with only one method: +The `GrantedAuthority` interface has only one method: +==== [source,java] ---- String getAuthority(); ---- +==== -This method allows -``AccessDecisionManager``s to obtain a precise `String` representation of the `GrantedAuthority`. -By returning a representation as a `String`, a `GrantedAuthority` can be easily "read" by most ``AccessDecisionManager``s. -If a `GrantedAuthority` cannot be precisely represented as a `String`, the `GrantedAuthority` is considered "complex" and `getAuthority()` must return `null`. - -An example of a "complex" `GrantedAuthority` would be an implementation that stores a list of operations and authority thresholds that apply to different customer account numbers. -Representing this complex `GrantedAuthority` as a `String` would be quite difficult, and as a result the `getAuthority()` method should return `null`. -This will indicate to any `AccessDecisionManager` that it will need to specifically support the `GrantedAuthority` implementation in order to understand its contents. +This method lets an +`AccessDecisionManager` instance to obtain a precise `String` representation of the `GrantedAuthority`. +By returning a representation as a `String`, a `GrantedAuthority` can be easily "`read`" by most `AccessDecisionManager` implementations. +If a `GrantedAuthority` cannot be precisely represented as a `String`, the `GrantedAuthority` is considered "`complex`" and `getAuthority()` must return `null`. -Spring Security includes one concrete `GrantedAuthority` implementation, `SimpleGrantedAuthority`. -This allows any user-specified `String` to be converted into a `GrantedAuthority`. -All ``AuthenticationProvider``s included with the security architecture use `SimpleGrantedAuthority` to populate the `Authentication` object. +An example of a "`complex`" `GrantedAuthority` would be an implementation that stores a list of operations and authority thresholds that apply to different customer account numbers. +Representing this complex `GrantedAuthority` as a `String` would be quite difficult. As a result, the `getAuthority()` method should return `null`. +This indicates to any `AccessDecisionManager` that it needs to support the specific `GrantedAuthority` implementation to understand its contents. +Spring Security includes one concrete `GrantedAuthority` implementation: `SimpleGrantedAuthority`. +This implementation lets any user-specified `String` be converted into a `GrantedAuthority`. +All `AuthenticationProvider` instances included with the security architecture use `SimpleGrantedAuthority` to populate the `Authentication` object. [[authz-pre-invocation]] == Pre-Invocation Handling -Spring Security provides interceptors which control access to secure objects such as method invocations or web requests. +Spring Security provides interceptors that control access to secure objects, such as method invocations or web requests. A pre-invocation decision on whether the invocation is allowed to proceed is made by the `AccessDecisionManager`. +=== The AuthorizationManager +`AuthorizationManager` supersedes both <>. + +Applications that customize an `AccessDecisionManager` or `AccessDecisionVoter` are encouraged to <>. + +``AuthorizationManager``s are called by the xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`] and are responsible for making final access control decisions. +The `AuthorizationManager` interface contains two methods: + +==== +[source,java] +---- +AuthorizationDecision check(Supplier authentication, Object secureObject); + +default AuthorizationDecision verify(Supplier authentication, Object secureObject) + throws AccessDeniedException { + // ... +} +---- +==== + +The ``AuthorizationManager``'s `check` method is passed all the relevant information it needs in order to make an authorization decision. +In particular, passing the secure `Object` enables those arguments contained in the actual secure object invocation to be inspected. +For example, let's assume the secure object was a `MethodInvocation`. +It would be easy to query the `MethodInvocation` for any `Customer` argument, and then implement some sort of security logic in the `AuthorizationManager` to ensure the principal is permitted to operate on that customer. +Implementations are expected to return a positive `AuthorizationDecision` if access is granted, negative `AuthorizationDecision` if access is denied, and a null `AuthorizationDecision` when abstaining from making a decision. + +`verify` calls `check` and subsequently throws an `AccessDeniedException` in the case of a negative `AuthorizationDecision`. + +[[authz-delegate-authorization-manager]] +=== Delegate-based AuthorizationManager Implementations +Whilst users can implement their own `AuthorizationManager` to control all aspects of authorization, Spring Security ships with a delegating `AuthorizationManager` that can collaborate with individual ``AuthorizationManager``s. + +`RequestMatcherDelegatingAuthorizationManager` will match the request with the most appropriate delegate `AuthorizationManager`. +For method security, you can use `AuthorizationManagerBeforeMethodInterceptor` and `AuthorizationManagerAfterMethodInterceptor`. + +<> illustrates the relevant classes. + +[[authz-authorization-manager-implementations]] +.Authorization Manager Implementations +image::{figures}/authorizationhierarchy.png[] + +Using this approach, a composition of `AuthorizationManager` implementations can be polled on an authorization decision. + +[[authz-authority-authorization-manager]] +==== AuthorityAuthorizationManager +The most common `AuthorizationManager` provided with Spring Security is `AuthorityAuthorizationManager`. +It is configured with a given set of authorities to look for on the current `Authentication`. +It will return positive `AuthorizationDecision` should the `Authentication` contain any of the configured authorities. +It will return a negative `AuthorizationDecision` otherwise. + +[[authz-authenticated-authorization-manager]] +==== AuthenticatedAuthorizationManager +Another manager is the `AuthenticatedAuthorizationManager`. +It can be used to differentiate between anonymous, fully-authenticated and remember-me authenticated users. +Many sites allow certain limited access under remember-me authentication, but require a user to confirm their identity by logging in for full access. + +[[authz-custom-authorization-manager]] +==== Custom Authorization Managers +Obviously, you can also implement a custom `AuthorizationManager` and you can put just about any access-control logic you want in it. +It might be specific to your application (business-logic related) or it might implement some security administration logic. +For example, you can create an implementation that can query Open Policy Agent or your own authorization database. + +[TIP] +You'll find a https://spring.io/blog/2009/01/03/spring-security-customization-part-2-adjusting-secured-session-in-real-time[blog article] on the Spring web site which describes how to use the legacy `AccessDecisionVoter` to deny access in real-time to users whose accounts have been suspended. +You can achieve the same outcome by implementing `AuthorizationManager` instead. + +[[authz-voter-adaptation]] +== Adapting AccessDecisionManager and AccessDecisionVoters + +Previous to `AuthorizationManager`, Spring Security published <>. + +In some cases, like migrating an older application, it may be desirable to introduce an `AuthorizationManager` that invokes an `AccessDecisionManager` or `AccessDecisionVoter`. + +To call an existing `AccessDecisionManager`, you can do: + +.Adapting an AccessDecisionManager +==== +.Java +[source,java,role="primary"] +---- +@Component +public class AccessDecisionManagerAuthorizationManagerAdapter implements AuthorizationManager { + private final AccessDecisionManager accessDecisionManager; + private final SecurityMetadataSource securityMetadataSource; + + @Override + public AuthorizationDecision check(Supplier authentication, Object object) { + try { + Collection attributes = this.securityMetadataSource.getAttributes(object); + this.accessDecisionManager.decide(authentication.get(), object, attributes); + return new AuthorizationDecision(true); + } catch (AccessDeniedException ex) { + return new AuthorizationDecision(false); + } + } + + @Override + public void verify(Supplier authentication, Object object) { + Collection attributes = this.securityMetadataSource.getAttributes(object); + this.accessDecisionManager.decide(authentication.get(), object, attributes); + } +} +---- +==== + +And then wire it into your `SecurityFilterChain`. + +Or to only call an `AccessDecisionVoter`, you can do: + +.Adapting an AccessDecisionVoter +==== +.Java +[source,java,role="primary"] +---- +@Component +public class AccessDecisionVoterAuthorizationManagerAdapter implements AuthorizationManager { + private final AccessDecisionVoter accessDecisionVoter; + private final SecurityMetadataSource securityMetadataSource; + + @Override + public AuthorizationDecision check(Supplier authentication, Object object) { + Collection attributes = this.securityMetadataSource.getAttributes(object); + int decision = this.accessDecisionVoter.vote(authentication.get(), object, attributes); + switch (decision) { + case ACCESS_GRANTED: + return new AuthorizationDecision(true); + case ACCESS_DENIED: + return new AuthorizationDecision(false); + } + return null; + } +} +---- +==== + +And then wire it into your `SecurityFilterChain`. + +[[authz-hierarchical-roles]] +== Hierarchical Roles +It is a common requirement that a particular role in an application should automatically "include" other roles. +For example, in an application which has the concept of an "admin" and a "user" role, you may want an admin to be able to do everything a normal user can. +To achieve this, you can either make sure that all admin users are also assigned the "user" role. +Alternatively, you can modify every access constraint which requires the "user" role to also include the "admin" role. +This can get quite complicated if you have a lot of different roles in your application. + +The use of a role-hierarchy allows you to configure which roles (or authorities) should include others. +An extended version of Spring Security's `RoleVoter`, `RoleHierarchyVoter`, is configured with a `RoleHierarchy`, from which it obtains all the "reachable authorities" which the user is assigned. +A typical configuration might look like this: + +.Hierarchical Roles Configuration +==== +.Java +[source,java,role="primary"] +---- +@Bean +AccessDecisionVoter hierarchyVoter() { + RoleHierarchy hierarchy = new RoleHierarchyImpl(); + hierarchy.setHierarchy("ROLE_ADMIN > ROLE_STAFF\n" + + "ROLE_STAFF > ROLE_USER\n" + + "ROLE_USER > ROLE_GUEST"); + return new RoleHierarcyVoter(hierarchy); +} +---- + +.Xml +[source,java,role="secondary"] +---- + + + + + + + + ROLE_ADMIN > ROLE_STAFF + ROLE_STAFF > ROLE_USER + ROLE_USER > ROLE_GUEST + + + +---- +==== + +Here we have four roles in a hierarchy `ROLE_ADMIN => ROLE_STAFF => ROLE_USER => ROLE_GUEST`. +A user who is authenticated with `ROLE_ADMIN`, will behave as if they have all four roles when security constraints are evaluated against an `AuthorizationManager` adapted to call the above `RoleHierarchyVoter`. +The `>` symbol can be thought of as meaning "includes". + +Role hierarchies offer a convenient means of simplifying the access-control configuration data for your application and/or reducing the number of authorities which you need to assign to a user. +For more complex requirements you may wish to define a logical mapping between the specific access-rights your application requires and the roles that are assigned to users, translating between the two when loading the user information. + +[[authz-legacy-note]] +== Legacy Authorization Components + +[NOTE] +Spring Security contains some legacy components. +Since they are not yet removed, documentation is included for historical purposes. +Their recommended replacements are above. [[authz-access-decision-manager]] === The AccessDecisionManager @@ -54,31 +255,32 @@ boolean supports(ConfigAttribute attribute); boolean supports(Class clazz); ---- -The ``AccessDecisionManager``'s `decide` method is passed all the relevant information it needs in order to make an authorization decision. -In particular, passing the secure `Object` enables those arguments contained in the actual secure object invocation to be inspected. -For example, let's assume the secure object was a `MethodInvocation`. -It would be easy to query the `MethodInvocation` for any `Customer` argument, and then implement some sort of security logic in the `AccessDecisionManager` to ensure the principal is permitted to operate on that customer. +The `decide` method of the `AccessDecisionManager` is passed all the relevant information it needs to make an authorization decision. +In particular, passing the secure `Object` lets those arguments contained in the actual secure object invocation be inspected. +For example, assume the secure object is a `MethodInvocation`. +You can query the `MethodInvocation` for any `Customer` argument and then implement some sort of security logic in the `AccessDecisionManager` to ensure the principal is permitted to operate on that customer. Implementations are expected to throw an `AccessDeniedException` if access is denied. The `supports(ConfigAttribute)` method is called by the `AbstractSecurityInterceptor` at startup time to determine if the `AccessDecisionManager` can process the passed `ConfigAttribute`. -The `supports(Class)` method is called by a security interceptor implementation to ensure the configured `AccessDecisionManager` supports the type of secure object that the security interceptor will present. +The `supports(Class)` method is called by a security interceptor implementation to ensure the configured `AccessDecisionManager` supports the type of secure object that the security interceptor presents. [[authz-voting-based]] === Voting-Based AccessDecisionManager Implementations -Whilst users can implement their own `AccessDecisionManager` to control all aspects of authorization, Spring Security includes several `AccessDecisionManager` implementations that are based on voting. -<> illustrates the relevant classes. +While users can implement their own `AccessDecisionManager` to control all aspects of authorization, Spring Security includes several `AccessDecisionManager` implementations that are based on voting. +<> describes the relevant classes. + +The following image shows the `AccessDecisionManager` interface: [[authz-access-voting]] .Voting Decision Manager image::{figures}/access-decision-voting.png[] - - -Using this approach, a series of `AccessDecisionVoter` implementations are polled on an authorization decision. +By using this approach, a series of `AccessDecisionVoter` implementations are polled on an authorization decision. The `AccessDecisionManager` then decides whether or not to throw an `AccessDeniedException` based on its assessment of the votes. The `AccessDecisionVoter` interface has three methods: +==== [source,java] ---- int vote(Authentication authentication, Object object, Collection attrs); @@ -87,56 +289,49 @@ boolean supports(ConfigAttribute attribute); boolean supports(Class clazz); ---- +==== -Concrete implementations return an `int`, with possible values being reflected in the `AccessDecisionVoter` static fields `ACCESS_ABSTAIN`, `ACCESS_DENIED` and `ACCESS_GRANTED`. -A voting implementation will return `ACCESS_ABSTAIN` if it has no opinion on an authorization decision. +Concrete implementations return an `int`, with possible values being reflected in the `AccessDecisionVoter` static fields named `ACCESS_ABSTAIN`, `ACCESS_DENIED` and `ACCESS_GRANTED`. +A voting implementation returns `ACCESS_ABSTAIN` if it has no opinion on an authorization decision. If it does have an opinion, it must return either `ACCESS_DENIED` or `ACCESS_GRANTED`. -There are three concrete ``AccessDecisionManager``s provided with Spring Security that tally the votes. -The `ConsensusBased` implementation will grant or deny access based on the consensus of non-abstain votes. +There are three concrete `AccessDecisionManager` implementations provided with Spring Security to tally the votes. +The `ConsensusBased` implementation grants or denies access based on the consensus of non-abstain votes. Properties are provided to control behavior in the event of an equality of votes or if all votes are abstain. -The `AffirmativeBased` implementation will grant access if one or more `ACCESS_GRANTED` votes were received (i.e. a deny vote will be ignored, provided there was at least one grant vote). +The `AffirmativeBased` implementation grants access if one or more `ACCESS_GRANTED` votes were received (in other words, a deny vote will be ignored, provided there was at least one grant vote). Like the `ConsensusBased` implementation, there is a parameter that controls the behavior if all voters abstain. The `UnanimousBased` provider expects unanimous `ACCESS_GRANTED` votes in order to grant access, ignoring abstains. -It will deny access if there is any `ACCESS_DENIED` vote. -Like the other implementations, there is a parameter that controls the behaviour if all voters abstain. - -It is possible to implement a custom `AccessDecisionManager` that tallies votes differently. -For example, votes from a particular `AccessDecisionVoter` might receive additional weighting, whilst a deny vote from a particular voter may have a veto effect. +It denies access if there is any `ACCESS_DENIED` vote. +Like the other implementations, there is a parameter that controls the behavior if all voters abstain. +You can implement a custom `AccessDecisionManager` that tallies votes differently. +For example, votes from a particular `AccessDecisionVoter` might receive additional weighting, while a deny vote from a particular voter may have a veto effect. [[authz-role-voter]] ==== RoleVoter -The most commonly used `AccessDecisionVoter` provided with Spring Security is the simple `RoleVoter`, which treats configuration attributes as simple role names and votes to grant access if the user has been assigned that role. +The most commonly used `AccessDecisionVoter` provided with Spring Security is the `RoleVoter`, which treats configuration attributes as role names and votes to grant access if the user has been assigned that role. -It will vote if any `ConfigAttribute` begins with the prefix `ROLE_`. -It will vote to grant access if there is a `GrantedAuthority` which returns a `String` representation (via the `getAuthority()` method) exactly equal to one or more `ConfigAttributes` starting with the prefix `ROLE_`. -If there is no exact match of any `ConfigAttribute` starting with `ROLE_`, the `RoleVoter` will vote to deny access. -If no `ConfigAttribute` begins with `ROLE_`, the voter will abstain. +It votes if any `ConfigAttribute` begins with the `ROLE_` prefix. +It votes to grant access if there is a `GrantedAuthority` that returns a `String` representation (from the `getAuthority()` method) exactly equal to one or more `ConfigAttributes` that start with the `ROLE_` prefix. +If there is no exact match of any `ConfigAttribute` starting with `ROLE_`, `RoleVoter` votes to deny access. +If no `ConfigAttribute` begins with `ROLE_`, the voter abstains. [[authz-authenticated-voter]] ==== AuthenticatedVoter -Another voter which we've implicitly seen is the `AuthenticatedVoter`, which can be used to differentiate between anonymous, fully-authenticated and remember-me authenticated users. -Many sites allow certain limited access under remember-me authentication, but require a user to confirm their identity by logging in for full access. +Another voter which we have implicitly seen is the `AuthenticatedVoter`, which can be used to differentiate between anonymous, fully-authenticated, and remember-me authenticated users. +Many sites allow certain limited access under remember-me authentication but require a user to confirm their identity by logging in for full access. -When we've used the attribute `IS_AUTHENTICATED_ANONYMOUSLY` to grant anonymous access, this attribute was being processed by the `AuthenticatedVoter`. -See the Javadoc for this class for more information. +When we have used the `IS_AUTHENTICATED_ANONYMOUSLY` attribute to grant anonymous access, this attribute was being processed by the `AuthenticatedVoter`. +For more information, see +{security-api-url}org/springframework/security/access/vote/AuthenticatedVoter.html[`AuthenticatedVoter`]. [[authz-custom-voter]] ==== Custom Voters -Obviously, you can also implement a custom `AccessDecisionVoter` and you can put just about any access-control logic you want in it. +You can also implement a custom `AccessDecisionVoter` and put just about any access-control logic you want in it. It might be specific to your application (business-logic related) or it might implement some security administration logic. -For example, you'll find a https://spring.io/blog/2009/01/03/spring-security-customization-part-2-adjusting-secured-session-in-real-time[blog article] on the Spring web site which describes how to use a voter to deny access in real-time to users whose accounts have been suspended. - - -[[authz-after-invocation-handling]] -== After Invocation Handling -Whilst the `AccessDecisionManager` is called by the `AbstractSecurityInterceptor` before proceeding with the secure object invocation, some applications need a way of modifying the object actually returned by the secure object invocation. -Whilst you could easily implement your own AOP concern to achieve this, Spring Security provides a convenient hook that has several concrete implementations that integrate with its ACL capabilities. - -<> illustrates Spring Security's `AfterInvocationManager` and its concrete implementations. +For example, on the Spring web site, you can find a https://spring.io/blog/2009/01/03/spring-security-customization-part-2-adjusting-secured-session-in-real-time[blog article] that describes how to use a voter to deny access in real-time to users whose accounts have been suspended. [[authz-after-invocation]] .After Invocation Implementation @@ -151,41 +346,3 @@ If you're using the typical Spring Security included `AccessDecisionManager` imp In turn, if the `AccessDecisionManager` property "`allowIfAllAbstainDecisions`" is `false`, an `AccessDeniedException` will be thrown. You may avoid this potential issue by either (i) setting "`allowIfAllAbstainDecisions`" to `true` (although this is generally not recommended) or (ii) simply ensure that there is at least one configuration attribute that an `AccessDecisionVoter` will vote to grant access for. This latter (recommended) approach is usually achieved through a `ROLE_USER` or `ROLE_AUTHENTICATED` configuration attribute. - - -[[authz-hierarchical-roles]] -== Hierarchical Roles -It is a common requirement that a particular role in an application should automatically "include" other roles. -For example, in an application which has the concept of an "admin" and a "user" role, you may want an admin to be able to do everything a normal user can. -To achieve this, you can either make sure that all admin users are also assigned the "user" role. -Alternatively, you can modify every access constraint which requires the "user" role to also include the "admin" role. -This can get quite complicated if you have a lot of different roles in your application. - -The use of a role-hierarchy allows you to configure which roles (or authorities) should include others. -An extended version of Spring Security's <>, `RoleHierarchyVoter`, is configured with a `RoleHierarchy`, from which it obtains all the "reachable authorities" which the user is assigned. -A typical configuration might look like this: - -[source,xml] ----- - - - - - - - - ROLE_ADMIN > ROLE_STAFF - ROLE_STAFF > ROLE_USER - ROLE_USER > ROLE_GUEST - - - ----- - -Here we have four roles in a hierarchy `ROLE_ADMIN => ROLE_STAFF => ROLE_USER => ROLE_GUEST`. -A user who is authenticated with `ROLE_ADMIN`, will behave as if they have all four roles when security constraints are evaluated against an `AccessDecisionManager` configured with the above `RoleHierarchyVoter`. -The `>` symbol can be thought of as meaning "includes". - -Role hierarchies offer a convenient means of simplifying the access-control configuration data for your application and/or reducing the number of authorities which you need to assign to a user. -For more complex requirements you may wish to define a logical mapping between the specific access-rights your application requires and the roles that are assigned to users, translating between the two when loading the user information. diff --git a/docs/modules/ROOT/pages/servlet/authorization/authorize-http-requests.adoc b/docs/modules/ROOT/pages/servlet/authorization/authorize-http-requests.adoc new file mode 100644 index 00000000000..0b02433caf5 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/authorization/authorize-http-requests.adoc @@ -0,0 +1,171 @@ +[[servlet-authorization-authorizationfilter]] += Authorize HttpServletRequests with AuthorizationFilter +:figures: servlet/authorization + +This section builds on xref:servlet/architecture.adoc#servlet-architecture[Servlet Architecture and Implementation] by digging deeper into how xref:servlet/authorization/index.adoc#servlet-authorization[authorization] works within Servlet-based applications. + +[NOTE] +`AuthorizationFilter` supersedes xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`]. +To remain backward compatible, `FilterSecurityInterceptor` remains the default. +This section discusses how `AuthorizationFilter` works and how to override the default configuration. + +The {security-api-url}org/springframework/security/web/access/intercept/AuthorizationFilter.html[`AuthorizationFilter`] provides xref:servlet/authorization/index.adoc#servlet-authorization[authorization] for ``HttpServletRequest``s. +It is inserted into the xref:servlet/architecture.adoc#servlet-filterchainproxy[FilterChainProxy] as one of the xref:servlet/architecture.adoc#servlet-security-filters[Security Filters]. + +You can override the default when you declare a `SecurityFilterChain`. +Instead of using xref:servlet/authorization/authorize-http-requests.adoc#servlet-authorize-requests-defaults[`authorizeRequests`], use `authorizeHttpRequests`, like so: + +.Use authorizeHttpRequests +==== +.Java +[source,java,role="primary"] +---- +@Bean +SecurityFilterChain web(HttpSecurity http) throws AuthenticationException { + http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest().authenticated(); + ) + // ... + + return http.build(); +} +---- +==== + +This improves on `authorizeRequests` in a number of ways: + +1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters. +This simplifies reuse and customization. +2. Delays `Authentication` lookup. +Instead of the authentication needing to be looked up for every request, it will only look it up in requests where an authorization decision requires authentication. +3. Bean-based configuration support. + +When `authorizeHttpRequests` is used instead of `authorizeRequests`, then {security-api-url}org/springframework/security/web/access/intercept/AuthorizationFilter.html[`AuthorizationFilter`] is used instead of xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`]. + +.Authorize HttpServletRequest +image::{figures}/authorizationfilter.png[] + +* image:{icondir}/number_1.png[] First, the `AuthorizationFilter` obtains an xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. +It wraps this in an `Supplier` in order to delay lookup. +* image:{icondir}/number_2.png[] Second, `AuthorizationFilter` creates a {security-api-url}org/springframework/security/web/FilterInvocation.html[`FilterInvocation`] from the `HttpServletRequest`, `HttpServletResponse`, and `FilterChain`. +// FIXME: link to FilterInvocation +* image:{icondir}/number_3.png[] Next, it passes the `Supplier` and `FilterInvocation` to the xref:servlet/architecture.adoc#authz-authorization-manager[`AuthorizationManager`]. +** image:{icondir}/number_4.png[] If authorization is denied, an `AccessDeniedException` is thrown. +In this case the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`. +** image:{icondir}/number_5.png[] If access is granted, `AuthorizationFilter` continues with the xref:servlet/architecture.adoc#servlet-filters-review[FilterChain] which allows the application to process normally. + +We can configure Spring Security to have different rules by adding more rules in order of precedence. + +.Authorize Requests +==== +.Java +[source,java,role="primary"] +---- +@Bean +SecurityFilterChain web(HttpSecurity http) throws Exception { + http + // ... + .authorizeHttpRequests(authorize -> authorize // <1> + .mvcMatchers("/resources/**", "/signup", "/about").permitAll() // <2> + .mvcMatchers("/admin/**").hasRole("ADMIN") // <3> + .mvcMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") // <4> + .anyRequest().denyAll() // <5> + ); + + return http.build(); +} +---- +==== +<1> There are multiple authorization rules specified. +Each rule is considered in the order they were declared. +<2> We specified multiple URL patterns that any user can access. +Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about". +<3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN". +You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix. +<4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA". +You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix. +<5> Any URL that has not already been matched on is denied access. +This is a good strategy if you do not want to accidentally forget to update your authorization rules. + +You can take a bean-based approach by constructing your own xref:servlet/authorization/architecture.adoc#authz-delegate-authorization-manager[`RequestMatcherDelegatingAuthorizationManager`] like so: + +.Configure RequestMatcherDelegatingAuthorizationManager +==== +.Java +[source,java,role="primary"] +---- +@Bean +SecurityFilterChain web(HttpSecurity http, AuthorizationManager access) + throws AuthenticationException { + http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest().access(access) + ) + // ... + + return http.build(); +} + +@Bean +AuthorizationManager requestMatcherAuthorizationManager(HandlerMappingIntrospector introspector) { + RequestMatcher permitAll = + new AndRequestMatcher( + new MvcRequestMatcher(introspector, "/resources/**"), + new MvcRequestMatcher(introspector, "/signup"), + new MvcRequestMatcher(introspector, "/about")); + RequestMatcher admin = new MvcRequestMatcher(introspector, "/admin/**"); + RequestMatcher db = new MvcRequestMatcher(introspector, "/db/**"); + RequestMatcher any = AnyRequestMatcher.INSTANCE; + AuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder() + .add(permitAll, (context) -> new AuthorizationDecision(true)) + .add(admin, AuthorityAuthorizationManager.hasRole("ADMIN")) + .add(db, AuthorityAuthorizationManager.hasRole("DBA")) + .add(any, new AuthenticatedAuthorizationManager()) + .build(); + return (context) -> manager.check(context.getRequest()); +} +---- +==== + +You can also wire xref:servlet/authorization/architecture.adoc#authz-custom-authorization-manager[your own custom authorization managers] for any request matcher. + +Here is an example of mapping a custom authorization manager to the `my/authorized/endpoint`: + +.Custom Authorization Manager +==== +.Java +[source,java,role="primary"] +---- +@Bean +SecurityFilterChain web(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests((authorize) -> authorize + .mvcMatchers("/my/authorized/endpoint").access(new CustomAuthorizationManager()); + ) + // ... + + return http.build(); +} +---- +==== + +Or you can provide it for all requests as seen below: + +.Custom Authorization Manager for All Requests +==== +.Java +[source,java,role="primary"] +---- +@Bean +SecurityFilterChain web(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest.access(new CustomAuthorizationManager()); + ) + // ... + + return http.build(); +} +---- +==== diff --git a/docs/modules/ROOT/pages/servlet/authorization/authorize-requests.adoc b/docs/modules/ROOT/pages/servlet/authorization/authorize-requests.adoc index bbf771a73b7..d28098cf00b 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/authorize-requests.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/authorize-requests.adoc @@ -2,28 +2,36 @@ = Authorize HttpServletRequest with FilterSecurityInterceptor :figures: servlet/authorization -This section builds on xref:servlet/architecture.adoc#servlet-architecture[Servlet Architecture and Implementation] by digging deeper into how xref:servlet/authorization/index.adoc#servlet-authorization[authorization] works within Servlet based applications. +[NOTE] +==== +`FilterSecurityInterceptor` is in the process of being replaced by xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`]. +Consider using that instead. +==== -The {security-api-url}org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html[`FilterSecurityInterceptor`] provides xref:servlet/authorization/index.adoc#servlet-authorization[authorization] for ``HttpServletRequest``s. +This section builds on xref:servlet/architecture.adoc#servlet-architecture[Servlet Architecture and Implementation] by digging deeper into how xref:servlet/authorization/index.adoc#servlet-authorization[authorization] works within Servlet-based applications. + +The {security-api-url}org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html[`FilterSecurityInterceptor`] provides xref:servlet/authorization/index.adoc#servlet-authorization[authorization] for `HttpServletRequest` instances. It is inserted into the xref:servlet/architecture.adoc#servlet-filterchainproxy[FilterChainProxy] as one of the xref:servlet/architecture.adoc#servlet-security-filters[Security Filters]. +The following image shows the role of `FilterSecurityInterceptor`: + .Authorize HttpServletRequest image::{figures}/filtersecurityinterceptor.png[] -* image:{icondir}/number_1.png[] First, the `FilterSecurityInterceptor` obtains an xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. -* image:{icondir}/number_2.png[] Second, `FilterSecurityInterceptor` creates a {security-api-url}org/springframework/security/web/FilterInvocation.html[`FilterInvocation`] from the `HttpServletRequest`, `HttpServletResponse`, and `FilterChain` that are passed into the `FilterSecurityInterceptor`. -// FIXME: link to FilterInvocation -* image:{icondir}/number_3.png[] Next, it passes the `FilterInvocation` to `SecurityMetadataSource` to get the ``ConfigAttribute``s. -* image:{icondir}/number_4.png[] Finally, it passes the `Authentication`, `FilterInvocation`, and ``ConfigAttribute``s to the `AccessDecisionManager`. -** image:{icondir}/number_5.png[] If authorization is denied, an `AccessDeniedException` is thrown. -In this case the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`. -** image:{icondir}/number_6.png[] If access is granted, `FilterSecurityInterceptor` continues with the xref:servlet/architecture.adoc#servlet-filters-review[FilterChain] which allows the application to process normally. +image:{icondir}/number_1.png[] The `FilterSecurityInterceptor` obtains an xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. +image:{icondir}/number_2.png[] `FilterSecurityInterceptor` creates a {security-api-url}org/springframework/security/web/FilterInvocation.html[`FilterInvocation`] from the `HttpServletRequest`, `HttpServletResponse`, and `FilterChain` that are passed into the `FilterSecurityInterceptor`. +image:{icondir}/number_3.png[] It passes the `FilterInvocation` to `SecurityMetadataSource` to get the ``ConfigAttribute``s. +image:{icondir}/number_4.png[] It passes the `Authentication`, `FilterInvocation`, and ``ConfigAttribute``s to the `AccessDecisionManager`. +image:{icondir}/number_5.png[] If authorization is denied, an `AccessDeniedException` is thrown. +In this case, the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`. +image:{icondir}/number_6.png[] If access is granted, `FilterSecurityInterceptor` continues with the xref:servlet/architecture.adoc#servlet-filters-review[`FilterChain`], which lets the application process normally. // configuration (xml/java) -By default, Spring Security's authorization will require all requests to be authenticated. -The explicit configuration looks like: +By default, Spring Security's authorization requires all requests to be authenticated. +The following listing shows the explicit configuration: +[[servlet-authorize-requests-defaults]] .Every Request Must be Authenticated ==== .Java @@ -61,7 +69,7 @@ fun configure(http: HttpSecurity) { ---- ==== -We can configure Spring Security to have different rules by adding more rules in order of precedence. +We can configure Spring Security to have different rules by adding more rules in order of precedence: .Authorize Requests ==== @@ -113,7 +121,6 @@ fun configure(http: HttpSecurity) { } } ---- -==== <1> There are multiple authorization rules specified. Each rule is considered in the order they were declared. <2> We specified multiple URL patterns that any user can access. @@ -124,3 +131,5 @@ You will notice that since we are invoking the `hasRole` method we do not need t You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix. <5> Any URL that has not already been matched on is denied access. This is a good strategy if you do not want to accidentally forget to update your authorization rules. +==== + diff --git a/docs/modules/ROOT/pages/servlet/authorization/expression-based.adoc b/docs/modules/ROOT/pages/servlet/authorization/expression-based.adoc index f5b916d6360..686b0f2be91 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/expression-based.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/expression-based.adoc @@ -1,20 +1,19 @@ [[el-access]] = Expression-Based Access Control -Spring Security 3.0 introduced the ability to use Spring EL expressions as an authorization mechanism in addition to the simple use of configuration attributes and access-decision voters which have been seen before. -Expression-based access control is built on the same architecture but allows complicated Boolean logic to be encapsulated in a single expression. +Spring Security 3.0 introduced the ability to use Spring Expression Language (SpEL) expressions as an authorization mechanism in addition to the existing configuration attributes and access-decision voters. +Expression-based access control is built on the same architecture but lets complicated Boolean logic be encapsulated in a single expression. == Overview -Spring Security uses Spring EL for expression support and you should look at how that works if you are interested in understanding the topic in more depth. -Expressions are evaluated with a "root object" as part of the evaluation context. -Spring Security uses specific classes for web and method security as the root object, in order to provide built-in expressions and access to values such as the current principal. - +Spring Security uses SpEL for expression support and you should look at how that works if you are interested in understanding the topic in more depth. +Expressions are evaluated with a "`root object`" as part of the evaluation context. +Spring Security uses specific classes for web and method security as the root object to provide built-in expressions and access to values, such as the current principal. [[el-common-built-in]] === Common Built-In Expressions The base class for expression root objects is `SecurityExpressionRoot`. -This provides some common expressions which are available in both web and method security. +This provides some common expressions that are available in both web and method security: [[common-expressions]] .Common built-in expressions @@ -24,95 +23,95 @@ This provides some common expressions which are available in both web and method | `hasRole(String role)` | Returns `true` if the current principal has the specified role. -For example, `hasRole('admin')` +Example: `hasRole('admin')` -By default if the supplied role does not start with 'ROLE_' it will be added. -This can be customized by modifying the `defaultRolePrefix` on `DefaultWebSecurityExpressionHandler`. +By default, if the supplied role does not start with `ROLE_`, it is added. +You can customize this behavior by modifying the `defaultRolePrefix` on `DefaultWebSecurityExpressionHandler`. | `hasAnyRole(String... roles)` | Returns `true` if the current principal has any of the supplied roles (given as a comma-separated list of strings). -For example, `hasAnyRole('admin', 'user')` +Example: `hasAnyRole('admin', 'user')`. -By default if the supplied role does not start with 'ROLE_' it will be added. -This can be customized by modifying the `defaultRolePrefix` on `DefaultWebSecurityExpressionHandler`. +By default, if the supplied role does not start with `ROLE_`, it is added. +You can customize this behavior by modifying the `defaultRolePrefix` on `DefaultWebSecurityExpressionHandler`. | `hasAuthority(String authority)` | Returns `true` if the current principal has the specified authority. -For example, `hasAuthority('read')` +Example: `hasAuthority('read')` | `hasAnyAuthority(String... authorities)` -| Returns `true` if the current principal has any of the supplied authorities (given as a comma-separated list of strings) +| Returns `true` if the current principal has any of the supplied authorities (given as a comma-separated list of strings). -For example, `hasAnyAuthority('read', 'write')` +Example: `hasAnyAuthority('read', 'write')`. | `principal` -| Allows direct access to the principal object representing the current user +| Allows direct access to the principal object that represents the current user. | `authentication` -| Allows direct access to the current `Authentication` object obtained from the `SecurityContext` +| Allows direct access to the current `Authentication` object obtained from the `SecurityContext`. | `permitAll` -| Always evaluates to `true` +| Always evaluates to `true`. | `denyAll` -| Always evaluates to `false` +| Always evaluates to `false`. | `isAnonymous()` -| Returns `true` if the current principal is an anonymous user +| Returns `true` if the current principal is an anonymous user. | `isRememberMe()` -| Returns `true` if the current principal is a remember-me user +| Returns `true` if the current principal is a remember-me user. | `isAuthenticated()` -| Returns `true` if the user is not anonymous +| Returns `true` if the user is not anonymous. | `isFullyAuthenticated()` -| Returns `true` if the user is not an anonymous or a remember-me user +| Returns `true` if the user is not an anonymous and is not a remember-me user. | `hasPermission(Object target, Object permission)` | Returns `true` if the user has access to the provided target for the given permission. -For example, `hasPermission(domainObject, 'read')` +Example, `hasPermission(domainObject, 'read')`. | `hasPermission(Object targetId, String targetType, Object permission)` | Returns `true` if the user has access to the provided target for the given permission. -For example, `hasPermission(1, 'com.example.domain.Message', 'read')` +Example, `hasPermission(1, 'com.example.domain.Message', 'read')`. |=== [[el-access-web]] == Web Security Expressions -To use expressions to secure individual URLs, you would first need to set the `use-expressions` attribute in the `` element to `true`. -Spring Security will then expect the `access` attributes of the `` elements to contain Spring EL expressions. -The expressions should evaluate to a Boolean, defining whether access should be allowed or not. -For example: +To use expressions to secure individual URLs, you first need to set the `use-expressions` attribute in the `` element to `true`. +Spring Security then expects the `access` attributes of the `` elements to contain SpEL expressions. +Each expression should evaluate to a Boolean, defining whether access should be allowed or not. +The following listing shows an example: +==== [source,xml] ---- - ... - ---- +==== -Here we have defined that the "admin" area of an application (defined by the URL pattern) should only be available to users who have the granted authority "admin" and whose IP address matches a local subnet. -We've already seen the built-in `hasRole` expression in the previous section. -The expression `hasIpAddress` is an additional built-in expression which is specific to web security. +Here, we have defined that the `admin` area of an application (defined by the URL pattern) should be available only to users who have the granted authority (`admin`) and whose IP address matches a local subnet. +We have already seen the built-in `hasRole` expression in the previous section. +The `hasIpAddress` expression is an additional built-in expression that is specific to web security. It is defined by the `WebSecurityExpressionRoot` class, an instance of which is used as the expression root object when evaluating web-access expressions. -This object also directly exposed the `HttpServletRequest` object under the name `request` so you can invoke the request directly in an expression. -If expressions are being used, a `WebExpressionVoter` will be added to the `AccessDecisionManager` which is used by the namespace. -So if you aren't using the namespace and want to use expressions, you will have to add one of these to your configuration. +This object also directly exposed the `HttpServletRequest` object under the name `request` so that you can invoke the request directly in an expression. +If expressions are being used, a `WebExpressionVoter` is added to the `AccessDecisionManager` that is used by the namespace. +So, if you do not use the namespace and want to use expressions, you have to add one of these to your configuration. [[el-access-web-beans]] === Referring to Beans in Web Security Expressions If you wish to extend the expressions that are available, you can easily refer to any Spring Bean you expose. -For example, assuming you have a Bean with the name of `webSecurity` that contains the following method signature: +For example, you could use the following, assuming you have a Bean with the name of `webSecurity` that contains the following method signature: ==== .Java @@ -136,7 +135,7 @@ class WebSecurity { ---- ==== -You could refer to the method using: +You could then refer to the method as follows: .Refer to method ==== @@ -144,7 +143,7 @@ You could refer to the method using: [source,java,role="primary"] ---- http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .antMatchers("/user/**").access("@webSecurity.check(authentication,request)") ... ) @@ -174,11 +173,11 @@ http { [[el-access-web-path-variables]] === Path Variables in Web Security Expressions -At times it is nice to be able to refer to path variables within a URL. -For example, consider a RESTful application that looks up a user by id from the URL path in the format `+/user/{userId}+`. +At times, it is nice to be able to refer to path variables within a URL. +For example, consider a RESTful application that looks up a user by ID from a URL path in a format of `+/user/{userId}+`. You can easily refer to the path variable by placing it in the pattern. -For example, if you had a Bean with the name of `webSecurity` that contains the following method signature: +For example, you could use the following if you had a Bean with the name of `webSecurity` that contains the following method signature: ==== .Java @@ -202,7 +201,7 @@ class WebSecurity { ---- ==== -You could refer to the method using: +You could then refer to the method as follows: .Path Variables ==== @@ -210,7 +209,7 @@ You could refer to the method using: [source,java,role="primary",attrs="-attributes"] ---- http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .antMatchers("/user/{userId}/**").access("@webSecurity.checkUserId(authentication,#userId)") ... ); @@ -237,28 +236,29 @@ http { ---- ==== -In this configuration URLs that match would pass in the path variable (and convert it) into checkUserId method. -For example, if the URL were `/user/123/resource`, then the id passed in would be `123`. +In this configuration, URLs that match would pass in the path variable (and convert it) into the `checkUserId` method. +For example, if the URL were `/user/123/resource`, the ID passed in would be `123`. == Method Security Expressions Method security is a bit more complicated than a simple allow or deny rule. -Spring Security 3.0 introduced some new annotations in order to allow comprehensive support for the use of expressions. - +Spring Security 3.0 introduced some new annotations to allow comprehensive support for the use of expressions. [[el-pre-post-annotations]] === @Pre and @Post Annotations -There are four annotations which support expression attributes to allow pre and post-invocation authorization checks and also to support filtering of submitted collection arguments or return values. -They are `@PreAuthorize`, `@PreFilter`, `@PostAuthorize` and `@PostFilter`. +There are four annotations that support expression attributes to allow pre and post-invocation authorization checks and also to support filtering of submitted collection arguments or return values. +They are `@PreAuthorize`, `@PreFilter`, `@PostAuthorize`, and `@PostFilter`. Their use is enabled through the `global-method-security` namespace element: +==== [source,xml] ---- ---- +==== ==== Access Control using @PreAuthorize and @PostAuthorize -The most obviously useful annotation is `@PreAuthorize` which decides whether a method can actually be invoked or not. -For example (from the {gh-samples-url}/servlet/xml/java/contacts[Contacts] sample application) +The most obviously useful annotation is `@PreAuthorize`, which decides whether a method can actually be invoked or not. +The following example (from the {gh-samples-url}/servlet/xml/java/contacts["Contacts" sample application]) uses the `@PreAuthorize` annotation: ==== .Java @@ -276,9 +276,9 @@ fun create(contact: Contact?) ---- ==== -which means that access will only be allowed for users with the role "ROLE_USER". -Obviously the same thing could easily be achieved using a traditional configuration and a simple configuration attribute for the required role. -But what about: +This means that access is allowed only for users with the `ROLE_USER` role. +Obviously, the same thing could easily be achieved by using a traditional configuration and a simple configuration attribute for the required role. +However, consider the following example: ==== .Java @@ -296,17 +296,17 @@ fun deletePermission(contact: Contact?, recipient: Sid?, permission: Permission? ---- ==== -Here we're actually using a method argument as part of the expression to decide whether the current user has the "admin" permission for the given contact. -The built-in `hasPermission()` expression is linked into the Spring Security ACL module through the application context, as we'll <>. +Here, we actually use a method argument as part of the expression to decide whether the current user has the `admin` permission for the given contact. +The built-in `hasPermission()` expression is linked into the Spring Security ACL module through the application context, as we <>. You can access any of the method arguments by name as expression variables. -There are a number of ways in which Spring Security can resolve the method arguments. +Spring Security can resolve the method arguments in a number of ways. Spring Security uses `DefaultSecurityParameterNameDiscoverer` to discover the parameter names. -By default, the following options are tried for a method as a whole. +By default, the following options are tried for a method. -* If Spring Security's `@P` annotation is present on a single argument to the method, the value will be used. -This is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names. -For example: +* If Spring Security's `@P` annotation is present on a single argument to the method, the value is used. +This is useful for interfaces compiled with a JDK prior to JDK 8 (which do not contain any information about the parameter names). +The following example uses the `@P` annotation: + @@ -336,14 +336,12 @@ fun doSomething(@P("c") contact: Contact?) + -Behind the scenes this is implemented using `AnnotationParameterNameDiscoverer` which can be customized to support the value attribute of any specified annotation. +Behind the scenes, this is implemented by using `AnnotationParameterNameDiscoverer`, which you can customize to support the value attribute of any specified annotation. -* If Spring Data's `@Param` annotation is present on at least one parameter for the method, the value will be used. +* If Spring Data's `@Param` annotation is present on at least one parameter for the method, the value is used. This is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names. -For example: - +The following example uses the `@Param` annotation: + - ==== .Java [source,java,role="primary"] @@ -367,23 +365,20 @@ import org.springframework.data.repository.query.Param fun findContactByName(@Param("n") name: String?): Contact? ---- ==== - + -Behind the scenes this is implemented using `AnnotationParameterNameDiscoverer` which can be customized to support the value attribute of any specified annotation. +Behind the scenes, this is implemented by using `AnnotationParameterNameDiscoverer`, which you can customize to support the value attribute of any specified annotation. -* If JDK 8 was used to compile the source with the -parameters argument and Spring 4+ is being used, then the standard JDK reflection API is used to discover the parameter names. +* If JDK 8 was used to compile the source with the `-parameters` argument and Spring 4+ is being used, the standard JDK reflection API is used to discover the parameter names. This works on both classes and interfaces. -* Last, if the code was compiled with the debug symbols, the parameter names will be discovered using the debug symbols. -This will not work for interfaces since they do not have debug information about the parameter names. +* Finally, if the code was compiled with the debug symbols, the parameter names are discovered by using the debug symbols. +This does not work for interfaces, since they do not have debug information about the parameter names. For interfaces, annotations or the JDK 8 approach must be used. .[[el-pre-post-annotations-spel]] --- -Any Spring-EL functionality is available within the expression, so you can also access properties on the arguments. -For example, if you wanted a particular method to only allow access to a user whose username matched that of the contact, you could write --- +Any SpEL functionality is available within the expression, so you can also access properties on the arguments. +For example, if you wanted a particular method to allow access only to a user whose username matched that of the contact, you could write ==== .Java @@ -406,16 +401,14 @@ You can also access its "principal" property directly, using the expression `pri The value will often be a `UserDetails` instance, so you might use an expression like `principal.username` or `principal.enabled`. .[[el-pre-post-annotations-post]] --- -Less commonly, you may wish to perform an access-control check after the method has been invoked. -This can be achieved using the `@PostAuthorize` annotation. -To access the return value from a method, use the built-in name `returnObject` in the expression. --- +Here, we access another built-in expression, `authentication`, which is the `Authentication` stored in the security context. +You can also access its `principal` property directly, by using the `principal` expression. +The value is often a `UserDetails` instance, so you might use an expression such as `principal.username` or `principal.enabled`. ==== Filtering using @PreFilter and @PostFilter -Spring Security supports filtering of collections, arrays, maps and streams using expressions. +Spring Security supports filtering of collections, arrays, maps, and streams by using expressions. This is most commonly performed on the return value of a method. -For example: +The following example uses `@PostFilter`: ==== .Java @@ -436,29 +429,30 @@ fun getAll(): List ==== When using the `@PostFilter` annotation, Spring Security iterates through the returned collection or map and removes any elements for which the supplied expression is false. -For an array, a new array instance will be returned containing filtered elements. -The name `filterObject` refers to the current object in the collection. -In case when a map is used it will refer to the current `Map.Entry` object which allows one to use `filterObject.key` or `filterObject.value` in the expresion. -You can also filter before the method call, using `@PreFilter`, though this is a less common requirement. -The syntax is just the same, but if there is more than one argument which is a collection type then you have to select one by name using the `filterTarget` property of this annotation. +For an array, a new array instance that contains filtered elements is returned. +`filterObject` refers to the current object in the collection. +When a map is used, it refers to the current `Map.Entry` object, which lets you use `filterObject.key` or `filterObject.value` in the expression. +You can also filter before the method call by using `@PreFilter`, though this is a less common requirement. +The syntax is the same. However, if there is more than one argument that is a collection type, you have to select one by name using the `filterTarget` property of this annotation. Note that filtering is obviously not a substitute for tuning your data retrieval queries. -If you are filtering large collections and removing many of the entries then this is likely to be inefficient. +If you are filtering large collections and removing many of the entries, this is likely to be inefficient. [[el-method-built-in]] === Built-In Expressions -There are some built-in expressions which are specific to method security, which we have already seen in use above. +There are some built-in expressions that are specific to method security, which we have already seen in use earlier. The `filterTarget` and `returnValue` values are simple enough, but the use of the `hasPermission()` expression warrants a closer look. [[el-permission-evaluator]] ==== The PermissionEvaluator interface `hasPermission()` expressions are delegated to an instance of `PermissionEvaluator`. -It is intended to bridge between the expression system and Spring Security's ACL system, allowing you to specify authorization constraints on domain objects, based on abstract permissions. +It is intended to bridge between the expression system and Spring Security's ACL system, letting you specify authorization constraints on domain objects, based on abstract permissions. It has no explicit dependencies on the ACL module, so you could swap that out for an alternative implementation if required. The interface has two methods: +==== [source,java] ---- boolean hasPermission(Authentication authentication, Object targetDomainObject, @@ -467,17 +461,19 @@ boolean hasPermission(Authentication authentication, Object targetDomainObject, boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission); ---- +==== -which map directly to the available versions of the expression, with the exception that the first argument (the `Authentication` object) is not supplied. +These methods map directly to the available versions of the expression, with the exception that the first argument (the `Authentication` object) is not supplied. The first is used in situations where the domain object, to which access is being controlled, is already loaded. -Then expression will return true if the current user has the given permission for that object. -The second version is used in cases where the object is not loaded, but its identifier is known. -An abstract "type" specifier for the domain object is also required, allowing the correct ACL permissions to be loaded. -This has traditionally been the Java class of the object, but does not have to be as long as it is consistent with how the permissions are loaded. +Then the expression returns `true` if the current user has the given permission for that object. +The second version is used in cases where the object is not loaded but its identifier is known. +An abstract "`type`" specifier for the domain object is also required, letting the correct ACL permissions be loaded. +This has traditionally been the Java class of the object but does not have to be, as long as it is consistent with how the permissions are loaded. To use `hasPermission()` expressions, you have to explicitly configure a `PermissionEvaluator` in your application context. -This would look something like this: +The following example shows how to do so: +==== [source,xml] ---- @@ -489,23 +485,26 @@ This would look something like this: ---- +==== Where `myPermissionEvaluator` is the bean which implements `PermissionEvaluator`. -Usually this will be the implementation from the ACL module which is called `AclPermissionEvaluator`. -See the {gh-samples-url}/servlet/xml/java/contacts[Contacts] sample application configuration for more details. +Usually, this is the implementation from the ACL module, which is called `AclPermissionEvaluator`. +See the {gh-samples-url}/servlet/xml/java/contacts[`Contacts`] sample application configuration for more details. ==== Method Security Meta Annotations You can make use of meta annotations for method security to make your code more readable. -This is especially convenient if you find that you are repeating the same complex expression throughout your code base. +This is especially convenient if you find that you repeat the same complex expression throughout your code base. For example, consider the following: +==== [source,java] ---- @PreAuthorize("#contact.name == authentication.name") ---- +==== -Instead of repeating this everywhere, we can create a meta annotation that can be used instead. +Instead of repeating this everywhere, you can create a meta annotation: ==== .Java @@ -525,6 +524,6 @@ annotation class ContactPermission ---- ==== -Meta annotations can be used for any of the Spring Security method security annotations. -In order to remain compliant with the specification JSR-250 annotations do not support meta annotations. +You can use meta annotations for any of the Spring Security method security annotations. +To remain compliant with the specification, JSR-250 annotations do not support meta annotations. diff --git a/docs/modules/ROOT/pages/servlet/authorization/index.adoc b/docs/modules/ROOT/pages/servlet/authorization/index.adoc index 847871e3622..a5281153725 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/index.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/index.adoc @@ -3,9 +3,10 @@ :page-section-summary-toc: 1 The advanced authorization capabilities within Spring Security represent one of the most compelling reasons for its popularity. -Irrespective of how you choose to authenticate - whether using a Spring Security-provided mechanism and provider, or integrating with a container or other non-Spring Security authentication authority - you will find the authorization services can be used within your application in a consistent and simple way. +Irrespective of how you choose to authenticate (whether using a Spring Security-provided mechanism and provider or integrating with a container or other non-Spring Security authentication authority), the authorization services can be used within your application in a consistent and simple way. + +In this part, we explore the different `AbstractSecurityInterceptor` implementations, which were introduced in Part I. +We then move on to explore how to fine-tune authorization through the use of domain access control lists. -In this part we'll explore the different `AbstractSecurityInterceptor` implementations, which were introduced in Part I. -We then move on to explore how to fine-tune authorization through use of domain access control lists. diff --git a/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc b/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc index 8b194fd2755..18a4f2de6b7 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc @@ -1,10 +1,10 @@ [[jc-method]] = Method Security -From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. +From version 2.0 onwards, Spring Security has improved support substantially for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the framework's original `@Secured` annotation. -From 3.0 you can also make use of new xref:servlet/authorization/expression-based.adoc#el-access[expression-based annotations]. -You can apply security to a single bean, using the `intercept-methods` element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts. +From 3.0, you can also make use of new xref:servlet/authorization/expression-based.adoc#el-access[expression-based annotations]. +You can apply security to a single bean, by using the `intercept-methods` element to decorate the bean declaration, or you can secure multiple beans across the entire service layer by using AspectJ style pointcuts. == EnableMethodSecurity @@ -600,8 +600,8 @@ and it will be invoked after the `@PostAuthorize` interceptor. [[jc-enable-global-method-security]] == EnableGlobalMethodSecurity -We can enable annotation-based security using the `@EnableGlobalMethodSecurity` annotation on any `@Configuration` instance. -For example, the following would enable Spring Security's `@Secured` annotation. +We can enable annotation-based security by using the `@EnableGlobalMethodSecurity` annotation on any `@Configuration` instance. +The following example enables Spring Security's `@Secured` annotation: ==== .Java @@ -625,7 +625,7 @@ open class MethodSecurityConfig { Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly. Spring Security's native annotation support defines a set of attributes for the method. -These will be passed to the AccessDecisionManager for it to make the actual decision: +These are passed to the `AccessDecisionManager` for it to make the actual decision: ==== .Java @@ -660,7 +660,7 @@ interface BankService { ---- ==== -Support for JSR-250 annotations can be enabled using +Support for JSR-250 annotations can be enabled by using: ==== .Java @@ -682,8 +682,8 @@ open class MethodSecurityConfig { ---- ==== -These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security's native annotations. -To use the new expression-based syntax, you would use +These are standards-based and let simple role-based constraints be applied but do not have the power Spring Security's native annotations. +To use the new expression-based syntax, you would use: ==== .Java @@ -705,7 +705,7 @@ open class MethodSecurityConfig { ---- ==== -and the equivalent Java code would be +The equivalent Java code is: ==== .Java @@ -742,8 +742,8 @@ interface BankService { == GlobalMethodSecurityConfiguration -Sometimes you may need to perform operations that are more complicated than are possible with the `@EnableGlobalMethodSecurity` annotation allow. -For these instances, you can extend the `GlobalMethodSecurityConfiguration` ensuring that the `@EnableGlobalMethodSecurity` annotation is present on your subclass. +Sometimes, you may need to perform operations that are more complicated than are possible with the `@EnableGlobalMethodSecurity` annotation. +For these instances, you can extend the `GlobalMethodSecurityConfiguration`, ensuring that the `@EnableGlobalMethodSecurity` annotation is present on your subclass. For example, if you wanted to provide a custom `MethodSecurityExpressionHandler`, you could use the following configuration: ==== @@ -773,22 +773,25 @@ open class MethodSecurityConfig : GlobalMethodSecurityConfiguration() { ---- ==== -For additional information about methods that can be overridden, refer to the `GlobalMethodSecurityConfiguration` Javadoc. +For additional information about methods that can be overridden, see the Javadoc for the {security-api-url}org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.html[`GlobalMethodSecurityConfiguration`] class. [[ns-global-method]] == The Element -This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element), and also to group together security pointcut declarations which will be applied across your entire application context. +This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element) and to group together security pointcut declarations that are applied across your entire application context. You should only declare one `` element. -The following declaration would enable support for Spring Security's `@Secured`: +The following declaration enables support for Spring Security's `@Secured`: +==== [source,xml] ---- ---- +==== -Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly. +Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly. Spring Security's native annotation support defines a set of attributes for the method. -These will be passed to the `AccessDecisionManager` for it to make the actual decision: +These are passed to the `AccessDecisionManager` for it to make the actual decision. +The following example shows the `@Secured` annotation in a typical interface: ==== .Java @@ -824,22 +827,26 @@ interface BankService { ---- ==== -Support for JSR-250 annotations can be enabled using +Support for JSR-250 annotations can be enabled by using: +==== [source,xml] ---- ---- +==== -These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security's native annotations. -To use the new expression-based syntax, you would use +These are standards-based and allow simple role-based constraints to be applied, but they do not have the power Spring Security's native annotations. +To use the expression-based syntax, use: +==== [source,xml] ---- ---- +==== -and the equivalent Java code would be +The equivalent Java code is: ==== .Java @@ -889,11 +896,12 @@ If two annotations are found which apply to a particular method, then only one o ==== [[ns-protect-pointcut]] -== Adding Security Pointcuts using protect-pointcut +== Adding Security Pointcuts by using protect-pointcut -The use of `protect-pointcut` is particularly powerful, as it allows you to apply security to many beans with only a simple declaration. +`protect-pointcut` is particularly powerful, as it lets you apply security to many beans with only a simple declaration. Consider the following example: +==== [source,xml] ---- @@ -901,8 +909,10 @@ Consider the following example: access="ROLE_USER"/> ---- +==== -This will protect all methods on beans declared in the application context whose classes are in the `com.mycompany` package and whose class names end in "Service". -Only users with the `ROLE_USER` role will be able to invoke these methods. -As with URL matching, the most specific matches must come first in the list of pointcuts, as the first matching expression will be used. +d. +This configuration protects all methods on beans declared in the application context whose classes are in the `com.mycompany` package and whose class names end in `Service`. +Only users with the `ROLE_USER` role can invoke these methods. +As with URL matching, the most specific matches must come first in the list of pointcuts, as the first matching expression is used. Security annotations take precedence over pointcuts. diff --git a/docs/modules/ROOT/pages/servlet/authorization/secure-objects.adoc b/docs/modules/ROOT/pages/servlet/authorization/secure-objects.adoc index b85afb3a5a1..84557b540ce 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/secure-objects.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/secure-objects.adoc @@ -2,25 +2,27 @@ [[secure-object-impls]] = Secure Object Implementations +This section covers how Spring Security handles Secure Object implementations. + [[aop-alliance]] == AOP Alliance (MethodInvocation) Security Interceptor -Prior to Spring Security 2.0, securing ``MethodInvocation``s needed quite a lot of boiler plate configuration. +Prior to Spring Security 2.0, securing `MethodInvocation` instances needed a lot of boiler plate configuration. Now the recommended approach for method security is to use xref:servlet/configuration/xml-namespace.adoc#ns-method-security[namespace configuration]. -This way the method security infrastructure beans are configured automatically for you so you don't really need to know about the implementation classes. -We'll just provide a quick overview of the classes that are involved here. +This way, the method security infrastructure beans are configured automatically for you, so you need not know about the implementation classes. +We provide only a quick overview of the classes that are involved here. -Method security is enforced using a `MethodSecurityInterceptor`, which secures ``MethodInvocation``s. +Method security is enforced by using a `MethodSecurityInterceptor`, which secures `MethodInvocation` instances. Depending on the configuration approach, an interceptor may be specific to a single bean or shared between multiple beans. The interceptor uses a `MethodSecurityMetadataSource` instance to obtain the configuration attributes that apply to a particular method invocation. `MapBasedMethodSecurityMetadataSource` is used to store configuration attributes keyed by method names (which can be wildcarded) and will be used internally when the attributes are defined in the application context using the `` or `` elements. -Other implementations will be used to handle annotation-based configuration. +Other implementations are used to handle annotation-based configuration. === Explicit MethodSecurityInterceptor Configuration -You can of course configure a `MethodSecurityInterceptor` directly in your application context for use with one of Spring AOP's proxying mechanisms: +You can configure a `MethodSecurityInterceptor` directly in your application context for use with one of Spring AOP's proxying mechanisms: +==== [source,xml] ---- - @@ -34,22 +36,22 @@ You can of course configure a `MethodSecurityInterceptor` directly in your appli ---- +==== [[aspectj]] == AspectJ (JoinPoint) Security Interceptor The AspectJ security interceptor is very similar to the AOP Alliance security interceptor discussed in the previous section. -Indeed we will only discuss the differences in this section. +We discuss only the differences in this section. The AspectJ interceptor is named `AspectJSecurityInterceptor`. -Unlike the AOP Alliance security interceptor, which relies on the Spring application context to weave in the security interceptor via proxying, the `AspectJSecurityInterceptor` is weaved in via the AspectJ compiler. +Unlike the AOP Alliance security interceptor, which relies on the Spring application context to weave in the security interceptor through proxying, the `AspectJSecurityInterceptor` is woven in through the AspectJ compiler. It would not be uncommon to use both types of security interceptors in the same application, with `AspectJSecurityInterceptor` being used for domain object instance security and the AOP Alliance `MethodSecurityInterceptor` being used for services layer security. -Let's first consider how the `AspectJSecurityInterceptor` is configured in the Spring application context: - +We first consider how the `AspectJSecurityInterceptor` is configured in the Spring application context: +==== [source,xml] ---- - @@ -63,16 +65,14 @@ Let's first consider how the `AspectJSecurityInterceptor` is configured in the S ---- +==== +The two interceptors can share the same `securityMetadataSource`, as the `SecurityMetadataSource` works with `java.lang.reflect.Method` instances rather than an AOP library-specific class. +Your access decisions have access to the relevant AOP library-specific invocation (`MethodInvocation` or `JoinPoint`) and can consider a range of additional criteria (such as method arguments) when making access decisions. -As you can see, aside from the class name, the `AspectJSecurityInterceptor` is exactly the same as the AOP Alliance security interceptor. -Indeed the two interceptors can share the same `securityMetadataSource`, as the `SecurityMetadataSource` works with ``java.lang.reflect.Method``s rather than an AOP library-specific class. -Of course, your access decisions have access to the relevant AOP library-specific invocation (ie `MethodInvocation` or `JoinPoint`) and as such can consider a range of addition criteria when making access decisions (such as method arguments). - -Next you'll need to define an AspectJ `aspect`. -For example: - +Next, you need to define an AspectJ `aspect`, as the following example shows: +==== [source,java] ---- @@ -118,16 +118,17 @@ public aspect DomainObjectInstanceSecurityAspect implements InitializingBean { } } ---- +==== -In the above example, the security interceptor will be applied to every instance of `PersistableEntity`, which is an abstract class not shown (you can use any other class or `pointcut` expression you like). +In the preceding example, the security interceptor is applied to every instance of `PersistableEntity`, which is an abstract class not shown (you can use any other class or `pointcut` expression you like). For those curious, `AspectJCallback` is needed because the `proceed();` statement has special meaning only within an `around()` body. The `AspectJSecurityInterceptor` calls this anonymous `AspectJCallback` class when it wants the target object to continue. -You will need to configure Spring to load the aspect and wire it with the `AspectJSecurityInterceptor`. -A bean declaration which achieves this is shown below: - +You need to configure Spring to load the aspect and wire it with the `AspectJSecurityInterceptor`. +The following example shows a bean declaration that achieves this: +==== [source,xml] ---- @@ -137,7 +138,6 @@ A bean declaration which achieves this is shown below: ---- +==== - -That's it! -Now you can create your beans from anywhere within your application, using whatever means you think fit (e.g. `new Person();`) and they will have the security interceptor applied. +Now you can create your beans from anywhere within your application, using whatever means you think fit (e.g. `new Person();`), and they have the security interceptor applied. diff --git a/docs/modules/ROOT/pages/servlet/configuration/java.adoc b/docs/modules/ROOT/pages/servlet/configuration/java.adoc index 985a01c5169..4a49676bf50 100644 --- a/docs/modules/ROOT/pages/servlet/configuration/java.adoc +++ b/docs/modules/ROOT/pages/servlet/configuration/java.adoc @@ -2,20 +2,24 @@ [[jc]] = Java Configuration -General support for https://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java[Java Configuration] was added to Spring Framework in Spring 3.1. -Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML. +General support for https://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java[Java configuration] was added to Spring Framework in Spring 3.1. +Spring Security 3.2 introduced Java configuration to let users configure Spring Security without the use of any XML. -If you are familiar with the xref:servlet/configuration/xml-namespace.adoc#ns-config[Security Namespace Configuration] then you should find quite a few similarities between it and the Security Java Configuration support. +If you are familiar with the xref:servlet/configuration/xml-namespace.adoc#ns-config[Security Namespace Configuration], you should find quite a few similarities between it and Spring Security Java configuration. -NOTE: Spring Security provides https://github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration[lots of sample applications] which demonstrate the use of Spring Security Java Configuration. +[NOTE] +==== +Spring Security provides https://github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration[lots of sample applications] to demonstrate the use of Spring Security Java Configuration. +==== +[[jc-hello-wsca]] == Hello Web Security Java Configuration The first step is to create our Spring Security Java Configuration. -The configuration creates a Servlet Filter known as the `springSecurityFilterChain` which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application. -You can find the most basic example of a Spring Security Java Configuration below: +The configuration creates a Servlet Filter known as the `springSecurityFilterChain`, which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, and so on) within your application. +The following example shows the most basic example of a Spring Security Java Configuration: -[[jc-hello-wsca]] +==== [source,java] ---- import org.springframework.beans.factory.annotation.Autowired; @@ -35,45 +39,45 @@ public class WebSecurityConfig { } } ---- +==== -There really isn't much to this configuration, but it does a lot. -You can find a summary of the features below: +This configuration is not complex or extensive, but it does a lot: * Require authentication to every URL in your application * Generate a login form for you -* Allow the user with the *Username* _user_ and the *Password* _password_ to authenticate with form based authentication -* Allow the user to logout +* Let the user with a *Username* of `user` and a *Password* of `password` authenticate with form based authentication +* Let the user logout * https://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attack] prevention * https://en.wikipedia.org/wiki/Session_fixation[Session Fixation] protection -* Security Header integration +* Security Header integration: ** https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security[HTTP Strict Transport Security] for secure requests ** https://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx[X-Content-Type-Options] integration -** Cache Control (can be overridden later by your application to allow caching of your static resources) +** Cache Control (which you can override later in your application to allow caching of your static resources) ** https://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx[X-XSS-Protection] integration ** X-Frame-Options integration to help prevent https://en.wikipedia.org/wiki/Clickjacking[Clickjacking] -* Integrate with the following Servlet API methods -** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[HttpServletRequest#getRemoteUser()] -** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[HttpServletRequest#getUserPrincipal()] -** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[HttpServletRequest#isUserInRole(java.lang.String)] -** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)[HttpServletRequest#login(java.lang.String, java.lang.String)] -** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[HttpServletRequest#logout()] +* Integration with the following Servlet API methods: +** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[`HttpServletRequest#getRemoteUser()`] +** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[`HttpServletRequest#getUserPrincipal()`] +** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[`HttpServletRequest#isUserInRole(java.lang.String)`] +** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)[`HttpServletRequest#login(java.lang.String, java.lang.String)`] +** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[`HttpServletRequest#logout()`] === AbstractSecurityWebApplicationInitializer -The next step is to register the `springSecurityFilterChain` with the war. -This can be done in Java Configuration with https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config[Spring's WebApplicationInitializer support] in a Servlet 3.0+ environment. -Not suprisingly, Spring Security provides a base class `AbstractSecurityWebApplicationInitializer` that will ensure the `springSecurityFilterChain` gets registered for you. +The next step is to register the `springSecurityFilterChain` with the WAR file. +You can do so in Java configuration with https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config[Spring's `WebApplicationInitializer` support] in a Servlet 3.0+ environment. +Not surprisingly, Spring Security provides a base class (`AbstractSecurityWebApplicationInitializer`) to ensure that the `springSecurityFilterChain` gets registered for you. The way in which we use `AbstractSecurityWebApplicationInitializer` differs depending on if we are already using Spring or if Spring Security is the only Spring component in our application. -* <> - Use these instructions if you are not using Spring already +* <> - Use these instructions if you are not already using Spring * <> - Use these instructions if you are already using Spring [[abstractsecuritywebapplicationinitializer-without-existing-spring]] === AbstractSecurityWebApplicationInitializer without Existing Spring -If you are not using Spring or Spring MVC, you will need to pass in the `WebSecurityConfig` into the superclass to ensure the configuration is picked up. -You can find an example below: +If you are not using Spring or Spring MVC, you need to pass the `WebSecurityConfig` to the superclass to ensure the configuration is picked up: +==== [source,java] ---- import org.springframework.security.web.context.*; @@ -86,20 +90,22 @@ public class SecurityWebApplicationInitializer } } ---- +==== -The `SecurityWebApplicationInitializer` will do the following things: +The `SecurityWebApplicationInitializer`: -* Automatically register the springSecurityFilterChain Filter for every URL in your application -* Add a ContextLoaderListener that loads the <>. +* Automatically registers the `springSecurityFilterChain` Filter for every URL in your application. +* Add a `ContextLoaderListener` that loads the <>. [[abstractsecuritywebapplicationinitializer-with-spring-mvc]] === AbstractSecurityWebApplicationInitializer with Spring MVC -If we were using Spring elsewhere in our application we probably already had a `WebApplicationInitializer` that is loading our Spring Configuration. -If we use the previous configuration we would get an error. +If we use Spring elsewhere in our application, we probably already have a `WebApplicationInitializer` that is loading our Spring Configuration. +If we use the previous configuration, we would get an error. Instead, we should register Spring Security with the existing `ApplicationContext`. -For example, if we were using Spring MVC our `SecurityWebApplicationInitializer` would look something like the following: +For example, if we use Spring MVC, our `SecurityWebApplicationInitializer` could look something like the following: +==== [source,java] ---- import org.springframework.security.web.context.*; @@ -109,12 +115,14 @@ public class SecurityWebApplicationInitializer } ---- +==== -This would simply only register the springSecurityFilterChain Filter for every URL in your application. -After that we would ensure that `WebSecurityConfig` was loaded in our existing ApplicationInitializer. -For example, if we were using Spring MVC it would be added in the `getRootConfigClasses()` +This onlys register the `springSecurityFilterChain` for every URL in your application. +After that, we need to ensure that `WebSecurityConfig` was loaded in our existing `ApplicationInitializer`. +For example, if we use Spring MVC it is added in the `getRootConfigClasses()`: [[message-web-application-inititializer-java]] +==== [source,java] ---- public class MvcWebApplicationInitializer extends @@ -128,16 +136,18 @@ public class MvcWebApplicationInitializer extends // ... other overrides ... } ---- +==== [[jc-httpsecurity]] == HttpSecurity -Thus far our <> only contains information about how to authenticate our users. +Thus far, our <> contains only information about how to authenticate our users. How does Spring Security know that we want to require all users to be authenticated? -How does Spring Security know we want to support form based authentication? -Actually, there is a configuration class that is being invoked behind the scenes called `WebSecurityConfigurerAdapter`. +How does Spring Security know we want to support form-based authentication? +Actually, there is a configuration class (called `WebSecurityConfigurerAdapter`) that is being invoked behind the scenes. It has a method called `configure` with the following default implementation: +==== [source,java] ---- protected void configure(HttpSecurity http) throws Exception { @@ -149,15 +159,17 @@ protected void configure(HttpSecurity http) throws Exception { .httpBasic(withDefaults()); } ---- +==== -The default configuration above: +The default configuration (shown in the preceding example): * Ensures that any request to our application requires the user to be authenticated -* Allows users to authenticate with form based login -* Allows users to authenticate with HTTP Basic authentication +* Lets users authenticate with form based login +* Lets users authenticate with HTTP Basic authentication -You will notice that this configuration is quite similar the XML Namespace configuration: +Note that this configuration is parallels the XML Namespace configuration: +==== [source,xml] ---- @@ -166,13 +178,15 @@ You will notice that this configuration is quite similar the XML Namespace confi ---- +==== -== Multiple HttpSecurity +== Multiple HttpSecurity Instances -We can configure multiple HttpSecurity instances just as we can have multiple `` blocks. +We can configure multiple `HttpSecurity` instances just as we can have multiple `` blocks in XML. The key is to extend the `WebSecurityConfigurerAdapter` multiple times. -For example, the following is an example of having a different configuration for URL's that start with `/api/`. +The following example has a different configuration for URL's that start with `/api/`. +==== [source,java] ---- @EnableWebSecurity @@ -193,7 +207,7 @@ public class MultiHttpSecurityConfig { protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") <3> - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().hasRole("ADMIN") ) .httpBasic(withDefaults()); @@ -206,7 +220,7 @@ public class MultiHttpSecurityConfig { @Override protected void configure(HttpSecurity http) throws Exception { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .formLogin(withDefaults()); @@ -214,20 +228,20 @@ public class MultiHttpSecurityConfig { } } ---- - -<1> Configure Authentication as normal +<1> Configure Authentication as usual. <2> Create an instance of `WebSecurityConfigurerAdapter` that contains `@Order` to specify which `WebSecurityConfigurerAdapter` should be considered first. -<3> The `http.antMatcher` states that this `HttpSecurity` will only be applicable to URLs that start with `/api/` +<3> The `http.antMatcher` states that this `HttpSecurity` is applicable only to URLs that start with `/api/`. <4> Create another instance of `WebSecurityConfigurerAdapter`. -If the URL does not start with `/api/` this configuration will be used. -This configuration is considered after `ApiWebSecurityConfigurationAdapter` since it has an `@Order` value after `1` (no `@Order` defaults to last). +If the URL does not start with `/api/`, this configuration is used. +This configuration is considered after `ApiWebSecurityConfigurationAdapter`, since it has an `@Order` value after `1` (no `@Order` defaults to last). +==== [[jc-custom-dsls]] == Custom DSLs -You can provide your own custom DSLs in Spring Security. -For example, you might have something that looks like this: +You can provide your own custom DSLs in Spring Security: +==== [source,java] ---- public class MyCustomDsl extends AbstractHttpConfigurer { @@ -260,11 +274,16 @@ public class MyCustomDsl extends AbstractHttpConfigurer @@ -43,13 +49,15 @@ You will notice that this configuration is quite similar the XML Namespace confi ---- +==== -== Multiple HttpSecurity +== Multiple HttpSecurity Instances -We can configure multiple HttpSecurity instances just as we can have multiple `` blocks. +We can configure multiple HttpSecurity instances, just as we can have multiple `` blocks. The key is to extend the `WebSecurityConfigurerAdapter` multiple times. -For example, the following is an example of having a different configuration for URL's that start with `/api/`. +The following example has a different configuration for URL's that start with `/api/`: +==== [source,kotlin] ---- @EnableWebSecurity @@ -91,9 +99,10 @@ class MultiHttpSecurityConfig { } ---- -<1> Configure Authentication as normal +<1> Configure Authentication as usual. <2> Create an instance of `WebSecurityConfigurerAdapter` that contains `@Order` to specify which `WebSecurityConfigurerAdapter` should be considered first. -<3> The `http.antMatcher` states that this `HttpSecurity` will only be applicable to URLs that start with `/api/` +<3> The `http.antMatcher` states that this `HttpSecurity` is applicable only to URLs that start with `/api/` <4> Create another instance of `WebSecurityConfigurerAdapter`. -If the URL does not start with `/api/` this configuration will be used. -This configuration is considered after `ApiWebSecurityConfigurationAdapter` since it has an `@Order` value after `1` (no `@Order` defaults to last). +If the URL does not start with `/api/`, this configuration is used. +This configuration is considered after `ApiWebSecurityConfigurationAdapter`, since it has an `@Order` value after `1` (no `@Order` defaults to last). +==== diff --git a/docs/modules/ROOT/pages/servlet/configuration/xml-namespace.adoc b/docs/modules/ROOT/pages/servlet/configuration/xml-namespace.adoc index 0168114c1b4..7d8f6db55bf 100644 --- a/docs/modules/ROOT/pages/servlet/configuration/xml-namespace.adoc +++ b/docs/modules/ROOT/pages/servlet/configuration/xml-namespace.adoc @@ -3,29 +3,30 @@ = Security Namespace Configuration -== Introduction Namespace configuration has been available since version 2.0 of the Spring Framework. -It allows you to supplement the traditional Spring beans application context syntax with elements from additional XML schema. +It lets you supplement the traditional Spring beans application context syntax with elements from additional XML schema. You can find more information in the Spring https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/[Reference Documentation]. -A namespace element can be used simply to allow a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax which more closely matches the problem domain and hides the underlying complexity from the user. -A simple element may conceal the fact that multiple beans and processing steps are being added to the application context. -For example, adding the following element from the security namespace to an application context will start up an embedded LDAP server for testing use within the application: +You can use a namespace element to more concisely configure an individual bean or, more powerfully, to define an alternative configuration syntax that more closely matches the problem domain and hides the underlying complexity from the user. +A simple element can conceal the fact that multiple beans and processing steps are being added to the application context. +For example, adding the following element from the `security` namespace to an application context starts up an embedded LDAP server for testing use within the application: +==== [source,xml] ---- ---- +==== This is much simpler than wiring up the equivalent Apache Directory Server beans. -The most common alternative configuration requirements are supported by attributes on the `ldap-server` element and the user is isolated from worrying about which beans they need to create and what the bean property names are. -footnote:[You can find out more about the use of the `ldap-server` element in the chapter on pass:specialcharacters,macros[xref:servlet/authentication/unpwd/ldap.adoc#servlet-authentication-ldap[LDAP Authentication]].]. -Use of a good XML editor while editing the application context file should provide information on the attributes and elements that are available. -We would recommend that you try out the https://spring.io/tools[Eclipse IDE with Spring Tools] as it has special features for working with standard Spring namespaces. - +The most common alternative configuration requirements are supported by attributes on the `ldap-server` element, and the user is isolated from worrying about which beans they need to create and what the bean property names are. +You can find out more about the use of the `ldap-server` element in the chapter on xref:servlet/authentication/passwords/ldap.adoc#servlet-authentication-ldap[LDAP Authentication]. +A good XML editor while editing the application context file should provide information on the attributes and elements that are available. +We recommend that you try the https://spring.io/tools/sts[Spring Tool Suite], as it has special features for working with standard Spring namespaces. -To start using the security namespace in your application context, you need to have the `spring-security-config` jar on your classpath. -Then all you need to do is add the schema declaration to your application context file: +To start using the `security` namespace in your application context, add the `spring-security-config` jar to your classpath. +Then, all you need to do is add the schema declaration to your application context file: +==== [source,xml] ---- ` element. +Once you have added this bean to your `web.xml`, you are ready to start editing your application context file. +Web security services are configured by the `` element. [[ns-minimal]] === A Minimal Configuration -All you need to enable web security to begin with is +To enable web security, you need the following configuration: +==== [source,xml] ---- @@ -123,31 +130,36 @@ All you need to enable web security to begin with is ---- +==== + +That listing says that we want: + +* All URLs within our application to be secured, requiring the role `ROLE_USER` to access them +* To log in to the application using a form with username and password +* A logout URL registered which will allow us to log out of the application -Which says that we want all URLs within our application to be secured, requiring the role `ROLE_USER` to access them, we want to log in to the application using a form with username and password, and that we want a logout URL registered which will allow us to log out of the application. -`` element is the parent for all web-related namespace functionality. -The `` element defines a `pattern` which is matched against the URLs of incoming requests using an ant path style syntax footnote:[See the section on pass:specialcharacters,macros[xref:servlet/exploits/firewall.adoc#servlet-httpfirewall[`HttpFirewall`]] for more details on how matches are actually performed.]. +The `` element is the parent for all web-related namespace functionality. +The `` element defines a `pattern`, which is matched against the URLs of incoming requests using Ant path syntax. See the section on xref:servlet/exploits/firewall.adoc#servlet-httpfirewall[`HttpFirewall`] for more details on how matches are actually performed. You can also use regular-expression matching as an alternative (see the namespace appendix for more details). -The `access` attribute defines the access requirements for requests matching the given pattern. +The `access` attribute defines the access requirements for requests that match the given pattern. With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request. -The prefix "ROLE_" is a marker which indicates that a simple comparison with the user's authorities should be made. +The `ROLE_` prefix is a marker that indicates that a simple comparison with the user's authorities should be made. In other words, a normal role-based check should be used. Access-control in Spring Security is not limited to the use of simple roles (hence the use of the prefix to differentiate between different types of security attributes). -We'll see later how the interpretation can vary footnote:[The interpretation of the comma-separated values in the `access` attribute depends on the implementation of the <> which is used.]. -In Spring Security 3.0, the attribute can also be populated with an xref:servlet/authorization/expression-based.adoc#el-access[EL expression]. +We see later how the interpretation can vary. The interpretation of the comma-separated values in the `access` attribute depends on the which implementation of the <> is used. +Since Spring Security 3.0, you can also populate the attribute with an xref:servlet/authorization/expression-based.adoc#el-access[EL expression]. [NOTE] ==== - -You can use multiple `` elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used. +You can use multiple `` elements to define different access requirements for different sets of URLs, but they are evaluated in the order listed and the first match is used. So you must put the most specific matches at the top. -You can also add a `method` attribute to limit the match to a particular HTTP method (`GET`, `POST`, `PUT` etc.). - +You can also add a `method` attribute to limit the match to a particular HTTP method (`GET`, `POST`, `PUT`, and so on). ==== -To add some users, you can define a set of test data directly in the namespace: +To add users, you can define a set of test data directly in the namespace: +==== [source,xml,attrs="-attributes"] ---- @@ -162,10 +174,12 @@ To add some users, you can define a set of test data directly in the namespace: ---- +==== -This is an example of a secure way of storing the same passwords. +The preceding listing shows an example of a secure way to store the same passwords. The password is prefixed with `+{bcrypt}+` to instruct `DelegatingPasswordEncoder`, which supports any configured `PasswordEncoder` for matching, that the passwords are hashed using BCrypt: +==== [source,xml,attrs="-attributes"] ---- @@ -181,37 +195,37 @@ The password is prefixed with `+{bcrypt}+` to instruct `DelegatingPasswordEncode ---- - +==== [subs="quotes"] **** -If you are familiar with pre-namespace versions of the framework, you can probably already guess roughly what's going on here. -The `` element is responsible for creating a `FilterChainProxy` and the filter beans which it uses. -Common problems like incorrect filter ordering are no longer an issue as the filter positions are predefined. +The `` element is responsible for creating a `FilterChainProxy` and the filter beans that it uses. +Previously common problems, such as incorrect filter ordering, are no longer an issue, as the filter positions are predefined. -The `` element creates a `DaoAuthenticationProvider` bean and the `` element creates an `InMemoryDaoImpl`. +The `` element creates a `DaoAuthenticationProvider` bean, and the `` element creates an `InMemoryDaoImpl`. All `authentication-provider` elements must be children of the `` element, which creates a `ProviderManager` and registers the authentication providers with it. -You can find more detailed information on the beans that are created in the xref:servlet/appendix/namespace.adoc#appendix-namespace[namespace appendix]. -It's worth cross-checking this if you want to start understanding what the important classes in the framework are and how they are used, particularly if you want to customise things later. +You can find more detailed information on the beans that are created in the xref:servlet/appendix/namespace/index.adoc#appendix-namespace[namespace appendix]. +You should cross-check this appendix if you want to start understanding what the important classes in the framework are and how they are used, particularly if you want to customize things later. **** -The configuration above defines two users, their passwords and their roles within the application (which will be used for access control). -It is also possible to load user information from a standard properties file using the `properties` attribute on `user-service`. +The preceding configuration defines two users, their passwords, and their roles within the application (which are used for access control). +You can also possible load user information from a standard properties file by setting the `properties` attribute on the `user-service` element. See the section on xref:servlet/authentication/passwords/in-memory.adoc#servlet-authentication-inmemory[in-memory authentication] for more details on the file format. -Using the `` element means that the user information will be used by the authentication manager to process authentication requests. -You can have multiple `` elements to define different authentication sources and each will be consulted in turn. +Using the `` element means that the user information is used by the authentication manager to process authentication requests. +You can have multiple `` elements to define different authentication sources. Each is consulted in turn. -At this point you should be able to start up your application and you will be required to log in to proceed. -Try it out, or try experimenting with the "tutorial" sample application that comes with the project. +At this point, you should be able to start up your application, and you should be required to log in to proceed. +Try it out, or try experimenting with the "`tutorial`" sample application that comes with the project. [[ns-form-target]] ==== Setting a Default Post-Login Destination -If a form login isn't prompted by an attempt to access a protected resource, the `default-target-url` option comes into play. -This is the URL the user will be taken to after successfully logging in, and defaults to "/". -You can also configure things so that the user __always__ ends up at this page (regardless of whether the login was "on-demand" or they explicitly chose to log in) by setting the `always-use-default-target` attribute to "true". -This is useful if your application always requires that the user starts at a "home" page, for example: +If a form login is not prompted by an attempt to access a protected resource, the `default-target-url` option comes into play. +This is the URL to which the user is taken after successfully logging in. it defaults to `/`. +You can also configure things so that the user _always_ ends up at this page (regardless of whether the login was "`on-demand`" or they explicitly chose to log in) by setting the `always-use-default-target` attribute to `true`. +This is useful if your application always requires that the user starts at a "`home`" page, for example: +==== [source,xml] ---- @@ -221,6 +235,7 @@ This is useful if your application always requires that the user starts at a "ho always-use-default-target='true' /> ---- +==== For even more control over the destination, you can use the `authentication-success-handler-ref` attribute as an alternative to `default-target-url`. The referenced bean should be an instance of `AuthenticationSuccessHandler`. @@ -228,15 +243,18 @@ The referenced bean should be an instance of `AuthenticationSuccessHandler`. [[ns-web-advanced]] == Advanced Web Features +This section covers various features that go beyond the basics. + [[ns-custom-filters]] === Adding in Your Own Filters -If you've used Spring Security before, you'll know that the framework maintains a chain of filters in order to apply its services. -You may want to add your own filters to the stack at particular locations or use a Spring Security filter for which there isn't currently a namespace configuration option (CAS, for example). -Or you might want to use a customized version of a standard namespace filter, such as the `UsernamePasswordAuthenticationFilter` which is created by the `` element, taking advantage of some of the extra configuration options which are available by using the bean explicitly. +If you have used Spring Security before, you know that the framework maintains a chain of filters that it uses to apply its services. +You may want to add your own filters to the stack at particular locations or use a Spring Security filter for which there is not currently a namespace configuration option (CAS, for example). +// FIXME: Is it still true that there is no CAS filter? +Alternatively, you might want to use a customized version of a standard namespace filter, such as the `UsernamePasswordAuthenticationFilter` (which is created by the `` element) to take advantage of some of the extra configuration options that are available when you use the bean explicitly. How can you do this with namespace configuration, since the filter chain is not directly exposed? -The order of the filters is always strictly enforced when using the namespace. -When the application context is being created, the filter beans are sorted by the namespace handling code and the standard Spring Security filters each have an alias in the namespace and a well-known position. +The order of the filters is always strictly enforced when you use the namespace. +When the application context is being created, the filter beans are sorted by the namespace handling code, and the standard Spring Security filters each have an alias in the namespace and a well-known position. [NOTE] ==== @@ -245,8 +263,7 @@ In version 3.0+ the sorting is now done at the bean metadata level, before the c This has implications for how you add your own filters to the stack as the entire filter list must be known during the parsing of the `` element, so the syntax has changed slightly in 3.0. ==== -The filters, aliases and namespace elements/attributes which create the filters are shown in <>. -The filters are listed in the order in which they occur in the filter chain. +The filters, aliases, and namespace elements and attributes that create the filters are shown in the following table, in the order in which they occur in the filter chain: [[filter-stack]] .Standard Filter Aliases and Ordering @@ -330,8 +347,9 @@ The filters are listed in the order in which they occur in the filter chain. | N/A |=== -You can add your own filter to the stack, using the `custom-filter` element and one of these names to specify the position your filter should appear at: +You can add your own filter to the stack by using the `custom-filter` element and one of these names to specify the position at which your filter should appear: +==== [source,xml] ---- @@ -340,40 +358,36 @@ You can add your own filter to the stack, using the `custom-filter` element and ---- +==== You can also use the `after` or `before` attributes if you want your filter to be inserted before or after another filter in the stack. -The names "FIRST" and "LAST" can be used with the `position` attribute to indicate that you want your filter to appear before or after the entire stack, respectively. +You can use `FIRST` and `LAST` with the `position` attribute to indicate that you want your filter to appear before or after the entire stack, respectively. .Avoiding filter position conflicts [TIP] ==== +If you insert a custom filter that may occupy the same position as one of the standard filters created by the namespace, you should not include the namespace versions by mistake. +Remove any elements that create filters whose functionality you want to replace. -If you are inserting a custom filter which may occupy the same position as one of the standard filters created by the namespace then it's important that you don't include the namespace versions by mistake. -Remove any elements which create filters whose functionality you want to replace. - -Note that you can't replace filters which are created by the use of the `` element itself - `SecurityContextPersistenceFilter`, `ExceptionTranslationFilter` or `FilterSecurityInterceptor`. -Some other filters are added by default, but you can disable them. -An `AnonymousAuthenticationFilter` is added by default and unless you have xref:servlet/authentication/session-management.adoc#ns-session-fixation[session-fixation protection] disabled, a `SessionManagementFilter` will also be added to the filter chain. - +Note that you cannot replace filters that are created by the use of the `` element itself: `SecurityContextPersistenceFilter`, `ExceptionTranslationFilter`, or `FilterSecurityInterceptor`. +By default, an `AnonymousAuthenticationFilter` is added and unless you have xref:servlet/authentication/session-management.adoc#ns-session-fixation[session-fixation protection] disabled, a `SessionManagementFilter` is also added to the filter chain. ==== -If you're replacing a namespace filter which requires an authentication entry point (i.e. where the authentication process is triggered by an attempt by an unauthenticated user to access to a secured resource), you will need to add a custom entry point bean too. - - +If you replace a namespace filter that requires an authentication entry point (that is, where the authentication process is triggered by an unauthenticated user's attempt to access to a secured resource), you need to add a custom entry-point bean too. [[ns-method-security]] == Method Security -From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. +Since version 2.0, Spring Security has substantial support for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the framework's original `@Secured` annotation. -From 3.0 you can also make use of new xref:servlet/authorization/expression-based.adoc#el-access[expression-based annotations]. -You can apply security to a single bean, using the `intercept-methods` element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts. +Since version 3.0, you can also make use of xref:servlet/authorization/expression-based.adoc#el-access[expression-based annotations]. +You can apply security to a single bean (by using the `intercept-methods` element to decorate the bean declaration), or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts. [[ns-access-manager]] == The Default AccessDecisionManager -This section assumes you have some knowledge of the underlying architecture for access-control within Spring Security. -If you don't you can skip it and come back to it later, as this section is only really relevant for people who need to do some customization in order to use more than simple role-based security. +This section assumes that you have some knowledge of the underlying architecture for access-control within Spring Security. +If you do not, you can skip it and come back to it later, as this section is relevant only for people who need to do some customization to use more than simple role-based security. -When you use a namespace configuration, a default instance of `AccessDecisionManager` is automatically registered for you and will be used for making access decisions for method invocations and web URL access, based on the access attributes you specify in your `intercept-url` and `protect-pointcut` declarations (and in annotations if you are using annotation secured methods). +When you use a namespace configuration, a default instance of `AccessDecisionManager` is automatically registered for you and is used to make access decisions for method invocations and web URL access, based on the access attributes you specify in your `intercept-url` and `protect-pointcut` declarations (and in annotations, if you use annotations to secure methods). The default strategy is to use an `AffirmativeBased` `AccessDecisionManager` with a `RoleVoter` and an `AuthenticatedVoter`. You can find out more about these in the chapter on xref:servlet/authorization/architecture.adoc#authz-arch[authorization]. @@ -381,22 +395,26 @@ You can find out more about these in the chapter on xref:servlet/authorization/a [[ns-custom-access-mgr]] === Customizing the AccessDecisionManager -If you need to use a more complicated access control strategy then it is easy to set an alternative for both method and web security. +If you need to use a more complicated access control strategy, you can set an alternative for both method and web security. -For method security, you do this by setting the `access-decision-manager-ref` attribute on `global-method-security` to the `id` of the appropriate `AccessDecisionManager` bean in the application context: +For method security, you do so by setting the `access-decision-manager-ref` attribute on `global-method-security` to the `id` of the appropriate `AccessDecisionManager` bean in the application context: +==== [source,xml] ---- ... ---- +==== -The syntax for web security is the same, but on the `http` element: +The syntax for web security is the same, but the attribute is on the `http` element: +==== [source,xml] ---- ... ---- +==== diff --git a/docs/modules/ROOT/pages/servlet/exploits/csrf.adoc b/docs/modules/ROOT/pages/servlet/exploits/csrf.adoc index fc2d4907353..8b298cdab6c 100644 --- a/docs/modules/ROOT/pages/servlet/exploits/csrf.adoc +++ b/docs/modules/ROOT/pages/servlet/exploits/csrf.adoc @@ -7,32 +7,32 @@ This section discusses Spring Security's xref:features/exploits/csrf.adoc#csrf[C == Using Spring Security CSRF Protection The steps to using Spring Security's CSRF protection are outlined below: -* <> -* <> -* <> +* <> +* <> +* <> [[servlet-csrf-idempotent]] === Use proper HTTP verbs -The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. +The first step to protecting against CSRF attacks is to ensure that your website uses proper HTTP verbs. This is covered in detail in xref:features/exploits/csrf.adoc#csrf-protection-idempotent[Safe Methods Must be Idempotent]. [[servlet-csrf-configure]] === Configure CSRF Protection The next step is to configure Spring Security's CSRF protection within your application. Spring Security's CSRF protection is enabled by default, but you may need to customize the configuration. -Below are a few common customizations. +The next few sections cover a few common customizations. [[servlet-csrf-configure-custom-repository]] ==== Custom CsrfTokenRepository -By default Spring Security stores the expected CSRF token in the `HttpSession` using `HttpSessionCsrfTokenRepository`. -There can be cases where users will want to configure a custom `CsrfTokenRepository`. -For example, it might be desirable to persist the `CsrfToken` in a cookie to <>. +By default, Spring Security stores the expected CSRF token in the `HttpSession` by using `HttpSessionCsrfTokenRepository`. +There can be cases where users want to configure a custom `CsrfTokenRepository`. +For example, it might be desirable to persist the `CsrfToken` in a cookie to <>. -By default the `CookieCsrfTokenRepository` will write to a cookie named `XSRF-TOKEN` and read it from a header named `X-XSRF-TOKEN` or the HTTP parameter `_csrf`. -These defaults come from https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection[AngularJS] +By default, the `CookieCsrfTokenRepository` writes to a cookie named `XSRF-TOKEN` and reads it from a header named `X-XSRF-TOKEN` or the HTTP parameter `_csrf`. +These defaults come from https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection[AngularJS]. -You can configure `CookieCsrfTokenRepository` in XML using the following: +You can configure `CookieCsrfTokenRepository` in XML byusing the following: .Store CSRF Token in a Cookie with XML Configuration @@ -52,12 +52,12 @@ You can configure `CookieCsrfTokenRepository` in XML using the following: [NOTE] ==== The sample explicitly sets `cookieHttpOnly=false`. -This is necessary to allow JavaScript (i.e. AngularJS) to read it. -If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit `cookieHttpOnly=false` to improve security. +This is necessary to allow JavaScript (such as AngularJS) to read it. +If you do not need the ability to read the cookie with JavaScript directly, we recommend omitting `cookieHttpOnly=false` to improve security. ==== -You can configure `CookieCsrfTokenRepository` in Java Configuration using: +You can configure `CookieCsrfTokenRepository` in Java or Kotlin configuration by using: .Store CSRF Token in a Cookie ==== @@ -98,17 +98,16 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { [NOTE] ==== The sample explicitly sets `cookieHttpOnly=false`. -This is necessary to allow JavaScript (i.e. AngularJS) to read it. -If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit `cookieHttpOnly=false` (by using `new CookieCsrfTokenRepository()` instead) to improve security. +This is necessary to let JavaScript (such as AngularJS) read it. +If you do not need the ability to read the cookie with JavaScript directly, we recommend omitting `cookieHttpOnly=false` (by using `new CookieCsrfTokenRepository()` instead) to improve security. ==== [[servlet-csrf-configure-disable]] ==== Disable CSRF Protection -CSRF protection is enabled by default. -However, it is simple to disable CSRF protection if it xref:features/exploits/csrf.adoc#csrf-when[makes sense for your application]. - -The XML configuration below will disable CSRF protection. +By default, CSRF protection is enabled. +However, you can disable CSRF protection if it xref:features/exploits/csrf.adoc#csrf-when[makes sense for your application]. +The following XML configuration disables CSRF protection: .Disable CSRF XML Configuration ==== @@ -121,7 +120,7 @@ The XML configuration below will disable CSRF protection. ---- ==== -The Java configuration below will disable CSRF protection. +The following Java or Kotlin configuration disables CSRF protection: .Disable CSRF ==== @@ -162,16 +161,16 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { [[servlet-csrf-include]] === Include the CSRF Token -In order for the xref:features/exploits/csrf.adoc#csrf-protection-stp[synchronizer token pattern] to protect against CSRF attacks, we must include the actual CSRF token in the HTTP request. -This must be included in a part of the request (i.e. form parameter, HTTP header, etc) that is not automatically included in the HTTP request by the browser. +For the xref:features/exploits/csrf.adoc#csrf-protection-stp[synchronizer token pattern] to protect against CSRF attacks, we must include the actual CSRF token in the HTTP request. +This must be included in a part of the request (a form parameter, an HTTP header, or other part) that is not automatically included in the HTTP request by the browser. -Spring Security's https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfFilter.html[CsrfFilter] exposes a https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfToken.html[CsrfToken] as an `HttpServletRequest` attribute named `_csrf`. +Spring Security's https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfFilter.html[`CsrfFilter`] exposes a https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfToken.html[`CsrfToken`] as an `HttpServletRequest` attribute named `_csrf`. This means that any view technology can access the `CsrfToken` to expose the expected token as either a <> or <>. -Fortunately, there are integrations listed below that make including the token in <> and <> requests even easier. +Fortunately, there are integrations listed later in this chapter that make including the token in <> and <> requests even easier. [[servlet-csrf-include-form]] ==== Form URL Encoded -In order to post an HTML form the CSRF token must be included in the form as a hidden input. +To post an HTML form, the CSRF token must be included in the form as a hidden input. For example, the rendered HTML might look like: .CSRF Token HTML @@ -184,26 +183,26 @@ For example, the rendered HTML might look like: ---- ==== -Next we will discuss various ways of including the CSRF token in a form as a hidden input. +Next, we discuss various ways of including the CSRF token in a form as a hidden input. [[servlet-csrf-include-form-auto]] ===== Automatic CSRF Token Inclusion -Spring Security's CSRF support provides integration with Spring's https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/support/RequestDataValueProcessor.html[RequestDataValueProcessor] via its https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/servlet/support/csrf/CsrfRequestDataValueProcessor.html[CsrfRequestDataValueProcessor]. -This means that if you leverage https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib[Spring’s form tag library], https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#integration-with-requestdatavalueprocessor[Thymeleaf], or any other view technology that integrates with `RequestDataValueProcessor`, then forms that have an unsafe HTTP method (i.e. post) will automatically include the actual CSRF token. +Spring Security's CSRF support provides integration with Spring's https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/support/RequestDataValueProcessor.html[`RequestDataValueProcessor`] through its https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/servlet/support/csrf/CsrfRequestDataValueProcessor.html[`CsrfRequestDataValueProcessor`]. +This means that, if you use https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib[Spring’s form tag library], https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#integration-with-requestdatavalueprocessor[Thymeleaf], or any other view technology that integrates with `RequestDataValueProcessor`, then forms that have an unsafe HTTP method (such as post) automatically include the actual CSRF token. [[servlet-csrf-include-form-tag]] ===== csrfInput Tag -If you are using JSPs, then you can use https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib[Spring’s form tag library]. -However, if that is not an option, you can also easily include the token with the xref:servlet/integrations/jsp-taglibs.adoc#taglibs-csrfinput[csrfInput] tag. +If you use JSPs, you can use https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib[Spring’s form tag library]. +However, if that is not an option, you can also include the token with the xref:servlet/integrations/jsp-taglibs.adoc#taglibs-csrfinput[csrfInput] tag. [[servlet-csrf-include-form-attr]] ===== CsrfToken Request Attribute If the <> for including the actual CSRF token in the request do not work, you can take advantage of the fact that the `CsrfToken` <> as an `HttpServletRequest` attribute named `_csrf`. -An example of doing this with a JSP is shown below: +The following example does this with a JSP: .CSRF Token in Form with Request Attribute ==== @@ -223,19 +222,19 @@ An example of doing this with a JSP is shown below: [[servlet-csrf-include-ajax]] ==== Ajax and JSON Requests -If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. -Instead you can submit the token within a HTTP header. +If you use JSON, you cannot submit the CSRF token within an HTTP parameter. +Instead, you can submit the token within a HTTP header. -In the following sections we will discuss various ways of including the CSRF token as an HTTP request header in JavaScript based applications. +The following sections discuss various ways of including the CSRF token as an HTTP request header in JavaScript based applications. [[servlet-csrf-include-ajax-auto]] ===== Automatic Inclusion -Spring Security can easily be <> to store the expected CSRF token in a cookie. -By storing the expected CSRF in a cookie, JavaScript frameworks like https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection[AngularJS] will automatically include the actual CSRF token in the HTTP request headers. +You can <> Spring Security to store the expected CSRF token in a cookie. +By storing the expected CSRF in a cookie, JavaScript frameworks, such as https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection[AngularJS], automatically include the actual CSRF token in the HTTP request headers. [[servlet-csrf-include-ajax-meta]] -===== Meta tags +===== Meta Tags An alternative pattern to <> is to include the CSRF token within your `meta` tags. The HTML might look something like this: @@ -254,8 +253,8 @@ The HTML might look something like this: ---- ==== -Once the meta tags contained the CSRF token, the JavaScript code would read the meta tags and include the CSRF token as a header. -If you were using jQuery, this could be done with the following: +Once the meta tags contain the CSRF token, the JavaScript code can read the meta tags and include the CSRF token as a header. +If you use jQuery, you can do this with the following code: .AJAX send CSRF Token ==== @@ -274,13 +273,13 @@ $(function () { [[servlet-csrf-include-ajax-meta-tag]] ====== csrfMeta tag -If you are using JSPs a simple way to write the CSRF token to the `meta` tags is by leveraging the xref:servlet/integrations/jsp-taglibs.adoc#taglibs-csrfmeta[csrfMeta] tag. +If you use JSPs, one way to write the CSRF token to the `meta` tags is by using the xref:servlet/integrations/jsp-taglibs.adoc#taglibs-csrfmeta[csrfMeta] tag. [[servlet-csrf-include-ajax-meta-attr]] ====== CsrfToken Request Attribute If the <> for including the actual CSRF token in the request do not work, you can take advantage of the fact that the `CsrfToken` <> as an `HttpServletRequest` attribute named `_csrf`. -An example of doing this with a JSP is shown below: +The following example does this with a JSP: .CSRF meta tag JSP ==== @@ -300,8 +299,8 @@ An example of doing this with a JSP is shown below: [[servlet-csrf-considerations]] == CSRF Considerations There are a few special considerations to consider when implementing protection against CSRF attacks. -This section discusses those considerations as it pertains to servlet environments. -Refer to xref:features/exploits/csrf.adoc#csrf-considerations[CSRF Considerations] for a more general discussion. +This section discusses those considerations as they pertain to servlet environments. +See xref:features/exploits/csrf.adoc#csrf-considerations[CSRF Considerations] for a more general discussion. [[servlet-considerations-csrf-login]] @@ -313,18 +312,18 @@ Spring Security's servlet support does this out of the box. [[servlet-considerations-csrf-logout]] === Logging Out -It is important to xref:features/exploits/csrf.adoc#csrf-considerations-logout[require CSRF for log out] requests to protect against forging log out attempts. -If CSRF protection is enabled (default), Spring Security's `LogoutFilter` to only process HTTP POST. -This ensures that log out requires a CSRF token and that a malicious user cannot forcibly log out your users. +It is important to xref:features/exploits/csrf.adoc#csrf-considerations-logout[require CSRF for log out] requests to protect against forging logout attempts. +If CSRF protection is enabled (the default), Spring Security's `LogoutFilter` to only process HTTP POST. +This ensures that logging out requires a CSRF token and that a malicious user cannot forcibly log out your users. The easiest approach is to use a form to log out. -If you really want a link, you can use JavaScript to have the link perform a POST (i.e. maybe on a hidden form). -For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that will perform the POST. +If you really want a link, you can use JavaScript to have the link perform a POST (maybe on a hidden form). +For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that performs the POST. -If you really want to use HTTP GET with logout you can do so, but remember this is generally not recommended. -For example, the following Java Configuration will perform logout with the URL `/logout` is requested with any HTTP method: +If you really want to use HTTP GET with logout, you can do so. However, remember that this is generally not recommended. +For example, the following Java Configuration logs out when the `/logout` URL is requested with any HTTP method: -.Log out with HTTP GET +.Log out with any HTTP method ==== .Java [source,java,role="primary"] @@ -364,18 +363,18 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { [[servlet-considerations-csrf-timeouts]] === CSRF and Session Timeouts -By default Spring Security stores the CSRF token in the `HttpSession`. -This can lead to a situation where the session expires which means there is not an expected CSRF token to validate against. +By default, Spring Security stores the CSRF token in the `HttpSession`. +This can lead to a situation where the session expires, leaving no CSRF token to validate against. -We've already discussed xref:features/exploits/csrf.adoc#csrf-considerations-login[general solutions] to session timeouts. +We have already discussed xref:features/exploits/csrf.adoc#csrf-considerations-login[general solutions] to session timeouts. This section discusses the specifics of CSRF timeouts as it pertains to the servlet support. -It is simple to change storage of the expected CSRF token to be in a cookie. -For details, refer to the <> section. +You can change the storage of the CSRF token to be in a cookie. +For details, see the <> section. If a token does expire, you might want to customize how it is handled by specifying a custom `AccessDeniedHandler`. The custom `AccessDeniedHandler` can process the `InvalidCsrfTokenException` any way you like. -For an example of how to customize the `AccessDeniedHandler` refer to the provided links for both xref:servlet/appendix/namespace.adoc#nsa-access-denied-handler[xml] and {gh-url}/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java#L64[Java configuration]. +For an example of how to customize the `AccessDeniedHandler`, see the provided links for both xref:servlet/appendix/namespace/http.adoc#nsa-access-denied-handler[xml] and {gh-url}/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java#L64[Java configuration]. // FIXME: We should add a custom AccessDeniedHandler section in the reference and update the links above @@ -386,23 +385,23 @@ This section discusses how to implement placing the CSRF token in the <` element of the `MultipartFilter` is placed before the `springSecurityFilterChain` within the `web.xml` file: .Initializer MultipartFilter ==== @@ -455,11 +454,11 @@ To ensure `MultipartFilter` is specified before the Spring Security filter with ==== [[servlet-csrf-considerations-multipart-url]] -==== Include CSRF Token in URL +==== Include a CSRF Token in a URL -If allowing unauthorized users to upload temporary files is not acceptable, an alternative is to place the `MultipartFilter` after the Spring Security filter and include the CSRF as a query parameter in the action attribute of the form. +If letting unauthorized users upload temporary files is not acceptable, an alternative is to place the `MultipartFilter` after the Spring Security filter and include the CSRF as a query parameter in the action attribute of the form. Since the `CsrfToken` is exposed as an `HttpServletRequest` <>, we can use that to create an `action` with the CSRF token in it. -An example with a jsp is shown below +The following example does this with a JSP: .CSRF Token in Action ==== @@ -475,5 +474,5 @@ An example with a jsp is shown below === HiddenHttpMethodFilter We have xref:features/exploits/csrf.adoc#csrf-considerations-multipart-body[already discussed] the trade-offs of placing the CSRF token in the body. -In Spring's Servlet support, overriding the HTTP method is done using https://docs.spring.io/spring-framework/docs/5.2.x/javadoc-api/org/springframework/web/filter/reactive/HiddenHttpMethodFilter.html[HiddenHttpMethodFilter]. -More information can be found in https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web.html#mvc-rest-method-conversion[HTTP Method Conversion] section of the reference documentation. +In Spring's Servlet support, overriding the HTTP method is done by using https://docs.spring.io/spring-framework/docs/5.2.x/javadoc-api/org/springframework/web/filter/reactive/HiddenHttpMethodFilter.html[`HiddenHttpMethodFilter`]. +You can find more information in the https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web.html#mvc-rest-method-conversion[HTTP Method Conversion] section of the reference documentation. diff --git a/docs/modules/ROOT/pages/servlet/exploits/firewall.adoc b/docs/modules/ROOT/pages/servlet/exploits/firewall.adoc index 7560afd6f0a..2231230ff2c 100644 --- a/docs/modules/ROOT/pages/servlet/exploits/firewall.adoc +++ b/docs/modules/ROOT/pages/servlet/exploits/firewall.adoc @@ -1,49 +1,49 @@ [[servlet-httpfirewall]] = HttpFirewall -Spring Security has several areas where patterns you have defined are tested against incoming requests in order to decide how the request should be handled. -This occurs when the `FilterChainProxy` decides which filter chain a request should be passed through and also when the `FilterSecurityInterceptor` decides which security constraints apply to a request. -It's important to understand what the mechanism is and what URL value is used when testing against the patterns that you define. +Spring Security has several areas where patterns you have defined are tested against incoming requests to decide how the request should be handled. +This occurs when the `FilterChainProxy` decides which filter chain a request should be passed through and when the `FilterSecurityInterceptor` decides which security constraints apply to a request. +It is important to understand what the mechanism is and what URL value is used when testing against the patterns that you define. -The Servlet Specification defines several properties for the `HttpServletRequest` which are accessible via getter methods, and which we might want to match against. -These are the `contextPath`, `servletPath`, `pathInfo` and `queryString`. +The servlet specification defines several properties for the `HttpServletRequest` that are accessible via getter methods and that we might want to match against. +These are the `contextPath`, `servletPath`, `pathInfo`, and `queryString`. Spring Security is only interested in securing paths within the application, so the `contextPath` is ignored. -Unfortunately, the servlet spec does not define exactly what the values of `servletPath` and `pathInfo` will contain for a particular request URI. +Unfortunately, the servlet spec does not define exactly what the values of `servletPath` and `pathInfo` contain for a particular request URI. For example, each path segment of a URL may contain parameters, as defined in https://www.ietf.org/rfc/rfc2396.txt[RFC 2396] -footnote:[You have probably seen this when a browser doesn't support cookies and the `jsessionid` parameter is appended to the URL after a semi-colon. -However the RFC allows the presence of these parameters in any path segment of the URL]. -The Specification does not clearly state whether these should be included in the `servletPath` and `pathInfo` values and the behaviour varies between different servlet containers. -There is a danger that when an application is deployed in a container which does not strip path parameters from these values, an attacker could add them to the requested URL in order to cause a pattern match to succeed or fail unexpectedly. -footnote:[The original values will be returned once the request leaves the `FilterChainProxy`, so will still be available to the application.]. +(You have probably seen this when a browser does not support cookies and the `jsessionid` parameter is appended to the URL after a semicolon. +However, the RFC allows the presence of these parameters in any path segment of the URL.) +The Specification does not clearly state whether these should be included in the `servletPath` and `pathInfo` values and the behavior varies between different servlet containers. +There is a danger that, when an application is deployed in a container that does not strip path parameters from these values, an attacker could add them to the requested URL to cause a pattern match to succeed or fail unexpectedly. +(The original values will be returned once the request leaves the `FilterChainProxy`, so will still be available to the application.) Other variations in the incoming URL are also possible. -For example, it could contain path-traversal sequences (like `/../`) or multiple forward slashes (`//`) which could also cause pattern-matches to fail. -Some containers normalize these out before performing the servlet mapping, but others don't. +For example, it could contain path-traversal sequences (such as `/../`) or multiple forward slashes (`//`) that could also cause pattern-matches to fail. +Some containers normalize these out before performing the servlet mapping, but others do not. To protect against issues like these, `FilterChainProxy` uses an `HttpFirewall` strategy to check and wrap the request. -Un-normalized requests are automatically rejected by default, and path parameters and duplicate slashes are removed for matching purposes. -footnote:[So, for example, an original request path `/secure;hack=1/somefile.html;hack=2` will be returned as `/secure/somefile.html`.]. -It is therefore essential that a `FilterChainProxy` is used to manage the security filter chain. -Note that the `servletPath` and `pathInfo` values are decoded by the container, so your application should not have any valid paths which contain semi-colons, as these parts will be removed for matching purposes. +By default, un-normalized requests are automatically rejected, and path parameters and duplicate slashes are removed for matching purposes. +(So, for example, an original request path of `/secure;hack=1/somefile.html;hack=2` is returned as `/secure/somefile.html`.) +It is, therefore, essential that a `FilterChainProxy` is used to manage the security filter chain. +Note that the `servletPath` and `pathInfo` values are decoded by the container, so your application should not have any valid paths that contain semi-colons, as these parts are removed for matching purposes. -As mentioned above, the default strategy is to use Ant-style paths for matching and this is likely to be the best choice for most users. -The strategy is implemented in the class `AntPathRequestMatcher` which uses Spring's `AntPathMatcher` to perform a case-insensitive match of the pattern against the concatenated `servletPath` and `pathInfo`, ignoring the `queryString`. +As mentioned earlier, the default strategy is to use Ant-style paths for matching, and this is likely to be the best choice for most users. +The strategy is implemented in the class `AntPathRequestMatcher`, which uses Spring's `AntPathMatcher` to perform a case-insensitive match of the pattern against the concatenated `servletPath` and `pathInfo`, ignoring the `queryString`. -If for some reason, you need a more powerful matching strategy, you can use regular expressions. +If you need a more powerful matching strategy, you can use regular expressions. The strategy implementation is then `RegexRequestMatcher`. -See the Javadoc for this class for more information. +See the {security-api-url}/org/springframework/security/web/util/matcher/RegexRequestMatcher.html[Javadoc for this class] for more information. -In practice we recommend that you use method security at your service layer, to control access to your application, and do not rely entirely on the use of security constraints defined at the web-application level. -URLs change and it is difficult to take account of all the possible URLs that an application might support and how requests might be manipulated. -You should try and restrict yourself to using a few simple ant paths which are simple to understand. -Always try to use a "deny-by-default" approach where you have a catch-all wildcard ( /** or **) defined last and denying access. +In practice, we recommend that you use method security at your service layer, to control access to your application, rather than rely entirely on the use of security constraints defined at the web-application level. +URLs change, and it is difficult to take into account all the possible URLs that an application might support and how requests might be manipulated. +You should restrict yourself to using a few simple Ant paths that are simple to understand. +Always try to use a "`deny-by-default`" approach, where you have a catch-all wildcard (`/**` or `**`) defined last to deny access. Security defined at the service layer is much more robust and harder to bypass, so you should always take advantage of Spring Security's method security options. The `HttpFirewall` also prevents https://www.owasp.org/index.php/HTTP_Response_Splitting[HTTP Response Splitting] by rejecting new line characters in the HTTP Response headers. -By default the `StrictHttpFirewall` is used. +By default, the `StrictHttpFirewall` implementation is used. This implementation rejects requests that appear to be malicious. -If it is too strict for your needs, then you can customize what types of requests are rejected. +If it is too strict for your needs, you can customize what types of requests are rejected. However, it is important that you do so knowing that this can open your application up to attacks. -For example, if you wish to leverage Spring MVC's Matrix Variables, the following configuration could be used: +For example, if you wish to use Spring MVC's matrix variables, you could use the following configuration: .Allow Matrix Variables ==== @@ -80,10 +80,10 @@ fun httpFirewall(): StrictHttpFirewall { ---- ==== -The `StrictHttpFirewall` provides an allowed list of valid HTTP methods that are allowed to protect against https://owasp.org/www-community/attacks/Cross_Site_Tracing[Cross Site Tracing (XST)] and https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/06-Test_HTTP_Methods[HTTP Verb Tampering]. -The default valid methods are "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", and "PUT". +To protect against https://www.owasp.org/index.php/Cross_Site_Tracing[Cross Site Tracing (XST)] and https://www.owasp.org/index.php/Test_HTTP_Methods_(OTG-CONFIG-006)[HTTP Verb Tampering], the `StrictHttpFirewall` provides an allowed list of valid HTTP methods that are allowed. +The default valid methods are `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, and `PUT`. If your application needs to modify the valid methods, you can configure a custom `StrictHttpFirewall` bean. -For example, the following will only allow HTTP "GET" and "POST" methods: +The following example allows only HTTP `GET` and `POST` methods: .Allow Only GET & POST @@ -123,29 +123,32 @@ fun httpFirewall(): StrictHttpFirewall { [TIP] ==== -If you are using `new MockHttpServletRequest()` it currently creates an HTTP method as an empty String "". -This is an invalid HTTP method and will be rejected by Spring Security. +If you use `new MockHttpServletRequest()`, it currently creates an HTTP method as an empty String (`""`). +This is an invalid HTTP method and is rejected by Spring Security. You can resolve this by replacing it with `new MockHttpServletRequest("GET", "")`. -See https://jira.spring.io/browse/SPR-16851[SPR_16851] for an issue requesting to improve this. +See https://jira.spring.io/browse/SPR-16851[SPR_16851] for an issue that requests improving this. ==== If you must allow any HTTP method (not recommended), you can use `StrictHttpFirewall.setUnsafeAllowAnyHttpMethod(true)`. -This will disable validation of the HTTP method entirely. +Doing so entirely disables validation of the HTTP method. [[servlet-httpfirewall-headers-parameters]] `StrictHttpFirewall` also checks header names and values and parameter names. It requires that each character have a defined code point and not be a control character. -This requirement can be relaxed or adjusted as necessary using the following methods: +This requirement can be relaxed or adjusted as necessary by using the following methods: * `StrictHttpFirewall#setAllowedHeaderNames(Predicate)` * `StrictHttpFirewall#setAllowedHeaderValues(Predicate)` * `StrictHttpFirewall#setAllowedParameterNames(Predicate)` -NOTE: Also, parameter values can be controlled with `setAllowedParameterValues(Predicate)`. +[NOTE] +==== +Parameter values can be also controlled with `setAllowedParameterValues(Predicate)`. +==== -For example, to switch off this check, you can wire your `StrictHttpFirewall` with ``Predicate``s that always return `true`, like so: +For example, to switch off this check, you can wire your `StrictHttpFirewall` with `Predicate` instances that always return `true`: .Allow Any Header Name, Header Value, and Parameter Name ==== @@ -176,12 +179,12 @@ fun httpFirewall(): StrictHttpFirewall { ---- ==== -Or, there might be a specific value that you need to allow. +Alternatively, there might be a specific value that you need to allow. -For example, iPhone Xʀ uses a `User-Agent` that includes a character not in the ISO-8859-1 charset. -Due to this fact, some application servers will parse this value into two separate characters, the latter being an undefined character. +For example, iPhone Xʀ uses a `User-Agent` that includes a character that is not in the ISO-8859-1 charset. +Due to this fact, some application servers parse this value into two separate characters, the latter being an undefined character. -You can address this with the `setAllowedHeaderValues` method, as you can see below: +You can address this with the `setAllowedHeaderValues` method: .Allow Certain User Agents ==== @@ -212,7 +215,7 @@ fun httpFirewall(): StrictHttpFirewall { ---- ==== -In the case of header values, you may instead consider parsing them as UTF-8 at verification time like so: +In the case of header values, you may instead consider parsing them as UTF-8 at verification time: .Parse Headers As UTF-8 ==== diff --git a/docs/modules/ROOT/pages/servlet/exploits/headers.adoc b/docs/modules/ROOT/pages/servlet/exploits/headers.adoc index 535f3e976bb..8e2b372d0c4 100644 --- a/docs/modules/ROOT/pages/servlet/exploits/headers.adoc +++ b/docs/modules/ROOT/pages/servlet/exploits/headers.adoc @@ -1,19 +1,19 @@ [[servlet-headers]] = Security HTTP Response Headers -xref:features/exploits/headers.adoc#headers[Security HTTP Response Headers] can be used to increase the security of web applications. -This section is dedicated to servlet based support for Security HTTP Response Headers. +You can use xref:features/exploits/headers.adoc#headers[Security HTTP Response Headers] to increase the security of web applications. +This section is dedicated to servlet-based support for Security HTTP Response Headers. [[servlet-headers-default]] == Default Security Headers Spring Security provides a xref:features/exploits/headers.adoc#headers-default[default set of Security HTTP Response Headers] to provide secure defaults. -While each of these headers are considered best practice, it should be noted that not all clients utilize the headers, so additional testing is encouraged. +While each of these headers are considered best practice, it should be noted that not all clients use the headers, so additional testing is encouraged. You can customize specific headers. -For example, assume that you want the defaults except you wish to specify `SAMEORIGIN` for <>. +For example, assume that you want the defaults but you wish to specify `SAMEORIGIN` for <>. -You can easily do this with the following Configuration: +You can do so with the following configuration: .Customize Default Security Headers ==== @@ -69,9 +69,9 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { ==== If you do not want the defaults to be added and want explicit control over what should be used, you can disable the defaults. -An example is provided below: +The next code listing shows how to do so. -If you are using Spring Security's Configuration the following will only add xref:features/exploits/headers.adoc#headers-cache-control[Cache Control]. +If you use Spring Security's configuration, the following adds only xref:features/exploits/headers.adoc#headers-cache-control[Cache Control]: .Customize Cache Control Headers ==== @@ -127,7 +127,7 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { ---- ==== -If necessary, you can disable all of the HTTP Security response headers with the following Configuration: +If necessary, you can disable all of the HTTP Security response headers with the following configuration: .Disable All HTTP Security Headers ==== @@ -179,11 +179,11 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { Spring Security includes xref:features/exploits/headers.adoc#headers-cache-control[Cache Control] headers by default. -However, if you actually want to cache specific responses, your application can selectively invoke https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#setHeader(java.lang.String,java.lang.String)[HttpServletResponse.setHeader(String,String)] to override the header set by Spring Security. -This is useful to ensure things like CSS, JavaScript, and images are properly cached. +However, if you actually want to cache specific responses, your application can selectively invoke https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#setHeader(java.lang.String,java.lang.String)[`HttpServletResponse.setHeader(String,String)`] to override the header set by Spring Security. +You can use this to ensure that content (such as CSS, JavaScript, and images) is properly cached. -When using Spring Web MVC, this is typically done within your configuration. -Details on how to do this can be found in the https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web.html#mvc-config-static-resources[Static Resources] portion of the Spring Reference documentation +When you use Spring Web MVC, this is typically done within your configuration. +You can find details on how to do this in the https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web.html#mvc-config-static-resources[Static Resources] portion of the Spring Reference documentation If necessary, you can also disable Spring Security's cache control HTTP response headers. @@ -243,7 +243,7 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { == Content Type Options Spring Security includes xref:features/exploits/headers.adoc#headers-content-type-options[Content-Type] headers by default. -However, you can disable it with: +However, you can disable it: .Content Type Options Disabled ==== @@ -300,9 +300,9 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { [[servlet-headers-hsts]] == HTTP Strict Transport Security (HSTS) -Spring Security provides the xref:features/exploits/headers.adoc#headers-hsts[Strict Transport Security] header by default. -However, you can customize the results explicitly. -For example, the following is an example of explicitly providing HSTS: +By default, Spring Security provides the xref:features/exploits/headers.adoc#headers-hsts[Strict Transport Security] header. +However, you can explicitly customize the results. +The following example explicitly provides HSTS: .Strict Transport Security ==== @@ -366,9 +366,9 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { [[servlet-headers-hpkp]] == HTTP Public Key Pinning (HPKP) -For passivity reasons, Spring Security provides servlet support for xref:features/exploits/headers.adoc#headers-hpkp[HTTP Public Key Pinning] but it is xref:features/exploits/headers.adoc#headers-hpkp-deprecated[no longer recommended]. +Spring Security provides servlet support for xref:features/exploits/headers.adoc#headers-hpkp[HTTP Public Key Pinning], but it is xref:features/exploits/headers.adoc#headers-hpkp-deprecated[no longer recommended]. -You can enable HPKP headers with the following Configuration: +You can enable HPKP headers with the following configuration: .HTTP Public Key Pinning ==== @@ -437,9 +437,9 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { [[servlet-headers-frame-options]] == X-Frame-Options -By default, Spring Security disables rendering within an iframe using xref:features/exploits/headers.adoc#headers-frame-options[X-Frame-Options]. +By default, Spring Security instructs browsers to block reflected XSS attacks by using the xref:features/exploits/headers.adoc#headers-frame-options[X-Frame-Options]. -You can customize frame options to use the same origin within a Configuration using the following: +For example, the following configuration specifies that Spring Security should no longer instruct browsers to block the content: .X-Frame-Options: SAMEORIGIN ==== @@ -499,9 +499,9 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { [[servlet-headers-xss-protection]] == X-XSS-Protection -By default, Spring Security instructs browsers to block reflected XSS attacks using the <. +By default, Spring Security instructs browsers to block reflected XSS attacks by using the <. However, you can change this default. -For example, the following Configuration specifies that Spring Security should no longer instruct browsers to block the content: +For example, the following configuration specifies that Spring Security should no longer instruct browsers to block the content: .X-XSS-Protection Customization ==== @@ -560,10 +560,10 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { [[servlet-headers-csp]] == Content Security Policy (CSP) -Spring Security does not add xref:features/exploits/headers.adoc#headers-csp[Content Security Policy] by default, because a reasonable default is impossible to know without context of the application. -The web application author must declare the security policy(s) to enforce and/or monitor for the protected resources. +Spring Security does not add xref:features/exploits/headers.adoc#headers-csp[Content Security Policy] by default, because a reasonable default is impossible to know without knowing the context of the application. +The web application author must declare the security policy (or policies) to enforce or monitor for the protected resources. -For example, given the following security policy: +Consider the following security policy: .Content Security Policy Example ==== @@ -573,7 +573,7 @@ Content-Security-Policy: script-src 'self' https://trustedscripts.example.com; o ---- ==== -You can enable the CSP header as shown below: +Given the preceding security policy, you can enable the CSP header: .Content Security Policy ==== @@ -694,7 +694,7 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { == Referrer Policy Spring Security does not add xref:features/exploits/headers.adoc#headers-referrer[Referrer Policy] headers by default. -You can enable the Referrer Policy header using the configuration as shown below: +You can enable the Referrer Policy header by using the configuration: .Referrer Policy ==== @@ -754,7 +754,7 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { == Feature Policy Spring Security does not add xref:features/exploits/headers.adoc#headers-feature[Feature Policy] headers by default. -The following `Feature-Policy` header: +Consider the following `Feature-Policy` header: .Feature-Policy Example ==== @@ -764,7 +764,7 @@ Feature-Policy: geolocation 'self' ---- ==== -can enable the Feature Policy header using the configuration shown below: +You can enable the preceding feature policy header by using the following configuration: .Feature-Policy ==== @@ -820,7 +820,7 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { == Permissions Policy Spring Security does not add xref:features/exploits/headers.adoc#headers-permissions[Permissions Policy] headers by default. -The following `Permissions-Policy` header: +Consider the following `Permissions-Policy` header: .Permissions-Policy Example ==== @@ -830,7 +830,7 @@ Permissions-Policy: geolocation=(self) ---- ==== -can enable the Permissions Policy header using the configuration shown below: +You can enable the preceding permissions policy header using the following configuration: .Permissions-Policy ==== @@ -890,7 +890,7 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { == Clear Site Data Spring Security does not add xref:features/exploits/headers.adoc#headers-clear-site-data[Clear-Site-Data] headers by default. -The following Clear-Site-Data header: +Consider the following Clear-Site-Data header: .Clear-Site-Data Example ==== @@ -899,7 +899,7 @@ Clear-Site-Data: "cache", "cookies" ---- ==== -can be sent on log out with the following configuration: +You can send the preceding header on log out with the following configuration: .Clear-Site-Data ==== @@ -945,15 +945,15 @@ However, it also provides hooks to enable adding custom headers. [[servlet-headers-static]] === Static Headers -There may be times you wish to inject custom security headers into your application that are not supported out of the box. -For example, given the following custom security header: +There may be times when you wish to inject custom security headers that are not supported out of the box into your application. +Consider the following custom security header: [source] ---- X-Custom-Security-Header: header-value ---- -The headers could be added to the response using the following Configuration: +Given the preceding header, you could add the headers to the response by using the following configuration: .StaticHeadersWriter ==== @@ -1009,8 +1009,8 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { === Headers Writer When the namespace or Java configuration does not support the headers you want, you can create a custom `HeadersWriter` instance or even provide a custom implementation of the `HeadersWriter`. -Let's take a look at an example of using an custom instance of `XFrameOptionsHeaderWriter`. -If you wanted to explicitly configure <> it could be done with the following Configuration: +The next example use a custom instance of `XFrameOptionsHeaderWriter`. +If you wanted to explicitly configure <>, you could do so with the following configuration: .Headers Writer ==== @@ -1071,11 +1071,11 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { [[headers-delegatingrequestmatcherheaderwriter]] === DelegatingRequestMatcherHeaderWriter -At times you may want to only write a header for certain requests. -For example, perhaps you want to only protect your log in page from being framed. +At times, you may want to write a header only for certain requests. +For example, perhaps you want to protect only your login page from being framed. You could use the `DelegatingRequestMatcherHeaderWriter` to do so. -An example of using `DelegatingRequestMatcherHeaderWriter` in Java Configuration can be seen below: +The following configuration example uses `DelegatingRequestMatcherHeaderWriter`: .DelegatingRequestMatcherHeaderWriter Java Configuration ==== diff --git a/docs/modules/ROOT/pages/servlet/exploits/http.adoc b/docs/modules/ROOT/pages/servlet/exploits/http.adoc index 3dc10d8ac79..c9a7e8846c6 100644 --- a/docs/modules/ROOT/pages/servlet/exploits/http.adoc +++ b/docs/modules/ROOT/pages/servlet/exploits/http.adoc @@ -1,16 +1,16 @@ [[servlet-http]] = HTTP -All HTTP based communication should be protected xref:features/exploits/http.adoc#http[using TLS]. +All HTTP-based communication should be protected xref:features/exploits/http.adoc#http[using TLS]. -Below you can find details around Servlet specific features that assist with HTTPS usage. +This section discusses the details of servlet-specific features that assist with HTTPS usage. [[servlet-http-redirect]] == Redirect to HTTPS -If a client makes a request using HTTP rather than HTTPS, Spring Security can be configured to redirect to HTTPS. +If a client makes a request using HTTP rather than HTTPS, you can configure Spring Security to redirect to HTTPS. -For example, the following Java configuration will redirect any HTTP requests to HTTPS: +For example, the following Java or Kotlin configuration redirects any HTTP requests to HTTPS: .Redirect to HTTPS ==== @@ -52,7 +52,7 @@ class SecurityConfig : WebSecurityConfigurerAdapter() { ---- ==== -The following XML configuration will redirect all HTTP requests to HTTPS +The following XML configuration redirects all HTTP requests to HTTPS .Redirect to HTTPS with XML Configuration ==== diff --git a/docs/modules/ROOT/pages/servlet/getting-started.adoc b/docs/modules/ROOT/pages/servlet/getting-started.adoc index adf4aa555f6..293505a544a 100644 --- a/docs/modules/ROOT/pages/servlet/getting-started.adoc +++ b/docs/modules/ROOT/pages/servlet/getting-started.adoc @@ -6,7 +6,7 @@ This section covers the minimum setup for how to use Spring Security with Spring [NOTE] ==== The completed application can be found {gh-samples-url}/servlet/spring-boot/java/hello-security[in our samples repository]. -For your convenience, you can download a minimal Spring Boot + Spring Security application by https://start.spring.io/starter.zip?type=maven-project&language=java&packaging=jar&jvmVersion=1.8&groupId=example&artifactId=hello-security&name=hello-security&description=Hello%20Security&packageName=example.hello-security&dependencies=web,security[clicking here]. +For your convenience, you can download https://start.spring.io/starter.zip?type=maven-project&language=java&packaging=jar&jvmVersion=1.8&groupId=example&artifactId=hello-security&name=hello-security&description=Hello%20Security&packageName=example.hello-security&dependencies=web,security[a minimal Spring Boot + Spring Security application]. ==== [[servlet-hello-dependencies]] @@ -40,12 +40,12 @@ Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336 // FIXME: Link to relevant portions of documentation // FIXME: Link to Spring Boot's Security Auto configuration classes -// FIXME: Add a links for what user's should do next +// FIXME: Add links for what user's should do next Spring Boot automatically: * Enables Spring Security's default configuration, which creates a servlet `Filter` as a bean named `springSecurityFilterChain`. -This bean is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, and so on) within your application. +This bean is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the login form, and so on) within your application. * Creates a `UserDetailsService` bean with a username of `user` and a randomly generated password that is logged to the console. * Registers the `Filter` with a bean named `springSecurityFilterChain` with the Servlet container for every request. diff --git a/docs/modules/ROOT/pages/servlet/integrations/concurrency.adoc b/docs/modules/ROOT/pages/servlet/integrations/concurrency.adoc new file mode 100644 index 00000000000..c3a597650d7 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/integrations/concurrency.adoc @@ -0,0 +1,176 @@ +[[concurrency]] += Concurrency Support + +In most environments, Security is stored on a per-`Thread` basis. +This means that when work is done on a new `Thread`, the `SecurityContext` is lost. +Spring Security provides some infrastructure to help make this much easier to manage. +Spring Security provides low-level abstractions for working with Spring Security in multi-threaded environments. +In fact, this is what Spring Security builds on to integrate with xref:servlet/integrations/servlet-api.adoc#servletapi-start-runnable[`AsyncContext.start(Runnable)`] and xref:servlet/integrations/mvc.adoc#mvc-async[Spring MVC Async Integration]. + +== DelegatingSecurityContextRunnable + +One of the most fundamental building blocks within Spring Security's concurrency support is the `DelegatingSecurityContextRunnable`. +It wraps a delegate `Runnable` to initialize the `SecurityContextHolder` with a specified `SecurityContext` for the delegate. +It then invokes the delegate `Runnable`, ensuring to clear the `SecurityContextHolder` afterwards. +The `DelegatingSecurityContextRunnable` looks something like this: + +==== +[source,java] +---- +public void run() { +try { + SecurityContextHolder.setContext(securityContext); + delegate.run(); +} finally { + SecurityContextHolder.clearContext(); +} +} +---- +==== + +While very simple, it makes it seamless to transfer the `SecurityContext` from one `Thread` to another. +This is important since, in most cases, the `SecurityContextHolder` acts on a per-`Thread` basis. +For example, you might have used Spring Security's xref:servlet/appendix/namespace/method-security.adoc#nsa-global-method-security[``] support to secure one of your services. +You can now transfer the `SecurityContext` of the current `Thread` to the `Thread` that invokes the secured service. +The following example show how you might do so: + +==== +[source,java] +---- +Runnable originalRunnable = new Runnable() { +public void run() { + // invoke secured service +} +}; + +SecurityContext context = SecurityContextHolder.getContext(); +DelegatingSecurityContextRunnable wrappedRunnable = + new DelegatingSecurityContextRunnable(originalRunnable, context); + +new Thread(wrappedRunnable).start(); +---- +==== + +The preceding code: + +* Creates a `Runnable` that invokes our secured service. +Note that it is not aware of Spring Security. +* Obtains the `SecurityContext` that we wish to use from the `SecurityContextHolder` and initializes the `DelegatingSecurityContextRunnable`. +* Uses the `DelegatingSecurityContextRunnable` to create a `Thread`. +* Starts the `Thread` we created. + +Since it is common to create a `DelegatingSecurityContextRunnable` with the `SecurityContext` from the `SecurityContextHolder`, there is a shortcut constructor for it. +The following code has the same effect as the preceding code: + + +==== +[source,java] +---- +Runnable originalRunnable = new Runnable() { +public void run() { + // invoke secured service +} +}; + +DelegatingSecurityContextRunnable wrappedRunnable = + new DelegatingSecurityContextRunnable(originalRunnable); + +new Thread(wrappedRunnable).start(); +---- +==== + +The code we have is simple to use, but it still requires knowledge that we are using Spring Security. +In the next section we will take a look at how we can utilize `DelegatingSecurityContextExecutor` to hide the fact that we are using Spring Security. + +== DelegatingSecurityContextExecutor + +In the previous section, we found that it was easy to use the `DelegatingSecurityContextRunnable`, but it was not ideal since we had to be aware of Spring Security to use it. +Now we look at how `DelegatingSecurityContextExecutor` can shield our code from any knowledge that we are using Spring Security. + +The design of `DelegatingSecurityContextExecutor` is similar to that of `DelegatingSecurityContextRunnable`, except that it accepts a delegate `Executor` instead of a delegate `Runnable`. +The following example shows how to use it: + +==== +[source,java] +---- +SecurityContext context = SecurityContextHolder.createEmptyContext(); +Authentication authentication = + new UsernamePasswordAuthenticationToken("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER")); +context.setAuthentication(authentication); + +SimpleAsyncTaskExecutor delegateExecutor = + new SimpleAsyncTaskExecutor(); +DelegatingSecurityContextExecutor executor = + new DelegatingSecurityContextExecutor(delegateExecutor, context); + +Runnable originalRunnable = new Runnable() { +public void run() { + // invoke secured service +} +}; + +executor.execute(originalRunnable); +---- +==== + +This code: + +Note that, in this example, we create the `SecurityContext` by hand. +However, it does not matter where or how we get the `SecurityContext` (for example, we could obtain it from the `SecurityContextHolder`). +* Creates a `delegateExecutor` that is in charge of executing submitted `Runnable` objects. +* Finally, we create a `DelegatingSecurityContextExecutor`, which is in charge of wrapping any `Runnable` that is passed into the `execute` method with a `DelegatingSecurityContextRunnable`. +It then passes the wrapped `Runnable` to the `delegateExecutor`. +In this case, the same `SecurityContext` is used for every `Runnable` submitted to our `DelegatingSecurityContextExecutor`. +This is nice if we run background tasks that need to be run by a user with elevated privileges. +* At this point, you may ask yourself, "`How does this shield my code of any knowledge of Spring Security?`" Instead of creating the `SecurityContext` and the `DelegatingSecurityContextExecutor` in our own code, we can inject an already initialized instance of `DelegatingSecurityContextExecutor`. + +Consider the following example: + +==== +[source,java] +---- +@Autowired +private Executor executor; // becomes an instance of our DelegatingSecurityContextExecutor + +public void submitRunnable() { +Runnable originalRunnable = new Runnable() { + public void run() { + // invoke secured service + } +}; +executor.execute(originalRunnable); +} +---- +==== + +Now our code is unaware that the `SecurityContext` is being propagated to the `Thread`, the `originalRunnable` is run, and the `SecurityContextHolder` is cleared out. +In this example, the same user is being used to run each thread. +What if we wanted to use the user from `SecurityContextHolder` (that is, the currently logged in-user) at the time we invoked `executor.execute(Runnable)` to process `originalRunnable`? +You can do so by removing the `SecurityContext` argument from our `DelegatingSecurityContextExecutor` constructor: + +==== +[source,java] +---- +SimpleAsyncTaskExecutor delegateExecutor = new SimpleAsyncTaskExecutor(); +DelegatingSecurityContextExecutor executor = + new DelegatingSecurityContextExecutor(delegateExecutor); +---- +==== + +Now, any time `executor.execute(Runnable)` is run, the `SecurityContext` is first obtained by the `SecurityContextHolder` and then that `SecurityContext` is used to create our `DelegatingSecurityContextRunnable`. +This means that we are running our `Runnable` with the same user that was used to invoke the `executor.execute(Runnable)` code. + +== Spring Security Concurrency Classes + +See the {security-api-url}index.html[Javadoc] for additional integrations with both the Java concurrent APIs and the Spring Task abstractions. +They are self-explanatory once you understand the previous code. + +* {security-api-url}org/springframework/security/concurrent/DelegatingSecurityContextCallable.html[`DelegatingSecurityContextCallable`] +* {security-api-url}org/springframework/security/concurrent/DelegatingSecurityContextExecutor.html[`DelegatingSecurityContextExecutor`] +* {security-api-url}org/springframework/security/concurrent/DelegatingSecurityContextExecutorService.html[`DelegatingSecurityContextExecutorService`] +* {security-api-url}org/springframework/security/concurrent/DelegatingSecurityContextRunnable.html[`DelegatingSecurityContextRunnable`] +* {security-api-url}org/springframework/security/concurrent/DelegatingSecurityContextScheduledExecutorService.html[`DelegatingSecurityContextScheduledExecutorService`] +* {security-api-url}org/springframework/security/scheduling/DelegatingSecurityContextSchedulingTaskExecutor.html[`DelegatingSecurityContextSchedulingTaskExecutor`] +* {security-api-url}org/springframework/security/task/DelegatingSecurityContextAsyncTaskExecutor.html[`DelegatingSecurityContextAsyncTaskExecutor`] +* {security-api-url}org/springframework/security/task/DelegatingSecurityContextTaskExecutor.html[`DelegatingSecurityContextTaskExecutor`] +* {security-api-url}org/springframework/security/scheduling/DelegatingSecurityContextTaskScheduler.html[`DelegatingSecurityContextTaskScheduler`] diff --git a/docs/modules/ROOT/pages/servlet/integrations/cors.adoc b/docs/modules/ROOT/pages/servlet/integrations/cors.adoc index aa5cb3ff172..d510fade8c8 100644 --- a/docs/modules/ROOT/pages/servlet/integrations/cors.adoc +++ b/docs/modules/ROOT/pages/servlet/integrations/cors.adoc @@ -2,11 +2,11 @@ = CORS Spring Framework provides https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors[first class support for CORS]. -CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the `JSESSIONID`). -If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it. +CORS must be processed before Spring Security, because the pre-flight request does not contain any cookies (that is, the `JSESSIONID`). +If the request does not contain any cookies and Spring Security is first, the request determines that the user is not authenticated (since there are no cookies in the request) and rejects it. The easiest way to ensure that CORS is handled first is to use the `CorsFilter`. -Users can integrate the `CorsFilter` with Spring Security by providing a `CorsConfigurationSource` using the following: +Users can integrate the `CorsFilter` with Spring Security by providing a `CorsConfigurationSource` that uses the following: ==== .Java @@ -61,8 +61,9 @@ open class WebSecurityConfig : WebSecurityConfigurerAdapter() { ---- ==== -or in XML +The following listing does the same thing in XML: +==== [source,xml] ---- @@ -73,8 +74,9 @@ or in XML ... ---- +==== -If you are using Spring MVC's CORS support, you can omit specifying the `CorsConfigurationSource` and Spring Security will leverage the CORS configuration provided to Spring MVC. +If you use Spring MVC's CORS support, you can omit specifying the `CorsConfigurationSource` and Spring Security uses the CORS configuration provided to Spring MVC: ==== .Java @@ -111,8 +113,9 @@ open class WebSecurityConfig : WebSecurityConfigurerAdapter() { ---- ==== -or in XML +The following listing does the same thing in XML: +==== [source,xml] ---- @@ -121,3 +124,4 @@ or in XML ... ---- +==== diff --git a/docs/modules/ROOT/pages/servlet/integrations/data.adoc b/docs/modules/ROOT/pages/servlet/integrations/data.adoc new file mode 100644 index 00000000000..6304c2c5c9c --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/integrations/data.adoc @@ -0,0 +1,50 @@ +[[data]] += Spring Data Integration + +Spring Security provides Spring Data integration that allows referring to the current user within your queries. +It is not only useful but necessary to include the user in the queries to support paged results, since filtering the results afterwards would not scale. + +[[data-configuration]] +== Spring Data & Spring Security Configuration + +To use this support, add the `org.springframework.security:spring-security-data` dependency and provide a bean of type `SecurityEvaluationContextExtension`. +In Java configuration, this would look like: + +==== +[source,java] +---- +@Bean +public SecurityEvaluationContextExtension securityEvaluationContextExtension() { + return new SecurityEvaluationContextExtension(); +} +---- +==== + +In XML Configuration, this would look like: + +==== +[source,xml] +---- + +---- +==== + +[[data-query]] +== Security Expressions within @Query + +Now you can use Spring Security within your queries: + +==== +[source,java] +---- +@Repository +public interface MessageRepository extends PagingAndSortingRepository { + @Query("select m from Message m where m.to.id = ?#{ principal?.id }") + Page findInbox(Pageable pageable); +} +---- +==== + +This checks to see if the `Authentication.getPrincipal().getId()` is equal to the recipient of the `Message`. +Note that this example assumes you have customized the principal to be an `Object` that has an `id` property. +By exposing the `SecurityEvaluationContextExtension` bean, all of the xref:servlet/authorization/expression-based.adoc#common-expressions[Common Security Expressions] are available within the query. diff --git a/docs/modules/ROOT/pages/servlet/integrations/index.adoc b/docs/modules/ROOT/pages/servlet/integrations/index.adoc index 8b8d1eb5813..63f75a119e4 100644 --- a/docs/modules/ROOT/pages/servlet/integrations/index.adoc +++ b/docs/modules/ROOT/pages/servlet/integrations/index.adoc @@ -2,4 +2,4 @@ :page-section-summary-toc: 1 Spring Security integrates with numerous frameworks and APIs. -In this section, we discuss Spring Security integration with: +This section describes various integrations that Spring Security has with other technologies: diff --git a/docs/modules/ROOT/pages/servlet/integrations/jackson.adoc b/docs/modules/ROOT/pages/servlet/integrations/jackson.adoc new file mode 100644 index 00000000000..d74a61a2210 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/integrations/jackson.adoc @@ -0,0 +1,32 @@ +[[jackson]] += Jackson Support + +Spring Security provides Jackson support for persisting Spring Security-related classes. +This can improve the performance of serializing Spring Security-related classes when working with distributed sessions (session replication, Spring Session, and so on). + +To use it, register the `SecurityJackson2Modules.getModules(ClassLoader)` with `ObjectMapper` (https://github.com/FasterXML/jackson-databind[jackson-databind]): + +==== +[source,java] +---- +ObjectMapper mapper = new ObjectMapper(); +ClassLoader loader = getClass().getClassLoader(); +List modules = SecurityJackson2Modules.getModules(loader); +mapper.registerModules(modules); + +// ... use ObjectMapper as normally ... +SecurityContext context = new SecurityContextImpl(); +// ... +String json = mapper.writeValueAsString(context); +---- +==== + +[NOTE] +==== +The following Spring Security modules provide Jackson support: + +- spring-security-core ({security-api-url}org/springframework/security/jackson2/CoreJackson2Module.html[`CoreJackson2Module`]) +- spring-security-web ({security-api-url}org/springframework/security/web/jackson2/WebJackson2Module.html[`WebJackson2Module`], {security-api-url}org/springframework/security/web/jackson2/WebServletJackson2Module.html[`WebServletJackson2Module`], {security-api-url}org/springframework/security/web/server/jackson2/WebServerJackson2Module.html[`WebServerJackson2Module`]) +- <> ({security-api-url}org/springframework/security/oauth2/client/jackson2/OAuth2ClientJackson2Module.html[`OAuth2ClientJackson2Module`]) +- spring-security-cas ({security-api-url}org/springframework/security/cas/jackson2/CasJackson2Module.html[`CasJackson2Module`]) +==== diff --git a/docs/modules/ROOT/pages/servlet/integrations/jsp-taglibs.adoc b/docs/modules/ROOT/pages/servlet/integrations/jsp-taglibs.adoc index 05bd1ea02cb..031a5ed389f 100644 --- a/docs/modules/ROOT/pages/servlet/integrations/jsp-taglibs.adoc +++ b/docs/modules/ROOT/pages/servlet/integrations/jsp-taglibs.adoc @@ -1,26 +1,33 @@ [[taglibs]] = JSP Tag Libraries -Spring Security has its own taglib which provides basic support for accessing security information and applying security constraints in JSPs. +Spring Security has its own taglib, which provides basic support for accessing security information and applying security constraints in JSPs. == Declaring the Taglib To use any of the tags, you must have the security taglib declared in your JSP: +==== [source,xml] ---- <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> ---- +==== [[taglibs-authorize]] == The authorize Tag This tag is used to determine whether its contents should be evaluated or not. -In Spring Security 3.0, it can be used in two ways footnote:[ +In Spring Security 3.0, it can be used in two ways. + +[NOTE] +==== The legacy options from Spring Security 2.0 are also supported, but discouraged. -]. -The first approach uses a xref:servlet/authorization/expression-based.adoc#el-access-web[web-security expression], specified in the `access` attribute of the tag. -The expression evaluation will be delegated to the `SecurityExpressionHandler` defined in the application context (you should have web expressions enabled in your `` namespace configuration to make sure this service is available). -So, for example, you might have +==== + +The first approach uses a xref:servlet/authorization/expression-based.adoc#el-access-web[web-security expression], which is specified in the `access` attribute of the tag. +The expression evaluation is delegated to the `SecurityExpressionHandler` defined in the application context (you should have web expressions enabled in your `` namespace configuration to make sure this service is available). +So, for example, you might have: +==== [source,xml] ---- @@ -29,10 +36,11 @@ This content will only be visible to users who have the "supervisor" authority i ---- +==== -When used in conjunction with Spring Security's PermissionEvaluator, the tag can also be used to check permissions. -For example: +When used in conjunction with Spring Security's `PermissionEvaluator`, the tag can also be used to check permissions: +==== [source,xml] ---- @@ -41,12 +49,14 @@ This content will only be visible to users who have read or write permission to ---- +==== -A common requirement is to only show a particular link, if the user is actually allowed to click it. -How can we determine in advance whether something will be allowed? This tag can also operate in an alternative mode which allows you to define a particular URL as an attribute. -If the user is allowed to invoke that URL, then the tag body will be evaluated, otherwise it will be skipped. -So you might have something like +A common requirement is to show only a particular link, assuming the user is actually allowed to click it. +How can we determine in advance whether something is allowed? This tag can also operate in an alternative mode that lets you define a particular URL as an attribute. +If the user is allowed to invoke that URL, the tag body is evaluated. Otherwise, it is skipped. +So you might have something like: +==== [source,xml] ---- @@ -55,60 +65,67 @@ This content will only be visible to users who are authorized to send requests t ---- +==== -To use this tag there must also be an instance of `WebInvocationPrivilegeEvaluator` in your application context. -If you are using the namespace, one will automatically be registered. +To use this tag, you must also have an instance of `WebInvocationPrivilegeEvaluator` in your application context. +If you are using the namespace, one is automatically registered. This is an instance of `DefaultWebInvocationPrivilegeEvaluator`, which creates a dummy web request for the supplied URL and invokes the security interceptor to see whether the request would succeed or fail. -This allows you to delegate to the access-control setup you defined using `intercept-url` declarations within the `` namespace configuration and saves having to duplicate the information (such as the required roles) within your JSPs. -This approach can also be combined with a `method` attribute, supplying the HTTP method, for a more specific match. +This lets you delegate to the access-control setup you defined by using `intercept-url` declarations within the `` namespace configuration and saves having to duplicate the information (such as the required roles) within your JSPs. +You can also combine this approach with a `method` attribute (supplying the HTTP method, such as `POST`) for a more specific match. -The Boolean result of evaluating the tag (whether it grants or denies access) can be stored in a page context scope variable by setting the `var` attribute to the variable name, avoiding the need for duplicating and re-evaluating the condition at other points in the page. +You can store the Boolean result of evaluating the tag (whether it grants or denies access) in a page context scope variable by setting the `var` attribute to the variable name, avoiding the need for duplicating and re-evaluating the condition at other points in the page. === Disabling Tag Authorization for Testing -Hiding a link in a page for unauthorized users doesn't prevent them from accessing the URL. +Hiding a link in a page for unauthorized users does not prevent them from accessing the URL. They could just type it into their browser directly, for example. -As part of your testing process, you may want to reveal the hidden areas in order to check that links really are secured at the back end. -If you set the system property `spring.security.disableUISecurity` to `true`, the `authorize` tag will still run but will not hide its contents. -By default it will also surround the content with `...` tags. -This allows you to display "hidden" content with a particular CSS style such as a different background colour. -Try running the "tutorial" sample application with this property enabled, for example. +As part of your testing process, you may want to reveal the hidden areas, to check that links really are secured at the back end. +If you set the `spring.security.disableUISecurity` system property to `true`, the `authorize` tag still runs but does not hide its contents. +By default, it also surrounds the content with `...` tags. +This lets you to display "`hidden`" content with a particular CSS style, such as a different background color. +Try running the "`tutorial`" sample application, for example, with this property enabled. -You can also set the properties `spring.security.securedUIPrefix` and `spring.security.securedUISuffix` if you want to change surrounding text from the default `span` tags (or use empty strings to remove it completely). +You can also set the `spring.security.securedUIPrefix` and `spring.security.securedUISuffix` properties if you want to change surrounding text from the default `span` tags (or use empty strings to remove it completely). == The authentication Tag This tag allows access to the current `Authentication` object stored in the security context. It renders a property of the object directly in the JSP. -So, for example, if the `principal` property of the `Authentication` is an instance of Spring Security's `UserDetails` object, then using `` will render the name of the current user. +So, for example, if the `principal` property of the `Authentication` is an instance of Spring Security's `UserDetails` object, then using `` renders the name of the current user. -Of course, it isn't necessary to use JSP tags for this kind of thing and some people prefer to keep as little logic as possible in the view. +Of course, it is not necessary to use JSP tags for this kind of thing, and some people prefer to keep as little logic as possible in the view. You can access the `Authentication` object in your MVC controller (by calling `SecurityContextHolder.getContext().getAuthentication()`) and add the data directly to your model for rendering by the view. == The accesscontrollist Tag This tag is only valid when used with Spring Security's ACL module. It checks a comma-separated list of required permissions for a specified domain object. -If the current user has all of those permissions, then the tag body will be evaluated. -If they don't, it will be skipped. -An example might be +If the current user has all of those permissions, the tag body is evaluated. +If they do not, it is skipped. -CAUTION: In general this tag should be considered deprecated. -Instead use the <>. +[CAUTION] +==== +In general, this tag should be considered deprecated. +Instead, use the <>. +==== +The following listing shows an example: + +==== [source,xml] ---- -This will be shown if the user has all of the permissions represented by the values "1" or "2" on the given object. + ---- +==== -The permissions are passed to the `PermissionFactory` defined in the application context, converting them to ACL `Permission` instances, so they may be any format which is supported by the factory - they don't have to be integers, they could be strings like `READ` or `WRITE`. -If no `PermissionFactory` is found, an instance of `DefaultPermissionFactory` will be used. -The `AclService` from the application context will be used to load the `Acl` instance for the supplied object. -The `Acl` will be invoked with the required permissions to check if all of them are granted. +The permissions are passed to the `PermissionFactory` defined in the application context, converting them to ACL `Permission` instances, so they may be any format that is supported by the factory. They do not have to be integers. They could be strings such as `READ` or `WRITE`. +If no `PermissionFactory` is found, an instance of `DefaultPermissionFactory` is used. +The `AclService` from the application context is used to load the `Acl` instance for the supplied object. +The `Acl` is invoked with the required permissions to check if all of them are granted. This tag also supports the `var` attribute, in the same way as the `authorize` tag. @@ -117,12 +134,14 @@ This tag also supports the `var` attribute, in the same way as the `authorize` t If CSRF protection is enabled, this tag inserts a hidden form field with the correct name and value for the CSRF protection token. If CSRF protection is not enabled, this tag outputs nothing. -Normally Spring Security automatically inserts a CSRF form field for any `` tags you use, but if for some reason you cannot use ``, `csrfInput` is a handy replacement. +Normally, Spring Security automatically inserts a CSRF form field for any `` tags you use, but if for some reason you cannot use ``, `csrfInput` is a handy replacement. You should place this tag within an HTML `
` block, where you would normally place other input fields. Do NOT place this tag within a Spring `` block. Spring Security handles Spring forms automatically. +The following listing shows an example: +==== [source,xml] ----
@@ -132,16 +151,19 @@ Spring Security handles Spring forms automatically. ...
---- +==== [[taglibs-csrfmeta]] == The csrfMetaTags Tag -If CSRF protection is enabled, this tag inserts meta tags containing the CSRF protection token form field and header names and CSRF protection token value. +If CSRF protection is enabled, this tag inserts meta tags that contain the CSRF protection token form field and header names and CSRF protection token value. These meta tags are useful for employing CSRF protection within JavaScript in your applications. You should place `csrfMetaTags` within an HTML `` block, where you would normally place other meta tags. -Once you use this tag, you can access the form field name, header name, and token value easily using JavaScript. +Once you use this tag, you can access the form field name, header name, and token value by using JavaScript. JQuery is used in this example to make the task easier. +The following listing shows an example: +==== [source,xml] ---- @@ -197,6 +219,6 @@ JQuery is used in this example to make the task easier. ---- +==== If CSRF protection is not enabled, `csrfMetaTags` outputs nothing. - diff --git a/docs/modules/ROOT/pages/servlet/integrations/localization.adoc b/docs/modules/ROOT/pages/servlet/integrations/localization.adoc new file mode 100644 index 00000000000..0c98781ba91 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/integrations/localization.adoc @@ -0,0 +1,38 @@ +[[localization]] += Localization +Spring Security supports localization of exception messages that end users are likely to see. +If your application is designed for English-speaking users, you need not do anything as, by default, all Security messages are in English. +If you need to support other locales, this section contains everything you need to know. + +All exception messages, including messages related to authentication failures and access being denied (authorization failures), can be localized. +Exceptions and logging messages that are focused on developers or system deployers (including incorrect attributes, interface contract violations, using incorrect constructors, startup time validation, debug-level logging) are not localized and instead are hard-coded in English within Spring Security's code. + +In the `spring-security-core-xx.jar`, you find an `org.springframework.security` package that, in turn, contains a `messages.properties` file as well as localized versions for some common languages. +Your `ApplicationContext` should refer to this, as Spring Security classes implement Spring's `MessageSourceAware` interface and expect the message resolver to be dependency injected at application context startup time. +Usually, all you need to do is register a bean inside your application context to refer to the messages. +The following listing shows an example: + +==== +[source,xml] +---- + + + +---- +==== + +The `messages.properties` is named in accordance with standard resource bundles and represents the default language supported by Spring Security messages. +This default file is in English. + +To customize the `messages.properties` file or support other languages, you should copy the file, rename it accordingly, and register it inside the preceding bean definition. +There are not a large number of message keys inside this file, so localization should not be considered a major initiative. +If you do perform localization of this file, consider sharing your work with the community by logging a JIRA task and attaching your appropriately-named localized version of `messages.properties`. + +Spring Security relies on Spring's localization support in order to actually look up the appropriate message. +For this to work, you have to make sure that the locale from the incoming request is stored in Spring's `org.springframework.context.i18n.LocaleContextHolder`. +Spring MVC's `DispatcherServlet` does this for your application automatically. However, since Spring Security's filters are invoked before this, the `LocaleContextHolder` needs to be set up to contain the correct `Locale` before the filters are called. +You can either do this in a filter yourself (which must come before the Spring Security filters in `web.xml`) or you can use Spring's `RequestContextFilter`. +See the Spring Framework documentation for further details on using localization with Spring. + +The `contacts` sample application is set up to use localized messages. diff --git a/docs/modules/ROOT/pages/servlet/integrations/mvc.adoc b/docs/modules/ROOT/pages/servlet/integrations/mvc.adoc index 23bb16ccaca..9e93aeaf634 100644 --- a/docs/modules/ROOT/pages/servlet/integrations/mvc.adoc +++ b/docs/modules/ROOT/pages/servlet/integrations/mvc.adoc @@ -7,25 +7,32 @@ This section covers the integration in further detail. [[mvc-enablewebmvcsecurity]] == @EnableWebMvcSecurity -NOTE: As of Spring Security 4.0, `@EnableWebMvcSecurity` is deprecated. -The replacement is `@EnableWebSecurity` which will determine adding the Spring MVC features based upon the classpath. +[NOTE] +==== +As of Spring Security 4.0, `@EnableWebMvcSecurity` is deprecated. +The replacement is `@EnableWebSecurity`, which adds the Spring MVC features, based upon the classpath. +==== -To enable Spring Security integration with Spring MVC add the `@EnableWebSecurity` annotation to your configuration. +To enable Spring Security integration with Spring MVC, add the `@EnableWebSecurity` annotation to your configuration. -NOTE: Spring Security provides the configuration using Spring MVC's https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web.html#mvc-config-customize[WebMvcConfigurer]. -This means that if you are using more advanced options, like integrating with `WebMvcConfigurationSupport` directly, then you will need to manually provide the Spring Security configuration. +[NOTE] +==== +Spring Security provides the configuration by using Spring MVC's https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web.html#mvc-config-customize[`WebMvcConfigurer`]. +This means that, if you use more advanced options, such as integrating with `WebMvcConfigurationSupport` directly, you need to manually provide the Spring Security configuration. +==== [[mvc-requestmatcher]] == MvcRequestMatcher Spring Security provides deep integration with how Spring MVC matches on URLs with `MvcRequestMatcher`. -This is helpful to ensure your Security rules match the logic used to handle your requests. +This is helpful to ensure that your Security rules match the logic used to handle your requests. -In order to use `MvcRequestMatcher` you must place the Spring Security Configuration in the same `ApplicationContext` as your `DispatcherServlet`. +To use `MvcRequestMatcher`, you must place the Spring Security Configuration in the same `ApplicationContext` as your `DispatcherServlet`. This is necessary because Spring Security's `MvcRequestMatcher` expects a `HandlerMappingIntrospector` bean with the name of `mvcHandlerMappingIntrospector` to be registered by your Spring MVC configuration that is used to perform the matching. -For a `web.xml` this means that you should place your configuration in the `DispatcherServlet.xml`. +For a `web.xml` file, this means that you should place your configuration in the `DispatcherServlet.xml`: +==== [source,xml] ---- @@ -53,8 +60,9 @@ For a `web.xml` this means that you should place your configuration in the `Disp / ---- +==== -Below `WebSecurityConfiguration` in placed in the ``DispatcherServlet``s `ApplicationContext`. +The following `WebSecurityConfiguration` in placed in the `ApplicationContext` of the `DispatcherServlet`. ==== .Java @@ -105,11 +113,11 @@ class SecurityInitializer : AbstractAnnotationConfigDispatcherServletInitializer [NOTE] ==== -It is always recommended to provide authorization rules by matching on the `HttpServletRequest` and method security. +We always recommend that you provide authorization rules by matching on the `HttpServletRequest` and method security. -Providing authorization rules by matching on `HttpServletRequest` is good because it happens very early in the code path and helps reduce the https://en.wikipedia.org/wiki/Attack_surface[attack surface]. -Method security ensures that if someone has bypassed the web authorization rules, that your application is still secured. -This is what is known as https://en.wikipedia.org/wiki/Defense_in_depth_(computing)[Defence in Depth] +Providing authorization rules by matching on `HttpServletRequest` is good, because it happens very early in the code path and helps reduce the https://en.wikipedia.org/wiki/Attack_surface[attack surface]. +Method security ensures that, if someone has bypassed the web authorization rules, your application is still secured. +This is known as https://en.wikipedia.org/wiki/Defense_in_depth_(computing)[Defense in Depth] ==== Consider a controller that is mapped as follows: @@ -120,6 +128,8 @@ Consider a controller that is mapped as follows: ---- @RequestMapping("/admin") public String admin() { + // ... +} ---- .Kotlin @@ -127,10 +137,12 @@ public String admin() { ---- @RequestMapping("/admin") fun admin(): String { + // ... +} ---- ==== -If we wanted to restrict access to this controller method to admin users, a developer can provide authorization rules by matching on the `HttpServletRequest` with the following: +To restrict access to this controller method to admin users, you can provide authorization rules by matching on the `HttpServletRequest` with the following: ==== .Java @@ -138,7 +150,7 @@ If we wanted to restrict access to this controller method to admin users, a deve ---- protected configure(HttpSecurity http) throws Exception { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .antMatchers("/admin").hasRole("ADMIN") ); } @@ -157,25 +169,26 @@ override fun configure(http: HttpSecurity) { ---- ==== -or in XML +The following listing does the same thing in XML: +==== [source,xml] ---- ---- +==== -With either configuration, the URL `/admin` will require the authenticated user to be an admin user. -However, depending on our Spring MVC configuration, the URL `/admin.html` will also map to our `admin()` method. -Additionally, depending on our Spring MVC configuration, the URL `/admin/` will also map to our `admin()` method. +With either configuration, the `/admin` URL requires the authenticated user to be an admin user. +However, depending on our Spring MVC configuration, the `/admin.html` URL also maps to our `admin()` method. +Additionally, depending on our Spring MVC configuration, the `/admin` URL also maps to our `admin()` method. -The problem is that our security rule is only protecting `/admin`. +The problem is that our security rule protects only `/admin`. We could add additional rules for all the permutations of Spring MVC, but this would be quite verbose and tedious. -Instead, we can leverage Spring Security's `MvcRequestMatcher`. -The following configuration will protect the same URLs that Spring MVC will match on by using Spring MVC to match on the URL. - +Instead, we can use Spring Security's `MvcRequestMatcher`. +The following configuration protects the same URLs that Spring MVC matches on by using Spring MVC to match on the URL. ==== .Java @@ -183,7 +196,7 @@ The following configuration will protect the same URLs that Spring MVC will matc ---- protected configure(HttpSecurity http) throws Exception { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .mvcMatchers("/admin").hasRole("ADMIN") ); } @@ -202,23 +215,25 @@ override fun configure(http: HttpSecurity) { ---- ==== -or in XML +The following XML has the same effect: +==== [source,xml] ---- ---- +==== [[mvc-authentication-principal]] == @AuthenticationPrincipal -Spring Security provides `AuthenticationPrincipalArgumentResolver` which can automatically resolve the current `Authentication.getPrincipal()` for Spring MVC arguments. -By using `@EnableWebSecurity` you will automatically have this added to your Spring MVC configuration. -If you use XML based configuration, you must add this yourself. -For example: +Spring Security provides `AuthenticationPrincipalArgumentResolver`, which can automatically resolve the current `Authentication.getPrincipal()` for Spring MVC arguments. +By using `@EnableWebSecurity`, you automatically have this added to your Spring MVC configuration. +If you use XML-based configuration, you must add this yourself: +==== [source,xml] ---- @@ -227,10 +242,11 @@ For example: ---- +==== -Once `AuthenticationPrincipalArgumentResolver` is properly configured, you can be entirely decoupled from Spring Security in your Spring MVC layer. +Once you have properly configured `AuthenticationPrincipalArgumentResolver`, you can entirely decouple from Spring Security in your Spring MVC layer. -Consider a situation where a custom `UserDetailsService` that returns an `Object` that implements `UserDetails` and your own `CustomUser` `Object`. The `CustomUser` of the currently authenticated user could be accessed using the following code: +Consider a situation where a custom `UserDetailsService` returns an `Object` that implements `UserDetails` and your own `CustomUser` `Object`. The `CustomUser` of the currently authenticated user could be accessed by using the following code: ==== .Java @@ -259,7 +275,7 @@ open fun findMessagesForUser(): ModelAndView { ---- ==== -As of Spring Security 3.2 we can resolve the argument more directly by adding an annotation. For example: +As of Spring Security 3.2, we can resolve the argument more directly by adding an annotation: ==== .Java @@ -287,10 +303,9 @@ open fun findMessagesForUser(@AuthenticationPrincipal customUser: CustomUser?): ---- ==== -Sometimes it may be necessary to transform the principal in some way. -For example, if `CustomUser` needed to be final it could not be extended. -In this situation the `UserDetailsService` might returns an `Object` that implements `UserDetails` and provides a method named `getCustomUser` to access `CustomUser`. -For example, it might look like: +Sometimes, you may need to transform the principal in some way. +For example, if `CustomUser` needed to be final, it could not be extended. +In this situation, the `UserDetailsService` might return an `Object` that implements `UserDetails` and provides a method named `getCustomUser` to access `CustomUser`: ==== .Java @@ -318,7 +333,7 @@ class CustomUserUserDetails( ---- ==== -We could then access the `CustomUser` using a https://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html[SpEL expression] that uses `Authentication.getPrincipal()` as the root object: +We could then access the `CustomUser` by using a https://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html[SpEL expression] that uses `Authentication.getPrincipal()` as the root object: ==== .Java @@ -350,8 +365,8 @@ open fun findMessagesForUser(@AuthenticationPrincipal(expression = "customUser") ---- ==== -We can also refer to Beans in our SpEL expressions. -For example, the following could be used if we were using JPA to manage our Users and we wanted to modify and save a property on the current user. +We can also refer to beans in our SpEL expressions. +For example, we could use the following if we were using JPA to manage our users and if we wanted to modify and save a property on the current user: ==== .Java @@ -393,11 +408,14 @@ open fun updateName( ---- ==== -We can further remove our dependency on Spring Security by making `@AuthenticationPrincipal` a meta annotation on our own annotation. -Below we demonstrate how we could do this on an annotation named `@CurrentUser`. +We can further remove our dependency on Spring Security by making `@AuthenticationPrincipal` a meta-annotation on our own annotation. +The next example demonstrates how we could do so on an annotation named `@CurrentUser`. -NOTE: It is important to realize that in order to remove the dependency on Spring Security, it is the consuming application that would create `@CurrentUser`. -This step is not strictly required, but assists in isolating your dependency to Spring Security to a more central location. +[NOTE] +==== +To remove the dependency on Spring Security, it is the consuming application that would create `@CurrentUser`. +This step is not strictly required but assists in isolating your dependency to Spring Security to a more central location. +==== ==== .Java @@ -421,8 +439,8 @@ annotation class CurrentUser ---- ==== -Now that `@CurrentUser` has been specified, we can use it to signal to resolve our `CustomUser` of the currently authenticated user. -We have also isolated our dependency on Spring Security to a single file. +We have isolated our dependency on Spring Security to a single file. +Now that `@CurrentUser` has been specified, we can use it to signal to resolve our `CustomUser` of the currently authenticated user: ==== .Java @@ -451,8 +469,8 @@ open fun findMessagesForUser(@CurrentUser customUser: CustomUser?): ModelAndView == Spring MVC Async Integration Spring Web MVC 3.2+ has excellent support for https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-async[Asynchronous Request Processing]. -With no additional configuration, Spring Security will automatically setup the `SecurityContext` to the `Thread` that invokes a `Callable` returned by your controllers. -For example, the following method will automatically have its `Callable` invoked with the `SecurityContext` that was available when the `Callable` was created: +With no additional configuration, Spring Security automatically sets up the `SecurityContext` to the `Thread` that invokes a `Callable` returned by your controllers. +For example, the following method automatically has its `Callable` invoked with the `SecurityContext` that was available when the `Callable` was created: ==== .Java @@ -483,25 +501,29 @@ open fun processUpload(file: MultipartFile?): Callable { ---- ==== -[NOTE] .Associating SecurityContext to Callable's + +[NOTE] ==== More technically speaking, Spring Security integrates with `WebAsyncManager`. -The `SecurityContext` that is used to process the `Callable` is the `SecurityContext` that exists on the `SecurityContextHolder` at the time `startCallableProcessing` is invoked. +The `SecurityContext` that is used to process the `Callable` is the `SecurityContext` that exists on the `SecurityContextHolder` when `startCallableProcessing` is invoked. ==== There is no automatic integration with a `DeferredResult` that is returned by controllers. -This is because `DeferredResult` is processed by the users and thus there is no way of automatically integrating with it. +This is because `DeferredResult` is processed by the users and, thus, there is no way of automatically integrating with it. However, you can still use xref:features/integrations/concurrency.adoc#concurrency[Concurrency Support] to provide transparent integration with Spring Security. [[mvc-csrf]] == Spring MVC and CSRF Integration +Spring Security integrates with Spring MVC to add CSRF protection. + === Automatic Token Inclusion -Spring Security will automatically xref:servlet/exploits/csrf.adoc#servlet-csrf-include[include the CSRF Token] within forms that use the https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-formtag[Spring MVC form tag]. -For example, the following JSP: +Spring Security automatically xref:servlet/exploits/csrf.adoc#servlet-csrf-include[include the CSRF Token] within forms that use the https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-formtag[Spring MVC form tag]. +Consider the following JSP: +==== [source,xml] ---- ---- +==== -Will output HTML that is similar to the following: +The preceding example output HTMLs that is similar to the following: +==== [source,xml] ---- @@ -539,15 +563,16 @@ Will output HTML that is similar to the following: ---- +==== [[mvc-csrf-resolver]] === Resolving the CsrfToken -Spring Security provides `CsrfTokenArgumentResolver` which can automatically resolve the current `CsrfToken` for Spring MVC arguments. -By using xref:servlet/configuration/java.adoc#jc-hello-wsca[@EnableWebSecurity] you will automatically have this added to your Spring MVC configuration. -If you use XML based configuration, you must add this yourself. +Spring Security provides `CsrfTokenArgumentResolver`, which can automatically resolve the current `CsrfToken` for Spring MVC arguments. +By using xref:servlet/configuration/java.adoc#jc-hello-wsca[@EnableWebSecurity], you automatically have this added to your Spring MVC configuration. +If you use XML-based configuration, you must add this yourself. -Once `CsrfTokenArgumentResolver` is properly configured, you can expose the `CsrfToken` to your static HTML based application. +Once `CsrfTokenArgumentResolver` is properly configured, you can expose the `CsrfToken` to your static HTML based application: ==== .Java @@ -577,4 +602,4 @@ class CsrfController { ==== It is important to keep the `CsrfToken` a secret from other domains. -This means if you are using https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS[Cross Origin Sharing (CORS)], you should **NOT** expose the `CsrfToken` to any external domains. +This means that, if you use https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS[Cross Origin Sharing (CORS)], you should *NOT* expose the `CsrfToken` to any external domains. diff --git a/docs/modules/ROOT/pages/servlet/integrations/servlet-api.adoc b/docs/modules/ROOT/pages/servlet/integrations/servlet-api.adoc index 741a0629f73..5a5d6c7d845 100644 --- a/docs/modules/ROOT/pages/servlet/integrations/servlet-api.adoc +++ b/docs/modules/ROOT/pages/servlet/integrations/servlet-api.adoc @@ -6,19 +6,20 @@ This section describes how Spring Security is integrated with the Servlet API. [[servletapi-25]] == Servlet 2.5+ Integration +This section describes how Spring Security integrates with the Servlet 2.5 specification. + [[servletapi-remote-user]] === HttpServletRequest.getRemoteUser() -The https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[HttpServletRequest.getRemoteUser()] will return the result of `SecurityContextHolder.getContext().getAuthentication().getName()` which is typically the current username. -This can be useful if you want to display the current username in your application. -Additionally, checking if this is null can be used to indicate if a user has authenticated or is anonymous. -Knowing if the user is authenticated or not can be useful for determining if certain UI elements should be shown or not (i.e. a log out link should only be displayed if the user is authenticated). +https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[`HttpServletRequest.getRemoteUser()`] returns the result of `SecurityContextHolder.getContext().getAuthentication().getName()`, which is typically the current username.This can be useful if you want to display the current username in your application. +Additionally, you can check this for null to determine whether a user has authenticated or is anonymous. +Knowing whether the user is authenticated or not can be useful for determining if certain UI elements should be shown or not (for example, a logout link that should be displayed only if the user is authenticated). [[servletapi-user-principal]] === HttpServletRequest.getUserPrincipal() -The https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[HttpServletRequest.getUserPrincipal()] will return the result of `SecurityContextHolder.getContext().getAuthentication()`. -This means it is an `Authentication` which is typically an instance of `UsernamePasswordAuthenticationToken` when using username and password based authentication. +https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[`HttpServletRequest.getUserPrincipal()`] returns the result of `SecurityContextHolder.getContext().getAuthentication()`. +This means that it is an `Authentication`, which is typically an instance of `UsernamePasswordAuthenticationToken` when using username- and password-based authentication. This can be useful if you need additional information about your user. For example, you might have created a custom `UserDetailsService` that returns a custom `UserDetails` containing a first and last name for your user. You could obtain this information with the following: @@ -56,8 +57,8 @@ Instead, one should centralize it to reduce any coupling of Spring Security and [[servletapi-user-in-role]] === HttpServletRequest.isUserInRole(String) -The https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[HttpServletRequest.isUserInRole(String)] will determine if `SecurityContextHolder.getContext().getAuthentication().getAuthorities()` contains a `GrantedAuthority` with the role passed into `isUserInRole(String)`. -Typically users should not pass in the "ROLE_" prefix into this method since it is added automatically. +https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[`HttpServletRequest.isUserInRole(String)`] determines if `SecurityContextHolder.getContext().getAuthentication().getAuthorities()` contains a `GrantedAuthority` with the role passed into `isUserInRole(String)`. +Typically, users should not pass the `ROLE_` prefix to this method, since it is added automatically. For example, if you want to determine if the current user has the authority "ROLE_ADMIN", you could use the following: ==== @@ -79,19 +80,19 @@ For example, you might display admin links only if the current user is an admin. [[servletapi-3]] == Servlet 3+ Integration -The following section describes the Servlet 3 methods that Spring Security integrates with. +The following section describes the Servlet 3 methods with which Spring Security integrates. [[servletapi-authenticate]] === HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse) -The https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#authenticate%28javax.servlet.http.HttpServletResponse%29[HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)] method can be used to ensure that a user is authenticated. -If they are not authenticated, the configured AuthenticationEntryPoint will be used to request the user to authenticate (i.e. redirect to the login page). +You can use the https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#authenticate%28javax.servlet.http.HttpServletResponse%29[`HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)`] method to ensure that a user is authenticated. +If they are not authenticated, the configured `AuthenticationEntryPoint` is used to request the user to authenticate (redirect to the login page). [[servletapi-login]] === HttpServletRequest.login(String,String) -The https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login%28java.lang.String,%20java.lang.String%29[HttpServletRequest.login(String,String)] method can be used to authenticate the user with the current `AuthenticationManager`. -For example, the following would attempt to authenticate with the username "user" and password "password": +You can use the https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login%28java.lang.String,%20java.lang.String%29[`HttpServletRequest.login(String,String)`] method to authenticate the user with the current `AuthenticationManager`. +For example, the following would attempt to authenticate with a username of `user` and a password of `password`: ==== .Java @@ -117,23 +118,23 @@ try { [NOTE] ==== -It is not necessary to catch the ServletException if you want Spring Security to process the failed authentication attempt. +You need not catch the `ServletException` if you want Spring Security to process the failed authentication attempt. ==== [[servletapi-logout]] === HttpServletRequest.logout() -The https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout%28%29[HttpServletRequest.logout()] method can be used to log the current user out. +You can use the https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout%28%29[`HttpServletRequest.logout()`] method to log out the current user. -Typically this means that the SecurityContextHolder will be cleared out, the HttpSession will be invalidated, any "Remember Me" authentication will be cleaned up, etc. -However, the configured LogoutHandler implementations will vary depending on your Spring Security configuration. -It is important to note that after HttpServletRequest.logout() has been invoked, you are still in charge of writing a response out. -Typically this would involve a redirect to the welcome page. +Typically, this means that the `SecurityContextHolder` is cleared out, the `HttpSession` is invalidated, any "`Remember Me`" authentication is cleaned up, and so on. +However, the configured `LogoutHandler` implementations vary, depending on your Spring Security configuration. +Note that, after `HttpServletRequest.logout()` has been invoked, you are still in charge of writing out a response. +Typically, this would involve a redirect to the welcome page. [[servletapi-start-runnable]] === AsyncContext.start(Runnable) -The https://docs.oracle.com/javaee/6/api/javax/servlet/AsyncContext.html#start%28java.lang.Runnable%29[AsyncContext.start(Runnable)] method that ensures your credentials will be propagated to the new Thread. -Using Spring Security's concurrency support, Spring Security overrides the AsyncContext.start(Runnable) to ensure that the current SecurityContext is used when processing the Runnable. -For example, the following would output the current user's Authentication: +The https://docs.oracle.com/javaee/6/api/javax/servlet/AsyncContext.html#start%28java.lang.Runnable%29[`AsyncContext.start(Runnable)`] method ensures your credentials are propagated to the new `Thread`. +By using Spring Security's concurrency support, Spring Security overrides `AsyncContext.start(Runnable)` to ensure that the current `SecurityContext` is used when processing the Runnable. +The following example outputs the current user's Authentication: ==== .Java @@ -175,10 +176,11 @@ async.start { [[servletapi-async]] === Async Servlet Support -If you are using Java Based configuration, you are ready to go. -If you are using XML configuration, there are a few updates that are necessary. -The first step is to ensure you have updated your web.xml to use at least the 3.0 schema as shown below: +If you use Java-based configuration, you are ready to go. +If you use XML configuration, a few updates are necessary. +The first step is to ensure that you have updated your `web.xml` file to use at least the 3.0 schema: +==== [source,xml] ---- ---- +==== -Next you need to ensure that your springSecurityFilterChain is setup for processing asynchronous requests. +Next, you need to ensure that your `springSecurityFilterChain` is set up for processing asynchronous requests: +==== [source,xml] ---- @@ -207,15 +211,15 @@ Next you need to ensure that your springSecurityFilterChain is setup for process ASYNC ---- +==== -That's it! -Now Spring Security will ensure that your SecurityContext is propagated on asynchronous requests too. +Now Spring Security ensures that your `SecurityContext` is propagated on asynchronous requests, too. -So how does it work? If you are not really interested, feel free to skip the remainder of this section, otherwise read on. -Most of this is built into the Servlet specification, but there is a little bit of tweaking that Spring Security does to ensure things work with asynchronous requests properly. -Prior to Spring Security 3.2, the SecurityContext from the SecurityContextHolder was automatically saved as soon as the HttpServletResponse was committed. -This can cause issues in an Async environment. -For example, consider the following: +So how does it work? If you are not really interested, feel free to skip the remainder of this section +Most of this is built into the Servlet specification, but there is a little bit of tweaking that Spring Security does to ensure things work properly with asynchronous requests. +Prior to Spring Security 3.2, the `SecurityContext` from the `SecurityContextHolder` was automatically saved as soon as the `HttpServletResponse` was committed. +This can cause issues in an asynchronous environment. +Consider the following example: ==== .Java @@ -258,11 +262,11 @@ object : Thread("AsyncThread") { ---- ==== -The issue is that this Thread is not known to Spring Security, so the SecurityContext is not propagated to it. -This means when we commit the HttpServletResponse there is no SecurityContext. -When Spring Security automatically saved the SecurityContext on committing the HttpServletResponse it would lose our logged in user. +The issue is that this `Thread` is not known to Spring Security, so the `SecurityContext` is not propagated to it. +This means that, when we commit the `HttpServletResponse`, there is no `SecurityContext`. +When Spring Security automatically saved the `SecurityContext` on committing the `HttpServletResponse`, it would lose a logged in user. -Since version 3.2, Spring Security is smart enough to no longer automatically save the SecurityContext on committing the HttpServletResponse as soon as HttpServletRequest.startAsync() is invoked. +Since version 3.2, Spring Security is smart enough to no longer automatically save the `SecurityContext` on committing the `HttpServletResponse` as soon as `HttpServletRequest.startAsync()` is invoked. [[servletapi-31]] == Servlet 3.1+ Integration @@ -270,4 +274,4 @@ The following section describes the Servlet 3.1 methods that Spring Security int [[servletapi-change-session-id]] === HttpServletRequest#changeSessionId() -The https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#changeSessionId()[HttpServletRequest.changeSessionId()] is the default method for protecting against xref:servlet/authentication/session-management.adoc#ns-session-fixation[Session Fixation] attacks in Servlet 3.1 and higher. +https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#changeSessionId()[HttpServletRequest.changeSessionId()] is the default method for protecting against xref:servlet/authentication/session-management.adoc#ns-session-fixation[Session Fixation] attacks in Servlet 3.1 and higher. diff --git a/docs/modules/ROOT/pages/servlet/integrations/websocket.adoc b/docs/modules/ROOT/pages/servlet/integrations/websocket.adoc index 6ae9b57a86a..e40483a5801 100644 --- a/docs/modules/ROOT/pages/servlet/integrations/websocket.adoc +++ b/docs/modules/ROOT/pages/servlet/integrations/websocket.adoc @@ -6,17 +6,16 @@ This section describes how to use Spring Security's WebSocket support. .Direct JSR-356 Support **** -Spring Security does not provide direct JSR-356 support because doing so would provide little value. -This is because the format is unknown, so there is https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-intro-sub-protocol[little Spring can do to secure an unknown format]. -Additionally, JSR-356 does not provide a way to intercept messages, so security would be rather invasive. +Spring Security does not provide direct JSR-356 support, because doing so would provide little value. +This is because the format is unknown, and there is https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-intro-sub-protocol[little Spring can do to secure an unknown format]. +Additionally, JSR-356 does not provide a way to intercept messages, so security would be invasive. **** [[websocket-configuration]] == WebSocket Configuration Spring Security 4.0 has introduced authorization support for WebSockets through the Spring Messaging abstraction. -To configure authorization using Java Configuration, simply extend the `AbstractSecurityWebSocketMessageBrokerConfigurer` and configure the `MessageSecurityMetadataSourceRegistry`. -For example: +To configure authorization by using Java Configuration, extend the `AbstractSecurityWebSocketMessageBrokerConfigurer` and configure the `MessageSecurityMetadataSourceRegistry`: ==== .Java @@ -43,17 +42,15 @@ open class WebSocketSecurityConfig : AbstractSecurityWebSocketMessageBrokerConfi } } ---- +<1> Any inbound CONNECT message requires a valid CSRF token to enforce the <>. +<2> The `SecurityContextHolder` is populated with the user within the `simpUser` header attribute for any inbound request. +<3> Our messages require the proper authorization. Specifically, any inbound message that starts with `/user/` will requires `ROLE_USER`. You can find additional details on authorization in <> ==== -This will ensure that: - -<1> Any inbound CONNECT message requires a valid CSRF token to enforce <> -<2> The SecurityContextHolder is populated with the user within the simpUser header attribute for any inbound request. -<3> Our messages require the proper authorization. Specifically, any inbound message that starts with "/user/" will require ROLE_USER. Additional details on authorization can be found in <> - -Spring Security also provides xref:servlet/appendix/namespace.adoc#nsa-websocket-security[XML Namespace] support for securing WebSockets. +Spring Security also provides xref:servlet/appendix/namespace/websocket.adoc#nsa-websocket-security[XML Namespace] support for securing WebSockets. A comparable XML based configuration looks like the following: +==== [source,xml] ---- @@ -61,28 +58,26 @@ A comparable XML based configuration looks like the following: ---- - -This will ensure that: - <1> Any inbound CONNECT message requires a valid CSRF token to enforce <> <2> The SecurityContextHolder is populated with the user within the simpUser header attribute for any inbound request. <3> Our messages require the proper authorization. Specifically, any inbound message that starts with "/user/" will require ROLE_USER. Additional details on authorization can be found in <> +==== + [[websocket-authentication]] == WebSocket Authentication WebSockets reuse the same authentication information that is found in the HTTP request when the WebSocket connection was made. -This means that the `Principal` on the `HttpServletRequest` will be handed off to WebSockets. -If you are using Spring Security, the `Principal` on the `HttpServletRequest` is overridden automatically. +This means that the `Principal` on the `HttpServletRequest` is handed off to WebSockets. +If you use Spring Security, the `Principal` on the `HttpServletRequest` is overridden automatically. -More concretely, to ensure a user has authenticated to your WebSocket application, all that is necessary is to ensure that you setup Spring Security to authenticate your HTTP based web application. +More concretely, to ensure a user has authenticated to your WebSocket application, all you need to do is ensure that you set up Spring Security to authenticate your HTTP based web application. [[websocket-authorization]] == WebSocket Authorization Spring Security 4.0 has introduced authorization support for WebSockets through the Spring Messaging abstraction. -To configure authorization using Java Configuration, simply extend the `AbstractSecurityWebSocketMessageBrokerConfigurer` and configure the `MessageSecurityMetadataSourceRegistry`. -For example: +To configure authorization by using Java configuration, extend the `AbstractSecurityWebSocketMessageBrokerConfigurer` and configure the `MessageSecurityMetadataSourceRegistry`: ==== .Java @@ -121,20 +116,18 @@ open class WebSocketSecurityConfig : AbstractSecurityWebSocketMessageBrokerConfi } } ---- -==== - -This will ensure that: - <1> Any message without a destination (i.e. anything other than Message type of MESSAGE or SUBSCRIBE) will require the user to be authenticated <2> Anyone can subscribe to /user/queue/errors <3> Any message that has a destination starting with "/app/" will be require the user to have the role ROLE_USER <4> Any message that starts with "/user/" or "/topic/friends/" that is of type SUBSCRIBE will require ROLE_USER <5> Any other message of type MESSAGE or SUBSCRIBE is rejected. Due to 6 we do not need this step, but it illustrates how one can match on specific message types. <6> Any other Message is rejected. This is a good idea to ensure that you do not miss any messages. +==== -Spring Security also provides xref:servlet/appendix/namespace.adoc#nsa-websocket-security[XML Namespace] support for securing WebSockets. +Spring Security also provides xref:servlet/appendix/namespace/websocket.adoc#nsa-websocket-security[XML Namespace] support for securing WebSockets. A comparable XML based configuration looks like the following: +==== [source,xml] ---- @@ -157,114 +150,115 @@ A comparable XML based configuration looks like the following: ---- - -This will ensure that: - <1> Any message of type CONNECT, UNSUBSCRIBE, or DISCONNECT will require the user to be authenticated <2> Anyone can subscribe to /user/queue/errors <3> Any message that has a destination starting with "/app/" will be require the user to have the role ROLE_USER <4> Any message that starts with "/user/" or "/topic/friends/" that is of type SUBSCRIBE will require ROLE_USER <5> Any other message of type MESSAGE or SUBSCRIBE is rejected. Due to 6 we do not need this step, but it illustrates how one can match on specific message types. <6> Any other message with a destination is rejected. This is a good idea to ensure that you do not miss any messages. +==== [[websocket-authorization-notes]] === WebSocket Authorization Notes -In order to properly secure your application it is important to understand Spring's WebSocket support. +To properly secure your application, you need to understand Spring's WebSocket support. [[websocket-authorization-notes-messagetypes]] ==== WebSocket Authorization on Message Types -It is important to understand the distinction between SUBSCRIBE and MESSAGE types of messages and how it works within Spring. +You need to understand the distinction between `SUBSCRIBE` and `MESSAGE` types of messages and how they work within Spring. -Consider a chat application. +Consider a chat application: -* The system can send notifications MESSAGE to all users through a destination of "/topic/system/notifications" -* Clients can receive notifications by SUBSCRIBE to the "/topic/system/notifications". +* The system can send a notification `MESSAGE` to all users through a destination of `/topic/system/notifications`. +* Clients can receive notifications by `SUBSCRIBE` to the `/topic/system/notifications`. -While we want clients to be able to SUBSCRIBE to "/topic/system/notifications", we do not want to enable them to send a MESSAGE to that destination. -If we allowed sending a MESSAGE to "/topic/system/notifications", then clients could send a message directly to that endpoint and impersonate the system. +While we want clients to be able to `SUBSCRIBE` to `/topic/system/notifications`, we do not want to enable them to send a `MESSAGE` to that destination. +If we allowed sending a `MESSAGE` to `/topic/system/notifications`, clients could send a message directly to that endpoint and impersonate the system. -In general, it is common for applications to deny any MESSAGE sent to a destination that starts with the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp[broker prefix] (i.e. "/topic/" or "/queue/"). +In general, it is common for applications to deny any `MESSAGE` sent to a destination that starts with the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp[broker prefix] (`/topic/` or `/queue/`). [[websocket-authorization-notes-destinations]] ==== WebSocket Authorization on Destinations -It is also is important to understand how destinations are transformed. +You should also understand how destinations are transformed. -Consider a chat application. +Consider a chat application: -* Users can send messages to a specific user by sending a message to the destination of "/app/chat". -* The application sees the message, ensures that the "from" attribute is specified as the current user (we cannot trust the client). -* The application then sends the message to the recipient using `SimpMessageSendingOperations.convertAndSendToUser("toUser", "/queue/messages", message)`. -* The message gets turned into the destination of "/queue/user/messages-" +* Users can send messages to a specific user by sending a message to the `/app/chat` destination. +* The application sees the message, ensures that the `from` attribute is specified as the current user (we cannot trust the client). +* The application then sends the message to the recipient by using `SimpMessageSendingOperations.convertAndSendToUser("toUser", "/queue/messages", message)`. +* The message gets turned into the destination of `/queue/user/messages-`. -With the application above, we want to allow our client to listen to "/user/queue" which is transformed into "/queue/user/messages-". -However, we do not want the client to be able to listen to "/queue/*" because that would allow the client to see messages for every user. +With this chat application, we want to let our client to listen `/user/queue`, which is transformed into `/queue/user/messages-`. +However, we do not want the client to be able to listen to `/queue/*`, because that would let the client see messages for every user. -In general, it is common for applications to deny any SUBSCRIBE sent to a message that starts with the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp[broker prefix] (i.e. "/topic/" or "/queue/"). -Of course we may provide exceptions to account for things like +In general, it is common for applications to deny any `SUBSCRIBE` sent to a message that starts with the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp[broker prefix] (`/topic/` or `/queue/`). +We may provide exceptions to account for things like +//FIXME: Like what? [[websocket-authorization-notes-outbound]] === Outbound Messages -Spring contains a section titled https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-message-flow[Flow of Messages] that describes how messages flow through the system. -It is important to note that Spring Security only secures the `clientInboundChannel`. +The Spring Framework reference documentation contains a section titled https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-message-flow["`Flow of Messages`"] that describes how messages flow through the system. +Note that Spring Security secures only the `clientInboundChannel`. Spring Security does not attempt to secure the `clientOutboundChannel`. The most important reason for this is performance. -For every message that goes in, there are typically many more that go out. +For every message that goes in, typically many more go out. Instead of securing the outbound messages, we encourage securing the subscription to the endpoints. [[websocket-sameorigin]] == Enforcing Same Origin Policy -It is important to emphasize that the browser does not enforce the https://en.wikipedia.org/wiki/Same-origin_policy[Same Origin Policy] for WebSocket connections. +Note that the browser does not enforce the https://en.wikipedia.org/wiki/Same-origin_policy[Same Origin Policy] for WebSocket connections. This is an extremely important consideration. [[websocket-sameorigin-why]] === Why Same Origin? Consider the following scenario. -A user visits bank.com and authenticates to their account. -The same user opens another tab in their browser and visits evil.com. -The Same Origin Policy ensures that evil.com cannot read or write data to bank.com. +A user visits `bank.com` and authenticates to their account. +The same user opens another tab in their browser and visits `evil.com`. +The Same Origin Policy ensures that `evil.com` cannot read data from or write data to `bank.com`. -With WebSockets the Same Origin Policy does not apply. -In fact, unless bank.com explicitly forbids it, evil.com can read and write data on behalf of the user. -This means that anything the user can do over the webSocket (i.e. transfer money), evil.com can do on that users behalf. +With WebSockets, the Same Origin Policy does not apply. +In fact, unless `bank.com` explicitly forbids it, `evil.com` can read and write data on behalf of the user. +This means that anything the user can do over the webSocket (such as transferring money), `evil.com` can do on that user's behalf. -Since SockJS tries to emulate WebSockets it also bypasses the Same Origin Policy. -This means developers need to explicitly protect their applications from external domains when using SockJS. +Since SockJS tries to emulate WebSockets, it also bypasses the Same Origin Policy. +This means that developers need to explicitly protect their applications from external domains when they use SockJS. [[websocket-sameorigin-spring]] === Spring WebSocket Allowed Origin Fortunately, since Spring 4.1.5 Spring's WebSocket and SockJS support restricts access to the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-server-allowed-origins[current domain]. -Spring Security adds an additional layer of protection to provide https://en.wikipedia.org/wiki/Defense_in_depth_(computing)[defence in depth]. +Spring Security adds an additional layer of protection to provide https://en.wikipedia.org/wiki/Defence_in_depth_(non-military)#Information_security[defense in depth]. [[websocket-sameorigin-csrf]] === Adding CSRF to Stomp Headers -By default Spring Security requires the xref:features/exploits/csrf.adoc#csrf[CSRF token] in any CONNECT message type. +By default, Spring Security requires the xref:features/exploits/csrf.adoc#csrf[CSRF token] in any `CONNECT` message type. This ensures that only a site that has access to the CSRF token can connect. -Since only the *Same Origin* can access the CSRF token, external domains are not allowed to make a connection. +Since only the *same origin* can access the CSRF token, external domains are not allowed to make a connection. Typically we need to include the CSRF token in an HTTP header or an HTTP parameter. However, SockJS does not allow for these options. -Instead, we must include the token in the Stomp headers +Instead, we must include the token in the Stomp headers. -Applications can xref:servlet/exploits/csrf.adoc#servlet-csrf-include[obtain a CSRF token] by accessing the request attribute named _csrf. -For example, the following will allow accessing the `CsrfToken` in a JSP: +Applications can xref:servlet/exploits/csrf.adoc#servlet-csrf-include[obtain a CSRF token] by accessing the request attribute named `_csrf`. +For example, the following allows accessing the `CsrfToken` in a JSP: +==== [source,javascript] ---- var headerName = "${_csrf.headerName}"; var token = "${_csrf.token}"; ---- +==== -If you are using static HTML, you can expose the `CsrfToken` on a REST endpoint. -For example, the following would expose the `CsrfToken` on the URL /csrf +If you use static HTML, you can expose the `CsrfToken` on a REST endpoint. +For example, the following would expose the `CsrfToken` on the `/csrf` URL: ==== .Java @@ -293,11 +287,11 @@ class CsrfController { ---- ==== -The JavaScript can make a REST call to the endpoint and use the response to populate the headerName and the token. +The JavaScript can make a REST call to the endpoint and use the response to populate the `headerName` and the token. -We can now include the token in our Stomp client. -For example: +We can now include the token in our Stomp client: +==== [source,javascript] ---- ... @@ -306,14 +300,15 @@ headers[headerName] = token; stompClient.connect(headers, function(frame) { ... -} +}) ---- +==== [[websocket-sameorigin-disable]] === Disable CSRF within WebSockets -If you want to allow other domains to access your site, you can disable Spring Security's protection. -For example, in Java Configuration you can use the following: +If you want to let other domains access your site, you can disable Spring Security's protection. +For example, in Java configuration you can use the following: ==== .Java @@ -351,18 +346,19 @@ open class WebSocketSecurityConfig : AbstractSecurityWebSocketMessageBrokerConfi == Working with SockJS https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-fallback[SockJS] provides fallback transports to support older browsers. -When using the fallback options we need to relax a few security constraints to allow SockJS to work with Spring Security. +When using the fallback options, we need to relax a few security constraints to allow SockJS to work with Spring Security. [[websocket-sockjs-sameorigin]] === SockJS & frame-options -SockJS may use an https://github.com/sockjs/sockjs-client/tree/v0.3.4[transport that leverages an iframe]. -By default Spring Security will xref:features/exploits/headers.adoc#headers-frame-options[deny] the site from being framed to prevent Clickjacking attacks. -To allow SockJS frame based transports to work, we need to configure Spring Security to allow the same origin to frame the content. +SockJS may use a https://github.com/sockjs/sockjs-client/tree/v0.3.4[transport that leverages an iframe]. +By default, Spring Security xref:features/exploits/headers.adoc#headers-frame-options[denies] the site from being framed to prevent clickjacking attacks. +To allow SockJS frame-based transports to work, we need to configure Spring Security to let the same origin frame the content. -You can customize X-Frame-Options with the xref:servlet/appendix/namespace.adoc#nsa-frame-options[frame-options] element. -For example, the following will instruct Spring Security to use "X-Frame-Options: SAMEORIGIN" which allows iframes within the same domain: +You can customize `X-Frame-Options` with the xref:servlet/appendix/namespace/http.adoc#nsa-frame-options[frame-options] element. +For example, the following instructs Spring Security to use `X-Frame-Options: SAMEORIGIN`, which allows iframes within the same domain: +==== [source,xml] ---- @@ -374,8 +370,9 @@ For example, the following will instruct Spring Security to use "X-Frame-Options ---- +==== -Similarly, you can customize frame options to use the same origin within Java Configuration using the following: +Similarly, you can customize frame options to use the same origin within Java Configuration by using the following: ==== .Java @@ -420,19 +417,19 @@ open class WebSecurityConfig : WebSecurityConfigurerAdapter() { [[websocket-sockjs-csrf]] === SockJS & Relaxing CSRF -SockJS uses a POST on the CONNECT messages for any HTTP based transport. -Typically we need to include the CSRF token in an HTTP header or an HTTP parameter. +SockJS uses a POST on the CONNECT messages for any HTTP-based transport. +Typically, we need to include the CSRF token in an HTTP header or an HTTP parameter. However, SockJS does not allow for these options. Instead, we must include the token in the Stomp headers as described in <>. -It also means we need to relax our CSRF protection with the web layer. +It also means that we need to relax our CSRF protection with the web layer. Specifically, we want to disable CSRF protection for our connect URLs. We do NOT want to disable CSRF protection for every URL. -Otherwise our site will be vulnerable to CSRF attacks. +Otherwise, our site is vulnerable to CSRF attacks. -We can easily achieve this by providing a CSRF RequestMatcher. -Our Java Configuration makes this extremely easy. -For example, if our stomp endpoint is "/chat" we can disable CSRF protection for only URLs that start with "/chat/" using the following configuration: +We can easily achieve this by providing a CSRF `RequestMatcher`. +Our Java configuration makes this easy. +For example, if our stomp endpoint is `/chat`, we can disable CSRF protection only for URLs that start with `/chat/` by using the following configuration: ==== .Java @@ -456,10 +453,12 @@ public class WebSecurityConfig .sameOrigin() ) ) - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize ... ) ... + } +} ---- .Kotlin @@ -482,13 +481,15 @@ open class WebSecurityConfig : WebSecurityConfigurerAdapter() { // ... } // ... - + } + } +} ---- ==== -If we are using XML based configuration, we can use the xref:servlet/appendix/namespace.adoc#nsa-csrf-request-matcher-ref[csrf@request-matcher-ref]. -For example: +If we use XML-based configuration, we can use thexref:servlet/appendix/namespace/http.adoc#nsa-csrf-request-matcher-ref[csrf@request-matcher-ref]. +==== [source,xml] ---- @@ -513,3 +514,4 @@ For example: ---- +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/client/authorization-grants.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/authorization-grants.adoc new file mode 100644 index 00000000000..6f42e92e047 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/authorization-grants.adoc @@ -0,0 +1,1354 @@ +[[oauth2Client-auth-grant-support]] += Authorization Grant Support + +This section describes Spring Security's support for authorization grants. + +[[oauth2Client-auth-code-grant]] +== Authorization Code + +[NOTE] +==== +See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] grant. +==== + +=== Obtaining Authorization + +[NOTE] +==== +See the https://tools.ietf.org/html/rfc6749#section-4.1.1[Authorization Request/Response] protocol flow for the Authorization Code grant. +==== + + + +=== Initiating the Authorization Request + +The `OAuth2AuthorizationRequestRedirectFilter` uses an `OAuth2AuthorizationRequestResolver` to resolve an `OAuth2AuthorizationRequest` and initiate the Authorization Code grant flow by redirecting the end-user's user-agent to the Authorization Server's Authorization Endpoint. + +The primary role of the `OAuth2AuthorizationRequestResolver` is to resolve an `OAuth2AuthorizationRequest` from the provided web request. +The default implementation `DefaultOAuth2AuthorizationRequestResolver` matches on the (default) path `+/oauth2/authorization/{registrationId}+`, extracting the `registrationId`, and using it to build the `OAuth2AuthorizationRequest` for the associated `ClientRegistration`. + +Consider the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +==== +[source,yaml,attrs="-attributes"] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + authorization-grant-type: authorization_code + redirect-uri: "{baseUrl}/authorized/okta" + scope: read, write + provider: + okta: + authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize + token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token +---- +==== + +Given the preceding properties, a request with the base path `/oauth2/authorization/okta` initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectFilter` and ultimately starts the Authorization Code grant flow. + +[NOTE] +==== +The `AuthorizationCodeOAuth2AuthorizedClientProvider` is an implementation of `OAuth2AuthorizedClientProvider` for the Authorization Code grant, +which also initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectFilter`. +==== + +If the OAuth 2.0 Client is a https://tools.ietf.org/html/rfc6749#section-2.1[Public Client], configure the OAuth 2.0 Client registration as follows: + +==== +[source,yaml,attrs="-attributes"] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-authentication-method: none + authorization-grant-type: authorization_code + redirect-uri: "{baseUrl}/authorized/okta" + ... +---- +==== + +Public Clients are supported by using https://tools.ietf.org/html/rfc7636[Proof Key for Code Exchange] (PKCE). +If the client is running in an untrusted environment (such as a native application or web browser-based application) and is therefore incapable of maintaining the confidentiality of its credentials, PKCE is automatically used when the following conditions are true: + +. `client-secret` is omitted (or empty) +. `client-authentication-method` is set to `none` (`ClientAuthenticationMethod.NONE`) + +[[oauth2Client-auth-code-redirect-uri]] +The `DefaultOAuth2AuthorizationRequestResolver` also supports `URI` template variables for the `redirect-uri` by using `UriComponentsBuilder`. + +The following configuration uses all the supported `URI` template variables: + +==== +[source,yaml,attrs="-attributes"] +---- +spring: + security: + oauth2: + client: + registration: + okta: + ... + redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}" + ... +---- +==== + +[NOTE] +==== +`+{baseUrl}+` resolves to `+{baseScheme}://{baseHost}{basePort}{basePath}+` +==== + +Configuring the `redirect-uri` with `URI` template variables is especially useful when the OAuth 2.0 Client is running behind a xref:features/exploits/http.adoc#http-proxy-server[Proxy Server]. +Doing so ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`. + +=== Customizing the Authorization Request + +One of the primary use cases an `OAuth2AuthorizationRequestResolver` can realize is the ability to customize the Authorization Request with additional parameters above the standard parameters defined in the OAuth 2.0 Authorization Framework. + +For example, OpenID Connect defines additional OAuth 2.0 request parameters for the https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest[Authorization Code Flow] extending from the standard parameters defined in the https://tools.ietf.org/html/rfc6749#section-4.1.1[OAuth 2.0 Authorization Framework]. +One of those extended parameters is the `prompt` parameter. + +[NOTE] +==== +The `prompt` parameter is optional. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for re-authentication and consent. The defined values are: `none`, `login`, `consent`, and `select_account`. +==== + +The following example shows how to configure the `DefaultOAuth2AuthorizationRequestResolver` with a `Consumer` that customizes the Authorization Request for `oauth2Login()`, by including the request parameter `prompt=consent`. + +==== +.Java +[source,java,role="primary"] +---- +@EnableWebSecurity +public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private ClientRegistrationRepository clientRegistrationRepository; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests(authorize -> authorize + .anyRequest().authenticated() + ) + .oauth2Login(oauth2 -> oauth2 + .authorizationEndpoint(authorization -> authorization + .authorizationRequestResolver( + authorizationRequestResolver(this.clientRegistrationRepository) + ) + ) + ); + } + + private OAuth2AuthorizationRequestResolver authorizationRequestResolver( + ClientRegistrationRepository clientRegistrationRepository) { + + DefaultOAuth2AuthorizationRequestResolver authorizationRequestResolver = + new DefaultOAuth2AuthorizationRequestResolver( + clientRegistrationRepository, "/oauth2/authorization"); + authorizationRequestResolver.setAuthorizationRequestCustomizer( + authorizationRequestCustomizer()); + + return authorizationRequestResolver; + } + + private Consumer authorizationRequestCustomizer() { + return customizer -> customizer + .additionalParameters(params -> params.put("prompt", "consent")); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + @Autowired + private lateinit var customClientRegistrationRepository: ClientRegistrationRepository + + override fun configure(http: HttpSecurity) { + http { + authorizeRequests { + authorize(anyRequest, authenticated) + } + oauth2Login { + authorizationEndpoint { + authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository) + } + } + } + } + + private fun authorizationRequestResolver( + clientRegistrationRepository: ClientRegistrationRepository?): OAuth2AuthorizationRequestResolver? { + val authorizationRequestResolver = DefaultOAuth2AuthorizationRequestResolver( + clientRegistrationRepository, "/oauth2/authorization") + authorizationRequestResolver.setAuthorizationRequestCustomizer( + authorizationRequestCustomizer()) + return authorizationRequestResolver + } + + private fun authorizationRequestCustomizer(): Consumer { + return Consumer { customizer -> + customizer + .additionalParameters { params -> params["prompt"] = "consent" } + } + } +} +---- +==== + +For the simple use case where the additional request parameter is always the same for a specific provider, you can add it directly in the `authorization-uri` property. + +For example, if the value for the request parameter `prompt` is always `consent` for the provider `okta`, you can configure it as follows: + +==== +[source,yaml] +---- +spring: + security: + oauth2: + client: + provider: + okta: + authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent +---- +==== + +The preceding example shows the common use case of adding a custom parameter on top of the standard parameters. +Alternatively, if your requirements are more advanced, you can take full control in building the Authorization Request URI by overriding the `OAuth2AuthorizationRequest.authorizationRequestUri` property. + +[TIP] +==== +`OAuth2AuthorizationRequest.Builder.build()` constructs the `OAuth2AuthorizationRequest.authorizationRequestUri`, which represents the Authorization Request URI including all query parameters using the `application/x-www-form-urlencoded` format. +==== + +The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property: + +==== +.Java +[source,java,role="primary"] +---- +private Consumer authorizationRequestCustomizer() { + return customizer -> customizer + .authorizationRequestUri(uriBuilder -> uriBuilder + .queryParam("prompt", "consent").build()); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +private fun authorizationRequestCustomizer(): Consumer { + return Consumer { customizer: OAuth2AuthorizationRequest.Builder -> + customizer + .authorizationRequestUri { uriBuilder: UriBuilder -> + uriBuilder + .queryParam("prompt", "consent").build() + } + } +} +---- +==== + + +=== Storing the Authorization Request + +The `AuthorizationRequestRepository` is responsible for the persistence of the `OAuth2AuthorizationRequest` from the time the Authorization Request is initiated to the time the Authorization Response is received (the callback). + +[TIP] +==== +The `OAuth2AuthorizationRequest` is used to correlate and validate the Authorization Response. +==== + +The default implementation of `AuthorizationRequestRepository` is `HttpSessionOAuth2AuthorizationRequestRepository`, which stores the `OAuth2AuthorizationRequest` in the `HttpSession`. + +If you have a custom implementation of `AuthorizationRequestRepository`, you can configure it as follows: + +.AuthorizationRequestRepository Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebSecurity +public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .oauth2Client(oauth2 -> oauth2 + .authorizationCodeGrant(codeGrant -> codeGrant + .authorizationRequestRepository(this.authorizationRequestRepository()) + ... + ) + ); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebSecurity +class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + oauth2Client { + authorizationCodeGrant { + authorizationRequestRepository = authorizationRequestRepository() + } + } + } + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + + +---- +==== + +=== Requesting an Access Token + +[NOTE] +==== +See the https://tools.ietf.org/html/rfc6749#section-4.1.3[Access Token Request/Response] protocol flow for the Authorization Code grant. +==== + +The default implementation of `OAuth2AccessTokenResponseClient` for the Authorization Code grant is `DefaultAuthorizationCodeTokenResponseClient`, which uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint. + +The `DefaultAuthorizationCodeTokenResponseClient` is flexible, as it lets you customize the pre-processing of the Token Request and/or post-handling of the Token Response. + + +=== Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `DefaultAuthorizationCodeTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. +The default implementation (`OAuth2AuthorizationCodeGrantRequestEntityConverter`) builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.1.3[OAuth 2.0 Access Token Request]. +However, providing a custom `Converter` would let you extend the standard Token Request and add custom parameter(s). + +To customize only the parameters of the request, you can provide `OAuth2AuthorizationCodeGrantRequestEntityConverter.setParametersConverter()` with a custom `Converter>` to completely override the parameters sent with the request. This is often simpler than constructing a `RequestEntity` directly. + +[TIP] +==== +If you prefer to only add additional parameters, you can provide `OAuth2AuthorizationCodeGrantRequestEntityConverter.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`. +==== + +[IMPORTANT] +==== +The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. +==== + +=== Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you need to provide `DefaultAuthorizationCodeTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. +The default `RestOperations` is configured as follows: + +==== +.Java +[source,java,role="primary"] +---- +RestTemplate restTemplate = new RestTemplate(Arrays.asList( + new FormHttpMessageConverter(), + new OAuth2AccessTokenResponseHttpMessageConverter())); + +restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val restTemplate = RestTemplate(listOf( + FormHttpMessageConverter(), + OAuth2AccessTokenResponseHttpMessageConverter())) + +restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() +---- +==== + +[TIP] +==== +Spring MVC `FormHttpMessageConverter` is required, as it is used when sending the OAuth 2.0 Access Token Request. +==== + +`OAuth2AccessTokenResponseHttpMessageConverter` is an `HttpMessageConverter` for an OAuth 2.0 Access Token Response. +You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used for converting the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. + +`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, such as `400 Bad Request`. +It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`. + +Whether you customize `DefaultAuthorizationCodeTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you need to configure it as follows: + +.Access Token Response Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebSecurity +public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .oauth2Client(oauth2 -> oauth2 + .authorizationCodeGrant(codeGrant -> codeGrant + .accessTokenResponseClient(this.accessTokenResponseClient()) + ... + ) + ); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebSecurity +class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + oauth2Client { + authorizationCodeGrant { + accessTokenResponseClient = accessTokenResponseClient() + } + } + } + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + + +---- +==== + + +[[oauth2Client-refresh-token-grant]] +== Refresh Token + +[NOTE] +==== +See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.5[Refresh Token]. +==== + + +=== Refreshing an Access Token + +[NOTE] +==== +See the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant. +==== + +The default implementation of `OAuth2AccessTokenResponseClient` for the Refresh Token grant is `DefaultRefreshTokenTokenResponseClient`, which uses a `RestOperations` when refreshing an access token at the Authorization Server’s Token Endpoint. + +The `DefaultRefreshTokenTokenResponseClient` is flexible, as it lets you customize the pre-processing of the Token Request or post-handling of the Token Response. + + +=== Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `DefaultRefreshTokenTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. +The default implementation (`OAuth2RefreshTokenGrantRequestEntityConverter`) builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-6[OAuth 2.0 Access Token Request]. +However, providing a custom `Converter` would let you extend the standard Token Request and add custom parameter(s). + +To customize only the parameters of the request, you can provide `OAuth2RefreshTokenGrantRequestEntityConverter.setParametersConverter()` with a custom `Converter>` to completely override the parameters sent with the request. This is often simpler than constructing a `RequestEntity` directly. + +[TIP] +==== +If you prefer to only add additional parameters, you can provide `OAuth2RefreshTokenGrantRequestEntityConverter.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`. +==== + +[IMPORTANT] +==== +The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. +==== + + +=== Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you need to provide `DefaultRefreshTokenTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. +The default `RestOperations` is configured as follows: + +==== +.Java +[source,java,role="primary"] +---- +RestTemplate restTemplate = new RestTemplate(Arrays.asList( + new FormHttpMessageConverter(), + new OAuth2AccessTokenResponseHttpMessageConverter())); + +restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val restTemplate = RestTemplate(listOf( + FormHttpMessageConverter(), + OAuth2AccessTokenResponseHttpMessageConverter())) + +restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() +---- +==== + +[TIP] +==== +Spring MVC `FormHttpMessageConverter` is required, as it is used when sending the OAuth 2.0 Access Token Request. +==== + +`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response. +You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used for converting the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. + +`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, such as `400 Bad Request`. +It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`. + +Whether you customize `DefaultRefreshTokenTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you need to configure it as follows: + +==== +.Java +[source,java,role="primary"] +---- +// Customize +OAuth2AccessTokenResponseClient refreshTokenTokenResponseClient = ... + +OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient)) + .build(); + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +// Customize +val refreshTokenTokenResponseClient: OAuth2AccessTokenResponseClient = ... + +val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) } + .build() + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) +---- +==== + +[NOTE] +==== +`OAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenOAuth2AuthorizedClientProvider`, +which is an implementation of an `OAuth2AuthorizedClientProvider` for the Refresh Token grant. +==== + +The `OAuth2RefreshToken` can optionally be returned in the Access Token Response for the `authorization_code` and `password` grant types. +If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2AuthorizedClient.getAccessToken()` is expired, it is automatically refreshed by the `RefreshTokenOAuth2AuthorizedClientProvider`. + + +[[oauth2Client-client-creds-grant]] +== Client Credentials + +[NOTE] +Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] grant. + + +=== Requesting an Access Token + +[NOTE] +==== +See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] grant. +==== + +The default implementation of `OAuth2AccessTokenResponseClient` for the Client Credentials grant is `DefaultClientCredentialsTokenResponseClient`, which uses a `RestOperations` when requesting an access token at the Authorization Server’s Token Endpoint. + +The `DefaultClientCredentialsTokenResponseClient` is flexible, as it lets you customize the pre-processing of the Token Request or post-handling of the Token Response. + + +=== Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `DefaultClientCredentialsTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. +The default implementation (`OAuth2ClientCredentialsGrantRequestEntityConverter`) builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.4.2[OAuth 2.0 Access Token Request]. +However, providing a custom `Converter` would let you extend the standard Token Request and add custom parameter(s). + +To customize only the parameters of the request, you can provide `OAuth2ClientCredentialsGrantRequestEntityConverter.setParametersConverter()` with a custom `Converter>` to completely override the parameters sent with the request. This is often simpler than constructing a `RequestEntity` directly. + +[TIP] +==== +If you prefer to only add additional parameters, you can provide `OAuth2ClientCredentialsGrantRequestEntityConverter.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`. +==== + +[IMPORTANT] +==== +The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. +==== + + +=== Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you need to provide `DefaultClientCredentialsTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. +The default `RestOperations` is configured as follows: + +==== +.Java +[source,java,role="primary"] +---- +RestTemplate restTemplate = new RestTemplate(Arrays.asList( + new FormHttpMessageConverter(), + new OAuth2AccessTokenResponseHttpMessageConverter())); + +restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val restTemplate = RestTemplate(listOf( + FormHttpMessageConverter(), + OAuth2AccessTokenResponseHttpMessageConverter())) + +restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() +---- +==== + +[TIP] +==== +Spring MVC `FormHttpMessageConverter` is required, as it is used when sending the OAuth 2.0 Access Token Request. +==== + +`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response. +You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used for converting the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. + +`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, such as `400 Bad Request`. +It uses an `OAuth2ErrorHttpMessageConverter` to convert the OAuth 2.0 Error parameters to an `OAuth2Error`. + +Whether you customize `DefaultClientCredentialsTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you need to configure it as follows: + +==== +.Java +[source,java,role="primary"] +---- +// Customize +OAuth2AccessTokenResponseClient clientCredentialsTokenResponseClient = ... + +OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient)) + .build(); + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +// Customize +val clientCredentialsTokenResponseClient: OAuth2AccessTokenResponseClient = ... + +val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) } + .build() + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) +---- +==== + +[NOTE] +==== +`OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsOAuth2AuthorizedClientProvider`, +which is an implementation of an `OAuth2AuthorizedClientProvider` for the Client Credentials grant. +==== + +=== Using the Access Token + +Consider the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +==== +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + authorization-grant-type: client_credentials + scope: read, write + provider: + okta: + token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token +---- +==== + +Further consider the following `OAuth2AuthorizedClientManager` `@Bean`: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientRepository authorizedClientRepository) { + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build(); + + DefaultOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { + val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build() + val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== + +Given the preceding properties and bean, you can obtain the `OAuth2AccessToken` as follows: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @Autowired + private OAuth2AuthorizedClientManager authorizedClientManager; + + @GetMapping("/") + public String index(Authentication authentication, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse) { + + OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(authentication) + .attributes(attrs -> { + attrs.put(HttpServletRequest.class.getName(), servletRequest); + attrs.put(HttpServletResponse.class.getName(), servletResponse); + }) + .build(); + OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); + + OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); + + ... + + return "index"; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +class OAuth2ClientController { + + @Autowired + private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager + + @GetMapping("/") + fun index(authentication: Authentication?, + servletRequest: HttpServletRequest, + servletResponse: HttpServletResponse): String { + val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(authentication) + .attributes(Consumer { attrs: MutableMap -> + attrs[HttpServletRequest::class.java.name] = servletRequest + attrs[HttpServletResponse::class.java.name] = servletResponse + }) + .build() + val authorizedClient = authorizedClientManager.authorize(authorizeRequest) + val accessToken: OAuth2AccessToken = authorizedClient.accessToken + + ... + + return "index" + } +} +---- +==== + +[NOTE] +==== +`HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes. +If not provided, they default to `ServletRequestAttributes` by using `RequestContextHolder.getRequestAttributes()`. +==== + +[[oauth2Client-password-grant]] +== Resource Owner Password Credentials + +[NOTE] +==== +See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] grant. +==== + +=== Requesting an Access Token + +[NOTE] +==== +See the https://tools.ietf.org/html/rfc6749#section-4.3.2[Access Token Request/Response] protocol flow for the Resource Owner Password Credentials grant. +==== + +The default implementation of `OAuth2AccessTokenResponseClient` for the Resource Owner Password Credentials grant is `DefaultPasswordTokenResponseClient`, which uses a `RestOperations` when requesting an access token at the Authorization Server’s Token Endpoint. + +The `DefaultPasswordTokenResponseClient` is flexible, as it lets you customize the pre-processing of the Token Request or post-handling of the Token Response. + +=== Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `DefaultPasswordTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. +The default implementation (`OAuth2PasswordGrantRequestEntityConverter`) builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.3.2[OAuth 2.0 Access Token Request]. +However, providing a custom `Converter` would let you extend the standard Token Request and add custom parameter(s). + +To customize only the parameters of the request, you can provide `OAuth2PasswordGrantRequestEntityConverter.setParametersConverter()` with a custom `Converter>` to completely override the parameters sent with the request. This is often simpler than constructing a `RequestEntity` directly. + +[TIP] +==== +If you prefer to only add additional parameters, you can provide `OAuth2PasswordGrantRequestEntityConverter.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`. +==== + +[IMPORTANT] +==== +The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. +==== + + +=== Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you need to provide `DefaultPasswordTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. +The default `RestOperations` is configured as follows: + +==== +.Java +[source,java,role="primary"] +---- +RestTemplate restTemplate = new RestTemplate(Arrays.asList( + new FormHttpMessageConverter(), + new OAuth2AccessTokenResponseHttpMessageConverter())); + +restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val restTemplate = RestTemplate(listOf( + FormHttpMessageConverter(), + OAuth2AccessTokenResponseHttpMessageConverter())) + +restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() +---- +==== + +[TIP] +==== +Spring MVC `FormHttpMessageConverter` is required, as it is used when sending the OAuth 2.0 Access Token Request. +==== + +`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response. +You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used to convert the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. + +`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, such as `400 Bad Request`. +It uses an `OAuth2ErrorHttpMessageConverter` to convert the OAuth 2.0 Error parameters to an `OAuth2Error`. + +Whether you customize `DefaultPasswordTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you need to configure it as follows: + +==== +.Java +[source,java,role="primary"] +---- +// Customize +OAuth2AccessTokenResponseClient passwordTokenResponseClient = ... + +OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient)) + .refreshToken() + .build(); + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val passwordTokenResponseClient: OAuth2AccessTokenResponseClient = ... + +val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .password { it.accessTokenResponseClient(passwordTokenResponseClient) } + .refreshToken() + .build() + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) +---- +==== + +[NOTE] +==== +`OAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordOAuth2AuthorizedClientProvider`, +which is an implementation of an `OAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant. +==== + +=== Using the Access Token + +Consider the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + authorization-grant-type: password + scope: read, write + provider: + okta: + token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token +---- + +Further consider the `OAuth2AuthorizedClientManager` `@Bean`: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientRepository authorizedClientRepository) { + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build(); + + DefaultOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters, + // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()); + + return authorizedClientManager; +} + +private Function> contextAttributesMapper() { + return authorizeRequest -> { + Map contextAttributes = Collections.emptyMap(); + HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName()); + String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME); + String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD); + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = new HashMap<>(); + + // `PasswordOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username); + contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password); + } + return contextAttributes; + }; +} +---- +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { + val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build() + val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + + // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters, + // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()) + return authorizedClientManager +} + +private fun contextAttributesMapper(): Function> { + return Function { authorizeRequest -> + var contextAttributes: MutableMap = mutableMapOf() + val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name) + val username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME) + val password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD) + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = hashMapOf() + + // `PasswordOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username + contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password + } + contextAttributes + } +} +---- +==== + +Given the preceding properties and bean, you can obtain the `OAuth2AccessToken` as follows: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @Autowired + private OAuth2AuthorizedClientManager authorizedClientManager; + + @GetMapping("/") + public String index(Authentication authentication, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse) { + + OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(authentication) + .attributes(attrs -> { + attrs.put(HttpServletRequest.class.getName(), servletRequest); + attrs.put(HttpServletResponse.class.getName(), servletResponse); + }) + .build(); + OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); + + OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); + + ... + + return "index"; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + @Autowired + private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager + + @GetMapping("/") + fun index(authentication: Authentication?, + servletRequest: HttpServletRequest, + servletResponse: HttpServletResponse): String { + val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(authentication) + .attributes(Consumer { + it[HttpServletRequest::class.java.name] = servletRequest + it[HttpServletResponse::class.java.name] = servletResponse + }) + .build() + val authorizedClient = authorizedClientManager.authorize(authorizeRequest) + val accessToken: OAuth2AccessToken = authorizedClient.accessToken + + ... + + return "index" + } +} +---- +==== + +[NOTE] +==== +`HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes. +If not provided, they default to `ServletRequestAttributes` using `RequestContextHolder.getRequestAttributes()`. +==== + + +[[oauth2Client-jwt-bearer-grant]] +== JWT Bearer + +[NOTE] +==== +Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on the https://datatracker.ietf.org/doc/html/rfc7523[JWT Bearer] grant. +==== + + +=== Requesting an Access Token + +[NOTE] +==== +Please refer to the https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[Access Token Request/Response] protocol flow for the JWT Bearer grant. +==== + +The default implementation of `OAuth2AccessTokenResponseClient` for the JWT Bearer grant is `DefaultJwtBearerTokenResponseClient`, which uses a `RestOperations` when requesting an access token at the Authorization Server’s Token Endpoint. + +The `DefaultJwtBearerTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. + + +=== Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `DefaultJwtBearerTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. +The default implementation `JwtBearerGrantRequestEntityConverter` builds a `RequestEntity` representation of a https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[OAuth 2.0 Access Token Request]. +However, providing a custom `Converter`, would allow you to extend the Token Request and add custom parameter(s). + +To customize only the parameters of the request, you can provide `JwtBearerGrantRequestEntityConverter.setParametersConverter()` with a custom `Converter>` to completely override the parameters sent with the request. This is often simpler than constructing a `RequestEntity` directly. + +[TIP] +If you prefer to only add additional parameters, you can provide `JwtBearerGrantRequestEntityConverter.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`. + + +=== Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultJwtBearerTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. +The default `RestOperations` is configured as follows: + +==== +.Java +[source,java,role="primary"] +---- +RestTemplate restTemplate = new RestTemplate(Arrays.asList( + new FormHttpMessageConverter(), + new OAuth2AccessTokenResponseHttpMessageConverter())); + +restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val restTemplate = RestTemplate(listOf( + FormHttpMessageConverter(), + OAuth2AccessTokenResponseHttpMessageConverter())) + +restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() +---- +==== + +[TIP] +==== +Spring MVC `FormHttpMessageConverter` is required as it's used when sending the OAuth 2.0 Access Token Request. +==== + +`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response. +You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used for converting the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. + +`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, eg. 400 Bad Request. +It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`. + +Whether you customize `DefaultJwtBearerTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example: + +==== +.Java +[source,java,role="primary"] +---- +// Customize +OAuth2AccessTokenResponseClient jwtBearerTokenResponseClient = ... + +JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider(); +jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient); + +OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .provider(jwtBearerAuthorizedClientProvider) + .build(); + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +// Customize +val jwtBearerTokenResponseClient: OAuth2AccessTokenResponseClient = ... + +val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider() +jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient); + +val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .provider(jwtBearerAuthorizedClientProvider) + .build() + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) +---- +==== + +=== Using the Access Token + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer + scope: read + provider: + okta: + token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token +---- + +...and the `OAuth2AuthorizedClientManager` `@Bean`: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientRepository authorizedClientRepository) { + + JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = + new JwtBearerOAuth2AuthorizedClientProvider(); + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .provider(jwtBearerAuthorizedClientProvider) + .build(); + + DefaultOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { + val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider() + val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .provider(jwtBearerAuthorizedClientProvider) + .build() + val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== + +You may obtain the `OAuth2AccessToken` as follows: + +==== +.Java +[source,java,role="primary"] +---- +@RestController +public class OAuth2ResourceServerController { + + @Autowired + private OAuth2AuthorizedClientManager authorizedClientManager; + + @GetMapping("/resource") + public String resource(JwtAuthenticationToken jwtAuthentication) { + OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(jwtAuthentication) + .build(); + OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); + OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); + + ... + + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +class OAuth2ResourceServerController { + + @Autowired + private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager + + @GetMapping("/resource") + fun resource(jwtAuthentication: JwtAuthenticationToken?): String { + val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(jwtAuthentication) + .build() + val authorizedClient = authorizedClientManager.authorize(authorizeRequest) + val accessToken: OAuth2AccessToken = authorizedClient.accessToken + + ... + + } +} +---- +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/client/authorized-clients.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/authorized-clients.adoc new file mode 100644 index 00000000000..1af0422a286 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/authorized-clients.adoc @@ -0,0 +1,271 @@ +[[oauth2Client-additional-features]] += Authorized Client Features + +This section covers additional features provided by Spring Security for the OAuth2 client. + + +[[oauth2Client-registered-authorized-client]] +== Resolving an Authorized Client + +The `@RegisteredOAuth2AuthorizedClient` annotation provides the ability to resolve a method parameter to an argument value of type `OAuth2AuthorizedClient`. +This is a convenient alternative compared to accessing the `OAuth2AuthorizedClient` by using the `OAuth2AuthorizedClientManager` or `OAuth2AuthorizedClientService`. +The following example shows how to use `@RegisteredOAuth2AuthorizedClient`: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @GetMapping("/") + public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { + OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); + + ... + + return "index"; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + @GetMapping("/") + fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String { + val accessToken = authorizedClient.accessToken + + ... + + return "index" + } +} +---- +==== + +The `@RegisteredOAuth2AuthorizedClient` annotation is handled by `OAuth2AuthorizedClientArgumentResolver`, which directly uses an xref:servlet/oauth2/client/core.adoc#oauth2Client-authorized-manager-provider[`OAuth2AuthorizedClientManager`] and, therefore, inherits its capabilities. + + +[[oauth2Client-webclient-servlet]] +== WebClient Integration for Servlet Environments + +The OAuth 2.0 Client support integrates with `WebClient` by using an `ExchangeFilterFunction`. + +The `ServletOAuth2AuthorizedClientExchangeFilterFunction` provides a mechanism for requesting protected resources by using an `OAuth2AuthorizedClient` and including the associated `OAuth2AccessToken` as a Bearer Token. +It directly uses an xref:servlet/oauth2/client/core.adoc#oauth2Client-authorized-manager-provider[`OAuth2AuthorizedClientManager`] and, therefore, inherits the following capabilities: + +* An `OAuth2AccessToken` is requested if the client has not yet been authorized. +** `authorization_code`: Triggers the Authorization Request redirect to initiate the flow. +** `client_credentials`: The access token is obtained directly from the Token Endpoint. +** `password`: The access token is obtained directly from the Token Endpoint. +* If the `OAuth2AccessToken` is expired, it is refreshed (or renewed) if an `OAuth2AuthorizedClientProvider` is available to perform the authorization + +The following code shows an example of how to configure `WebClient` with OAuth 2.0 Client support: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { + ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { + val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build() +} +---- +==== + +=== Providing the Authorized Client + +The `ServletOAuth2AuthorizedClientExchangeFilterFunction` determines the client to use (for a request) by resolving the `OAuth2AuthorizedClient` from the `ClientRequest.attributes()` (request attributes). + +The following code shows how to set an `OAuth2AuthorizedClient` as a request attribute: + +==== +.Java +[source,java,role="primary"] +---- +@GetMapping("/") +public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { + String resourceUri = ... + + String body = webClient + .get() + .uri(resourceUri) + .attributes(oauth2AuthorizedClient(authorizedClient)) <1> + .retrieve() + .bodyToMono(String.class) + .block(); + + ... + + return "index"; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@GetMapping("/") +fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String { + val resourceUri: String = ... + val body: String = webClient + .get() + .uri(resourceUri) + .attributes(oauth2AuthorizedClient(authorizedClient)) <1> + .retrieve() + .bodyToMono() + .block() + + ... + + return "index" +} +---- +<1> `oauth2AuthorizedClient()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. +==== + +The following code shows how to set the `ClientRegistration.getRegistrationId()` as a request attribute: + +==== +.Java +[source,java,role="primary"] +---- +@GetMapping("/") +public String index() { + String resourceUri = ... + + String body = webClient + .get() + .uri(resourceUri) + .attributes(clientRegistrationId("okta")) <1> + .retrieve() + .bodyToMono(String.class) + .block(); + + ... + + return "index"; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@GetMapping("/") +fun index(): String { + val resourceUri: String = ... + + val body: String = webClient + .get() + .uri(resourceUri) + .attributes(clientRegistrationId("okta")) <1> + .retrieve() + .bodyToMono() + .block() + + ... + + return "index" +} +---- +<1> `clientRegistrationId()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. +==== + + +=== Defaulting the Authorized Client + +If neither `OAuth2AuthorizedClient` or `ClientRegistration.getRegistrationId()` is provided as a request attribute, the `ServletOAuth2AuthorizedClientExchangeFilterFunction` can determine the _default_ client to use, depending on its configuration. + +If `setDefaultOAuth2AuthorizedClient(true)` is configured and the user has authenticated by using `HttpSecurity.oauth2Login()`, the `OAuth2AccessToken` associated with the current `OAuth2AuthenticationToken` is used. + +The following code shows the specific configuration: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { + ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + oauth2Client.setDefaultOAuth2AuthorizedClient(true); + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { + val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + oauth2Client.setDefaultOAuth2AuthorizedClient(true) + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build() +} +---- +==== + +[WARNING] +==== +Be cautious with this feature, since all HTTP requests receive the access token. +==== + +Alternatively, if `setDefaultClientRegistrationId("okta")` is configured with a valid `ClientRegistration`, the `OAuth2AccessToken` associated with the `OAuth2AuthorizedClient` is used. + +The following code shows the specific configuration: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { + ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + oauth2Client.setDefaultClientRegistrationId("okta"); + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { + val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + oauth2Client.setDefaultClientRegistrationId("okta") + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build() +} +---- +==== + +[WARNING] +==== +Be cautious with this feature, since all HTTP requests receive the access token. +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/client/client-authentication.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/client-authentication.adoc new file mode 100644 index 00000000000..630c72b18c0 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/client-authentication.adoc @@ -0,0 +1,165 @@ +[[oauth2Client-client-auth-support]] += Client Authentication Support + + +[[oauth2Client-jwt-bearer-auth]] +== JWT Bearer + +[NOTE] +Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] Client Authentication. + +The default implementation for JWT Bearer Client Authentication is `NimbusJwtClientAuthenticationParametersConverter`, +which is a `Converter` that customizes the Token Request parameters by adding +a signed JSON Web Token (JWS) in the `client_assertion` parameter. + +The `java.security.PrivateKey` or `javax.crypto.SecretKey` used for signing the JWS +is supplied by the `com.nimbusds.jose.jwk.JWK` resolver associated with `NimbusJwtClientAuthenticationParametersConverter`. + + +=== Authenticate using `private_key_jwt` + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-authentication-method: private_key_jwt + authorization-grant-type: authorization_code + ... +---- + +The following example shows how to configure `DefaultAuthorizationCodeTokenResponseClient`: + +==== +.Java +[source,java,role="primary"] +---- +Function jwkResolver = (clientRegistration) -> { + if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { + // Assuming RSA key type + RSAPublicKey publicKey = ... + RSAPrivateKey privateKey = ... + return new RSAKey.Builder(publicKey) + .privateKey(privateKey) + .keyID(UUID.randomUUID().toString()) + .build(); + } + return null; +}; + +OAuth2AuthorizationCodeGrantRequestEntityConverter requestEntityConverter = + new OAuth2AuthorizationCodeGrantRequestEntityConverter(); +requestEntityConverter.addParametersConverter( + new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); + +DefaultAuthorizationCodeTokenResponseClient tokenResponseClient = + new DefaultAuthorizationCodeTokenResponseClient(); +tokenResponseClient.setRequestEntityConverter(requestEntityConverter); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val jwkResolver: Function = + Function { clientRegistration -> + if (clientRegistration.clientAuthenticationMethod.equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { + // Assuming RSA key type + var publicKey: RSAPublicKey + var privateKey: RSAPrivateKey + RSAKey.Builder(publicKey) = //... + .privateKey(privateKey) = //... + .keyID(UUID.randomUUID().toString()) + .build() + } + null + } + +val requestEntityConverter = OAuth2AuthorizationCodeGrantRequestEntityConverter() +requestEntityConverter.addParametersConverter( + NimbusJwtClientAuthenticationParametersConverter(jwkResolver) +) + +val tokenResponseClient = DefaultAuthorizationCodeTokenResponseClient() +tokenResponseClient.setRequestEntityConverter(requestEntityConverter) +---- +==== + + +=== Authenticate using `client_secret_jwt` + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + client-authentication-method: client_secret_jwt + authorization-grant-type: client_credentials + ... +---- + +The following example shows how to configure `DefaultClientCredentialsTokenResponseClient`: + +==== +.Java +[source,java,role="primary"] +---- +Function jwkResolver = (clientRegistration) -> { + if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_JWT)) { + SecretKeySpec secretKey = new SecretKeySpec( + clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), + "HmacSHA256"); + return new OctetSequenceKey.Builder(secretKey) + .keyID(UUID.randomUUID().toString()) + .build(); + } + return null; +}; + +OAuth2ClientCredentialsGrantRequestEntityConverter requestEntityConverter = + new OAuth2ClientCredentialsGrantRequestEntityConverter(); +requestEntityConverter.addParametersConverter( + new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); + +DefaultClientCredentialsTokenResponseClient tokenResponseClient = + new DefaultClientCredentialsTokenResponseClient(); +tokenResponseClient.setRequestEntityConverter(requestEntityConverter); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val jwkResolver = Function { clientRegistration: ClientRegistration -> + if (clientRegistration.clientAuthenticationMethod == ClientAuthenticationMethod.CLIENT_SECRET_JWT) { + val secretKey = SecretKeySpec( + clientRegistration.clientSecret.toByteArray(StandardCharsets.UTF_8), + "HmacSHA256" + ) + OctetSequenceKey.Builder(secretKey) + .keyID(UUID.randomUUID().toString()) + .build() + } + null +} + +val requestEntityConverter = OAuth2ClientCredentialsGrantRequestEntityConverter() +requestEntityConverter.addParametersConverter( + NimbusJwtClientAuthenticationParametersConverter(jwkResolver) +) + +val tokenResponseClient = DefaultClientCredentialsTokenResponseClient() +tokenResponseClient.setRequestEntityConverter(requestEntityConverter) +---- +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/client/core.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/core.adoc new file mode 100644 index 00000000000..df80c5ab03f --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/core.adoc @@ -0,0 +1,451 @@ +[[oauth2Client-core-interface-class]] += Core Interfaces and Classes + +This section describes the OAuth2 core interfaces and classes that Spring Security offers. + +[[oauth2Client-client-registration]] +== ClientRegistration + +`ClientRegistration` is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. + +A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details. +A `ClientRegistration` object holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details. + +`ClientRegistration` and its properties are defined as follows: + +==== +[source,java] +---- +public final class ClientRegistration { + private String registrationId; <1> + private String clientId; <2> + private String clientSecret; <3> + private ClientAuthenticationMethod clientAuthenticationMethod; <4> + private AuthorizationGrantType authorizationGrantType; <5> + private String redirectUri; <6> + private Set scopes; <7> + private ProviderDetails providerDetails; + private String clientName; <8> + + public class ProviderDetails { + private String authorizationUri; <9> + private String tokenUri; <10> + private UserInfoEndpoint userInfoEndpoint; + private String jwkSetUri; <11> + private String issuerUri; <12> + private Map configurationMetadata; <13> + + public class UserInfoEndpoint { + private String uri; <14> + private AuthenticationMethod authenticationMethod; <15> + private String userNameAttributeName; <16> + + } + } +} +---- +<1> `registrationId`: The ID that uniquely identifies the `ClientRegistration`. +<2> `clientId`: The client identifier. +<3> `clientSecret`: The client secret. +<4> `clientAuthenticationMethod`: The method used to authenticate the Client with the Provider. +The supported values are *client_secret_basic*, *client_secret_post*, *private_key_jwt*, *client_secret_jwt* and *none* https://tools.ietf.org/html/rfc6749#section-2.1[(public clients)]. +<5> `authorizationGrantType`: The OAuth 2.0 Authorization Framework defines four https://tools.ietf.org/html/rfc6749#section-1.3[Authorization Grant] types. + The supported values are `authorization_code`, `client_credentials`, `password`, as well as, extension grant type `urn:ietf:params:oauth:grant-type:jwt-bearer`. +<6> `redirectUri`: The client's registered redirect URI that the _Authorization Server_ redirects the end-user's user-agent + to after the end-user has authenticated and authorized access to the client. +<7> `scopes`: The scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile. +<8> `clientName`: A descriptive name used for the client. +The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page. +<9> `authorizationUri`: The Authorization Endpoint URI for the Authorization Server. +<10> `tokenUri`: The Token Endpoint URI for the Authorization Server. +<11> `jwkSetUri`: The URI used to retrieve the https://tools.ietf.org/html/rfc7517[JSON Web Key (JWK)] Set from the Authorization Server, +which contains the cryptographic key(s) used to verify the https://tools.ietf.org/html/rfc7515[JSON Web Signature (JWS)] of the ID Token and (optionally) the UserInfo Response. +<12> `issuerUri`: Returns the issuer identifier URI for the OpenID Connect 1.0 provider or the OAuth 2.0 Authorization Server. +<13> `configurationMetadata`: The https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[OpenID Provider Configuration Information]. +This information is available only if the Spring Boot 2.x property `spring.security.oauth2.client.provider.[providerId].issuerUri` is configured. +<14> `(userInfoEndpoint)uri`: The UserInfo Endpoint URI used to access the claims and attributes of the authenticated end-user. +<15> `(userInfoEndpoint)authenticationMethod`: The authentication method used when sending the access token to the UserInfo Endpoint. +The supported values are *header*, *form*, and *query*. +<16> `userNameAttributeName`: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user. +==== + +You can initially configure a `ClientRegistration` by using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint]. + +`ClientRegistrations` provides convenience methods for configuring a `ClientRegistration` in this way, as follows: + +==== +.Java +[source,java,role="primary"] +---- +ClientRegistration clientRegistration = + ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build(); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build() +---- +==== + +The preceding code queries, in series, `https://idp.example.com/issuer/.well-known/openid-configuration`, `https://idp.example.com/.well-known/openid-configuration/issuer`, and `https://idp.example.com/.well-known/oauth-authorization-server/issuer`, stopping at the first to return a 200 response. + +As an alternative, you can use `ClientRegistrations.fromOidcIssuerLocation()` to query only the OpenID Connect Provider's Configuration endpoint. + +[[oauth2Client-client-registration-repo]] +== ClientRegistrationRepository + +The `ClientRegistrationRepository` serves as a repository for OAuth 2.0 / OpenID Connect 1.0 `ClientRegistration`(s). + +[NOTE] +==== +Client registration information is ultimately stored and owned by the associated Authorization Server. +This repository provides the ability to retrieve a subset of the primary client registration information, which is stored with the Authorization Server. +==== + +Spring Boot 2.x auto-configuration binds each of the properties under `spring.security.oauth2.client.registration._[registrationId]_` to an instance of `ClientRegistration` and then composes each of the `ClientRegistration` instance(s) within a `ClientRegistrationRepository`. + +[NOTE] +==== +The default implementation of `ClientRegistrationRepository` is `InMemoryClientRegistrationRepository`. +==== + +The auto-configuration also registers the `ClientRegistrationRepository` as a `@Bean` in the `ApplicationContext` so that it is available for dependency injection, if needed by the application. + +The following listing shows an example: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @Autowired + private ClientRegistrationRepository clientRegistrationRepository; + + @GetMapping("/") + public String index() { + ClientRegistration oktaRegistration = + this.clientRegistrationRepository.findByRegistrationId("okta"); + + ... + + return "index"; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + + @Autowired + private lateinit var clientRegistrationRepository: ClientRegistrationRepository + + @GetMapping("/") + fun index(): String { + val oktaRegistration = + this.clientRegistrationRepository.findByRegistrationId("okta") + + //... + + return "index"; + } +} +---- +==== + +[[oauth2Client-authorized-client]] +== OAuth2AuthorizedClient + +`OAuth2AuthorizedClient` is a representation of an Authorized Client. +A client is considered to be authorized when the end-user (the Resource Owner) has granted authorization to the client to access its protected resources. + +`OAuth2AuthorizedClient` serves the purpose of associating an `OAuth2AccessToken` (and optional `OAuth2RefreshToken`) to a `ClientRegistration` (client) and resource owner, who is the `Principal` end-user that granted the authorization. + + +[[oauth2Client-authorized-repo-service]] +== OAuth2AuthorizedClientRepository and OAuth2AuthorizedClientService + +`OAuth2AuthorizedClientRepository` is responsible for persisting `OAuth2AuthorizedClient`(s) between web requests, whereas the primary role of `OAuth2AuthorizedClientService` is to manage `OAuth2AuthorizedClient`(s) at the application-level. + +From a developer perspective, the `OAuth2AuthorizedClientRepository` or `OAuth2AuthorizedClientService` provides the ability to look up an `OAuth2AccessToken` associated with a client so that it can be used to initiate a protected resource request. + +The following listing shows an example: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @Autowired + private OAuth2AuthorizedClientService authorizedClientService; + + @GetMapping("/") + public String index(Authentication authentication) { + OAuth2AuthorizedClient authorizedClient = + this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()); + + OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); + + ... + + return "index"; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + + @Autowired + private lateinit var authorizedClientService: OAuth2AuthorizedClientService + + @GetMapping("/") + fun index(authentication: Authentication): String { + val authorizedClient: OAuth2AuthorizedClient = + this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()); + val accessToken = authorizedClient.accessToken + + ... + + return "index"; + } +} +---- +==== + +[NOTE] +==== +Spring Boot 2.x auto-configuration registers an `OAuth2AuthorizedClientRepository` or an `OAuth2AuthorizedClientService` `@Bean` in the `ApplicationContext`. +However, the application can override and register a custom `OAuth2AuthorizedClientRepository` or `OAuth2AuthorizedClientService` `@Bean`. +==== + +The default implementation of `OAuth2AuthorizedClientService` is `InMemoryOAuth2AuthorizedClientService`, which stores `OAuth2AuthorizedClient` objects in-memory. + +Alternatively, you can configure the JDBC implementation `JdbcOAuth2AuthorizedClientService` to persist `OAuth2AuthorizedClient` instances in a database. + +[NOTE] +==== +`JdbcOAuth2AuthorizedClientService` depends on the table definition described in xref:servlet/appendix/database-schema.adoc#dbschema-oauth2-client[ OAuth 2.0 Client Schema]. +==== + + +[[oauth2Client-authorized-manager-provider]] +== OAuth2AuthorizedClientManager and OAuth2AuthorizedClientProvider + +The `OAuth2AuthorizedClientManager` is responsible for the overall management of `OAuth2AuthorizedClient`(s). + +The primary responsibilities include: + +* Authorizing (or re-authorizing) an OAuth 2.0 Client, by using an `OAuth2AuthorizedClientProvider`. +* Delegating the persistence of an `OAuth2AuthorizedClient`, typically by using an `OAuth2AuthorizedClientService` or `OAuth2AuthorizedClientRepository`. +* Delegating to an `OAuth2AuthorizationSuccessHandler` when an OAuth 2.0 Client has been successfully authorized (or re-authorized). +* Delegating to an `OAuth2AuthorizationFailureHandler` when an OAuth 2.0 Client fails to authorize (or re-authorize). + +An `OAuth2AuthorizedClientProvider` implements a strategy for authorizing (or re-authorizing) an OAuth 2.0 Client. +Implementations typically implement an authorization grant type, such as `authorization_code`, `client_credentials`, and others. + +The default implementation of `OAuth2AuthorizedClientManager` is `DefaultOAuth2AuthorizedClientManager`, which is associated with an `OAuth2AuthorizedClientProvider` that may support multiple authorization grant types using a delegation-based composite. +You can use `OAuth2AuthorizedClientProviderBuilder` to configure and build the delegation-based composite. + +The following code shows an example of how to configure and build an `OAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials`, and `password` authorization grant types: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientRepository authorizedClientRepository) { + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build(); + + DefaultOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { + val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build() + val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== + +When an authorization attempt succeeds, the `DefaultOAuth2AuthorizedClientManager` delegates to the `OAuth2AuthorizationSuccessHandler`, which (by default) saves the `OAuth2AuthorizedClient` through the `OAuth2AuthorizedClientRepository`. +In the case of a re-authorization failure (for example, a refresh token is no longer valid), the previously saved `OAuth2AuthorizedClient` is removed from the `OAuth2AuthorizedClientRepository` through the `RemoveAuthorizedClientOAuth2AuthorizationFailureHandler`. +You can customize the default behavior through `setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)` and `setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)`. + +The `DefaultOAuth2AuthorizedClientManager` is also associated with a `contextAttributesMapper` of type `Function>`, which is responsible for mapping attribute(s) from the `OAuth2AuthorizeRequest` to a `Map` of attributes to be associated to the `OAuth2AuthorizationContext`. +This can be useful when you need to supply an `OAuth2AuthorizedClientProvider` with required (supported) attribute(s), eg. the `PasswordOAuth2AuthorizedClientProvider` requires the resource owner's `username` and `password` to be available in `OAuth2AuthorizationContext.getAttributes()`. + +The following code shows an example of the `contextAttributesMapper`: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientRepository authorizedClientRepository) { + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build(); + + DefaultOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters, + // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()); + + return authorizedClientManager; +} + +private Function> contextAttributesMapper() { + return authorizeRequest -> { + Map contextAttributes = Collections.emptyMap(); + HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName()); + String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME); + String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD); + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = new HashMap<>(); + + // `PasswordOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username); + contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password); + } + return contextAttributes; + }; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { + val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build() + val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + + // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters, + // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()) + return authorizedClientManager +} + +private fun contextAttributesMapper(): Function> { + return Function { authorizeRequest -> + var contextAttributes: MutableMap = mutableMapOf() + val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name) + val username: String = servletRequest.getParameter(OAuth2ParameterNames.USERNAME) + val password: String = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD) + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = hashMapOf() + + // `PasswordOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username + contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password + } + contextAttributes + } +} +---- +==== + +The `DefaultOAuth2AuthorizedClientManager` is designed to be used _within_ the context of a `HttpServletRequest`. +When operating _outside_ of a `HttpServletRequest` context, use `AuthorizedClientServiceOAuth2AuthorizedClientManager` instead. + +A service application is a common use case for when to use an `AuthorizedClientServiceOAuth2AuthorizedClientManager`. +Service applications often run in the background, without any user interaction, and typically run under a system-level account instead of a user account. +An OAuth 2.0 Client configured with the `client_credentials` grant type can be considered a type of service application. + +The following code shows an example of how to configure an `AuthorizedClientServiceOAuth2AuthorizedClientManager` that provides support for the `client_credentials` grant type: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientService authorizedClientService) { + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build(); + + AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = + new AuthorizedClientServiceOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientService); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientService: OAuth2AuthorizedClientService): OAuth2AuthorizedClientManager { + val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build() + val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientService) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/client/index.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/index.adoc new file mode 100644 index 00000000000..c00067fcba7 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/index.adoc @@ -0,0 +1,146 @@ +[[oauth2client]] += OAuth 2.0 Client +:page-section-summary-toc: 1 + +The OAuth 2.0 Client features provide support for the Client role as defined in the https://tools.ietf.org/html/rfc6749#section-1.1[OAuth 2.0 Authorization Framework]. + +At a high-level, the core features available are: + +.Authorization Grant support +* https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] +* https://tools.ietf.org/html/rfc6749#section-6[Refresh Token] +* https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] +* https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] +* https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[JWT Bearer] + +.Client Authentication support +* https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] + +.HTTP Client support +* xref:servlet/oauth2/client/authorized-clients.adoc#oauth2Client-webclient-servlet[`WebClient` integration for Servlet Environments] (for requesting protected resources) + +The `HttpSecurity.oauth2Client()` DSL provides a number of configuration options for customizing the core components used by OAuth 2.0 Client. +In addition, `HttpSecurity.oauth2Client().authorizationCodeGrant()` enables the customization of the Authorization Code grant. + +The following code shows the complete configuration options provided by the `HttpSecurity.oauth2Client()` DSL: + +.OAuth2 Client Configuration Options +==== +.Java +[source,java,role="primary"] +---- +@EnableWebSecurity +public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .oauth2Client(oauth2 -> oauth2 + .clientRegistrationRepository(this.clientRegistrationRepository()) + .authorizedClientRepository(this.authorizedClientRepository()) + .authorizedClientService(this.authorizedClientService()) + .authorizationCodeGrant(codeGrant -> codeGrant + .authorizationRequestRepository(this.authorizationRequestRepository()) + .authorizationRequestResolver(this.authorizationRequestResolver()) + .accessTokenResponseClient(this.accessTokenResponseClient()) + ) + ); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebSecurity +class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + oauth2Client { + clientRegistrationRepository = clientRegistrationRepository() + authorizedClientRepository = authorizedClientRepository() + authorizedClientService = authorizedClientService() + authorizationCodeGrant { + authorizationRequestRepository = authorizationRequestRepository() + authorizationRequestResolver = authorizationRequestResolver() + accessTokenResponseClient = accessTokenResponseClient() + } + } + } + } +} +---- +==== + +In addition to the `HttpSecurity.oauth2Client()` DSL, XML configuration is also supported. + +The following code shows the complete configuration options available in the xref:servlet/appendix/namespace/http.adoc#nsa-oauth2-client[ security namespace]: + +.OAuth2 Client XML Configuration Options +==== +[source,xml] +---- + + + + + +---- +==== + +The `OAuth2AuthorizedClientManager` is responsible for managing the authorization (or re-authorization) of an OAuth 2.0 Client, in collaboration with one or more `OAuth2AuthorizedClientProvider`(s). + +The following code shows an example of how to register an `OAuth2AuthorizedClientManager` `@Bean` and associate it with an `OAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials`, and `password` authorization grant types: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientRepository authorizedClientRepository) { + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build(); + + DefaultOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { + val authorizedClientProvider: OAuth2AuthorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build() + val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-login.adoc b/docs/modules/ROOT/pages/servlet/oauth2/login/advanced.adoc similarity index 50% rename from docs/modules/ROOT/pages/servlet/oauth2/oauth2-login.adoc rename to docs/modules/ROOT/pages/servlet/oauth2/login/advanced.adoc index db5ee9c5065..65e72a164dc 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-login.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/login/advanced.adoc @@ -1,581 +1,5 @@ -[[oauth2login]] -= OAuth 2.0 Login - -The OAuth 2.0 Login feature provides an application with the capability to have users log in to the application by using their existing account at an OAuth 2.0 Provider (e.g. GitHub) or OpenID Connect 1.0 Provider (such as Google). -OAuth 2.0 Login implements the use cases: "Login with Google" or "Login with GitHub". - -NOTE: OAuth 2.0 Login is implemented by using the *Authorization Code Grant*, as specified in the https://tools.ietf.org/html/rfc6749#section-4.1[OAuth 2.0 Authorization Framework] and https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth[OpenID Connect Core 1.0]. - - -[[oauth2login-sample-boot]] -== Spring Boot 2.x Sample - -Spring Boot 2.x brings full auto-configuration capabilities for OAuth 2.0 Login. - -This section shows how to configure the {gh-samples-url}/servlet/spring-boot/java/oauth2/login[*OAuth 2.0 Login sample*] using _Google_ as the _Authentication Provider_ and covers the following topics: - -* <> -* <> -* <> -* <> - - -[[oauth2login-sample-initial-setup]] -=== Initial setup - -To use Google's OAuth 2.0 authentication system for login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials. - -NOTE: https://developers.google.com/identity/protocols/OpenIDConnect[Google's OAuth 2.0 implementation] for authentication conforms to the https://openid.net/connect/[OpenID Connect 1.0] specification and is https://openid.net/certification/[OpenID Certified]. - -Follow the instructions on the https://developers.google.com/identity/protocols/OpenIDConnect[OpenID Connect] page, starting in the section, "Setting up OAuth 2.0". - -After completing the "Obtain OAuth 2.0 credentials" instructions, you should have a new OAuth Client with credentials consisting of a Client ID and a Client Secret. - - -[[oauth2login-sample-redirect-uri]] -=== Setting the redirect URI - -The redirect URI is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with Google and have granted access to the OAuth Client _(<>)_ on the Consent page. - -In the "Set a redirect URI" sub-section, ensure that the *Authorized redirect URIs* field is set to `http://localhost:8080/login/oauth2/code/google`. - -TIP: The default redirect URI template is `+{baseUrl}/login/oauth2/code/{registrationId}+`. -The *_registrationId_* is a unique identifier for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration]. - -IMPORTANT: If the OAuth Client is running behind a proxy server, it is recommended to check xref:features/exploits/http.adoc#http-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured. -Also, see the supported xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. - - -[[oauth2login-sample-application-config]] -=== Configure application.yml - -Now that you have a new OAuth Client with Google, you need to configure the application to use the OAuth Client for the _authentication flow_. -To do so: - -. Go to `application.yml` and set the following configuration: -+ -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: <1> - google: <2> - client-id: google-client-id - client-secret: google-client-secret ----- -+ -.OAuth Client properties -==== -<1> `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties. -<2> Following the base property prefix is the ID for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration], such as google. -==== - -. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. - - -[[oauth2login-sample-boot-application]] -=== Boot up the application - -Launch the Spring Boot 2.x sample and go to `http://localhost:8080`. -You are then redirected to the default _auto-generated_ login page, which displays a link for Google. - -Click on the Google link, and you are then redirected to Google for authentication. - -After authenticating with your Google account credentials, the next page presented to you is the Consent screen. -The Consent screen asks you to either allow or deny access to the OAuth Client you created earlier. -Click *Allow* to authorize the OAuth Client to access your email address and basic profile information. - -At this point, the OAuth Client retrieves your email address and basic profile information from the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session. - - -[[oauth2login-boot-property-mappings]] -== Spring Boot 2.x Property Mappings - -The following table outlines the mapping of the Spring Boot 2.x OAuth Client properties to the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration] properties. - -|=== -|Spring Boot 2.x |ClientRegistration - -|`spring.security.oauth2.client.registration._[registrationId]_` -|`registrationId` - -|`spring.security.oauth2.client.registration._[registrationId]_.client-id` -|`clientId` - -|`spring.security.oauth2.client.registration._[registrationId]_.client-secret` -|`clientSecret` - -|`spring.security.oauth2.client.registration._[registrationId]_.client-authentication-method` -|`clientAuthenticationMethod` - -|`spring.security.oauth2.client.registration._[registrationId]_.authorization-grant-type` -|`authorizationGrantType` - -|`spring.security.oauth2.client.registration._[registrationId]_.redirect-uri` -|`redirectUri` - -|`spring.security.oauth2.client.registration._[registrationId]_.scope` -|`scopes` - -|`spring.security.oauth2.client.registration._[registrationId]_.client-name` -|`clientName` - -|`spring.security.oauth2.client.provider._[providerId]_.authorization-uri` -|`providerDetails.authorizationUri` - -|`spring.security.oauth2.client.provider._[providerId]_.token-uri` -|`providerDetails.tokenUri` - -|`spring.security.oauth2.client.provider._[providerId]_.jwk-set-uri` -|`providerDetails.jwkSetUri` - -|`spring.security.oauth2.client.provider._[providerId]_.issuer-uri` -|`providerDetails.issuerUri` - -|`spring.security.oauth2.client.provider._[providerId]_.user-info-uri` -|`providerDetails.userInfoEndpoint.uri` - -|`spring.security.oauth2.client.provider._[providerId]_.user-info-authentication-method` -|`providerDetails.userInfoEndpoint.authenticationMethod` - -|`spring.security.oauth2.client.provider._[providerId]_.user-name-attribute` -|`providerDetails.userInfoEndpoint.userNameAttributeName` -|=== - -[TIP] -A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint], by specifying the `spring.security.oauth2.client.provider._[providerId]_.issuer-uri` property. - - -[[oauth2login-common-oauth2-provider]] -== CommonOAuth2Provider - -`CommonOAuth2Provider` pre-defines a set of default client properties for a number of well known providers: Google, GitHub, Facebook, and Okta. - -For example, the `authorization-uri`, `token-uri`, and `user-info-uri` do not change often for a Provider. -Therefore, it makes sense to provide default values in order to reduce the required configuration. - -As demonstrated previously, when we <>, only the `client-id` and `client-secret` properties are required. - -The following listing shows an example: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - google: - client-id: google-client-id - client-secret: google-client-secret ----- - -[TIP] -The auto-defaulting of client properties works seamlessly here because the `registrationId` (`google`) matches the `GOOGLE` `enum` (case-insensitive) in `CommonOAuth2Provider`. - -For cases where you may want to specify a different `registrationId`, such as `google-login`, you can still leverage auto-defaulting of client properties by configuring the `provider` property. - -The following listing shows an example: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - google-login: <1> - provider: google <2> - client-id: google-client-id - client-secret: google-client-secret ----- -<1> The `registrationId` is set to `google-login`. -<2> The `provider` property is set to `google`, which will leverage the auto-defaulting of client properties set in `CommonOAuth2Provider.GOOGLE.getBuilder()`. - - -[[oauth2login-custom-provider-properties]] -== Configuring Custom Provider Properties - -There are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain). - -For example, an OAuth Client registered with Okta is assigned to a specific sub-domain and have their own protocol endpoints. - -For these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: `spring.security.oauth2.client.provider._[providerId]_`. - -The following listing shows an example: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-secret: okta-client-secret - provider: - okta: <1> - authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize - token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token - user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo - user-name-attribute: sub - jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys ----- - -<1> The base property (`spring.security.oauth2.client.provider.okta`) allows for custom configuration of protocol endpoint locations. - - -[[oauth2login-override-boot-autoconfig]] -== Overriding Spring Boot 2.x Auto-configuration - -The Spring Boot 2.x auto-configuration class for OAuth Client support is `OAuth2ClientAutoConfiguration`. - -It performs the following tasks: - -* Registers a `ClientRegistrationRepository` `@Bean` composed of `ClientRegistration`(s) from the configured OAuth Client properties. -* Provides a `WebSecurityConfigurerAdapter` `@Configuration` and enables OAuth 2.0 Login through `httpSecurity.oauth2Login()`. - -If you need to override the auto-configuration based on your specific requirements, you may do so in the following ways: - -* <> -* <> -* <> - - -[[oauth2login-register-clientregistrationrepository-bean]] -=== Register a ClientRegistrationRepository @Bean - -The following example shows how to register a `ClientRegistrationRepository` `@Bean`: - -==== -.Java -[source,java,role="primary",attrs="-attributes"] ----- -@Configuration -public class OAuth2LoginConfig { - - @Bean - public ClientRegistrationRepository clientRegistrationRepository() { - return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); - } - - private ClientRegistration googleClientRegistration() { - return ClientRegistration.withRegistrationId("google") - .clientId("google-client-id") - .clientSecret("google-client-secret") - .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") - .scope("openid", "profile", "email", "address", "phone") - .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") - .tokenUri("https://www.googleapis.com/oauth2/v4/token") - .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") - .userNameAttributeName(IdTokenClaimNames.SUB) - .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") - .clientName("Google") - .build(); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary",attrs="-attributes"] ----- -@Configuration -class OAuth2LoginConfig { - @Bean - fun clientRegistrationRepository(): ClientRegistrationRepository { - return InMemoryClientRegistrationRepository(googleClientRegistration()) - } - - private fun googleClientRegistration(): ClientRegistration { - return ClientRegistration.withRegistrationId("google") - .clientId("google-client-id") - .clientSecret("google-client-secret") - .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") - .scope("openid", "profile", "email", "address", "phone") - .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") - .tokenUri("https://www.googleapis.com/oauth2/v4/token") - .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") - .userNameAttributeName(IdTokenClaimNames.SUB) - .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") - .clientName("Google") - .build() - } -} ----- -==== - - -[[oauth2login-provide-websecurityconfigureradapter]] -=== Provide a WebSecurityConfigurerAdapter - -The following example shows how to provide a `WebSecurityConfigurerAdapter` with `@EnableWebSecurity` and enable OAuth 2.0 login through `httpSecurity.oauth2Login()`: - -.OAuth2 Login Configuration -==== -.Java -[source,java,role="primary"] ----- -@EnableWebSecurity -public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests(authorize -> authorize - .anyRequest().authenticated() - ) - .oauth2Login(withDefaults()); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@EnableWebSecurity -class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { - - override fun configure(http: HttpSecurity) { - http { - authorizeRequests { - authorize(anyRequest, authenticated) - } - oauth2Login { } - } - } -} ----- -==== - - -[[oauth2login-completely-override-autoconfiguration]] -=== Completely Override the Auto-configuration - -The following example shows how to completely override the auto-configuration by registering a `ClientRegistrationRepository` `@Bean` and providing a `WebSecurityConfigurerAdapter`. - -.Overriding the auto-configuration -==== -.Java -[source,java,role="primary",attrs="-attributes"] ----- -@Configuration -public class OAuth2LoginConfig { - - @EnableWebSecurity - public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests(authorize -> authorize - .anyRequest().authenticated() - ) - .oauth2Login(withDefaults()); - } - } - - @Bean - public ClientRegistrationRepository clientRegistrationRepository() { - return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); - } - - private ClientRegistration googleClientRegistration() { - return ClientRegistration.withRegistrationId("google") - .clientId("google-client-id") - .clientSecret("google-client-secret") - .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") - .scope("openid", "profile", "email", "address", "phone") - .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") - .tokenUri("https://www.googleapis.com/oauth2/v4/token") - .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") - .userNameAttributeName(IdTokenClaimNames.SUB) - .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") - .clientName("Google") - .build(); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary",attrs="-attributes"] ----- -@Configuration -class OAuth2LoginConfig { - - @EnableWebSecurity - class OAuth2LoginSecurityConfig: WebSecurityConfigurerAdapter() { - - override fun configure(http: HttpSecurity) { - http { - authorizeRequests { - authorize(anyRequest, authenticated) - } - oauth2Login { } - } - } - } - - @Bean - fun clientRegistrationRepository(): ClientRegistrationRepository { - return InMemoryClientRegistrationRepository(googleClientRegistration()) - } - - private fun googleClientRegistration(): ClientRegistration { - return ClientRegistration.withRegistrationId("google") - .clientId("google-client-id") - .clientSecret("google-client-secret") - .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") - .scope("openid", "profile", "email", "address", "phone") - .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") - .tokenUri("https://www.googleapis.com/oauth2/v4/token") - .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") - .userNameAttributeName(IdTokenClaimNames.SUB) - .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") - .clientName("Google") - .build() - } -} ----- -==== - - -[[oauth2login-javaconfig-wo-boot]] -== Java Configuration without Spring Boot 2.x - -If you are not able to use Spring Boot 2.x and would like to configure one of the pre-defined providers in `CommonOAuth2Provider` (for example, Google), apply the following configuration: - -.OAuth2 Login Configuration -==== -.Java -[source,java,role="primary"] ----- -@Configuration -public class OAuth2LoginConfig { - - @EnableWebSecurity - public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests(authorize -> authorize - .anyRequest().authenticated() - ) - .oauth2Login(withDefaults()); - } - } - - @Bean - public ClientRegistrationRepository clientRegistrationRepository() { - return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); - } - - @Bean - public OAuth2AuthorizedClientService authorizedClientService( - ClientRegistrationRepository clientRegistrationRepository) { - return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository); - } - - @Bean - public OAuth2AuthorizedClientRepository authorizedClientRepository( - OAuth2AuthorizedClientService authorizedClientService) { - return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService); - } - - private ClientRegistration googleClientRegistration() { - return CommonOAuth2Provider.GOOGLE.getBuilder("google") - .clientId("google-client-id") - .clientSecret("google-client-secret") - .build(); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Configuration -open class OAuth2LoginConfig { - @EnableWebSecurity - open class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { - override fun configure(http: HttpSecurity) { - http { - authorizeRequests { - authorize(anyRequest, authenticated) - } - oauth2Login { } - } - } - } - - @Bean - open fun clientRegistrationRepository(): ClientRegistrationRepository { - return InMemoryClientRegistrationRepository(googleClientRegistration()) - } - - @Bean - open fun authorizedClientService( - clientRegistrationRepository: ClientRegistrationRepository? - ): OAuth2AuthorizedClientService { - return InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository) - } - - @Bean - open fun authorizedClientRepository( - authorizedClientService: OAuth2AuthorizedClientService? - ): OAuth2AuthorizedClientRepository { - return AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService) - } - - private fun googleClientRegistration(): ClientRegistration { - return CommonOAuth2Provider.GOOGLE.getBuilder("google") - .clientId("google-client-id") - .clientSecret("google-client-secret") - .build() - } -} ----- - -.Xml -[source,xml,role="secondary"] ----- - - - - - - - - - - - - - - ----- -==== - - [[oauth2login-advanced]] -== Advanced Configuration += Advanced Configuration `HttpSecurity.oauth2Login()` provides a number of configuration options for customizing OAuth 2.0 Login. The main configuration options are grouped into their protocol endpoint counterparts. @@ -645,14 +69,14 @@ The main goal of the `oauth2Login()` DSL was to closely align with the naming, a The OAuth 2.0 Authorization Framework defines the https://tools.ietf.org/html/rfc6749#section-3[Protocol Endpoints] as follows: -The authorization process utilizes two authorization server endpoints (HTTP resources): +The authorization process uses two authorization server endpoints (HTTP resources): -* Authorization Endpoint: Used by the client to obtain authorization from the resource owner via user-agent redirection. +* Authorization Endpoint: Used by the client to obtain authorization from the resource owner through user-agent redirection. * Token Endpoint: Used by the client to exchange an authorization grant for an access token, typically with client authentication. -As well as one client endpoint: +The authorization process also uses one client endpoint: -* Redirection Endpoint: Used by the authorization server to return responses containing authorization credentials to the client via the resource owner user-agent. +* Redirection Endpoint: Used by the authorization server to return responses that contain authorization credentials to the client through the resource owner user-agent. The OpenID Connect Core 1.0 specification defines the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] as follows: @@ -737,7 +161,7 @@ class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { In addition to the `oauth2Login()` DSL, XML configuration is also supported. -The following code shows the complete configuration options available in the xref:servlet/appendix/namespace.adoc#nsa-oauth2-login[ security namespace]: +The following code shows the complete configuration options available in the xref:servlet/appendix/namespace/http.adoc#nsa-oauth2-login[ security namespace]: .OAuth2 Login XML Configuration Options ==== @@ -764,20 +188,24 @@ The following code shows the complete configuration options available in the xre The following sections go into more detail on each of the configuration options available: -* <> -* <> -* <> +* <> +* <> +* <> +* <> +* <> [[oauth2login-advanced-login-page]] -=== OAuth 2.0 Login Page +== OAuth 2.0 Login Page By default, the OAuth 2.0 Login Page is auto-generated by the `DefaultLoginPageGeneratingFilter`. The default login page shows each configured OAuth Client with its `ClientRegistration.clientName` as a link, which is capable of initiating the Authorization Request (or OAuth 2.0 Login). [NOTE] -In order for `DefaultLoginPageGeneratingFilter` to show links for configured OAuth Clients, the registered `ClientRegistrationRepository` needs to also implement `Iterable`. +==== +For `DefaultLoginPageGeneratingFilter` to show links for configured OAuth Clients, the registered `ClientRegistrationRepository` needs to also implement `Iterable`. See `InMemoryClientRegistrationRepository` for reference. +==== The link's destination for each OAuth Client defaults to the following: @@ -785,10 +213,12 @@ The link's destination for each OAuth Client defaults to the following: The following line shows an example: +==== [source,html] ---- Google ---- +==== To override the default login page, configure `oauth2Login().loginPage()` and (optionally) `oauth2Login().authorizationEndpoint().baseUri()`. @@ -848,34 +278,39 @@ class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { ==== [IMPORTANT] +==== You need to provide a `@Controller` with a `@RequestMapping("/login/oauth2")` that is capable of rendering the custom login page. +==== [TIP] -==== +===== As noted earlier, configuring `oauth2Login().authorizationEndpoint().baseUri()` is optional. However, if you choose to customize it, ensure the link to each OAuth Client matches the `authorizationEndpoint().baseUri()`. The following line shows an example: - +==== [source,html] ---- Google ---- ==== +===== [[oauth2login-advanced-redirection-endpoint]] -=== Redirection Endpoint +== Redirection Endpoint -The Redirection Endpoint is used by the Authorization Server for returning the Authorization Response (which contains the authorization credentials) to the client via the Resource Owner user-agent. +The Redirection Endpoint is used by the Authorization Server for returning the Authorization Response (which contains the authorization credentials) to the client through the Resource Owner user-agent. [TIP] +==== OAuth 2.0 Login leverages the Authorization Code Grant. Therefore, the authorization credential is the authorization code. +==== The default Authorization Response `baseUri` (redirection endpoint) is `*/login/oauth2/code/**`, which is defined in `OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI`. -If you would like to customize the Authorization Response `baseUri`, configure it as shown in the following example: +If you would like to customize the Authorization Response `baseUri`, configure it as follows: .Redirection Endpoint Configuration ==== @@ -928,13 +363,14 @@ class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { ==== [IMPORTANT] -==== +===== You also need to ensure the `ClientRegistration.redirectUri` matches the custom Authorization Response `baseUri`. The following listing shows an example: +==== .Java -[source,java,role="primary",attrs="-attributes"] +[source,java,role="primary",subs="-attributes"] ---- return CommonOAuth2Provider.GOOGLE.getBuilder("google") .clientId("google-client-id") @@ -944,7 +380,7 @@ return CommonOAuth2Provider.GOOGLE.getBuilder("google") ---- .Kotlin -[source,kotlin,role="secondary",attrs="-attributes"] +[source,kotlin,role="secondary",subs="-attributes"] ---- return CommonOAuth2Provider.GOOGLE.getBuilder("google") .clientId("google-client-id") @@ -953,36 +389,37 @@ return CommonOAuth2Provider.GOOGLE.getBuilder("google") .build() ---- ==== +===== [[oauth2login-advanced-userinfo-endpoint]] -=== UserInfo Endpoint +== UserInfo Endpoint The UserInfo Endpoint includes a number of configuration options, as described in the following sub-sections: -* <> -* <> -* <> +* <> +* <> +* <> [[oauth2login-advanced-map-authorities]] -==== Mapping User Authorities +=== Mapping User Authorities -After the user successfully authenticates with the OAuth 2.0 Provider, the `OAuth2User.getAuthorities()` (or `OidcUser.getAuthorities()`) may be mapped to a new set of `GrantedAuthority` instances, which will be supplied to `OAuth2AuthenticationToken` when completing the authentication. +After the user successfully authenticates with the OAuth 2.0 Provider, the `OAuth2User.getAuthorities()` (or `OidcUser.getAuthorities()`) can be mapped to a new set of `GrantedAuthority` instances, which are supplied to `OAuth2AuthenticationToken` when completing the authentication. [TIP] `OAuth2AuthenticationToken.getAuthorities()` is used for authorizing requests, such as in `hasRole('USER')` or `hasRole('ADMIN')`. There are a couple of options to choose from when mapping user authorities: -* <> -* <> +* <> +* <> [[oauth2login-advanced-map-authorities-grantedauthoritiesmapper]] -===== Using a GrantedAuthoritiesMapper +==== Using a GrantedAuthoritiesMapper -Provide an implementation of `GrantedAuthoritiesMapper` and configure it as shown in the following example: +Provide an implementation of `GrantedAuthoritiesMapper` and configure it, as follows: .Granted Authorities Mapper Configuration ==== @@ -1082,7 +519,7 @@ class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { ---- ==== -Alternatively, you may register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the configuration, as shown in the following example: +Alternatively, you can register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the configuration, as follows: .Granted Authorities Mapper Bean Configuration ==== @@ -1126,11 +563,11 @@ class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { ==== [[oauth2login-advanced-map-authorities-oauth2userservice]] -===== Delegation-based strategy with OAuth2UserService +==== Delegation-based Strategy with OAuth2UserService -This strategy is advanced compared to using a `GrantedAuthoritiesMapper`, however, it's also more flexible as it gives you access to the `OAuth2UserRequest` and `OAuth2User` (when using an OAuth 2.0 UserService) or `OidcUserRequest` and `OidcUser` (when using an OpenID Connect 1.0 UserService). +This strategy is advanced compared to using a `GrantedAuthoritiesMapper`. However, it is also more flexible, as it gives you access to the `OAuth2UserRequest` and `OAuth2User` (when using an OAuth 2.0 UserService) or `OidcUserRequest` and `OidcUser` (when using an OpenID Connect 1.0 UserService). -The `OAuth2UserRequest` (and `OidcUserRequest`) provides you access to the associated `OAuth2AccessToken`, which is very useful in the cases where the _delegator_ needs to fetch authority information from a protected resource before it can map the custom authorities for the user. +The `OAuth2UserRequest` (and `OidcUserRequest`) provides you access to the associated `OAuth2AccessToken`, which is very useful in cases where the _delegator_ needs to fetch authority information from a protected resource before it can map the custom authorities for the user. The following example shows how to implement and configure a delegation-based strategy using an OpenID Connect 1.0 UserService: @@ -1228,31 +665,35 @@ class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { [[oauth2login-advanced-oauth2-user-service]] -==== OAuth 2.0 UserService +=== OAuth 2.0 UserService `DefaultOAuth2UserService` is an implementation of an `OAuth2UserService` that supports standard OAuth 2.0 Provider's. [NOTE] +==== `OAuth2UserService` obtains the user attributes of the end-user (the resource owner) from the UserInfo Endpoint (by using the access token granted to the client during the authorization flow) and returns an `AuthenticatedPrincipal` in the form of an `OAuth2User`. +==== -`DefaultOAuth2UserService` uses a `RestOperations` when requesting the user attributes at the UserInfo Endpoint. +`DefaultOAuth2UserService` uses a `RestOperations` instance when requesting the user attributes at the UserInfo Endpoint. If you need to customize the pre-processing of the UserInfo Request, you can provide `DefaultOAuth2UserService.setRequestEntityConverter()` with a custom `Converter>`. The default implementation `OAuth2UserRequestEntityConverter` builds a `RequestEntity` representation of a UserInfo Request that sets the `OAuth2AccessToken` in the `Authorization` header by default. -On the other end, if you need to customize the post-handling of the UserInfo Response, you will need to provide `DefaultOAuth2UserService.setRestOperations()` with a custom configured `RestOperations`. +On the other end, if you need to customize the post-handling of the UserInfo Response, you need to provide `DefaultOAuth2UserService.setRestOperations()` with a custom configured `RestOperations`. The default `RestOperations` is configured as follows: +==== [source,java] ---- RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); ---- +==== `OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error (400 Bad Request). It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`. -Whether you customize `DefaultOAuth2UserService` or provide your own implementation of `OAuth2UserService`, you'll need to configure it as shown in the following example: +Whether you customize `DefaultOAuth2UserService` or provide your own implementation of `OAuth2UserService`, you need to configure it as follows: ==== .Java @@ -1304,15 +745,15 @@ class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { [[oauth2login-advanced-oidc-user-service]] -==== OpenID Connect 1.0 UserService +=== OpenID Connect 1.0 UserService `OidcUserService` is an implementation of an `OAuth2UserService` that supports OpenID Connect 1.0 Provider's. The `OidcUserService` leverages the `DefaultOAuth2UserService` when requesting the user attributes at the UserInfo Endpoint. -If you need to customize the pre-processing of the UserInfo Request and/or the post-handling of the UserInfo Response, you will need to provide `OidcUserService.setOauth2UserService()` with a custom configured `DefaultOAuth2UserService`. +If you need to customize the pre-processing of the UserInfo Request or the post-handling of the UserInfo Response, you need to provide `OidcUserService.setOauth2UserService()` with a custom configured `DefaultOAuth2UserService`. -Whether you customize `OidcUserService` or provide your own implementation of `OAuth2UserService` for OpenID Connect 1.0 Provider's, you'll need to configure it as shown in the following example: +Whether you customize `OidcUserService` or provide your own implementation of `OAuth2UserService` for OpenID Connect 1.0 Provider's, you need to configure it as follows: ==== .Java @@ -1364,18 +805,18 @@ class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { [[oauth2login-advanced-idtoken-verify]] -=== ID Token Signature Verification +== ID Token Signature Verification OpenID Connect 1.0 Authentication introduces the https://openid.net/specs/openid-connect-core-1_0.html#IDToken[ID Token], which is a security token that contains Claims about the Authentication of an End-User by an Authorization Server when used by a Client. -The ID Token is represented as a https://tools.ietf.org/html/rfc7519[JSON Web Token] (JWT) and MUST be signed using https://tools.ietf.org/html/rfc7515[JSON Web Signature] (JWS). +The ID Token is represented as a https://tools.ietf.org/html/rfc7519[JSON Web Token] (JWT) and MUST be signed by using https://tools.ietf.org/html/rfc7515[JSON Web Signature] (JWS). The `OidcIdTokenDecoderFactory` provides a `JwtDecoder` used for `OidcIdToken` signature verification. The default algorithm is `RS256` but may be different when assigned during client registration. -For these cases, a resolver may be configured to return the expected JWS algorithm assigned for a specific client. +For these cases, you can configure a resolver to return the expected JWS algorithm assigned for a specific client. -The JWS algorithm resolver is a `Function` that accepts a `ClientRegistration` and returns the expected `JwsAlgorithm` for the client, eg. `SignatureAlgorithm.RS256` or `MacAlgorithm.HS256` +The JWS algorithm resolver is a `Function` that accepts a `ClientRegistration` and returns the expected `JwsAlgorithm` for the client, such as `SignatureAlgorithm.RS256` or `MacAlgorithm.HS256` -The following code shows how to configure the `OidcIdTokenDecoderFactory` `@Bean` to default to `MacAlgorithm.HS256` for all `ClientRegistration`: +The following code shows how to configure the `OidcIdTokenDecoderFactory` `@Bean` to default to `MacAlgorithm.HS256` for all `ClientRegistration` instances: ==== .Java @@ -1402,21 +843,26 @@ fun idTokenDecoderFactory(): JwtDecoderFactory { ==== [NOTE] -For MAC based algorithms such as `HS256`, `HS384` or `HS512`, the `client-secret` corresponding to the `client-id` is used as the symmetric key for signature verification. +==== +For MAC-based algorithms (such as `HS256`, `HS384`, or `HS512`), the `client-secret` that corresponds to the `client-id` is used as the symmetric key for signature verification. +==== [TIP] +==== If more than one `ClientRegistration` is configured for OpenID Connect 1.0 Authentication, the JWS algorithm resolver may evaluate the provided `ClientRegistration` to determine which algorithm to return. +==== [[oauth2login-advanced-oidc-logout]] -=== OpenID Connect 1.0 Logout +== OpenID Connect 1.0 Logout -OpenID Connect Session Management 1.0 allows the ability to log out the End-User at the Provider using the Client. +OpenID Connect Session Management 1.0 allows the ability to log out the end user at the Provider by using the Client. One of the strategies available is https://openid.net/specs/openid-connect-session-1_0.html#RPLogout[RP-Initiated Logout]. -If the OpenID Provider supports both Session Management and https://openid.net/specs/openid-connect-discovery-1_0.html[Discovery], the client may obtain the `end_session_endpoint` `URL` from the OpenID Provider's https://openid.net/specs/openid-connect-session-1_0.html#OPMetadata[Discovery Metadata]. -This can be achieved by configuring the `ClientRegistration` with the `issuer-uri`, as in the following example: +If the OpenID Provider supports both Session Management and https://openid.net/specs/openid-connect-discovery-1_0.html[Discovery], the client can obtain the `end_session_endpoint` `URL` from the OpenID Provider's https://openid.net/specs/openid-connect-session-1_0.html#OPMetadata[Discovery Metadata]. +You can do so by configuring the `ClientRegistration` with the `issuer-uri`, as follows: +==== [source,yaml] ---- spring: @@ -1432,8 +878,9 @@ spring: okta: issuer-uri: https://dev-1234.oktapreview.com ---- +==== -...and the `OidcClientInitiatedLogoutSuccessHandler`, which implements RP-Initiated Logout, may be configured as follows: +Also, you can configure `OidcClientInitiatedLogoutSuccessHandler`, which implements RP-Initiated Logout, as follows: ==== .Java @@ -1448,7 +895,7 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2Login(withDefaults()) @@ -1468,9 +915,6 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { return oidcLogoutSuccessHandler; } } - -NOTE: `OidcClientInitiatedLogoutSuccessHandler` supports the `{baseUrl}` placeholder. -If used, the application's base URL, like `https://app.example.org`, will replace it at request time. ---- .Kotlin @@ -1502,8 +946,11 @@ class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { return oidcLogoutSuccessHandler } } - -NOTE: `OidcClientInitiatedLogoutSuccessHandler` supports the `{baseUrl}` placeholder. -If used, the application's base URL, like `https://app.example.org`, will replace it at request time. ---- ==== + +[NOTE] +==== +`OidcClientInitiatedLogoutSuccessHandler` supports the `+{baseUrl}+` placeholder. +If used, the application's base URL, such as `https://app.example.org`, replaces it at request time. +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/login/core.adoc b/docs/modules/ROOT/pages/servlet/oauth2/login/core.adoc new file mode 100644 index 00000000000..10f991a5591 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/login/core.adoc @@ -0,0 +1,581 @@ += Core Configuration + +[[oauth2login-sample-boot]] +== Spring Boot 2.x Sample + +Spring Boot 2.x brings full auto-configuration capabilities for OAuth 2.0 Login. + +This section shows how to configure the {gh-samples-url}/boot/oauth2login[*OAuth 2.0 Login sample*] by using _Google_ as the _Authentication Provider_ and covers the following topics: + +* <> +* <> +* <> +* <> + + +[[oauth2login-sample-initial-setup]] +=== Initial Setup + +To use Google's OAuth 2.0 authentication system for login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials. + +[NOTE] +==== +https://developers.google.com/identity/protocols/OpenIDConnect[Google's OAuth 2.0 implementation] for authentication conforms to the https://openid.net/connect/[OpenID Connect 1.0] specification and is https://openid.net/certification/[OpenID certified]. +==== + +Follow the instructions on the https://developers.google.com/identity/protocols/OpenIDConnect[OpenID Connect] page, starting in the "`Setting up OAuth 2.0`" section. + +After completing the "`Obtain OAuth 2.0 credentials`" instructions, you should have new OAuth Client with credentials consisting of a Client ID and a Client Secret. + + +[[oauth2login-sample-redirect-uri]] +=== Setting the Redirect URI + +The redirect URI is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with Google and have granted access to the OAuth Client (<>) on the Consent page. + +In the "`Set a redirect URI`" subsection, ensure that the *Authorized redirect URIs* field is set to `http://localhost:8080/login/oauth2/code/google`. + +[TIP] +==== +The default redirect URI template is `+{baseUrl}/login/oauth2/code/{registrationId}+`. +The `registrationId` is a unique identifier for the xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[`ClientRegistration`]. +==== + +[IMPORTANT] +==== +If the OAuth Client runs behind a proxy server, you should check the xref:features/exploits/http.adoc#http-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured. +Also, see the supported xref:servlet/oauth2/client/authorization-grants.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. +==== + + +[[oauth2login-sample-application-config]] +=== Configure application.yml + +Now that you have a new OAuth Client with Google, you need to configure the application to use the OAuth Client for the _authentication flow_. +To do so: + +. Go to `application.yml` and set the following configuration: ++ +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: <1> + google: <2> + client-id: google-client-id + client-secret: google-client-secret +---- ++ +.OAuth Client properties +==== +<1> `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties. +<2> Following the base property prefix is the ID for the xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[`ClientRegistration`], such as Google. +==== + +. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. + + +[[oauth2login-sample-boot-application]] +=== Boot up the Application + +Launch the Spring Boot 2.x sample and go to `http://localhost:8080`. +You are then redirected to the default _auto-generated_ login page, which displays a link for Google. + +Click on the Google link, and you are then redirected to Google for authentication. + +After authenticating with your Google account credentials, you see the Consent screen. +The Consent screen asks you to either allow or deny access to the OAuth Client you created earlier. +Click *Allow* to authorize the OAuth Client to access your email address and basic profile information. + +At this point, the OAuth Client retrieves your email address and basic profile information from the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session. + + +[[oauth2login-boot-property-mappings]] +== Spring Boot 2.x Property Mappings + +The following table outlines the mapping of the Spring Boot 2.x OAuth Client properties to the xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[ClientRegistration] properties. + +|=== +|Spring Boot 2.x |ClientRegistration + +|`spring.security.oauth2.client.registration._[registrationId]_` +|`registrationId` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-id` +|`clientId` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-secret` +|`clientSecret` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-authentication-method` +|`clientAuthenticationMethod` + +|`spring.security.oauth2.client.registration._[registrationId]_.authorization-grant-type` +|`authorizationGrantType` + +|`spring.security.oauth2.client.registration._[registrationId]_.redirect-uri` +|`redirectUri` + +|`spring.security.oauth2.client.registration._[registrationId]_.scope` +|`scopes` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-name` +|`clientName` + +|`spring.security.oauth2.client.provider._[providerId]_.authorization-uri` +|`providerDetails.authorizationUri` + +|`spring.security.oauth2.client.provider._[providerId]_.token-uri` +|`providerDetails.tokenUri` + +|`spring.security.oauth2.client.provider._[providerId]_.jwk-set-uri` +|`providerDetails.jwkSetUri` + +|`spring.security.oauth2.client.provider._[providerId]_.issuer-uri` +|`providerDetails.issuerUri` + +|`spring.security.oauth2.client.provider._[providerId]_.user-info-uri` +|`providerDetails.userInfoEndpoint.uri` + +|`spring.security.oauth2.client.provider._[providerId]_.user-info-authentication-method` +|`providerDetails.userInfoEndpoint.authenticationMethod` + +|`spring.security.oauth2.client.provider._[providerId]_.user-name-attribute` +|`providerDetails.userInfoEndpoint.userNameAttributeName` +|=== + +[TIP] +==== +You can initially configure a `ClientRegistration` by using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint], by specifying the `spring.security.oauth2.client.provider._[providerId]_.issuer-uri` property. +==== + + +[[oauth2login-common-oauth2-provider]] +== CommonOAuth2Provider + +`CommonOAuth2Provider` pre-defines a set of default client properties for a number of well known providers: Google, GitHub, Facebook, and Okta. + +For example, the `authorization-uri`, `token-uri`, and `user-info-uri` do not change often for a provider. +Therefore, it makes sense to provide default values, to reduce the required configuration. + +As demonstrated previously, when we <>, only the `client-id` and `client-secret` properties are required. + +The following listing shows an example: + +==== +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + google: + client-id: google-client-id + client-secret: google-client-secret +---- +==== + +[TIP] +The auto-defaulting of client properties works seamlessly here because the `registrationId` (`google`) matches the `GOOGLE` `enum` (case-insensitive) in `CommonOAuth2Provider`. + +For cases where you may want to specify a different `registrationId`, such as `google-login`, you can still leverage auto-defaulting of client properties by configuring the `provider` property. + +The following listing shows an example: + +==== +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + google-login: <1> + provider: google <2> + client-id: google-client-id + client-secret: google-client-secret +---- +<1> The `registrationId` is set to `google-login`. +<2> The `provider` property is set to `google`, which will leverage the auto-defaulting of client properties set in `CommonOAuth2Provider.GOOGLE.getBuilder()`. +==== + +[[oauth2login-custom-provider-properties]] +== Configuring Custom Provider Properties + +There are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain). + +For example, an OAuth Client registered with Okta is assigned to a specific sub-domain and have their own protocol endpoints. + +For these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: `spring.security.oauth2.client.provider._[providerId]_`. + +The following listing shows an example: + +==== +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + provider: + okta: <1> + authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize + token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token + user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo + user-name-attribute: sub + jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys +---- +<1> The base property (`spring.security.oauth2.client.provider.okta`) allows for custom configuration of protocol endpoint locations. +==== + +[[oauth2login-override-boot-autoconfig]] +== Overriding Spring Boot 2.x Auto-configuration + +The Spring Boot 2.x auto-configuration class for OAuth Client support is `OAuth2ClientAutoConfiguration`. + +It performs the following tasks: + +* Registers a `ClientRegistrationRepository` `@Bean` composed of `ClientRegistration`(s) from the configured OAuth Client properties. +* Provides a `WebSecurityConfigurerAdapter` `@Configuration` and enables OAuth 2.0 Login through `httpSecurity.oauth2Login()`. + +If you need to override the auto-configuration based on your specific requirements, you may do so in the following ways: + +* <> +* <> +* <> + + +[[oauth2login-register-clientregistrationrepository-bean]] +=== Register a ClientRegistrationRepository @Bean + +The following example shows how to register a `ClientRegistrationRepository` `@Bean`: + +==== +.Java +[source,java,role="primary",attrs="-attributes"] +---- +@Configuration +public class OAuth2LoginConfig { + + @Bean + public ClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); + } + + private ClientRegistration googleClientRegistration() { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary",attrs="-attributes"] +---- +@Configuration +class OAuth2LoginConfig { + @Bean + fun clientRegistrationRepository(): ClientRegistrationRepository { + return InMemoryClientRegistrationRepository(googleClientRegistration()) + } + + private fun googleClientRegistration(): ClientRegistration { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build() + } +} +---- +==== + + +[[oauth2login-provide-websecurityconfigureradapter]] +=== Provide a WebSecurityConfigurerAdapter + +The following example shows how to provide a `WebSecurityConfigurerAdapter` with `@EnableWebSecurity` and enable OAuth 2.0 login through `httpSecurity.oauth2Login()`: + +.OAuth2 Login Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebSecurity +public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests(authorize -> authorize + .anyRequest().authenticated() + ) + .oauth2Login(withDefaults()); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebSecurity +class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + authorizeRequests { + authorize(anyRequest, authenticated) + } + oauth2Login { } + } + } +} +---- +==== + + +[[oauth2login-completely-override-autoconfiguration]] +=== Completely Override the Auto-configuration + +The following example shows how to completely override the auto-configuration by registering a `ClientRegistrationRepository` `@Bean` and providing a `WebSecurityConfigurerAdapter`. + +.Overriding the auto-configuration +==== +.Java +[source,java,role="primary",attrs="-attributes"] +---- +@Configuration +public class OAuth2LoginConfig { + + @EnableWebSecurity + public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests(authorize -> authorize + .anyRequest().authenticated() + ) + .oauth2Login(withDefaults()); + } + } + + @Bean + public ClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); + } + + private ClientRegistration googleClientRegistration() { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary",attrs="-attributes"] +---- +@Configuration +class OAuth2LoginConfig { + + @EnableWebSecurity + class OAuth2LoginSecurityConfig: WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + authorizeRequests { + authorize(anyRequest, authenticated) + } + oauth2Login { } + } + } + } + + @Bean + fun clientRegistrationRepository(): ClientRegistrationRepository { + return InMemoryClientRegistrationRepository(googleClientRegistration()) + } + + private fun googleClientRegistration(): ClientRegistration { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build() + } +} +---- +==== + + +[[oauth2login-javaconfig-wo-boot]] +== Java Configuration without Spring Boot 2.x + +If you are not able to use Spring Boot 2.x and would like to configure one of the pre-defined providers in `CommonOAuth2Provider` (for example, Google), apply the following configuration: + +.OAuth2 Login Configuration +==== +.Java +[source,java,role="primary"] +---- +@Configuration +public class OAuth2LoginConfig { + + @EnableWebSecurity + public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests(authorize -> authorize + .anyRequest().authenticated() + ) + .oauth2Login(withDefaults()); + } + } + + @Bean + public ClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); + } + + @Bean + public OAuth2AuthorizedClientService authorizedClientService( + ClientRegistrationRepository clientRegistrationRepository) { + return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository); + } + + @Bean + public OAuth2AuthorizedClientRepository authorizedClientRepository( + OAuth2AuthorizedClientService authorizedClientService) { + return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService); + } + + private ClientRegistration googleClientRegistration() { + return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Configuration +open class OAuth2LoginConfig { + @EnableWebSecurity + open class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() { + override fun configure(http: HttpSecurity) { + http { + authorizeRequests { + authorize(anyRequest, authenticated) + } + oauth2Login { } + } + } + } + + @Bean + open fun clientRegistrationRepository(): ClientRegistrationRepository { + return InMemoryClientRegistrationRepository(googleClientRegistration()) + } + + @Bean + open fun authorizedClientService( + clientRegistrationRepository: ClientRegistrationRepository? + ): OAuth2AuthorizedClientService { + return InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository) + } + + @Bean + open fun authorizedClientRepository( + authorizedClientService: OAuth2AuthorizedClientService? + ): OAuth2AuthorizedClientRepository { + return AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService) + } + + private fun googleClientRegistration(): ClientRegistration { + return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .build() + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + + + + + + + + + + + +---- +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/login/index.adoc b/docs/modules/ROOT/pages/servlet/oauth2/login/index.adoc new file mode 100644 index 00000000000..596ab12170a --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/login/index.adoc @@ -0,0 +1,11 @@ +[[oauth2login]] += OAuth 2.0 Login +:page-section-summary-toc: 1 + +The OAuth 2.0 Login feature lets an application have users log in to the application by using their existing account at an OAuth 2.0 Provider (such as GitHub) or OpenID Connect 1.0 Provider (such as Google). +OAuth 2.0 Login implements two use cases: "`Login with Google`" or "`Login with GitHub`". + +[NOTE] +==== +OAuth 2.0 Login is implemented by using the *Authorization Code Grant*, as specified in the https://tools.ietf.org/html/rfc6749#section-4.1[OAuth 2.0 Authorization Framework] and https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth[OpenID Connect Core 1.0]. +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc b/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc deleted file mode 100644 index c02a4a0bc65..00000000000 --- a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc +++ /dev/null @@ -1,2290 +0,0 @@ -[[oauth2client]] -= OAuth 2.0 Client - -The OAuth 2.0 Client features provide support for the Client role as defined in the https://tools.ietf.org/html/rfc6749#section-1.1[OAuth 2.0 Authorization Framework]. - -At a high-level, the core features available are: - -.Authorization Grant support -* https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] -* https://tools.ietf.org/html/rfc6749#section-6[Refresh Token] -* https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] -* https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] -* https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[JWT Bearer] - -.Client Authentication support -* https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] - -.HTTP Client support -* <> (for requesting protected resources) - -The `HttpSecurity.oauth2Client()` DSL provides a number of configuration options for customizing the core components used by OAuth 2.0 Client. -In addition, `HttpSecurity.oauth2Client().authorizationCodeGrant()` enables the customization of the Authorization Code grant. - -The following code shows the complete configuration options provided by the `HttpSecurity.oauth2Client()` DSL: - -.OAuth2 Client Configuration Options -==== -.Java -[source,java,role="primary"] ----- -@EnableWebSecurity -public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .oauth2Client(oauth2 -> oauth2 - .clientRegistrationRepository(this.clientRegistrationRepository()) - .authorizedClientRepository(this.authorizedClientRepository()) - .authorizedClientService(this.authorizedClientService()) - .authorizationCodeGrant(codeGrant -> codeGrant - .authorizationRequestRepository(this.authorizationRequestRepository()) - .authorizationRequestResolver(this.authorizationRequestResolver()) - .accessTokenResponseClient(this.accessTokenResponseClient()) - ) - ); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@EnableWebSecurity -class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() { - - override fun configure(http: HttpSecurity) { - http { - oauth2Client { - clientRegistrationRepository = clientRegistrationRepository() - authorizedClientRepository = authorizedClientRepository() - authorizedClientService = authorizedClientService() - authorizationCodeGrant { - authorizationRequestRepository = authorizationRequestRepository() - authorizationRequestResolver = authorizationRequestResolver() - accessTokenResponseClient = accessTokenResponseClient() - } - } - } - } -} ----- -==== - -In addition to the `HttpSecurity.oauth2Client()` DSL, XML configuration is also supported. - -The following code shows the complete configuration options available in the xref:servlet/appendix/namespace.adoc#nsa-oauth2-client[ security namespace]: - -.OAuth2 Client XML Configuration Options -==== -[source,xml] ----- - - - - - ----- -==== - -The `OAuth2AuthorizedClientManager` is responsible for managing the authorization (or re-authorization) of an OAuth 2.0 Client, in collaboration with one or more `OAuth2AuthorizedClientProvider`(s). - -The following code shows an example of how to register an `OAuth2AuthorizedClientManager` `@Bean` and associate it with an `OAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build(); - - DefaultOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { - val authorizedClientProvider: OAuth2AuthorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build() - val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - -The following sections will go into more detail on the core components used by OAuth 2.0 Client and the configuration options available: - -* <> -** <> -** <> -** <> -** <> -** <> -* <> -** <> -** <> -** <> -** <> -** <> -* <> -** <> -* <> -** <> -* <> - - -[[oauth2Client-core-interface-class]] -== Core Interfaces / Classes - - -[[oauth2Client-client-registration]] -=== ClientRegistration - -`ClientRegistration` is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. - -A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details. - -`ClientRegistration` and its properties are defined as follows: - -[source,java] ----- -public final class ClientRegistration { - private String registrationId; <1> - private String clientId; <2> - private String clientSecret; <3> - private ClientAuthenticationMethod clientAuthenticationMethod; <4> - private AuthorizationGrantType authorizationGrantType; <5> - private String redirectUri; <6> - private Set scopes; <7> - private ProviderDetails providerDetails; - private String clientName; <8> - - public class ProviderDetails { - private String authorizationUri; <9> - private String tokenUri; <10> - private UserInfoEndpoint userInfoEndpoint; - private String jwkSetUri; <11> - private String issuerUri; <12> - private Map configurationMetadata; <13> - - public class UserInfoEndpoint { - private String uri; <14> - private AuthenticationMethod authenticationMethod; <15> - private String userNameAttributeName; <16> - - } - } -} ----- -<1> `registrationId`: The ID that uniquely identifies the `ClientRegistration`. -<2> `clientId`: The client identifier. -<3> `clientSecret`: The client secret. -<4> `clientAuthenticationMethod`: The method used to authenticate the Client with the Provider. -The supported values are *client_secret_basic*, *client_secret_post*, *private_key_jwt*, *client_secret_jwt* and *none* https://tools.ietf.org/html/rfc6749#section-2.1[(public clients)]. -<5> `authorizationGrantType`: The OAuth 2.0 Authorization Framework defines four https://tools.ietf.org/html/rfc6749#section-1.3[Authorization Grant] types. - The supported values are `authorization_code`, `client_credentials`, `password`, as well as, extension grant type `urn:ietf:params:oauth:grant-type:jwt-bearer`. -<6> `redirectUri`: The client's registered redirect URI that the _Authorization Server_ redirects the end-user's user-agent - to after the end-user has authenticated and authorized access to the client. -<7> `scopes`: The scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile. -<8> `clientName`: A descriptive name used for the client. -The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page. -<9> `authorizationUri`: The Authorization Endpoint URI for the Authorization Server. -<10> `tokenUri`: The Token Endpoint URI for the Authorization Server. -<11> `jwkSetUri`: The URI used to retrieve the https://tools.ietf.org/html/rfc7517[JSON Web Key (JWK)] Set from the Authorization Server, - which contains the cryptographic key(s) used to verify the https://tools.ietf.org/html/rfc7515[JSON Web Signature (JWS)] of the ID Token and optionally the UserInfo Response. -<12> `issuerUri`: Returns the issuer identifier uri for the OpenID Connect 1.0 provider or the OAuth 2.0 Authorization Server. -<13> `configurationMetadata`: The https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[OpenID Provider Configuration Information]. - This information will only be available if the Spring Boot 2.x property `spring.security.oauth2.client.provider.[providerId].issuerUri` is configured. -<14> `(userInfoEndpoint)uri`: The UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user. -<15> `(userInfoEndpoint)authenticationMethod`: The authentication method used when sending the access token to the UserInfo Endpoint. -The supported values are *header*, *form* and *query*. -<16> `userNameAttributeName`: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user. - -A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint]. - -`ClientRegistrations` provides convenience methods for configuring a `ClientRegistration` in this way, as can be seen in the following example: - -==== -.Java -[source,java,role="primary"] ----- -ClientRegistration clientRegistration = - ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build(); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build() ----- -==== - -The above code will query in series `https://idp.example.com/issuer/.well-known/openid-configuration`, and then `https://idp.example.com/.well-known/openid-configuration/issuer`, and finally `https://idp.example.com/.well-known/oauth-authorization-server/issuer`, stopping at the first to return a 200 response. - -As an alternative, you can use `ClientRegistrations.fromOidcIssuerLocation()` to only query the OpenID Connect Provider's Configuration endpoint. - -[[oauth2Client-client-registration-repo]] -=== ClientRegistrationRepository - -The `ClientRegistrationRepository` serves as a repository for OAuth 2.0 / OpenID Connect 1.0 `ClientRegistration`(s). - -[NOTE] -Client registration information is ultimately stored and owned by the associated Authorization Server. -This repository provides the ability to retrieve a sub-set of the primary client registration information, which is stored with the Authorization Server. - -Spring Boot 2.x auto-configuration binds each of the properties under `spring.security.oauth2.client.registration._[registrationId]_` to an instance of `ClientRegistration` and then composes each of the `ClientRegistration` instance(s) within a `ClientRegistrationRepository`. - -[NOTE] -The default implementation of `ClientRegistrationRepository` is `InMemoryClientRegistrationRepository`. - -The auto-configuration also registers the `ClientRegistrationRepository` as a `@Bean` in the `ApplicationContext` so that it is available for dependency-injection, if needed by the application. - -The following listing shows an example: - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @Autowired - private ClientRegistrationRepository clientRegistrationRepository; - - @GetMapping("/") - public String index() { - ClientRegistration oktaRegistration = - this.clientRegistrationRepository.findByRegistrationId("okta"); - - ... - - return "index"; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - - @Autowired - private lateinit var clientRegistrationRepository: ClientRegistrationRepository - - @GetMapping("/") - fun index(): String { - val oktaRegistration = - this.clientRegistrationRepository.findByRegistrationId("okta") - - //... - - return "index"; - } -} ----- -==== - -[[oauth2Client-authorized-client]] -=== OAuth2AuthorizedClient - -`OAuth2AuthorizedClient` is a representation of an Authorized Client. -A client is considered to be authorized when the end-user (Resource Owner) has granted authorization to the client to access its protected resources. - -`OAuth2AuthorizedClient` serves the purpose of associating an `OAuth2AccessToken` (and optional `OAuth2RefreshToken`) to a `ClientRegistration` (client) and resource owner, who is the `Principal` end-user that granted the authorization. - - -[[oauth2Client-authorized-repo-service]] -=== OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService - -`OAuth2AuthorizedClientRepository` is responsible for persisting `OAuth2AuthorizedClient`(s) between web requests. -Whereas, the primary role of `OAuth2AuthorizedClientService` is to manage `OAuth2AuthorizedClient`(s) at the application-level. - -From a developer perspective, the `OAuth2AuthorizedClientRepository` or `OAuth2AuthorizedClientService` provides the capability to lookup an `OAuth2AccessToken` associated with a client so that it may be used to initiate a protected resource request. - -The following listing shows an example: - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @Autowired - private OAuth2AuthorizedClientService authorizedClientService; - - @GetMapping("/") - public String index(Authentication authentication) { - OAuth2AuthorizedClient authorizedClient = - this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()); - - OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); - - ... - - return "index"; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - - @Autowired - private lateinit var authorizedClientService: OAuth2AuthorizedClientService - - @GetMapping("/") - fun index(authentication: Authentication): String { - val authorizedClient: OAuth2AuthorizedClient = - this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()); - val accessToken = authorizedClient.accessToken - - ... - - return "index"; - } -} ----- -==== - -[NOTE] -Spring Boot 2.x auto-configuration registers an `OAuth2AuthorizedClientRepository` and/or `OAuth2AuthorizedClientService` `@Bean` in the `ApplicationContext`. -However, the application may choose to override and register a custom `OAuth2AuthorizedClientRepository` or `OAuth2AuthorizedClientService` `@Bean`. - -The default implementation of `OAuth2AuthorizedClientService` is `InMemoryOAuth2AuthorizedClientService`, which stores `OAuth2AuthorizedClient`(s) in-memory. - -Alternatively, the JDBC implementation `JdbcOAuth2AuthorizedClientService` may be configured for persisting `OAuth2AuthorizedClient`(s) in a database. - -[NOTE] -`JdbcOAuth2AuthorizedClientService` depends on the table definition described in xref:servlet/appendix/database-schema.adoc#dbschema-oauth2-client[ OAuth 2.0 Client Schema]. - - -[[oauth2Client-authorized-manager-provider]] -=== OAuth2AuthorizedClientManager / OAuth2AuthorizedClientProvider - -The `OAuth2AuthorizedClientManager` is responsible for the overall management of `OAuth2AuthorizedClient`(s). - -The primary responsibilities include: - -* Authorizing (or re-authorizing) an OAuth 2.0 Client, using an `OAuth2AuthorizedClientProvider`. -* Delegating the persistence of an `OAuth2AuthorizedClient`, typically using an `OAuth2AuthorizedClientService` or `OAuth2AuthorizedClientRepository`. -* Delegating to an `OAuth2AuthorizationSuccessHandler` when an OAuth 2.0 Client has been successfully authorized (or re-authorized). -* Delegating to an `OAuth2AuthorizationFailureHandler` when an OAuth 2.0 Client fails to authorize (or re-authorize). - -An `OAuth2AuthorizedClientProvider` implements a strategy for authorizing (or re-authorizing) an OAuth 2.0 Client. -Implementations will typically implement an authorization grant type, eg. `authorization_code`, `client_credentials`, etc. - -The default implementation of `OAuth2AuthorizedClientManager` is `DefaultOAuth2AuthorizedClientManager`, which is associated with an `OAuth2AuthorizedClientProvider` that may support multiple authorization grant types using a delegation-based composite. -The `OAuth2AuthorizedClientProviderBuilder` may be used to configure and build the delegation-based composite. - -The following code shows an example of how to configure and build an `OAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build(); - - DefaultOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { - val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build() - val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - -When an authorization attempt succeeds, the `DefaultOAuth2AuthorizedClientManager` will delegate to the `OAuth2AuthorizationSuccessHandler`, which (by default) will save the `OAuth2AuthorizedClient` via the `OAuth2AuthorizedClientRepository`. -In the case of a re-authorization failure, eg. a refresh token is no longer valid, the previously saved `OAuth2AuthorizedClient` will be removed from the `OAuth2AuthorizedClientRepository` via the `RemoveAuthorizedClientOAuth2AuthorizationFailureHandler`. -The default behaviour may be customized via `setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)` and `setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)`. - -The `DefaultOAuth2AuthorizedClientManager` is also associated with a `contextAttributesMapper` of type `Function>`, which is responsible for mapping attribute(s) from the `OAuth2AuthorizeRequest` to a `Map` of attributes to be associated to the `OAuth2AuthorizationContext`. -This can be useful when you need to supply an `OAuth2AuthorizedClientProvider` with required (supported) attribute(s), eg. the `PasswordOAuth2AuthorizedClientProvider` requires the resource owner's `username` and `password` to be available in `OAuth2AuthorizationContext.getAttributes()`. - -The following code shows an example of the `contextAttributesMapper`: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .password() - .refreshToken() - .build(); - - DefaultOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters, - // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` - authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()); - - return authorizedClientManager; -} - -private Function> contextAttributesMapper() { - return authorizeRequest -> { - Map contextAttributes = Collections.emptyMap(); - HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName()); - String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME); - String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD); - if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - contextAttributes = new HashMap<>(); - - // `PasswordOAuth2AuthorizedClientProvider` requires both attributes - contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username); - contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password); - } - return contextAttributes; - }; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { - val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .password() - .refreshToken() - .build() - val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - - // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters, - // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` - authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()) - return authorizedClientManager -} - -private fun contextAttributesMapper(): Function> { - return Function { authorizeRequest -> - var contextAttributes: MutableMap = mutableMapOf() - val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name) - val username: String = servletRequest.getParameter(OAuth2ParameterNames.USERNAME) - val password: String = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD) - if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - contextAttributes = hashMapOf() - - // `PasswordOAuth2AuthorizedClientProvider` requires both attributes - contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username - contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password - } - contextAttributes - } -} ----- -==== - -The `DefaultOAuth2AuthorizedClientManager` is designed to be used *_within_* the context of a `HttpServletRequest`. -When operating *_outside_* of a `HttpServletRequest` context, use `AuthorizedClientServiceOAuth2AuthorizedClientManager` instead. - -A _service application_ is a common use case for when to use an `AuthorizedClientServiceOAuth2AuthorizedClientManager`. -Service applications often run in the background, without any user interaction, and typically run under a system-level account instead of a user account. -An OAuth 2.0 Client configured with the `client_credentials` grant type can be considered a type of service application. - -The following code shows an example of how to configure an `AuthorizedClientServiceOAuth2AuthorizedClientManager` that provides support for the `client_credentials` grant type: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientService authorizedClientService) { - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials() - .build(); - - AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = - new AuthorizedClientServiceOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientService); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientService: OAuth2AuthorizedClientService): OAuth2AuthorizedClientManager { - val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials() - .build() - val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientService) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - - -[[oauth2Client-auth-grant-support]] -== Authorization Grant Support - - -[[oauth2Client-auth-code-grant]] -=== Authorization Code - -[NOTE] -Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] grant. - - -==== Obtaining Authorization - -[NOTE] -Please refer to the https://tools.ietf.org/html/rfc6749#section-4.1.1[Authorization Request/Response] protocol flow for the Authorization Code grant. - - -==== Initiating the Authorization Request - -The `OAuth2AuthorizationRequestRedirectFilter` uses an `OAuth2AuthorizationRequestResolver` to resolve an `OAuth2AuthorizationRequest` and initiate the Authorization Code grant flow by redirecting the end-user's user-agent to the Authorization Server's Authorization Endpoint. - -The primary role of the `OAuth2AuthorizationRequestResolver` is to resolve an `OAuth2AuthorizationRequest` from the provided web request. -The default implementation `DefaultOAuth2AuthorizationRequestResolver` matches on the (default) path `+/oauth2/authorization/{registrationId}+` extracting the `registrationId` and using it to build the `OAuth2AuthorizationRequest` for the associated `ClientRegistration`. - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml,attrs="-attributes"] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-secret: okta-client-secret - authorization-grant-type: authorization_code - redirect-uri: "{baseUrl}/authorized/okta" - scope: read, write - provider: - okta: - authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize - token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token ----- - -A request with the base path `/oauth2/authorization/okta` will initiate the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectFilter` and ultimately start the Authorization Code grant flow. - -[NOTE] -The `AuthorizationCodeOAuth2AuthorizedClientProvider` is an implementation of `OAuth2AuthorizedClientProvider` for the Authorization Code grant, -which also initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectFilter`. - -If the OAuth 2.0 Client is a https://tools.ietf.org/html/rfc6749#section-2.1[Public Client], then configure the OAuth 2.0 Client registration as follows: - -[source,yaml,attrs="-attributes"] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-authentication-method: none - authorization-grant-type: authorization_code - redirect-uri: "{baseUrl}/authorized/okta" - ... ----- - -Public Clients are supported using https://tools.ietf.org/html/rfc7636[Proof Key for Code Exchange] (PKCE). -If the client is running in an untrusted environment (eg. native application or web browser-based application) and therefore incapable of maintaining the confidentiality of it's credentials, PKCE will automatically be used when the following conditions are true: - -. `client-secret` is omitted (or empty) -. `client-authentication-method` is set to "none" (`ClientAuthenticationMethod.NONE`) - -[[oauth2Client-auth-code-redirect-uri]] -The `DefaultOAuth2AuthorizationRequestResolver` also supports `URI` template variables for the `redirect-uri` using `UriComponentsBuilder`. - -The following configuration uses all the supported `URI` template variables: - -[source,yaml,attrs="-attributes"] ----- -spring: - security: - oauth2: - client: - registration: - okta: - ... - redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}" - ... ----- - -[NOTE] -`+{baseUrl}+` resolves to `+{baseScheme}://{baseHost}{basePort}{basePath}+` - -Configuring the `redirect-uri` with `URI` template variables is especially useful when the OAuth 2.0 Client is running behind a xref:features/exploits/http.adoc#http-proxy-server[Proxy Server]. -This ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`. - -==== Customizing the Authorization Request - -One of the primary use cases an `OAuth2AuthorizationRequestResolver` can realize is the ability to customize the Authorization Request with additional parameters above the standard parameters defined in the OAuth 2.0 Authorization Framework. - -For example, OpenID Connect defines additional OAuth 2.0 request parameters for the https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest[Authorization Code Flow] extending from the standard parameters defined in the https://tools.ietf.org/html/rfc6749#section-4.1.1[OAuth 2.0 Authorization Framework]. -One of those extended parameters is the `prompt` parameter. - -[NOTE] -OPTIONAL. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent. The defined values are: none, login, consent, select_account - -The following example shows how to configure the `DefaultOAuth2AuthorizationRequestResolver` with a `Consumer` that customizes the Authorization Request for `oauth2Login()`, by including the request parameter `prompt=consent`. - -==== -.Java -[source,java,role="primary"] ----- -@EnableWebSecurity -public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private ClientRegistrationRepository clientRegistrationRepository; - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests(authorize -> authorize - .anyRequest().authenticated() - ) - .oauth2Login(oauth2 -> oauth2 - .authorizationEndpoint(authorization -> authorization - .authorizationRequestResolver( - authorizationRequestResolver(this.clientRegistrationRepository) - ) - ) - ); - } - - private OAuth2AuthorizationRequestResolver authorizationRequestResolver( - ClientRegistrationRepository clientRegistrationRepository) { - - DefaultOAuth2AuthorizationRequestResolver authorizationRequestResolver = - new DefaultOAuth2AuthorizationRequestResolver( - clientRegistrationRepository, "/oauth2/authorization"); - authorizationRequestResolver.setAuthorizationRequestCustomizer( - authorizationRequestCustomizer()); - - return authorizationRequestResolver; - } - - private Consumer authorizationRequestCustomizer() { - return customizer -> customizer - .additionalParameters(params -> params.put("prompt", "consent")); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@EnableWebSecurity -class SecurityConfig : WebSecurityConfigurerAdapter() { - - @Autowired - private lateinit var customClientRegistrationRepository: ClientRegistrationRepository - - override fun configure(http: HttpSecurity) { - http { - authorizeRequests { - authorize(anyRequest, authenticated) - } - oauth2Login { - authorizationEndpoint { - authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository) - } - } - } - } - - private fun authorizationRequestResolver( - clientRegistrationRepository: ClientRegistrationRepository?): OAuth2AuthorizationRequestResolver? { - val authorizationRequestResolver = DefaultOAuth2AuthorizationRequestResolver( - clientRegistrationRepository, "/oauth2/authorization") - authorizationRequestResolver.setAuthorizationRequestCustomizer( - authorizationRequestCustomizer()) - return authorizationRequestResolver - } - - private fun authorizationRequestCustomizer(): Consumer { - return Consumer { customizer -> - customizer - .additionalParameters { params -> params["prompt"] = "consent" } - } - } -} ----- -==== - -For the simple use case, where the additional request parameter is always the same for a specific provider, it may be added directly in the `authorization-uri` property. - -For example, if the value for the request parameter `prompt` is always `consent` for the provider `okta`, than simply configure as follows: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - provider: - okta: - authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent ----- - -The preceding example shows the common use case of adding a custom parameter on top of the standard parameters. -Alternatively, if your requirements are more advanced, you can take full control in building the Authorization Request URI by simply overriding the `OAuth2AuthorizationRequest.authorizationRequestUri` property. - -[TIP] -`OAuth2AuthorizationRequest.Builder.build()` constructs the `OAuth2AuthorizationRequest.authorizationRequestUri`, which represents the Authorization Request URI including all query parameters using the `application/x-www-form-urlencoded` format. - -The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example, and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property. - -==== -.Java -[source,java,role="primary"] ----- -private Consumer authorizationRequestCustomizer() { - return customizer -> customizer - .authorizationRequestUri(uriBuilder -> uriBuilder - .queryParam("prompt", "consent").build()); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -private fun authorizationRequestCustomizer(): Consumer { - return Consumer { customizer: OAuth2AuthorizationRequest.Builder -> - customizer - .authorizationRequestUri { uriBuilder: UriBuilder -> - uriBuilder - .queryParam("prompt", "consent").build() - } - } -} ----- -==== - - -==== Storing the Authorization Request - -The `AuthorizationRequestRepository` is responsible for the persistence of the `OAuth2AuthorizationRequest` from the time the Authorization Request is initiated to the time the Authorization Response is received (the callback). - -[TIP] -The `OAuth2AuthorizationRequest` is used to correlate and validate the Authorization Response. - -The default implementation of `AuthorizationRequestRepository` is `HttpSessionOAuth2AuthorizationRequestRepository`, which stores the `OAuth2AuthorizationRequest` in the `HttpSession`. - -If you have a custom implementation of `AuthorizationRequestRepository`, you may configure it as shown in the following example: - -.AuthorizationRequestRepository Configuration -==== -.Java -[source,java,role="primary"] ----- -@EnableWebSecurity -public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .oauth2Client(oauth2 -> oauth2 - .authorizationCodeGrant(codeGrant -> codeGrant - .authorizationRequestRepository(this.authorizationRequestRepository()) - ... - ) - ); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@EnableWebSecurity -class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() { - - override fun configure(http: HttpSecurity) { - http { - oauth2Client { - authorizationCodeGrant { - authorizationRequestRepository = authorizationRequestRepository() - } - } - } - } -} ----- - -.Xml -[source,xml,role="secondary"] ----- - - - - - ----- -==== - -==== Requesting an Access Token - -[NOTE] -Please refer to the https://tools.ietf.org/html/rfc6749#section-4.1.3[Access Token Request/Response] protocol flow for the Authorization Code grant. - -The default implementation of `OAuth2AccessTokenResponseClient` for the Authorization Code grant is `DefaultAuthorizationCodeTokenResponseClient`, which uses a `RestOperations` for exchanging an authorization code for an access token at the Authorization Server’s Token Endpoint. - -The `DefaultAuthorizationCodeTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. - - -==== Customizing the Access Token Request - -If you need to customize the pre-processing of the Token Request, you can provide `DefaultAuthorizationCodeTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. -The default implementation `OAuth2AuthorizationCodeGrantRequestEntityConverter` builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.1.3[OAuth 2.0 Access Token Request]. -However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s). - -IMPORTANT: The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. - - -==== Customizing the Access Token Response - -On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultAuthorizationCodeTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. -The default `RestOperations` is configured as follows: - -==== -.Java -[source,java,role="primary"] ----- -RestTemplate restTemplate = new RestTemplate(Arrays.asList( - new FormHttpMessageConverter(), - new OAuth2AccessTokenResponseHttpMessageConverter())); - -restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val restTemplate = RestTemplate(listOf( - FormHttpMessageConverter(), - OAuth2AccessTokenResponseHttpMessageConverter())) - -restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() ----- -==== - -TIP: Spring MVC `FormHttpMessageConverter` is required as it's used when sending the OAuth 2.0 Access Token Request. - -`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response. -You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used for converting the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. - -`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, eg. 400 Bad Request. -It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`. - -Whether you customize `DefaultAuthorizationCodeTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example: - -.Access Token Response Configuration -==== -.Java -[source,java,role="primary"] ----- -@EnableWebSecurity -public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .oauth2Client(oauth2 -> oauth2 - .authorizationCodeGrant(codeGrant -> codeGrant - .accessTokenResponseClient(this.accessTokenResponseClient()) - ... - ) - ); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@EnableWebSecurity -class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() { - - override fun configure(http: HttpSecurity) { - http { - oauth2Client { - authorizationCodeGrant { - accessTokenResponseClient = accessTokenResponseClient() - } - } - } - } -} ----- - -.Xml -[source,xml,role="secondary"] ----- - - - - - ----- -==== - - -[[oauth2Client-refresh-token-grant]] -=== Refresh Token - -[NOTE] -Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.5[Refresh Token]. - - -==== Refreshing an Access Token - -[NOTE] -Please refer to the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant. - -The default implementation of `OAuth2AccessTokenResponseClient` for the Refresh Token grant is `DefaultRefreshTokenTokenResponseClient`, which uses a `RestOperations` when refreshing an access token at the Authorization Server’s Token Endpoint. - -The `DefaultRefreshTokenTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. - - -==== Customizing the Access Token Request - -If you need to customize the pre-processing of the Token Request, you can provide `DefaultRefreshTokenTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. -The default implementation `OAuth2RefreshTokenGrantRequestEntityConverter` builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-6[OAuth 2.0 Access Token Request]. -However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s). - -IMPORTANT: The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. - - -==== Customizing the Access Token Response - -On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultRefreshTokenTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. -The default `RestOperations` is configured as follows: - -==== -.Java -[source,java,role="primary"] ----- -RestTemplate restTemplate = new RestTemplate(Arrays.asList( - new FormHttpMessageConverter(), - new OAuth2AccessTokenResponseHttpMessageConverter())); - -restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val restTemplate = RestTemplate(listOf( - FormHttpMessageConverter(), - OAuth2AccessTokenResponseHttpMessageConverter())) - -restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() ----- -==== - -TIP: Spring MVC `FormHttpMessageConverter` is required as it's used when sending the OAuth 2.0 Access Token Request. - -`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response. -You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used for converting the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. - -`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, eg. 400 Bad Request. -It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`. - -Whether you customize `DefaultRefreshTokenTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example: - -==== -.Java -[source,java,role="primary"] ----- -// Customize -OAuth2AccessTokenResponseClient refreshTokenTokenResponseClient = ... - -OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient)) - .build(); - -... - -authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -// Customize -val refreshTokenTokenResponseClient: OAuth2AccessTokenResponseClient = ... - -val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) } - .build() - -... - -authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) ----- -==== - -[NOTE] -`OAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenOAuth2AuthorizedClientProvider`, -which is an implementation of an `OAuth2AuthorizedClientProvider` for the Refresh Token grant. - -The `OAuth2RefreshToken` may optionally be returned in the Access Token Response for the `authorization_code` and `password` grant types. -If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2AuthorizedClient.getAccessToken()` is expired, it will automatically be refreshed by the `RefreshTokenOAuth2AuthorizedClientProvider`. - - -[[oauth2Client-client-creds-grant]] -=== Client Credentials - -[NOTE] -Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] grant. - - -==== Requesting an Access Token - -[NOTE] -Please refer to the https://tools.ietf.org/html/rfc6749#section-4.4.2[Access Token Request/Response] protocol flow for the Client Credentials grant. - -The default implementation of `OAuth2AccessTokenResponseClient` for the Client Credentials grant is `DefaultClientCredentialsTokenResponseClient`, which uses a `RestOperations` when requesting an access token at the Authorization Server’s Token Endpoint. - -The `DefaultClientCredentialsTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. - - -==== Customizing the Access Token Request - -If you need to customize the pre-processing of the Token Request, you can provide `DefaultClientCredentialsTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. -The default implementation `OAuth2ClientCredentialsGrantRequestEntityConverter` builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.4.2[OAuth 2.0 Access Token Request]. -However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s). - -IMPORTANT: The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. - - -==== Customizing the Access Token Response - -On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultClientCredentialsTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. -The default `RestOperations` is configured as follows: - -==== -.Java -[source,java,role="primary"] ----- -RestTemplate restTemplate = new RestTemplate(Arrays.asList( - new FormHttpMessageConverter(), - new OAuth2AccessTokenResponseHttpMessageConverter())); - -restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val restTemplate = RestTemplate(listOf( - FormHttpMessageConverter(), - OAuth2AccessTokenResponseHttpMessageConverter())) - -restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() ----- -==== - -TIP: Spring MVC `FormHttpMessageConverter` is required as it's used when sending the OAuth 2.0 Access Token Request. - -`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response. -You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used for converting the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. - -`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, eg. 400 Bad Request. -It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`. - -Whether you customize `DefaultClientCredentialsTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example: - -==== -.Java -[source,java,role="primary"] ----- -// Customize -OAuth2AccessTokenResponseClient clientCredentialsTokenResponseClient = ... - -OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient)) - .build(); - -... - -authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -// Customize -val clientCredentialsTokenResponseClient: OAuth2AccessTokenResponseClient = ... - -val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) } - .build() - -... - -authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) ----- -==== - -[NOTE] -`OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsOAuth2AuthorizedClientProvider`, -which is an implementation of an `OAuth2AuthorizedClientProvider` for the Client Credentials grant. - -==== Using the Access Token - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-secret: okta-client-secret - authorization-grant-type: client_credentials - scope: read, write - provider: - okta: - token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token ----- - -...and the `OAuth2AuthorizedClientManager` `@Bean`: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials() - .build(); - - DefaultOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { - val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials() - .build() - val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - -You may obtain the `OAuth2AccessToken` as follows: - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @Autowired - private OAuth2AuthorizedClientManager authorizedClientManager; - - @GetMapping("/") - public String index(Authentication authentication, - HttpServletRequest servletRequest, - HttpServletResponse servletResponse) { - - OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") - .principal(authentication) - .attributes(attrs -> { - attrs.put(HttpServletRequest.class.getName(), servletRequest); - attrs.put(HttpServletResponse.class.getName(), servletResponse); - }) - .build(); - OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); - - OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); - - ... - - return "index"; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -class OAuth2ClientController { - - @Autowired - private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager - - @GetMapping("/") - fun index(authentication: Authentication?, - servletRequest: HttpServletRequest, - servletResponse: HttpServletResponse): String { - val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") - .principal(authentication) - .attributes(Consumer { attrs: MutableMap -> - attrs[HttpServletRequest::class.java.name] = servletRequest - attrs[HttpServletResponse::class.java.name] = servletResponse - }) - .build() - val authorizedClient = authorizedClientManager.authorize(authorizeRequest) - val accessToken: OAuth2AccessToken = authorizedClient.accessToken - - ... - - return "index" - } -} ----- -==== - -[NOTE] -`HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes. -If not provided, it will default to `ServletRequestAttributes` using `RequestContextHolder.getRequestAttributes()`. - - -[[oauth2Client-password-grant]] -=== Resource Owner Password Credentials - -[NOTE] -Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] grant. - - -==== Requesting an Access Token - -[NOTE] -Please refer to the https://tools.ietf.org/html/rfc6749#section-4.3.2[Access Token Request/Response] protocol flow for the Resource Owner Password Credentials grant. - -The default implementation of `OAuth2AccessTokenResponseClient` for the Resource Owner Password Credentials grant is `DefaultPasswordTokenResponseClient`, which uses a `RestOperations` when requesting an access token at the Authorization Server’s Token Endpoint. - -The `DefaultPasswordTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. - - -==== Customizing the Access Token Request - -If you need to customize the pre-processing of the Token Request, you can provide `DefaultPasswordTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. -The default implementation `OAuth2PasswordGrantRequestEntityConverter` builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.3.2[OAuth 2.0 Access Token Request]. -However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s). - -IMPORTANT: The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. - - -==== Customizing the Access Token Response - -On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultPasswordTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. -The default `RestOperations` is configured as follows: - -==== -.Java -[source,java,role="primary"] ----- -RestTemplate restTemplate = new RestTemplate(Arrays.asList( - new FormHttpMessageConverter(), - new OAuth2AccessTokenResponseHttpMessageConverter())); - -restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val restTemplate = RestTemplate(listOf( - FormHttpMessageConverter(), - OAuth2AccessTokenResponseHttpMessageConverter())) - -restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() ----- -==== - -TIP: Spring MVC `FormHttpMessageConverter` is required as it's used when sending the OAuth 2.0 Access Token Request. - -`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response. -You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used for converting the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. - -`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, eg. 400 Bad Request. -It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`. - -Whether you customize `DefaultPasswordTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example: - -==== -.Java -[source,java,role="primary"] ----- -// Customize -OAuth2AccessTokenResponseClient passwordTokenResponseClient = ... - -OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient)) - .refreshToken() - .build(); - -... - -authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val passwordTokenResponseClient: OAuth2AccessTokenResponseClient = ... - -val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .password { it.accessTokenResponseClient(passwordTokenResponseClient) } - .refreshToken() - .build() - -... - -authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) ----- -==== - -[NOTE] -`OAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordOAuth2AuthorizedClientProvider`, -which is an implementation of an `OAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant. - -==== Using the Access Token - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-secret: okta-client-secret - authorization-grant-type: password - scope: read, write - provider: - okta: - token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token ----- - -...and the `OAuth2AuthorizedClientManager` `@Bean`: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .password() - .refreshToken() - .build(); - - DefaultOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters, - // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` - authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()); - - return authorizedClientManager; -} - -private Function> contextAttributesMapper() { - return authorizeRequest -> { - Map contextAttributes = Collections.emptyMap(); - HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName()); - String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME); - String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD); - if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - contextAttributes = new HashMap<>(); - - // `PasswordOAuth2AuthorizedClientProvider` requires both attributes - contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username); - contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password); - } - return contextAttributes; - }; -} ----- -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { - val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .password() - .refreshToken() - .build() - val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - - // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters, - // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` - authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()) - return authorizedClientManager -} - -private fun contextAttributesMapper(): Function> { - return Function { authorizeRequest -> - var contextAttributes: MutableMap = mutableMapOf() - val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name) - val username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME) - val password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD) - if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - contextAttributes = hashMapOf() - - // `PasswordOAuth2AuthorizedClientProvider` requires both attributes - contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username - contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password - } - contextAttributes - } -} ----- -==== - -You may obtain the `OAuth2AccessToken` as follows: - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @Autowired - private OAuth2AuthorizedClientManager authorizedClientManager; - - @GetMapping("/") - public String index(Authentication authentication, - HttpServletRequest servletRequest, - HttpServletResponse servletResponse) { - - OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") - .principal(authentication) - .attributes(attrs -> { - attrs.put(HttpServletRequest.class.getName(), servletRequest); - attrs.put(HttpServletResponse.class.getName(), servletResponse); - }) - .build(); - OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); - - OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); - - ... - - return "index"; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - @Autowired - private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager - - @GetMapping("/") - fun index(authentication: Authentication?, - servletRequest: HttpServletRequest, - servletResponse: HttpServletResponse): String { - val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") - .principal(authentication) - .attributes(Consumer { - it[HttpServletRequest::class.java.name] = servletRequest - it[HttpServletResponse::class.java.name] = servletResponse - }) - .build() - val authorizedClient = authorizedClientManager.authorize(authorizeRequest) - val accessToken: OAuth2AccessToken = authorizedClient.accessToken - - ... - - return "index" - } -} ----- -==== - -[NOTE] -`HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes. -If not provided, it will default to `ServletRequestAttributes` using `RequestContextHolder.getRequestAttributes()`. - - -[[oauth2Client-jwt-bearer-grant]] -=== JWT Bearer - -[NOTE] -Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on the https://datatracker.ietf.org/doc/html/rfc7523[JWT Bearer] grant. - - -==== Requesting an Access Token - -[NOTE] -Please refer to the https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[Access Token Request/Response] protocol flow for the JWT Bearer grant. - -The default implementation of `OAuth2AccessTokenResponseClient` for the JWT Bearer grant is `DefaultJwtBearerTokenResponseClient`, which uses a `RestOperations` when requesting an access token at the Authorization Server’s Token Endpoint. - -The `DefaultJwtBearerTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. - - -==== Customizing the Access Token Request - -If you need to customize the pre-processing of the Token Request, you can provide `DefaultJwtBearerTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. -The default implementation `JwtBearerGrantRequestEntityConverter` builds a `RequestEntity` representation of a https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[OAuth 2.0 Access Token Request]. -However, providing a custom `Converter`, would allow you to extend the Token Request and add custom parameter(s). - - -==== Customizing the Access Token Response - -On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultJwtBearerTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. -The default `RestOperations` is configured as follows: - -==== -.Java -[source,java,role="primary"] ----- -RestTemplate restTemplate = new RestTemplate(Arrays.asList( - new FormHttpMessageConverter(), - new OAuth2AccessTokenResponseHttpMessageConverter())); - -restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val restTemplate = RestTemplate(listOf( - FormHttpMessageConverter(), - OAuth2AccessTokenResponseHttpMessageConverter())) - -restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler() ----- -==== - -TIP: Spring MVC `FormHttpMessageConverter` is required as it's used when sending the OAuth 2.0 Access Token Request. - -`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response. -You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()` with a custom `Converter, OAuth2AccessTokenResponse>` that is used for converting the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`. - -`OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, eg. 400 Bad Request. -It uses an `OAuth2ErrorHttpMessageConverter` for converting the OAuth 2.0 Error parameters to an `OAuth2Error`. - -Whether you customize `DefaultJwtBearerTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example: - -==== -.Java -[source,java,role="primary"] ----- -// Customize -OAuth2AccessTokenResponseClient jwtBearerTokenResponseClient = ... - -JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider(); -jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient); - -OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .provider(jwtBearerAuthorizedClientProvider) - .build(); - -... - -authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -// Customize -val jwtBearerTokenResponseClient: OAuth2AccessTokenResponseClient = ... - -val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider() -jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient); - -val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .provider(jwtBearerAuthorizedClientProvider) - .build() - -... - -authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) ----- -==== - -==== Using the Access Token - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-secret: okta-client-secret - authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer - scope: read - provider: - okta: - token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token ----- - -...and the `OAuth2AuthorizedClientManager` `@Bean`: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { - - JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = - new JwtBearerOAuth2AuthorizedClientProvider(); - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .provider(jwtBearerAuthorizedClientProvider) - .build(); - - DefaultOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { - val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider() - val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .provider(jwtBearerAuthorizedClientProvider) - .build() - val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - -You may obtain the `OAuth2AccessToken` as follows: - -==== -.Java -[source,java,role="primary"] ----- -@RestController -public class OAuth2ResourceServerController { - - @Autowired - private OAuth2AuthorizedClientManager authorizedClientManager; - - @GetMapping("/resource") - public String resource(JwtAuthenticationToken jwtAuthentication) { - OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") - .principal(jwtAuthentication) - .build(); - OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest); - OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); - - ... - - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -class OAuth2ResourceServerController { - - @Autowired - private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager - - @GetMapping("/resource") - fun resource(jwtAuthentication: JwtAuthenticationToken?): String { - val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") - .principal(jwtAuthentication) - .build() - val authorizedClient = authorizedClientManager.authorize(authorizeRequest) - val accessToken: OAuth2AccessToken = authorizedClient.accessToken - - ... - - } -} ----- -==== - - -[[oauth2Client-client-auth-support]] -== Client Authentication Support - - -[[oauth2Client-jwt-bearer-auth]] -=== JWT Bearer - -[NOTE] -Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] Client Authentication. - -The default implementation for JWT Bearer Client Authentication is `NimbusJwtClientAuthenticationParametersConverter`, -which is a `Converter` that customizes the Token Request parameters by adding -a signed JSON Web Token (JWS) in the `client_assertion` parameter. - -The `java.security.PrivateKey` or `javax.crypto.SecretKey` used for signing the JWS -is supplied by the `com.nimbusds.jose.jwk.JWK` resolver associated with `NimbusJwtClientAuthenticationParametersConverter`. - - -==== Authenticate using `private_key_jwt` - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-authentication-method: private_key_jwt - authorization-grant-type: authorization_code - ... ----- - -The following example shows how to configure `DefaultAuthorizationCodeTokenResponseClient`: - -==== -.Java -[source,java,role="primary"] ----- -Function jwkResolver = (clientRegistration) -> { - if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { - // Assuming RSA key type - RSAPublicKey publicKey = ... - RSAPrivateKey privateKey = ... - return new RSAKey.Builder(publicKey) - .privateKey(privateKey) - .keyID(UUID.randomUUID().toString()) - .build(); - } - return null; -}; - -OAuth2AuthorizationCodeGrantRequestEntityConverter requestEntityConverter = - new OAuth2AuthorizationCodeGrantRequestEntityConverter(); -requestEntityConverter.addParametersConverter( - new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); - -DefaultAuthorizationCodeTokenResponseClient tokenResponseClient = - new DefaultAuthorizationCodeTokenResponseClient(); -tokenResponseClient.setRequestEntityConverter(requestEntityConverter); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val jwkResolver: Function = - Function { clientRegistration -> - if (clientRegistration.clientAuthenticationMethod.equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { - // Assuming RSA key type - var publicKey: RSAPublicKey - var privateKey: RSAPrivateKey - RSAKey.Builder(publicKey) = //... - .privateKey(privateKey) = //... - .keyID(UUID.randomUUID().toString()) - .build() - } - null - } - -val requestEntityConverter = OAuth2AuthorizationCodeGrantRequestEntityConverter() -requestEntityConverter.addParametersConverter( - NimbusJwtClientAuthenticationParametersConverter(jwkResolver) -) - -val tokenResponseClient = DefaultAuthorizationCodeTokenResponseClient() -tokenResponseClient.setRequestEntityConverter(requestEntityConverter) ----- -==== - - -==== Authenticate using `client_secret_jwt` - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-secret: okta-client-secret - client-authentication-method: client_secret_jwt - authorization-grant-type: client_credentials - ... ----- - -The following example shows how to configure `DefaultClientCredentialsTokenResponseClient`: - -==== -.Java -[source,java,role="primary"] ----- -Function jwkResolver = (clientRegistration) -> { - if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_JWT)) { - SecretKeySpec secretKey = new SecretKeySpec( - clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), - "HmacSHA256"); - return new OctetSequenceKey.Builder(secretKey) - .keyID(UUID.randomUUID().toString()) - .build(); - } - return null; -}; - -OAuth2ClientCredentialsGrantRequestEntityConverter requestEntityConverter = - new OAuth2ClientCredentialsGrantRequestEntityConverter(); -requestEntityConverter.addParametersConverter( - new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); - -DefaultClientCredentialsTokenResponseClient tokenResponseClient = - new DefaultClientCredentialsTokenResponseClient(); -tokenResponseClient.setRequestEntityConverter(requestEntityConverter); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val jwkResolver = Function { clientRegistration: ClientRegistration -> - if (clientRegistration.clientAuthenticationMethod == ClientAuthenticationMethod.CLIENT_SECRET_JWT) { - val secretKey = SecretKeySpec( - clientRegistration.clientSecret.toByteArray(StandardCharsets.UTF_8), - "HmacSHA256" - ) - OctetSequenceKey.Builder(secretKey) - .keyID(UUID.randomUUID().toString()) - .build() - } - null -} - -val requestEntityConverter = OAuth2ClientCredentialsGrantRequestEntityConverter() -requestEntityConverter.addParametersConverter( - NimbusJwtClientAuthenticationParametersConverter(jwkResolver) -) - -val tokenResponseClient = DefaultClientCredentialsTokenResponseClient() -tokenResponseClient.setRequestEntityConverter(requestEntityConverter) ----- -==== - - -[[oauth2Client-additional-features]] -== Additional Features - - -[[oauth2Client-registered-authorized-client]] -=== Resolving an Authorized Client - -The `@RegisteredOAuth2AuthorizedClient` annotation provides the capability of resolving a method parameter to an argument value of type `OAuth2AuthorizedClient`. -This is a convenient alternative compared to accessing the `OAuth2AuthorizedClient` using the `OAuth2AuthorizedClientManager` or `OAuth2AuthorizedClientService`. - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @GetMapping("/") - public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { - OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); - - ... - - return "index"; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - @GetMapping("/") - fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String { - val accessToken = authorizedClient.accessToken - - ... - - return "index" - } -} ----- -==== - -The `@RegisteredOAuth2AuthorizedClient` annotation is handled by `OAuth2AuthorizedClientArgumentResolver`, which directly uses an <> and therefore inherits it's capabilities. - - -[[oauth2Client-webclient-servlet]] -== WebClient integration for Servlet Environments - -The OAuth 2.0 Client support integrates with `WebClient` using an `ExchangeFilterFunction`. - -The `ServletOAuth2AuthorizedClientExchangeFilterFunction` provides a simple mechanism for requesting protected resources by using an `OAuth2AuthorizedClient` and including the associated `OAuth2AccessToken` as a Bearer Token. -It directly uses an <> and therefore inherits the following capabilities: - -* An `OAuth2AccessToken` will be requested if the client has not yet been authorized. -** `authorization_code` - triggers the Authorization Request redirect to initiate the flow -** `client_credentials` - the access token is obtained directly from the Token Endpoint -** `password` - the access token is obtained directly from the Token Endpoint -* If the `OAuth2AccessToken` is expired, it will be refreshed (or renewed) if an `OAuth2AuthorizedClientProvider` is available to perform the authorization - -The following code shows an example of how to configure `WebClient` with OAuth 2.0 Client support: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { - ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = - new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { - val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build() -} ----- -==== - -=== Providing the Authorized Client - -The `ServletOAuth2AuthorizedClientExchangeFilterFunction` determines the client to use (for a request) by resolving the `OAuth2AuthorizedClient` from the `ClientRequest.attributes()` (request attributes). - -The following code shows how to set an `OAuth2AuthorizedClient` as a request attribute: - -==== -.Java -[source,java,role="primary"] ----- -@GetMapping("/") -public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { - String resourceUri = ... - - String body = webClient - .get() - .uri(resourceUri) - .attributes(oauth2AuthorizedClient(authorizedClient)) <1> - .retrieve() - .bodyToMono(String.class) - .block(); - - ... - - return "index"; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@GetMapping("/") -fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String { - val resourceUri: String = ... - val body: String = webClient - .get() - .uri(resourceUri) - .attributes(oauth2AuthorizedClient(authorizedClient)) <1> - .retrieve() - .bodyToMono() - .block() - - ... - - return "index" -} ----- -==== - -<1> `oauth2AuthorizedClient()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. - -The following code shows how to set the `ClientRegistration.getRegistrationId()` as a request attribute: - -==== -.Java -[source,java,role="primary"] ----- -@GetMapping("/") -public String index() { - String resourceUri = ... - - String body = webClient - .get() - .uri(resourceUri) - .attributes(clientRegistrationId("okta")) <1> - .retrieve() - .bodyToMono(String.class) - .block(); - - ... - - return "index"; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@GetMapping("/") -fun index(): String { - val resourceUri: String = ... - - val body: String = webClient - .get() - .uri(resourceUri) - .attributes(clientRegistrationId("okta")) <1> - .retrieve() - .bodyToMono() - .block() - - ... - - return "index" -} ----- -==== -<1> `clientRegistrationId()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. - - -=== Defaulting the Authorized Client - -If neither `OAuth2AuthorizedClient` or `ClientRegistration.getRegistrationId()` is provided as a request attribute, the `ServletOAuth2AuthorizedClientExchangeFilterFunction` can determine the _default_ client to use depending on it's configuration. - -If `setDefaultOAuth2AuthorizedClient(true)` is configured and the user has authenticated using `HttpSecurity.oauth2Login()`, the `OAuth2AccessToken` associated with the current `OAuth2AuthenticationToken` is used. - -The following code shows the specific configuration: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { - ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = - new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); - oauth2Client.setDefaultOAuth2AuthorizedClient(true); - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { - val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) - oauth2Client.setDefaultOAuth2AuthorizedClient(true) - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build() -} ----- -==== - -[WARNING] -It is recommended to be cautious with this feature since all HTTP requests will receive the access token. - -Alternatively, if `setDefaultClientRegistrationId("okta")` is configured with a valid `ClientRegistration`, the `OAuth2AccessToken` associated with the `OAuth2AuthorizedClient` is used. - -The following code shows the specific configuration: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { - ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = - new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); - oauth2Client.setDefaultClientRegistrationId("okta"); - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { - val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) - oauth2Client.setDefaultClientRegistrationId("okta") - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build() -} ----- -==== - -[WARNING] -It is recommended to be cautious with this feature since all HTTP requests will receive the access token. diff --git a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/bearer-tokens.adoc b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/bearer-tokens.adoc index 9c35a4b87db..a9a1877affe 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/bearer-tokens.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/bearer-tokens.adoc @@ -241,7 +241,7 @@ fun rest(): RestTemplate { [NOTE] Unlike the {security-api-url}org/springframework/security/oauth2/client/OAuth2AuthorizedClientManager.html[OAuth 2.0 Authorized Client Manager], this filter interceptor makes no attempt to renew the token, should it be expired. -To obtain this level of support, please create an interceptor using the xref:servlet/oauth2/oauth2-client.adoc#oauth2client[OAuth 2.0 Authorized Client Manager]. +To obtain this level of support, please create an interceptor using the xref:servlet/oauth2/client/index.adoc#oauth2client[OAuth 2.0 Authorized Client Manager]. [[oauth2resourceserver-bearertoken-failure]] == Bearer Token Failure diff --git a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/index.adoc b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/index.adoc index 1633c5bacf8..52e991a0f44 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/index.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/index.adoc @@ -2,7 +2,7 @@ = OAuth 2.0 Resource Server :figures: servlet/oauth2 -Spring Security supports protecting endpoints using two forms of OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens]: +Spring Security supports protecting endpoints by using two forms of OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens]: * https://tools.ietf.org/html/rfc7519[JWT] * Opaque Tokens @@ -10,31 +10,31 @@ Spring Security supports protecting endpoints using two forms of OAuth 2.0 https This is handy in circumstances where an application has delegated its authority management to an https://tools.ietf.org/html/rfc6749[authorization server] (for example, Okta or Ping Identity). This authorization server can be consulted by resource servers to authorize requests. -This section provides details on how Spring Security provides support for OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens]. +This section details how Spring Security provides support for OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens]. [NOTE] ==== Working samples for both {gh-samples-url}/servlet/spring-boot/java/oauth2/resource-server/jwe[JWTs] and {gh-samples-url}/servlet/spring-boot/java/oauth2/resource-server/opaque[Opaque Tokens] are available in the {gh-samples-url}[Spring Security Samples repository]. ==== -Let's take a look at how Bearer Token Authentication works within Spring Security. -First, we see that, like xref:servlet/authentication/passwords/basic.adoc#servlet-authentication-basic[Basic Authentication], the https://tools.ietf.org/html/rfc7235#section-4.1[WWW-Authenticate] header is sent back to an unauthenticated client. +Now we can consider how Bearer Token Authentication works within Spring Security. +First, we see that, as with xref:servlet/authentication/passwords/basic.adoc#servlet-authentication-basic[Basic Authentication], the https://tools.ietf.org/html/rfc7235#section-4.1[WWW-Authenticate] header is sent back to an unauthenticated client: .Sending WWW-Authenticate Header image::{figures}/bearerauthenticationentrypoint.png[] The figure above builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram. -image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized. +image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the `/private` resource for which the user is not authorized. -image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`. +image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is _Denied_ by throwing an `AccessDeniedException`. -image:{icondir}/number_3.png[] Since the user is not authenticated, xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__. -The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.html[`BearerTokenAuthenticationEntryPoint`] which sends a WWW-Authenticate header. -The `RequestCache` is typically a `NullRequestCache` that does not save the request since the client is capable of replaying the requests it originally requested. +image:{icondir}/number_3.png[] Since the user is not authenticated, xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates _Start Authentication_. +The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationEntryPoint.html[`BearerTokenAuthenticationEntryPoint`], which sends a `WWW-Authenticate` header. +The `RequestCache` is typically a `NullRequestCache` that does not save the request, since the client is capable of replaying the requests it originally requested. When a client receives the `WWW-Authenticate: Bearer` header, it knows it should retry with a bearer token. -Below is the flow for the bearer token being processed. +The following image shows the flow for the bearer token being processed: [[oauth2resourceserver-authentication-bearertokenauthenticationfilter]] .Authenticating Bearer Token diff --git a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/jwt.adoc b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/jwt.adoc index 64ebfda12f1..5a6d0ffee53 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/jwt.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/jwt.adoc @@ -146,7 +146,7 @@ The first is a `WebSecurityConfigurerAdapter` that configures the app as a resou ---- protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); @@ -182,7 +182,7 @@ Replacing this is as simple as exposing the bean within the application: public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read") .anyRequest().authenticated() ) @@ -299,7 +299,7 @@ An authorization server's JWK Set Uri can be configured < authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 @@ -359,7 +359,7 @@ More powerful than `jwkSetUri()` is `decoder()`, which will completely replace a public class DirectlyConfiguredJwtDecoder extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 @@ -719,7 +719,7 @@ This means that to protect an endpoint or method with a scope derived from a JWT public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts") .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages") .anyRequest().authenticated() @@ -926,7 +926,7 @@ static class CustomAuthenticationConverter implements Converter authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 diff --git a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/multitenancy.adoc b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/multitenancy.adoc index 07f804d5cc0..bfd53945432 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/multitenancy.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/multitenancy.adoc @@ -53,7 +53,7 @@ And then specify this `AuthenticationManagerResolver` in the DSL: [source,java,role="primary"] ---- http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 @@ -109,7 +109,7 @@ JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIs ("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo"); http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 @@ -176,7 +176,7 @@ JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver(authenticationManagers::get); http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 diff --git a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/opaque-token.adoc b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/opaque-token.adoc index 4e0c618599c..acccfbc16fa 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/opaque-token.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/opaque-token.adoc @@ -188,7 +188,7 @@ When use Opaque Token, this `WebSecurityConfigurerAdapter` looks like: ---- protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken); @@ -224,7 +224,7 @@ Replacing this is as simple as exposing the bean within the application: public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read") .anyRequest().authenticated() ) @@ -338,7 +338,7 @@ An authorization server's Introspection Uri can be configured < authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 @@ -400,7 +400,7 @@ More powerful than `introspectionUri()` is `introspector()`, which will complete public class DirectlyConfiguredIntrospector extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 @@ -479,7 +479,7 @@ This means that to protect an endpoint or method with a scope derived from an Op public class MappedAuthorities extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http - .authorizeRequests(authorizeRequests -> authorizeRequests + .authorizeHttpRequests(authorizeRequests -> authorizeRequests .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts") .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages") .anyRequest().authenticated() diff --git a/docs/modules/ROOT/pages/servlet/saml2/login/authentication.adoc b/docs/modules/ROOT/pages/servlet/saml2/login/authentication.adoc index 2d6efa7ab2c..65edf60069c 100644 --- a/docs/modules/ROOT/pages/servlet/saml2/login/authentication.adoc +++ b/docs/modules/ROOT/pages/servlet/saml2/login/authentication.adoc @@ -38,7 +38,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ); http - .authorizeRequests(authz -> authz + .authorizeHttpRequests(authz -> authz .anyRequest().authenticated() ) .saml2Login(saml2 -> saml2 @@ -106,7 +106,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { }); http - .authorizeRequests(authz -> authz + .authorizeHttpRequests(authz -> authz .anyRequest().authenticated() ) .saml2Login(saml2 -> saml2 @@ -310,7 +310,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { AuthenticationManager authenticationManager = new MySaml2AuthenticationManager(...); http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .saml2Login(saml2 -> saml2 diff --git a/docs/modules/ROOT/pages/servlet/saml2/login/index.adoc b/docs/modules/ROOT/pages/servlet/saml2/login/index.adoc index 30b8a715e69..f6a133a6c7d 100644 --- a/docs/modules/ROOT/pages/servlet/saml2/login/index.adoc +++ b/docs/modules/ROOT/pages/servlet/saml2/login/index.adoc @@ -2,10 +2,13 @@ = SAML 2.0 Login :page-section-summary-toc: 1 -The SAML 2.0 Login feature provides an application with the capability to act as a SAML 2.0 Relying Party, having users https://wiki.shibboleth.net/confluence/display/CONCEPT/FlowsAndConfig[log in] to the application by using their existing account at a SAML 2.0 Asserting Party (Okta, ADFS, etc). +The SAML 2.0 Login feature provides an application with the ability to act as a SAML 2.0 relying party, having users https://wiki.shibboleth.net/confluence/display/CONCEPT/FlowsAndConfig[log in] to the application by using their existing account at a SAML 2.0 Asserting Party (Okta, ADFS, and others). -NOTE: SAML 2.0 Login is implemented by using the *Web Browser SSO Profile*, as specified in +[NOTE] +==== +SAML 2.0 Login is implemented by using the *Web Browser SSO Profile*, as specified in https://www.oasis-open.org/committees/download.php/35389/sstc-saml-profiles-errata-2.0-wd-06-diff.pdf#page=15[SAML 2 Profiles]. +==== [[servlet-saml2login-spring-security-history]] Since 2009, support for relying parties has existed as an https://github.com/spring-projects/spring-security-saml/tree/1e013b07a7772defd6a26fcfae187c9bf661ee8f#spring-saml[extension project]. diff --git a/docs/modules/ROOT/pages/servlet/saml2/login/overview.adoc b/docs/modules/ROOT/pages/servlet/saml2/login/overview.adoc index e7198c64f9c..6374500e2e4 100644 --- a/docs/modules/ROOT/pages/servlet/saml2/login/overview.adoc +++ b/docs/modules/ROOT/pages/servlet/saml2/login/overview.adoc @@ -2,50 +2,58 @@ :figures: servlet/saml2 :icondir: icons -Let's take a look at how SAML 2.0 Relying Party Authentication works within Spring Security. -First, we see that, like xref:servlet/oauth2/oauth2-login.adoc[OAuth 2.0 Login], Spring Security takes the user to a third-party for performing authentication. -It does this through a series of redirects. +We start by examining how SAML 2.0 Relying Party Authentication works within Spring Security. +First, we see that, like <>, Spring Security takes the user to a third party for performing authentication. +It does this through a series of redirects: .Redirecting to Asserting Party Authentication image::{figures}/saml2webssoauthenticationrequestfilter.png[] +[NOTE] +==== The figure above builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] and xref:servlet/authentication/architecture.adoc#servlet-authentication-abstractprocessingfilter[`AbstractAuthenticationProcessingFilter`] diagrams: +==== -image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized. +image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the `/private` resource, for which it is not authorized. -image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`. +image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is _Denied_ by throwing an `AccessDeniedException`. -image:{icondir}/number_3.png[] Since the user lacks authorization, the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__. -The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html[`LoginUrlAuthenticationEntryPoint`] which redirects to xref:servlet/saml2/login/authentication-requests.adoc#servlet-saml2login-sp-initiated-factory[the `` generating endpoint], `Saml2WebSsoAuthenticationRequestFilter`. -Or, if you've <>, it will first redirect to a picker page. +image:{icondir}/number_3.png[] Since the user lacks authorization, the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates _Start Authentication_. +The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html[`LoginUrlAuthenticationEntryPoint`], which redirects to <` generating endpoint>>, `Saml2WebSsoAuthenticationRequestFilter`. +Alternatively, if you have <>, it first redirects to a picker page. image:{icondir}/number_4.png[] Next, the `Saml2WebSsoAuthenticationRequestFilter` creates, signs, serializes, and encodes a `` using its configured <>. -image:{icondir}/number_5.png[] Then, the browser takes this `` and presents it to the asserting party. -The asserting party attempts to authentication the user. -If successful, it will return a `` back to the browser. +image:{icondir}/number_5.png[] Then the browser takes this `` and presents it to the asserting party. +The asserting party tries to authentication the user. +If successful, it returns a `` back to the browser. image:{icondir}/number_6.png[] The browser then POSTs the `` to the assertion consumer service endpoint. +The following image shows how Spring Security authenticates a ``. + [[servlet-saml2login-authentication-saml2webssoauthenticationfilter]] .Authenticating a `` image::{figures}/saml2webssoauthenticationfilter.png[] +[NOTE] +==== The figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram. +==== image:{icondir}/number_1.png[] When the browser submits a `` to the application, it xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-authenticate-responses[delegates to `Saml2WebSsoAuthenticationFilter`]. This filter calls its configured `AuthenticationConverter` to create a `Saml2AuthenticationToken` by extracting the response from the `HttpServletRequest`. This converter additionally resolves the <> and supplies it to `Saml2AuthenticationToken`. image:{icondir}/number_2.png[] Next, the filter passes the token to its configured xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`]. -By default, it will use the <>. +By default, it uses the <>. -image:{icondir}/number_3.png[] If authentication fails, then __Failure__ +image:{icondir}/number_3.png[] If authentication fails, then _Failure_. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] is cleared out. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is invoked to restart the authentication process. -image:{icondir}/number_4.png[] If authentication is successful, then __Success__. +image:{icondir}/number_4.png[] If authentication is successful, then _Success_. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`]. * The `Saml2WebSsoAuthenticationFilter` invokes `FilterChain#doFilter(request,response)` to continue with the rest of the application logic. @@ -59,16 +67,19 @@ It builds off of the OpenSAML library. [[servlet-saml2login-minimalconfiguration]] == Minimal Configuration -When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a service provider consists of two basic steps. -First, include the needed dependencies and second, indicate the necessary asserting party metadata. +When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a service provider consists of two basic steps: +. Include the needed dependencies. +. Indicate the necessary asserting party metadata. [NOTE] -Also, this presupposes that you've already xref:servlet/saml2/metadata.adoc#servlet-saml2login-metadata[registered the relying party with your asserting party]. +Also, this configuration presupposes that you have already xref:servlet/saml2/metadata.adoc#servlet-saml2login-metadata[registered the relying party with your asserting party]. +[[saml2-specifying-identity-provider-metadata]] === Specifying Identity Provider Metadata -In a Spring Boot application, to specify an identity provider's metadata, simply do: +In a Spring Boot application, to specify an identity provider's metadata, create configuration similar to the following: +==== [source,yml] ---- spring: @@ -84,37 +95,42 @@ spring: singlesignon.url: https://idp.example.com/issuer/sso singlesignon.sign-request: false ---- +==== -where +where: -* `https://idp.example.com/issuer` is the value contained in the `Issuer` attribute of the SAML responses that the identity provider will issue -* `classpath:idp.crt` is the location on the classpath for the identity provider's certificate for verifying SAML responses, and -* `https://idp.example.com/issuer/sso` is the endpoint where the identity provider is expecting ``AuthnRequest``s. +* `https://idp.example.com/issuer` is the value contained in the `Issuer` attribute of the SAML responses that the identity provider issues. +* `classpath:idp.crt` is the location on the classpath for the identity provider's certificate for verifying SAML responses. +* `https://idp.example.com/issuer/sso` is the endpoint where the identity provider is expecting `AuthnRequest` instances. * `adfs` is <> And that's it! [NOTE] +==== Identity Provider and Asserting Party are synonymous, as are Service Provider and Relying Party. These are frequently abbreviated as AP and RP, respectively. +==== === Runtime Expectations -As configured above, the application processes any `+POST /login/saml2/sso/{registrationId}+` request containing a `SAMLResponse` parameter: +As configured <>, the application processes any `+POST /login/saml2/sso/{registrationId}+` request containing a `SAMLResponse` parameter: -[source,html] +==== +[source,http] ---- POST /login/saml2/sso/adfs HTTP/1.1 SAMLResponse=PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZ... ---- +==== -There are two ways to see induce your asserting party to generate a `SAMLResponse`: +There are two ways to induce your asserting party to generate a `SAMLResponse`: -* First, you can navigate to your asserting party. +* You can navigate to your asserting party. It likely has some kind of link or button for each registered relying party that you can click to send the `SAMLResponse`. -* Second, you can navigate to a protected page in your app, for example, `http://localhost:8080`. -Your app then redirects to the configured asserting party which then sends the `SAMLResponse`. +* You can navigate to a protected page in your application -- for example, `http://localhost:8080`. +Your application then redirects to the configured asserting party, which then sends the `SAMLResponse`. From here, consider jumping to: @@ -127,22 +143,24 @@ From here, consider jumping to: Spring Security's SAML 2.0 support has a couple of design goals: -* First, rely on a library for SAML 2.0 operations and domain objects. +* Rely on a library for SAML 2.0 operations and domain objects. To achieve this, Spring Security uses OpenSAML. -* Second, ensure this library is not required when using Spring Security's SAML support. +* Ensure that this library is not required when using Spring Security's SAML support. To achieve this, any interfaces or classes where Spring Security uses OpenSAML in the contract remain encapsulated. -This makes it possible for you to switch out OpenSAML for some other library or even an unsupported version of OpenSAML. +This makes it possible for you to switch out OpenSAML for some other library or an unsupported version of OpenSAML. -As a natural outcome of the above two goals, Spring Security's SAML API is quite small relative to other modules. -Instead, classes like `OpenSaml4AuthenticationRequestFactory` and `OpenSaml4AuthenticationProvider` expose ``Converter``s that customize various steps in the authentication process. +As a natural outcome of these two goals, Spring Security's SAML API is quite small relative to other modules. +Instead, such classes as `OpenSamlAuthenticationRequestFactory` and `OpenSamlAuthenticationProvider` expose `Converter` implementationss that customize various steps in the authentication process. -For example, once your application receives a `SAMLResponse` and delegates to `Saml2WebSsoAuthenticationFilter`, the filter will delegate to `OpenSaml4AuthenticationProvider`. +For example, once your application receives a `SAMLResponse` and delegates to `Saml2WebSsoAuthenticationFilter`, the filter delegates to `OpenSamlAuthenticationProvider`: [NOTE] +==== For backward compatibility, Spring Security will use the latest OpenSAML 3 by default. Note, though that OpenSAML 3 has reached it's end-of-life and updating to OpenSAML 4.x is recommended. For that reason, Spring Security supports both OpenSAML 3.x and 4.x. If you manage your OpenSAML dependency to 4.x, then Spring Security will select its OpenSAML 4.x implementations. +==== .Authenticating an OpenSAML `Response` image:{figures}/opensamlauthenticationprovider.png[] @@ -156,11 +174,11 @@ image:{icondir}/number_2.png[] The xref:servlet/authentication/architecture.adoc image:{icondir}/number_3.png[] The authentication provider deserializes the response into an OpenSAML `Response` and checks its signature. If the signature is invalid, authentication fails. -image:{icondir}/number_4.png[] Then, the provider xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-opensamlauthenticationprovider-decryption[decrypts any `EncryptedAssertion` elements]. +image:{icondir}/number_4.png[] Then the provider xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-opensamlauthenticationprovider-decryption[decrypts any `EncryptedAssertion` elements]. If any decryptions fail, authentication fails. image:{icondir}/number_5.png[] Next, the provider validates the response's `Issuer` and `Destination` values. -If they don't match what's in the `RelyingPartyRegistration`, authentication fails. +If they do not match what's in the `RelyingPartyRegistration`, authentication fails. image:{icondir}/number_6.png[] After that, the provider verifies the signature of each `Assertion`. If any signature is invalid, authentication fails. @@ -185,7 +203,7 @@ The resulting `Authentication#getPrincipal` is a Spring Security `Saml2Authentic [[servlet-saml2login-opensaml-customization]] === Customizing OpenSAML Configuration -Any class that uses both Spring Security and OpenSAML should statically initialize `OpenSamlInitializationService` at the beginning of the class, like so: +Any class that uses both Spring Security and OpenSAML should statically initialize `OpenSamlInitializationService` at the beginning of the class: ==== .Java @@ -272,14 +290,14 @@ companion object { ---- ==== -The `requireInitialize` method may only be called once per application instance. +The `requireInitialize` method may be called only once per application instance. [[servlet-saml2login-sansboot]] == Overriding or Replacing Boot Auto Configuration -There are two ``@Bean``s that Spring Boot generates for a relying party. +Spring Boot generates two `@Bean` objects for a relying party. -The first is a `WebSecurityConfigurerAdapter` that configures the app as a relying party. +The first is a `WebSecurityConfigurerAdapter` that configures the application as a relying party. When including `spring-security-saml2-service-provider`, the `WebSecurityConfigurerAdapter` looks like: .Default JWT Configuration @@ -289,7 +307,7 @@ When including `spring-security-saml2-service-provider`, the `WebSecurityConfigu ---- protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .saml2Login(withDefaults()); @@ -310,7 +328,7 @@ fun configure(http: HttpSecurity) { ---- ==== -If the application doesn't expose a `WebSecurityConfigurerAdapter` bean, then Spring Boot will expose the above default one. +If the application does not expose a `WebSecurityConfigurerAdapter` bean, Spring Boot exposes the preceding default one. You can replace this by exposing the bean within the application: @@ -323,7 +341,7 @@ You can replace this by exposing the bean within the application: public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .mvcMatchers("/messages/**").hasAuthority("ROLE_USER") .anyRequest().authenticated() ) @@ -351,14 +369,14 @@ class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() { ---- ==== -The above requires the role of `USER` for any URL that starts with `/messages/`. +The preceding example requires the role of `USER` for any URL that starts with `/messages/`. [[servlet-saml2login-relyingpartyregistrationrepository]] The second `@Bean` Spring Boot creates is a {security-api-url}org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationRepository.html[`RelyingPartyRegistrationRepository`], which represents the asserting party and relying party metadata. -This includes things like the location of the SSO endpoint the relying party should use when requesting authentication from the asserting party. +This includes such things as the location of the SSO endpoint the relying party should use when requesting authentication from the asserting party. You can override the default by publishing your own `RelyingPartyRegistrationRepository` bean. -For example, you can look up the asserting party's configuration by hitting its metadata endpoint like so: +For example, you can look up the asserting party's configuration by hitting its metadata endpoint: .Relying Party Registration Repository ==== @@ -399,7 +417,7 @@ open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? { [NOTE] The `registrationId` is an arbitrary value that you choose for differentiating between registrations. -Or you can provide each detail manually, as you can see below: +Alternatively, you can provide each detail manually: .Relying Party Registration Repository Manual Configuration ==== @@ -456,11 +474,13 @@ open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository { ==== [NOTE] -Note that `X509Support` is an OpenSAML class, used here in the snippet for brevity +==== +`X509Support` is an OpenSAML class, used in the preceding snippet for brevity. +==== [[servlet-saml2login-relyingpartyregistrationrepository-dsl]] -Alternatively, you can directly wire up the repository using the DSL, which will also override the auto-configured `WebSecurityConfigurerAdapter`: +Alternatively, you can directly wire up the repository by using the DSL, which also overrides the auto-configured `WebSecurityConfigurerAdapter`: .Custom Relying Party Registration DSL ==== @@ -471,7 +491,7 @@ Alternatively, you can directly wire up the repository using the DSL, which will public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http - .authorizeRequests(authorize -> authorize + .authorizeHttpRequests(authorize -> authorize .mvcMatchers("/messages/**").hasAuthority("ROLE_USER") .anyRequest().authenticated() ) @@ -503,12 +523,14 @@ class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() { ==== [NOTE] +==== A relying party can be multi-tenant by registering more than one relying party in the `RelyingPartyRegistrationRepository`. +==== [[servlet-saml2login-relyingpartyregistration]] == RelyingPartyRegistration A {security-api-url}org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.html[`RelyingPartyRegistration`] -instance represents a link between an relying party and assering party's metadata. +instance represents a link between an relying party and an asserting party's metadata. In a `RelyingPartyRegistration`, you can provide relying party metadata like its `Issuer` value, where it expects SAML Responses to be sent to, and any credentials that it owns for the purposes of signing or decrypting payloads. @@ -549,7 +571,7 @@ try (InputStream source = new ByteArrayInputStream(xml.getBytes())) { } ---- -Though a more sophisticated setup is also possible, like so: +A more sophisticated setup is also possible: ==== .Java @@ -587,24 +609,28 @@ val relyingPartyRegistration = ==== [TIP] +==== The top-level metadata methods are details about the relying party. The methods inside `assertingPartyDetails` are details about the asserting party. +==== [NOTE] +==== The location where a relying party is expecting SAML Responses is the Assertion Consumer Service Location. +==== The default for the relying party's `entityId` is `+{baseUrl}/saml2/service-provider-metadata/{registrationId}+`. This is this value needed when configuring the asserting party to know about your relying party. The default for the `assertionConsumerServiceLocation` is `+/login/saml2/sso/{registrationId}+`. -It's mapped by default to <> in the filter chain. +By default, it is mapped to <> in the filter chain. [[servlet-saml2login-rpr-uripatterns]] === URI Patterns -You probably noticed in the above examples the `+{baseUrl}+` and `+{registrationId}+` placeholders. +You probably noticed the `+{baseUrl}+` and `+{registrationId}+` placeholders in the preceding examples. -These are useful for generating URIs. As such, the relying party's `entityId` and `assertionConsumerServiceLocation` support the following placeholders: +These are useful for generating URIs. As a result, the relying party's `entityId` and `assertionConsumerServiceLocation` support the following placeholders: * `baseUrl` - the scheme, host, and port of a deployed application * `registrationId` - the registration id for this relying party @@ -612,36 +638,36 @@ These are useful for generating URIs. As such, the relying party's `entityId` an * `baseHost` - the host of a deployed application * `basePort` - the port of a deployed application -For example, the `assertionConsumerServiceLocation` defined above was: +For example, the `assertionConsumerServiceLocation` defined earlier was: `+/my-login-endpoint/{registrationId}+` -which in a deployed application would translate to +In a deployed application, it translates to: `+/my-login-endpoint/adfs+` -The `entityId` above was defined as: +The `entityId` shown earlier was defined as: `+{baseUrl}/{registrationId}+` -which in a deployed application would translate to +In a deployed application, that translates to: `+https://rp.example.com/adfs+` [[servlet-saml2login-rpr-credentials]] === Credentials -You also likely noticed the credential that was used. +In the example shown <>, you also likely noticed the credential that was used. -Oftentimes, a relying party will use the same key to sign payloads as well as decrypt them. -Or it will use the same key to verify payloads as well as encrypt them. +Oftentimes, a relying party uses the same key to sign payloads as well as decrypt them. +Alternatively, it can use the same key to verify payloads as well as encrypt them. Because of this, Spring Security ships with `Saml2X509Credential`, a SAML-specific credential that simplifies configuring the same key for different use cases. -At a minimum, it's necessary to have a certificate from the asserting party so that the asserting party's signed responses can be verified. +At a minimum, you need to have a certificate from the asserting party so that the asserting party's signed responses can be verified. -To construct a `Saml2X509Credential` that you'll use to verify assertions from the asserting party, you can load the file and use -the `CertificateFactory` like so: +To construct a `Saml2X509Credential` that you can use to verify assertions from the asserting party, you can load the file and use +the `CertificateFactory`: ==== .Java @@ -667,11 +693,11 @@ resource.inputStream.use { ---- ==== -Let's say that the asserting party is going to also encrypt the assertion. -In that case, the relying party will need a private key to be able to decrypt the encrypted value. +Suppose that the asserting party is going to also encrypt the assertion. +In that case, the relying party needs a private key to decrypt the encrypted value. -In that case, you'll need an `RSAPrivateKey` as well as its corresponding `X509Certificate`. -You can load the first using Spring Security's `RsaKeyConverters` utility class and the second as you did before: +In that case, you need an `RSAPrivateKey` as well as its corresponding `X509Certificate`. +You can load the first by using Spring Security's `RsaKeyConverters` utility class and the second as you did before: ==== .Java @@ -698,20 +724,22 @@ resource.inputStream.use { ==== [TIP] -When you specify the locations of these files as the appropriate Spring Boot properties, then Spring Boot will perform these conversions for you. +==== +When you specify the locations of these files as the appropriate Spring Boot properties, Spring Boot performs these conversions for you. +==== [[servlet-saml2login-rpr-relyingpartyregistrationresolver]] === Resolving the Relying Party from the Request -As seen so far, Spring Security resolves the `RelyingPartyRegistration` by looking for the registration id in the URI path. +As seen so far, Spring Security resolves the `RelyingPartyRegistration` by looking for the registration ID in the URI path. -There are a number of reasons you may want to customize. Among them: +You may want to customize for a number of reasons, including: -* You may know that you will never be a multi-tenant application and so want to have a simpler URL scheme -* You may identify tenants in a way other than by the URI path +* You may know that your application is never going to be a multi-tenant application and, as a result, want a simpler URL scheme. +* You may identify tenants in a way other than by the URI path. To customize the way that a `RelyingPartyRegistration` is resolved, you can configure a custom `RelyingPartyRegistrationResolver`. -The default looks up the registration id from the URI's last path element and looks it up in your `RelyingPartyRegistrationRepository`. +The default looks up the registration ID from the URI's last path element and looks it up in your `RelyingPartyRegistrationRepository`. You can provide a simpler resolver that, for example, always returns the same relying party: @@ -745,10 +773,12 @@ class SingleRelyingPartyRegistrationResolver(delegate: RelyingPartyRegistrationR ---- ==== -Then, you can provide this resolver to the appropriate filters that xref:servlet/saml2/login/authentication-requests.adoc#servlet-saml2login-sp-initiated-factory[produce ````s], xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-authenticate-responses[authenticate ````s], and xref:servlet/saml2/metadata.adoc#servlet-saml2login-metadata[produce `` metadata]. +Then you can provide this resolver to the appropriate filters that xref:servlet/saml2/login/authentication-requests.adoc#servlet-saml2login-sp-initiated-factory[produce `` instances], xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-authenticate-responses[authenticate `` instances], and xref:servlet/saml2/metadata.adoc#servlet-saml2login-metadata[produce `` metadata]. [NOTE] +==== Remember that if you have any placeholders in your `RelyingPartyRegistration`, your resolver implementation should resolve them. +==== [[servlet-saml2login-rpr-duplicated]] === Duplicated Relying Party Configurations @@ -756,15 +786,16 @@ Remember that if you have any placeholders in your `RelyingPartyRegistration`, y When an application uses multiple asserting parties, some configuration is duplicated between `RelyingPartyRegistration` instances: * The relying party's `entityId` -* Its `assertionConsumerServiceLocation`, and -* Its credentials, for example its signing or decryption credentials +* Its `assertionConsumerServiceLocation` +* Its credentials -- for example, its signing or decryption credentials -What's nice about this setup is credentials may be more easily rotated for some identity providers vs others. +This setup may let credentials be more easily rotated for some identity providers versus others. The duplication can be alleviated in a few different ways. -First, in YAML this can be alleviated with references, like so: +First, in YAML this can be alleviated with references: +==== [source,yaml] ---- spring: @@ -782,10 +813,11 @@ spring: identityprovider: entity-id: ... ---- +==== -Second, in a database, it's not necessary to replicate `RelyingPartyRegistration` 's model. +Second, in a database, you need not replicate the model of `RelyingPartyRegistration`. -Third, in Java, you can create a custom configuration method, like so: +Third, in Java, you can create a custom configuration method: ==== .Java diff --git a/docs/modules/ROOT/pages/servlet/saml2/logout.adoc b/docs/modules/ROOT/pages/servlet/saml2/logout.adoc index 0d1a886753f..9dba271b78c 100644 --- a/docs/modules/ROOT/pages/servlet/saml2/logout.adoc +++ b/docs/modules/ROOT/pages/servlet/saml2/logout.adoc @@ -35,6 +35,7 @@ RelyingPartyRegistrationRepository registrations() { RelyingPartyRegistration registration = RelyingPartyRegistrations .fromMetadataLocation("https://ap.example.org/metadata") .registrationId("id") + .singleLogoutServiceLocation("{baseUrl}/logout/saml2/slo") .signingX509Credentials((signing) -> signing.add(credential)) <1> .build(); return new InMemoryRelyingPartyRegistrationRepository(registration); @@ -43,7 +44,7 @@ RelyingPartyRegistrationRepository registrations() { @Bean SecurityFilterChain web(HttpSecurity http, RelyingPartyRegistrationRepository registrations) throws Exception { http - .authorizeRequests((authorize) -> authorize + .authorizeHttpRequests((authorize) -> authorize .anyRequest().authenticated() ) .saml2Login(withDefaults()) @@ -73,6 +74,10 @@ Also, your application can participate in an AP-initiated logout when the assert 3. Create, sign, and serialize a `` based on the xref:servlet/saml2/login/overview.adoc#servlet-saml2login-relyingpartyregistration[`RelyingPartyRegistration`] associated with the just logged-out user 4. Send a redirect or post to the asserting party based on the xref:servlet/saml2/login/overview.adoc#servlet-saml2login-relyingpartyregistration[`RelyingPartyRegistration`] +NOTE: Adding `saml2Logout` adds the capability for logout to the service provider. +Because it is an optional capability, you need to enable it for each individual `RelyingPartyRegistration`. +You can do this by setting the `RelyingPartyRegistration.Builder#singleLogoutServiceLocation` property. + == Configuring Logout Endpoints There are three behaviors that can be triggered by different endpoints: diff --git a/docs/modules/ROOT/pages/servlet/test/method.adoc b/docs/modules/ROOT/pages/servlet/test/method.adoc index e5e639464e7..bb52c1ad9d2 100644 --- a/docs/modules/ROOT/pages/servlet/test/method.adoc +++ b/docs/modules/ROOT/pages/servlet/test/method.adoc @@ -1,8 +1,8 @@ [[test-method]] = Testing Method Security -This section demonstrates how to use Spring Security's Test support to test method based security. -We first introduce a `MessageService` that requires the user to be authenticated in order to access it. +This section demonstrates how to use Spring Security's Test support to test method-based security. +We first introduce a `MessageService` that requires the user to be authenticated to be able to access it: ==== .Java @@ -32,18 +32,20 @@ class HelloMessageService : MessageService { ---- ==== -The result of `getMessage` is a String saying "Hello" to the current Spring Security `Authentication`. -An example of the output is displayed below. +The result of `getMessage` is a `String` that says "`Hello`" to the current Spring Security `Authentication`. +The follwoing listing shows example output: +==== [source,text] ---- Hello org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ca25360: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER ---- +==== [[test-method-setup]] == Security Test Setup -Before we can use Spring Security Test support, we must perform some setup. An example can be seen below: +Before we can use the Spring Security test support, we must perform some setup: ==== .Java @@ -52,6 +54,8 @@ Before we can use Spring Security Test support, we must perform some setup. An e @RunWith(SpringJUnit4ClassRunner.class) // <1> @ContextConfiguration // <2> public class WithMockUserTests { + // ... +} ---- .Kotlin @@ -60,22 +64,24 @@ public class WithMockUserTests { @RunWith(SpringJUnit4ClassRunner::class) @ContextConfiguration class WithMockUserTests { + // ... +} ---- -==== - -This is a basic example of how to setup Spring Security Test. The highlights are: - <1> `@RunWith` instructs the spring-test module that it should create an `ApplicationContext`. This is no different than using the existing Spring Test support. For additional information, refer to the https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/htmlsingle/#integration-testing-annotations-standard[Spring Reference] <2> `@ContextConfiguration` instructs the spring-test the configuration to use to create the `ApplicationContext`. Since no configuration is specified, the default configuration locations will be tried. This is no different than using the existing Spring Test support. For additional information, refer to the https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/htmlsingle/#testcontext-ctx-management[Spring Reference] +==== -NOTE: Spring Security hooks into Spring Test support using the `WithSecurityContextTestExecutionListener` which will ensure our tests are ran with the correct user. +[NOTE] +==== +Spring Security hooks into Spring Test support through the `WithSecurityContextTestExecutionListener`, which ensures that our tests are run with the correct user. It does this by populating the `SecurityContextHolder` prior to running our tests. -If you are using reactive method security, you will also need `ReactorContextTestExecutionListener` which populates `ReactiveSecurityContextHolder`. -After the test is done, it will clear out the `SecurityContextHolder`. -If you only need Spring Security related support, you can replace `@ContextConfiguration` with `@SecurityTestExecutionListeners`. +If you use reactive method security, you also need `ReactorContextTestExecutionListener`, which populates `ReactiveSecurityContextHolder`. +After the test is done, it clears out the `SecurityContextHolder`. +If you need only Spring Security related support, you can replace `@ContextConfiguration` with `@SecurityTestExecutionListeners`. +==== -Remember we added the `@PreAuthorize` annotation to our `HelloMessageService` and so it requires an authenticated user to invoke it. -If we ran the following test, we would expect the following test will pass: +Remember, we added the `@PreAuthorize` annotation to our `HelloMessageService`, so it requires an authenticated user to invoke it. +If we run the tests, we expect the following test will pass: ==== .Java @@ -130,14 +136,16 @@ fun getMessageWithMockUser() { Specifically the following is true: -* The user with the username "user" does not have to exist since we are mocking the user -* The `Authentication` that is populated in the `SecurityContext` is of type `UsernamePasswordAuthenticationToken` -* The principal on the `Authentication` is Spring Security's `User` object -* The `User` will have the username of "user", the password "password", and a single `GrantedAuthority` named "ROLE_USER" is used. +* The user with a username of `user` does not have to exist, since we mock the user object. +* The `Authentication` that is populated in the `SecurityContext` is of type `UsernamePasswordAuthenticationToken`. +* The principal on the `Authentication` is Spring Security's `User` object. +* The `User` has a username of `user`. +* The `User` has a password of `password`. +* A single `GrantedAuthority` named `ROLE_USER` is used. -Our example is nice because we are able to leverage a lot of defaults. +The preceding example is handy, because it lets us use a lot of defaults. What if we wanted to run the test with a different username? -The following test would run with the username "customUser". Again, the user does not need to actually exist. +The following test would run with a username of `customUser` (again, the user does not need to actually exist): ==== .Java @@ -164,7 +172,7 @@ fun getMessageWithMockUserCustomUsername() { ==== We can also easily customize the roles. -For example, this test will be invoked with the username "admin" and the roles "ROLE_USER" and "ROLE_ADMIN". +For example, the following test is invoked with a username of `admin` and roles of `ROLE_USER` and `ROLE_ADMIN`. ==== .Java @@ -190,8 +198,8 @@ fun getMessageWithMockUserCustomUser() { ---- ==== -If we do not want the value to automatically be prefixed with ROLE_ we can leverage the authorities attribute. -For example, this test will be invoked with the username "admin" and the authorities "USER" and "ADMIN". +If we do not want the value to automatically be prefixed with `ROLE_` we can use the `authorities` attribute. +For example, the following test is invoked with a username of `admin` and the `USER` and `ADMIN` authorities. ==== .Java @@ -217,9 +225,9 @@ fun getMessageWithMockUserCustomUsername() { ---- ==== -Of course it can be a bit tedious placing the annotation on every test method. -Instead, we can place the annotation at the class level and every test will use the specified user. -For example, the following would run every test with a user with the username "admin", the password "password", and the roles "ROLE_USER" and "ROLE_ADMIN". +It can be a bit tedious to place the annotation on every test method. +Instead, we can place the annotation at the class level. Then every test uses the specified user. +The following example runs every test with a user whose username is `admin`, whose password is `password`, and who has the `ROLE_USER` and `ROLE_ADMIN` roles: ==== .Java @@ -229,6 +237,8 @@ For example, the following would run every test with a user with the username "a @ContextConfiguration @WithMockUser(username="admin",roles={"USER","ADMIN"}) public class WithMockUserTests { + // ... +} ---- .Kotlin @@ -238,11 +248,13 @@ public class WithMockUserTests { @ContextConfiguration @WithMockUser(username="admin",roles=["USER","ADMIN"]) class WithMockUserTests { + // ... +} ---- ==== -If you are using JUnit 5's `@Nested` test support, you can also place the annotation on the enclosing class to apply to all nested classes. -For example, the following would run every test with a user with the username "admin", the password "password", and the roles "ROLE_USER" and "ROLE_ADMIN" for both test methods. +If you use JUnit 5's `@Nested` test support, you can also place the annotation on the enclosing class to apply to all nested classes. +The following example runs every test with a user whose username is `admin`, whose password is `password`, and who has the `ROLE_USER` and `ROLE_ADMIN` roles for both test methods. ==== .Java @@ -283,22 +295,24 @@ class WithMockUserTests { ---- ==== -By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event. +By default, the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event. This is the equivalent of happening before JUnit's `@Before`. -You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit's `@Before` but before the test method is invoked. +You can change this to happen during the `TestExecutionListener.beforeTestExecution` event, which is after JUnit's `@Before` but before the test method is invoked: +==== [source,java] ---- @WithMockUser(setupBefore = TestExecutionEvent.TEST_EXECUTION) ---- +==== [[test-method-withanonymoususer]] == @WithAnonymousUser Using `@WithAnonymousUser` allows running as an anonymous user. -This is especially convenient when you wish to run most of your tests with a specific user, but want to run a few tests as an anonymous user. -For example, the following will run withMockUser1 and withMockUser2 using <> and anonymous as an anonymous user. +This is especially convenient when you wish to run most of your tests with a specific user but want to run a few tests as an anonymous user. +The following example runs `withMockUser1` and `withMockUser2` by using <> and `anonymous` as an anonymous user: ==== .Java @@ -347,28 +361,30 @@ class WithUserClassLevelAuthenticationTests { ---- ==== -By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event. +By default, the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event. This is the equivalent of happening before JUnit's `@Before`. -You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit's `@Before` but before the test method is invoked. +You can change this to happen during the `TestExecutionListener.beforeTestExecution` event, which is after JUnit's `@Before` but before the test method is invoked: +==== [source,java] ---- @WithAnonymousUser(setupBefore = TestExecutionEvent.TEST_EXECUTION) ---- +==== [[test-method-withuserdetails]] == @WithUserDetails -While `@WithMockUser` is a very convenient way to get started, it may not work in all instances. -For example, it is common for applications to expect that the `Authentication` principal be of a specific type. +While `@WithMockUser` is a convenient way to get started, it may not work in all instances. +For example, some applications expect the `Authentication` principal to be of a specific type. This is done so that the application can refer to the principal as the custom type and reduce coupling on Spring Security. -The custom principal is often times returned by a custom `UserDetailsService` that returns an object that implements both `UserDetails` and the custom type. -For situations like this, it is useful to create the test user using the custom `UserDetailsService`. +The custom principal is often returned by a custom `UserDetailsService` that returns an object that implements both `UserDetails` and the custom type. +For situations like this, it is useful to create the test user by using a custom `UserDetailsService`. That is exactly what `@WithUserDetails` does. -Assuming we have a `UserDetailsService` exposed as a bean, the following test will be invoked with an `Authentication` of type `UsernamePasswordAuthenticationToken` and a principal that is returned from the `UserDetailsService` with the username of "user". +Assuming we have a `UserDetailsService` exposed as a bean, the following test is invoked with an `Authentication` of type `UsernamePasswordAuthenticationToken` and a principal that is returned from the `UserDetailsService` with the username of `user`: ==== .Java @@ -395,7 +411,7 @@ fun getMessageWithUserDetails() { ==== We can also customize the username used to lookup the user from our `UserDetailsService`. -For example, this test would be run with a principal that is returned from the `UserDetailsService` with the username of "customUsername". +For example, this test can be run with a principal that is returned from the `UserDetailsService` with the username of `customUsername`: ==== .Java @@ -422,7 +438,7 @@ fun getMessageWithUserDetailsCustomUsername() { ==== We can also provide an explicit bean name to look up the `UserDetailsService`. -For example, this test would look up the username of "customUsername" using the `UserDetailsService` with the bean name "myUserDetailsService". +The following test looks up the username of `customUsername` by using the `UserDetailsService` with a bean name of `myUserDetailsService`: ==== .Java @@ -448,28 +464,29 @@ fun getMessageWithUserDetailsServiceBeanName() { ---- ==== -Like `@WithMockUser` we can also place our annotation at the class level so that every test uses the same user. -However unlike `@WithMockUser`, `@WithUserDetails` requires the user to exist. +As we did with `@WithMockUser`, we can also place our annotation at the class level so that every test uses the same user. +However, unlike `@WithMockUser`, `@WithUserDetails` requires the user to exist. -By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event. +By default, the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event. This is the equivalent of happening before JUnit's `@Before`. -You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit's `@Before` but before the test method is invoked. +You can change this to happen during the `TestExecutionListener.beforeTestExecution` event, which is after JUnit's `@Before` but before the test method is invoked: +==== [source,java] ---- @WithUserDetails(setupBefore = TestExecutionEvent.TEST_EXECUTION) ---- - +==== [[test-method-withsecuritycontext]] == @WithSecurityContext -We have seen that `@WithMockUser` is an excellent choice if we are not using a custom `Authentication` principal. -Next we discovered that `@WithUserDetails` would allow us to use a custom `UserDetailsService` to create our `Authentication` principal but required the user to exist. -We will now see an option that allows the most flexibility. +We have seen that `@WithMockUser` is an excellent choice if we do not use a custom `Authentication` principal. +Next, we discovered that `@WithUserDetails` lets us use a custom `UserDetailsService` to create our `Authentication` principal but requires the user to exist. +We now see an option that allows the most flexibility. We can create our own annotation that uses the `@WithSecurityContext` to create any `SecurityContext` we want. -For example, we might create an annotation named `@WithMockCustomUser` as shown below: +For example, we might create an annotation named `@WithMockCustomUser`: ==== .Java @@ -495,9 +512,9 @@ annotation class WithMockCustomUser(val username: String = "rob", val name: Stri ==== You can see that `@WithMockCustomUser` is annotated with the `@WithSecurityContext` annotation. -This is what signals to Spring Security Test support that we intend to create a `SecurityContext` for the test. -The `@WithSecurityContext` annotation requires we specify a `SecurityContextFactory` that will create a new `SecurityContext` given our `@WithMockCustomUser` annotation. -You can find our `WithMockCustomUserSecurityContextFactory` implementation below: +This is what signals to Spring Security test support that we intend to create a `SecurityContext` for the test. +The `@WithSecurityContext` annotation requires that we specify a `SecurityContextFactory` to create a new `SecurityContext`, given our `@WithMockCustomUser` annotation. +The following listing shows our `WithMockCustomUserSecurityContextFactory` implementation: ==== .Java @@ -535,7 +552,7 @@ class WithMockCustomUserSecurityContextFactory : WithSecurityContextFactory> -* <> +* <> +* <> [[test-mockmvc-securitycontextholder-rpp]] == Running as a User in Spring MVC Test with RequestPostProcessor -There are a number of options available to associate a user to the current `HttpServletRequest`. -For example, the following will run as a user (which does not need to exist) with the username "user", the password "password", and the role "ROLE_USER": - -[NOTE] -==== -The support works by associating the user to the `HttpServletRequest`. -To associate the request to the `SecurityContextHolder` you need to ensure that the `SecurityContextPersistenceFilter` is associated with the `MockMvc` instance. -A few ways to do this are: - -* Invoking xref:servlet/test/mockmvc/setup.adoc#test-mockmvc-setup[`apply(springSecurity())`] -* Adding Spring Security's `FilterChainProxy` to `MockMvc` -* Manually adding `SecurityContextPersistenceFilter` to the `MockMvc` instance may make sense when using `MockMvcBuilders.standaloneSetup` -==== +You have a number of options to associate a user to the current `HttpServletRequest`. +The following example runs as a user (which does not need to exist) whose username is `user`, whose password is `password`, and whose role is `ROLE_USER`: ==== .Java @@ -41,6 +30,19 @@ mvc.get("/") { ---- ==== +[NOTE] +==== +The support works by associating the user to the `HttpServletRequest`. +To associate the request to the `SecurityContextHolder`, you need to ensure that the `SecurityContextPersistenceFilter` is associated with the `MockMvc` instance. +You can do so in a number of ways: + +* Invoking xref:servlet/test/mockmvc/setup.adoc#test-mockmvc-setup[`apply(springSecurity())`] +* Adding Spring Security's `FilterChainProxy` to `MockMvc` +* Manually adding `SecurityContextPersistenceFilter` to the `MockMvc` instance may make sense when using `MockMvcBuilders.standaloneSetup` +==== + + + You can easily make customizations. For example, the following will run as a user (which does not need to exist) with the username "admin", the password "pass", and the roles "ROLE_USER" and "ROLE_ADMIN". diff --git a/docs/modules/ROOT/pages/servlet/test/mockmvc/csrf.adoc b/docs/modules/ROOT/pages/servlet/test/mockmvc/csrf.adoc index 3449151fa5d..1df2930e5c2 100644 --- a/docs/modules/ROOT/pages/servlet/test/mockmvc/csrf.adoc +++ b/docs/modules/ROOT/pages/servlet/test/mockmvc/csrf.adoc @@ -1,7 +1,7 @@ [[test-mockmvc-csrf]] = Testing with CSRF Protection -When testing any non-safe HTTP methods and using Spring Security's CSRF protection, you must be sure to include a valid CSRF Token in the request. +When testing any non-safe HTTP methods and using Spring Security's CSRF protection, you must include a valid CSRF Token in the request. To specify a valid CSRF token as a request parameter use the CSRF xref:servlet/test/mockmvc/request-post-processors.adoc[`RequestPostProcessor`] like so: ==== @@ -21,7 +21,7 @@ mvc.post("/") { ---- ==== -If you like you can include CSRF token in the header instead: +If you like, you can include CSRF token in the header instead: ==== .Java @@ -40,7 +40,7 @@ mvc.post("/") { ---- ==== -You can also test providing an invalid CSRF token using the following: +You can also test providing an invalid CSRF token by using the following: ==== .Java diff --git a/docs/modules/ROOT/pages/servlet/test/mockmvc/request-post-processors.adoc b/docs/modules/ROOT/pages/servlet/test/mockmvc/request-post-processors.adoc index 7cd154b8c79..95708f9a01d 100644 --- a/docs/modules/ROOT/pages/servlet/test/mockmvc/request-post-processors.adoc +++ b/docs/modules/ROOT/pages/servlet/test/mockmvc/request-post-processors.adoc @@ -1,9 +1,9 @@ [[test-mockmvc-smmrpp]] = SecurityMockMvcRequestPostProcessors :page-section-summary-toc: 1 -Spring MVC Test provides a convenient interface called a `RequestPostProcessor` that can be used to modify a request. +Spring MVC Test provides a convenient interface (`RequestPostProcessor`) that you can use to modify a request. Spring Security provides a number of `RequestPostProcessor` implementations that make testing easier. -In order to use Spring Security's `RequestPostProcessor` implementations ensure the following static import is used: +To use Spring Security's `RequestPostProcessor` implementations, use the following static import: ==== .Java diff --git a/docs/modules/ROOT/pages/servlet/test/mockmvc/setup.adoc b/docs/modules/ROOT/pages/servlet/test/mockmvc/setup.adoc index 207f5856d24..ee3928c508f 100644 --- a/docs/modules/ROOT/pages/servlet/test/mockmvc/setup.adoc +++ b/docs/modules/ROOT/pages/servlet/test/mockmvc/setup.adoc @@ -1,12 +1,14 @@ [[test-mockmvc-setup]] = Setting Up MockMvc and Spring Security -In order to use Spring Security with Spring MVC Test it is necessary to add the Spring Security `FilterChainProxy` as a `Filter`. -It is also necessary to add Spring Security's `TestSecurityContextHolderPostProcessor` to support xref:servlet/test/mockmvc/setup.adoc#test-mockmvc-withmockuser[Running as a User in Spring MVC Test with Annotations]. -This can be done using Spring Security's `SecurityMockMvcConfigurers.springSecurity()`. -For example: +[NOTE] +==== +Spring Security's testing support requires spring-test-4.1.3.RELEASE or greater. +==== -NOTE: Spring Security's testing support requires spring-test-4.1.3.RELEASE or greater. +To use Spring Security with Spring MVC Test, add the Spring Security `FilterChainProxy` as a `Filter`. +You also need to add Spring Security's `TestSecurityContextHolderPostProcessor` to support xref:servlet/test/mockmvc/setup.adoc#test-mockmvc-withmockuser[Running as a User in Spring MVC Test with Annotations]. +To do so, use Spring Security's `SecurityMockMvcConfigurers.springSecurity()`: ==== .Java @@ -32,8 +34,8 @@ public class CsrfShowcaseTests { .apply(springSecurity()) // <1> .build(); } - -... + // ... +} ---- .Kotlin @@ -56,8 +58,9 @@ class CsrfShowcaseTests { .apply(springSecurity()) // <1> .build() } -// ... + // ... +} ---- +<1> `SecurityMockMvcConfigurers.springSecurity()` will perform all of the initial setup we need to integrate Spring Security with Spring MVC Test ==== -<1> `SecurityMockMvcConfigurers.springSecurity()` will perform all of the initial setup we need to integrate Spring Security with Spring MVC Test diff --git a/docs/modules/ROOT/pages/whats-new.adoc b/docs/modules/ROOT/pages/whats-new.adoc index 24ab50b3121..0767ff7cb4a 100644 --- a/docs/modules/ROOT/pages/whats-new.adoc +++ b/docs/modules/ROOT/pages/whats-new.adoc @@ -1,53 +1,5 @@ [[new]] -= What's New in Spring Security 5.6 += What's New in Spring Security 6.0 -Spring Security 5.6 provides a number of new features. +Spring Security 6.0 provides a number of new features. Below are the highlights of the release. - -* All new https://antora.org/[Antora] based https://docs.spring.io/spring-security/[documentation]. - -[[whats-new-servlet]] -== Servlet -* Core - -** Introduced https://github.com/spring-projects/spring-security/issues/10226[`SecurityContextChangedListener`] -** Improved https://github.com/spring-projects/spring-security/pull/10279[Method Security Logging] - -* Configuration - -** Introduced https://github.com/spring-projects/spring-security/pull/9630[`AuthorizationManager`] for method security - -* SAML 2.0 Service Provider - -** Added https://github.com/spring-projects/spring-security/pull/9483[SAML 2.0 Single Logout Support] -** Added https://github.com/spring-projects/spring-security/pull/10060[Saml2AuthenticationRequestRepository] -** Added https://github.com/spring-projects/spring-security/issues/9486[`RelyingPartyRegistrationResolver`] -** Improved ``Saml2LoginConfigurer``'s handling of https://github.com/spring-projects/spring-security/issues/10268[`Saml2AuthenticationTokenConverter`] - - -* OAuth 2.0 Login - -** Added https://github.com/spring-projects/spring-security/pull/10041[`Converter` for `Authentication` result] - -* OAuth 2.0 Client - -** Improved https://github.com/spring-projects/spring-security/pull/9791[Client Credentials encoding] -** Improved https://github.com/spring-projects/spring-security/pull/9779[Access Token Response parsing] -** Added https://github.com/spring-projects/spring-security/pull/10155[custom grant types support] for Authorization Requests -** Introduced https://github.com/spring-projects/spring-security/pull/9208[JwtEncoder] - -* Testing - -** Added support to https://github.com/spring-projects/spring-security/pull/9737[propagate the TestSecurityContextHolder to SecurityContextHolder] - -[[whats-new-webflux]] -== WebFlux - -* OAuth 2.0 Client - -** Improved https://github.com/spring-projects/spring-security/pull/9791[Client Credentials encoding] -** Added https://github.com/spring-projects/spring-security/pull/10131[custom headers support] for Access Token Requests -** Added https://github.com/spring-projects/spring-security/pull/10269[custom response parsing] for Access Token Requests -** Added https://github.com/spring-projects/spring-security/pull/10327[jwt-bearer Grant Type support] for Access Token Requests -** Added https://github.com/spring-projects/spring-security/pull/10336[JWT Client Authentication support] for Access Token Requests -** Improved https://github.com/spring-projects/spring-security/pull/10373[Reactive OAuth 2.0 Client Documentation] diff --git a/docs/spring-security-docs.gradle b/docs/spring-security-docs.gradle index 5ee9288720f..7f92f94281a 100644 --- a/docs/spring-security-docs.gradle +++ b/docs/spring-security-docs.gradle @@ -1,13 +1,24 @@ +plugins { + id "io.github.rwinch.antora" version "0.0.2" +} + apply plugin: 'io.spring.convention.docs' apply plugin: 'java' -tasks.register("generateAntora") { - group = "Documentation" - description = "Generates antora files" - dependsOn 'generateAntoraYml', 'generateAntoraComponentVersion' +antora { + antoraVersion = "3.0.0-alpha.8" + arguments = ["--fetch", "--stacktrace"] } -tasks.register("generateAntoraYml") { +tasks.antora { + environment = [ + "ALGOLIA_API_KEY" : "82c7ead946afbac3cf98c32446154691", + "ALGOLIA_APP_ID" : "244V8V9FGG", + "ALGOLIA_INDEX_NAME" : "security-docs" + ] +} + +tasks.register("generateAntora") { group = "Documentation" description = "Generates the antora.yml for dynamic properties" doLast { @@ -30,9 +41,12 @@ tasks.register("generateAntoraYml") { def outputFile = new File("$buildDir/generateAntora/antora.yml") outputFile.getParentFile().mkdirs() outputFile.createNewFile() - outputFile.setText("""name: ROOT + def antoraYmlText = file("antora.yml").getText() + outputFile.setText("""$antoraYmlText title: Spring Security start_page: ROOT:index.adoc +nav: +- modules/ROOT/nav.adoc asciidoc: attributes: icondir: icons @@ -49,18 +63,6 @@ ${ymlVersions} } } -tasks.register("generateAntoraComponentVersion") { - group = "Documentation" - description = "Generates the antora.component.version file" - doLast { - def outputFile = new File("$buildDir/generateAntora/antora.component.version") - outputFile.getParentFile().mkdirs() - outputFile.createNewFile() - def antoraVersion = project.version.replaceAll(/^(\d+\.\d+)\.\d+(-\w+)?$/, '$1') - outputFile.setText("$antoraVersion") - } -} - dependencies { diff --git a/etc/s101/repository/repository.xml b/etc/s101/repository/repository.xml index 73bfd664c12..c5f5dde1512 100644 --- a/etc/s101/repository/repository.xml +++ b/etc/s101/repository/repository.xml @@ -9,6 +9,6 @@ - + diff --git a/etc/s101/repository/snapshots/baseline/arch.hsx b/etc/s101/repository/snapshots/baseline/arch.hsx index 0490635bd09..23fcfebda02 100644 Binary files a/etc/s101/repository/snapshots/baseline/arch.hsx and b/etc/s101/repository/snapshots/baseline/arch.hsx differ diff --git a/etc/s101/repository/snapshots/baseline/key-measures.xml b/etc/s101/repository/snapshots/baseline/key-measures.xml index fd9b9a39497..0d21683bd84 100644 --- a/etc/s101/repository/snapshots/baseline/key-measures.xml +++ b/etc/s101/repository/snapshots/baseline/key-measures.xml @@ -1,139 +1,122 @@ - + - - - + - + - - - - - + + + + + - - - - - - - - - - - + + + + + + + + + + + - - - - - - + + + - 33 - - - - 1537 - + 17377 + - 14020 - + 12707 + - 19845 - + 5668 + - 3782 + 6341 - 40 - + 70 + - 17256 - + 392 + - 841 - + 9256 + - 16810 - + 13997 + - 4234 - + 6415 + - 5515 - + 79 + - 816 - + 1680 + - 3825 - + 14097 + - 19862 - + 19282 + - 8118 - + 595 + - 986 - + 14292 + - 19803 - + 88 + - 380 - + 2075 + - 16796 + 13404 - 18844 - - - - 19804 - + 8028 + - 7455 - - - - 1215 - + 2621 + diff --git a/etc/s101/repository/snapshots/baseline/package-slice.hsx b/etc/s101/repository/snapshots/baseline/package-slice.hsx index f43d49e98ec..7f65345e3d5 100644 Binary files a/etc/s101/repository/snapshots/baseline/package-slice.hsx and b/etc/s101/repository/snapshots/baseline/package-slice.hsx differ diff --git a/etc/s101/repository/snapshots/baseline/settings.hsx b/etc/s101/repository/snapshots/baseline/settings.hsx index ab19d2271f1..fc2a90b8c6e 100644 Binary files a/etc/s101/repository/snapshots/baseline/settings.hsx and b/etc/s101/repository/snapshots/baseline/settings.hsx differ diff --git a/etc/s101/repository/snapshots/baseline/spec.hsx b/etc/s101/repository/snapshots/baseline/spec.hsx index c3e4e92e31d..b16739bcc11 100644 Binary files a/etc/s101/repository/snapshots/baseline/spec.hsx and b/etc/s101/repository/snapshots/baseline/spec.hsx differ diff --git a/etc/s101/repository/snapshots/baseline/summary.hsx b/etc/s101/repository/snapshots/baseline/summary.hsx index 12d5432bd97..d4bb35130b8 100644 Binary files a/etc/s101/repository/snapshots/baseline/summary.hsx and b/etc/s101/repository/snapshots/baseline/summary.hsx differ diff --git a/etc/s101/repository/snapshots/baseline/xb.hsx b/etc/s101/repository/snapshots/baseline/xb.hsx index a68939c0118..71ac23910e5 100644 Binary files a/etc/s101/repository/snapshots/baseline/xb.hsx and b/etc/s101/repository/snapshots/baseline/xb.hsx differ diff --git a/etc/s101/repository/snapshots/baseline/xblite.hsx b/etc/s101/repository/snapshots/baseline/xblite.hsx index 685d1528e29..890fb5ca0af 100644 Binary files a/etc/s101/repository/snapshots/baseline/xblite.hsx and b/etc/s101/repository/snapshots/baseline/xblite.hsx differ diff --git a/etc/s101/repository/snapshots/baseline/xs-offenders.hsx b/etc/s101/repository/snapshots/baseline/xs-offenders.hsx index 6b4806467f3..3eee42db2a2 100644 Binary files a/etc/s101/repository/snapshots/baseline/xs-offenders.hsx and b/etc/s101/repository/snapshots/baseline/xs-offenders.hsx differ diff --git a/gradle.properties b/gradle.properties index 98647346123..30d795e20ae 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,12 +1,12 @@ -aspectjVersion=1.9.7 +aspectjVersion=1.9.8.RC3 springJavaformatVersion=0.0.29 springBootVersion=2.4.2 -springFrameworkVersion=5.3.11 +springFrameworkVersion=6.0.0-M1 openSamlVersion=3.4.6 -version=5.6.0-SNAPSHOT +version=6.0.0-SNAPSHOT kotlinVersion=1.5.31 -samplesBranch=main -org.gradle.jvmargs=-Xmx3g -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError +samplesBranch=6.0.x +org.gradle.jvmargs=-Xmx3g -XX:+HeapDumpOnOutOfMemoryError org.gradle.parallel=true org.gradle.caching=true kotlin.stdlib.default.dependency=false diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c023e..7454180f2ae 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ffed3a254e9..e750102e092 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c811..1b6c787337f 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,101 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the @@ -106,80 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/itest/context/spring-security-itest-context.gradle b/itest/context/spring-security-itest-context.gradle index 9e3334454ab..15d323cc9f2 100644 --- a/itest/context/spring-security-itest-context.gradle +++ b/itest/context/spring-security-itest-context.gradle @@ -10,7 +10,7 @@ dependencies { implementation 'org.springframework:spring-tx' testImplementation project(':spring-security-web') - testImplementation 'javax.servlet:javax.servlet-api' + testImplementation 'jakarta.servlet:jakarta.servlet-api' testImplementation 'org.springframework:spring-web' testImplementation "org.assertj:assertj-core" testImplementation "org.junit.jupiter:junit-jupiter-api" diff --git a/itest/context/src/integration-test/java/org/springframework/security/integration/HttpNamespaceWithMultipleInterceptorsTests.java b/itest/context/src/integration-test/java/org/springframework/security/integration/HttpNamespaceWithMultipleInterceptorsTests.java index 8f52555cdbc..ea9a91c155a 100644 --- a/itest/context/src/integration-test/java/org/springframework/security/integration/HttpNamespaceWithMultipleInterceptorsTests.java +++ b/itest/context/src/integration-test/java/org/springframework/security/integration/HttpNamespaceWithMultipleInterceptorsTests.java @@ -16,7 +16,7 @@ package org.springframework.security.integration; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/itest/context/src/integration-test/java/org/springframework/security/integration/HttpPathParameterStrippingTests.java b/itest/context/src/integration-test/java/org/springframework/security/integration/HttpPathParameterStrippingTests.java index 7ddef561722..44af9454501 100644 --- a/itest/context/src/integration-test/java/org/springframework/security/integration/HttpPathParameterStrippingTests.java +++ b/itest/context/src/integration-test/java/org/springframework/security/integration/HttpPathParameterStrippingTests.java @@ -16,7 +16,7 @@ package org.springframework.security.integration; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/itest/context/src/integration-test/java/org/springframework/security/integration/SEC936ApplicationContextTests.java b/itest/context/src/integration-test/java/org/springframework/security/integration/SEC936ApplicationContextTests.java deleted file mode 100644 index cc49be6d4e0..00000000000 --- a/itest/context/src/integration-test/java/org/springframework/security/integration/SEC936ApplicationContextTests.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.integration; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.session.SessionRegistry; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -/** - * @author Luke Taylor - * @since 2.0 - */ -@ContextConfiguration(locations = { "/sec-936-app-context.xml" }) -@ExtendWith(SpringExtension.class) -public class SEC936ApplicationContextTests { - - /** - * SessionRegistry is used as the test service interface (nothing to do with the test) - */ - @Autowired - private SessionRegistry sessionRegistry; - - @Test - public void securityInterceptorHandlesCallWithNoTargetObject() { - SecurityContextHolder.getContext() - .setAuthentication(new UsernamePasswordAuthenticationToken("bob", "bobspassword")); - assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.sessionRegistry::getAllPrincipals); - } - -} diff --git a/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java b/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java index e53d4f839e6..a450851c4f0 100644 --- a/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java +++ b/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; diff --git a/itest/context/src/main/java/org/springframework/security/integration/UserDetailsServiceImpl.java b/itest/context/src/main/java/org/springframework/security/integration/UserDetailsServiceImpl.java index ad732690fbe..0752822fd3d 100755 --- a/itest/context/src/main/java/org/springframework/security/integration/UserDetailsServiceImpl.java +++ b/itest/context/src/main/java/org/springframework/security/integration/UserDetailsServiceImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2021 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,7 +16,6 @@ package org.springframework.security.integration; -import org.springframework.beans.factory.annotation.Required; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.transaction.annotation.Transactional; @@ -32,7 +31,6 @@ public UserDetails loadUserByUsername(String username) { return null; } - @Required public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } diff --git a/itest/web/spring-security-itest-web.gradle b/itest/web/spring-security-itest-web.gradle index 26feb48b14e..4a82c48b079 100644 --- a/itest/web/spring-security-itest-web.gradle +++ b/itest/web/spring-security-itest-web.gradle @@ -5,7 +5,7 @@ dependencies { implementation 'org.springframework:spring-context' implementation 'org.springframework:spring-web' - compileOnly 'javax.servlet:javax.servlet-api' + compileOnly 'jakarta.servlet:jakarta.servlet-api' testImplementation project(':spring-security-core') testImplementation project(':spring-security-test') @@ -21,7 +21,7 @@ dependencies { testImplementation "org.mockito:mockito-core" testImplementation "org.mockito:mockito-junit-jupiter" testImplementation "org.springframework:spring-test" - testImplementation 'javax.servlet:javax.servlet-api' + testImplementation 'jakarta.servlet:jakarta.servlet-api' testRuntimeOnly project(':spring-security-config') testRuntimeOnly project(':spring-security-ldap') diff --git a/ldap/spring-security-ldap.gradle b/ldap/spring-security-ldap.gradle index e16802ea452..f1c8074af4f 100644 --- a/ldap/spring-security-ldap.gradle +++ b/ldap/spring-security-ldap.gradle @@ -8,6 +8,7 @@ dependencies { api 'org.springframework:spring-core' api 'org.springframework:spring-tx' + optional 'com.fasterxml.jackson.core:jackson-databind' optional 'ldapsdk:ldapsdk' optional "com.unboundid:unboundid-ldapsdk" optional "org.apache.directory.server:apacheds-core" @@ -34,6 +35,7 @@ dependencies { testImplementation "org.mockito:mockito-core" testImplementation "org.mockito:mockito-junit-jupiter" testImplementation "org.springframework:spring-test" + testImplementation 'org.skyscreamer:jsonassert' } integrationTest { diff --git a/ldap/src/main/java/org/springframework/security/ldap/DefaultSpringSecurityContextSource.java b/ldap/src/main/java/org/springframework/security/ldap/DefaultSpringSecurityContextSource.java index 0d8e8403b73..0471113f6cc 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/DefaultSpringSecurityContextSource.java +++ b/ldap/src/main/java/org/springframework/security/ldap/DefaultSpringSecurityContextSource.java @@ -28,6 +28,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.core.log.LogMessage; import org.springframework.ldap.core.support.DirContextAuthenticationStrategy; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.core.support.SimpleDirContextAuthenticationStrategy; @@ -72,7 +73,7 @@ public DefaultSpringSecurityContextSource(String providerUrl) { String url = tokenizer.nextToken(); String urlRootDn = LdapUtils.parseRootDnFromUrl(url); urls.add(url.substring(0, url.lastIndexOf(urlRootDn))); - this.logger.info(" URL '" + url + "', root DN is '" + urlRootDn + "'"); + this.logger.info(LogMessage.format("Configure with URL %s and root DN %s", url, urlRootDn)); Assert.isTrue(rootDn == null || rootDn.equals(urlRootDn), "Root DNs must be the same when using multiple URLs"); rootDn = (rootDn != null) ? rootDn : urlRootDn; @@ -89,7 +90,7 @@ public void setupEnvironment(Hashtable env, String dn, String password) { // Remove the pooling flag unless authenticating as the 'manager' user. if (!DefaultSpringSecurityContextSource.this.userDn.equals(dn) && env.containsKey(SUN_LDAP_POOLING_FLAG)) { - DefaultSpringSecurityContextSource.this.logger.debug("Removing pooling flag for user " + dn); + DefaultSpringSecurityContextSource.this.logger.trace("Removing pooling flag for user " + dn); env.remove(SUN_LDAP_POOLING_FLAG); } } diff --git a/ldap/src/main/java/org/springframework/security/ldap/LdapUtils.java b/ldap/src/main/java/org/springframework/security/ldap/LdapUtils.java index a222bf48a81..5909eb8f7aa 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/LdapUtils.java +++ b/ldap/src/main/java/org/springframework/security/ldap/LdapUtils.java @@ -53,7 +53,7 @@ public static void closeContext(Context ctx) { } } catch (NamingException ex) { - logger.error("Failed to close context.", ex); + logger.debug("Failed to close context.", ex); } } @@ -64,7 +64,7 @@ public static void closeEnumeration(NamingEnumeration ne) { } } catch (NamingException ex) { - logger.error("Failed to close enumeration.", ex); + logger.debug("Failed to close enumeration.", ex); } } diff --git a/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java b/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java index 08c281b1e9b..42d4067b260 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java +++ b/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java @@ -166,7 +166,7 @@ public Set>> searchForMultipleAttributeValues(String ba encodedParams[i] = LdapEncoder.filterEncode(params[i].toString()); } String formattedFilter = MessageFormat.format(filter, encodedParams); - logger.debug(LogMessage.format("Using filter: %s", formattedFilter)); + logger.trace(LogMessage.format("Using filter: %s", formattedFilter)); HashSet>> result = new HashSet<>(); ContextMapper roleMapper = (ctx) -> { DirContextAdapter adapter = (DirContextAdapter) ctx; @@ -223,7 +223,7 @@ private void extractStringAttributeValues(DirContextAdapter adapter, Map stringValues = new ArrayList<>(); @@ -233,9 +233,9 @@ private void extractStringAttributeValues(DirContextAdapter adapter, Map resultsEnum = ctx.search(searchBaseDn, filter, params, buildControls(searchControls)); - logger.debug(LogMessage.format("Searching for entry under DN '%s', base = '%s', filter = '%s'", ctxBaseDn, + logger.trace(LogMessage.format("Searching for entry under DN '%s', base = '%s', filter = '%s'", ctxBaseDn, searchBaseDn, filter)); Set results = new HashSet<>(); try { @@ -284,7 +284,7 @@ public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, } catch (PartialResultException ex) { LdapUtils.closeEnumeration(resultsEnum); - logger.info("Ignoring PartialResultException"); + logger.trace("Ignoring PartialResultException"); } if (results.size() != 1) { throw new IncorrectResultSizeDataAccessException(1, results.size()); diff --git a/ldap/src/main/java/org/springframework/security/ldap/authentication/AbstractLdapAuthenticationProvider.java b/ldap/src/main/java/org/springframework/security/ldap/authentication/AbstractLdapAuthenticationProvider.java index 9a0e1a56ebb..5b7fb37ce54 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/authentication/AbstractLdapAuthenticationProvider.java +++ b/ldap/src/main/java/org/springframework/security/ldap/authentication/AbstractLdapAuthenticationProvider.java @@ -24,7 +24,6 @@ import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.context.support.MessageSourceAccessor; -import org.springframework.core.log.LogMessage; import org.springframework.ldap.core.DirContextOperations; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; @@ -68,7 +67,6 @@ public Authentication authenticate(Authentication authentication) throws Authent UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication; String username = userToken.getName(); String password = (String) authentication.getCredentials(); - this.logger.debug(LogMessage.format("Processing authentication request for user: %s", username)); if (!StringUtils.hasLength(username)) { throw new BadCredentialsException( this.messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username")); @@ -104,6 +102,7 @@ protected Authentication createSuccessfulAuthentication(UsernamePasswordAuthenti UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, password, this.authoritiesMapper.mapAuthorities(user.getAuthorities())); result.setDetails(authentication.getDetails()); + this.logger.debug("Authenticated user"); return result; } diff --git a/ldap/src/main/java/org/springframework/security/ldap/authentication/BindAuthenticator.java b/ldap/src/main/java/org/springframework/security/ldap/authentication/BindAuthenticator.java index 1c4fa66eff3..8dc0a39eee4 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/authentication/BindAuthenticator.java +++ b/ldap/src/main/java/org/springframework/security/ldap/authentication/BindAuthenticator.java @@ -65,7 +65,7 @@ public DirContextOperations authenticate(Authentication authentication) { String username = authentication.getName(); String password = (String) authentication.getCredentials(); if (!StringUtils.hasLength(password)) { - logger.debug(LogMessage.format("Rejecting empty password for user %s", username)); + logger.debug(LogMessage.format("Failed to authenticate since no credentials provided")); throw new BadCredentialsException( this.messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password")); } @@ -76,11 +76,18 @@ public DirContextOperations authenticate(Authentication authentication) { break; } } + if (user == null) { + logger.debug(LogMessage.of(() -> "Failed to bind with any user DNs " + getUserDns(username))); + } // Otherwise use the configured search object to find the user and authenticate // with the returned DN. if (user == null && getUserSearch() != null) { + logger.trace("Searching for user using " + getUserSearch()); DirContextOperations userFromSearch = getUserSearch().searchForUser(username); user = bindWithDn(userFromSearch.getDn().toString(), username, password, userFromSearch.getAttributes()); + if (user == null) { + logger.debug("Failed to find user using " + getUserSearch()); + } } if (user == null) { throw new BadCredentialsException( @@ -98,13 +105,12 @@ private DirContextOperations bindWithDn(String userDnStr, String username, Strin DistinguishedName userDn = new DistinguishedName(userDnStr); DistinguishedName fullDn = new DistinguishedName(userDn); fullDn.prepend(ctxSource.getBaseLdapPath()); - logger.debug(LogMessage.format("Attempting to bind as %s", fullDn)); + logger.trace(LogMessage.format("Attempting to bind as %s", fullDn)); DirContext ctx = null; try { ctx = getContextSource().getContext(fullDn.toString(), password); // Check for password policy control PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx); - logger.debug("Retrieving attributes..."); if (attrs == null || attrs.size() == 0) { attrs = ctx.getAttributes(userDn, getUserAttributes()); } @@ -112,6 +118,7 @@ private DirContextOperations bindWithDn(String userDnStr, String username, Strin if (ppolicy != null) { result.setAttributeValue(ppolicy.getID(), ppolicy); } + logger.debug(LogMessage.format("Bound %s", fullDn)); return result; } catch (NamingException ex) { @@ -141,7 +148,7 @@ private DirContextOperations bindWithDn(String userDnStr, String username, Strin * logger. */ protected void handleBindException(String userDn, String username, Throwable cause) { - logger.debug(LogMessage.format("Failed to bind as %s: %s", userDn, cause)); + logger.trace(LogMessage.format("Failed to bind as %s", userDn), cause); } } diff --git a/ldap/src/main/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticator.java b/ldap/src/main/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticator.java index a64b8b03682..7d79d358ef9 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticator.java +++ b/ldap/src/main/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticator.java @@ -76,25 +76,37 @@ public DirContextOperations authenticate(final Authentication authentication) { user = ldapTemplate.retrieveEntry(userDn, getUserAttributes()); } catch (NameNotFoundException ignore) { + logger.trace(LogMessage.format("Failed to retrieve user with %s", userDn), ignore); } if (user != null) { break; } } + if (user == null) { + logger.debug(LogMessage.of(() -> "Failed to retrieve user with any user DNs " + getUserDns(username))); + } if (user == null && getUserSearch() != null) { + logger.trace("Searching for user using " + getUserSearch()); user = getUserSearch().searchForUser(username); + if (user == null) { + logger.debug("Failed to find user using " + getUserSearch()); + } } if (user == null) { throw new UsernameNotFoundException("User not found: " + username); } - if (logger.isDebugEnabled()) { - logger.debug(LogMessage.format("Performing LDAP compare of password attribute '%s' for user '%s'", + if (logger.isTraceEnabled()) { + logger.trace(LogMessage.format("Comparing password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn())); } if (this.usePasswordAttrCompare && isPasswordAttrCompare(user, password)) { + logger.debug(LogMessage.format("Locally matched password attribute '%s' for user '%s'", + this.passwordAttributeName, user.getDn())); return user; } if (isLdapPasswordCompare(user, ldapTemplate, password)) { + logger.debug(LogMessage.format("LDAP-matched password attribute '%s' for user '%s'", + this.passwordAttributeName, user.getDn())); return user; } throw new BadCredentialsException( diff --git a/ldap/src/main/java/org/springframework/security/ldap/authentication/SpringSecurityAuthenticationSource.java b/ldap/src/main/java/org/springframework/security/ldap/authentication/SpringSecurityAuthenticationSource.java index 14584623fc3..0db213cfaa9 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/authentication/SpringSecurityAuthenticationSource.java +++ b/ldap/src/main/java/org/springframework/security/ldap/authentication/SpringSecurityAuthenticationSource.java @@ -48,7 +48,7 @@ public class SpringSecurityAuthenticationSource implements AuthenticationSource public String getPrincipal() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { - log.warn("No Authentication object set in SecurityContext - returning empty String as Principal"); + log.debug("Returning empty String as Principal since authentication is null"); return ""; } Object principal = authentication.getPrincipal(); @@ -57,7 +57,7 @@ public String getPrincipal() { return details.getDn(); } if (authentication instanceof AnonymousAuthenticationToken) { - log.debug("Anonymous Authentication, returning empty String as Principal"); + log.debug("Returning empty String as Principal since authentication is anonymous"); return ""; } throw new IllegalArgumentException( @@ -71,7 +71,7 @@ public String getPrincipal() { public String getCredentials() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { - log.warn("No Authentication object set in SecurityContext - returning empty String as Credentials"); + log.debug("Returning empty String as Credentials since authentication is null"); return ""; } return (String) authentication.getCredentials(); diff --git a/ldap/src/main/java/org/springframework/security/ldap/jackson2/InetOrgPersonMixin.java b/ldap/src/main/java/org/springframework/security/ldap/jackson2/InetOrgPersonMixin.java new file mode 100644 index 00000000000..fca449114e9 --- /dev/null +++ b/ldap/src/main/java/org/springframework/security/ldap/jackson2/InetOrgPersonMixin.java @@ -0,0 +1,39 @@ +/* + * Copyright 2015-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.ldap.jackson2; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +import org.springframework.security.jackson2.SecurityJackson2Modules; +import org.springframework.security.ldap.userdetails.InetOrgPerson; + +/** + * This Jackson mixin is used to serialize/deserialize {@link InetOrgPerson}. + * + * @since 5.7 + * @see LdapJackson2Module + * @see SecurityJackson2Modules + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) +@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +@JsonIgnoreProperties(ignoreUnknown = true) +abstract class InetOrgPersonMixin { + +} diff --git a/ldap/src/main/java/org/springframework/security/ldap/jackson2/LdapAuthorityMixin.java b/ldap/src/main/java/org/springframework/security/ldap/jackson2/LdapAuthorityMixin.java new file mode 100644 index 00000000000..85fe16f5fdb --- /dev/null +++ b/ldap/src/main/java/org/springframework/security/ldap/jackson2/LdapAuthorityMixin.java @@ -0,0 +1,48 @@ +/* + * Copyright 2015-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.ldap.jackson2; + +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +import org.springframework.security.jackson2.SecurityJackson2Modules; +import org.springframework.security.ldap.userdetails.LdapAuthority; + +/** + * This Jackson mixin is used to serialize/deserialize {@link LdapAuthority}. + * + * @since 5.7 + * @see LdapJackson2Module + * @see SecurityJackson2Modules + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) +@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) +@JsonIgnoreProperties(ignoreUnknown = true) +abstract class LdapAuthorityMixin { + + @JsonCreator + LdapAuthorityMixin(@JsonProperty("role") String role, @JsonProperty("dn") String dn, + @JsonProperty("attributes") Map> attributes) { + } + +} diff --git a/ldap/src/main/java/org/springframework/security/ldap/jackson2/LdapJackson2Module.java b/ldap/src/main/java/org/springframework/security/ldap/jackson2/LdapJackson2Module.java new file mode 100644 index 00000000000..62cb17a11a3 --- /dev/null +++ b/ldap/src/main/java/org/springframework/security/ldap/jackson2/LdapJackson2Module.java @@ -0,0 +1,63 @@ +/* + * Copyright 2015-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.ldap.jackson2; + +import com.fasterxml.jackson.core.Version; +import com.fasterxml.jackson.databind.module.SimpleModule; + +import org.springframework.security.jackson2.SecurityJackson2Modules; +import org.springframework.security.ldap.userdetails.InetOrgPerson; +import org.springframework.security.ldap.userdetails.LdapAuthority; +import org.springframework.security.ldap.userdetails.LdapUserDetailsImpl; +import org.springframework.security.ldap.userdetails.Person; + +/** + * Jackson module for {@code spring-security-ldap}. This module registers + * {@link LdapAuthorityMixin}, {@link LdapUserDetailsImplMixin}, {@link PersonMixin}, + * {@link InetOrgPersonMixin}. + * + * If not already enabled, default typing will be automatically enabled as type info is + * required to properly serialize/deserialize objects. In order to use this module just + * add it to your {@code ObjectMapper} configuration. + * + *
+ *     ObjectMapper mapper = new ObjectMapper();
+ *     mapper.registerModule(new LdapJackson2Module());
+ * 
+ * + * Note: use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get list of all + * security modules. + * + * @since 5.7 + * @see SecurityJackson2Modules + */ +public class LdapJackson2Module extends SimpleModule { + + public LdapJackson2Module() { + super(LdapJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null)); + } + + @Override + public void setupModule(SetupContext context) { + SecurityJackson2Modules.enableDefaultTyping(context.getOwner()); + context.setMixInAnnotations(LdapAuthority.class, LdapAuthorityMixin.class); + context.setMixInAnnotations(LdapUserDetailsImpl.class, LdapUserDetailsImplMixin.class); + context.setMixInAnnotations(Person.class, PersonMixin.class); + context.setMixInAnnotations(InetOrgPerson.class, InetOrgPersonMixin.class); + } + +} diff --git a/ldap/src/main/java/org/springframework/security/ldap/jackson2/LdapUserDetailsImplMixin.java b/ldap/src/main/java/org/springframework/security/ldap/jackson2/LdapUserDetailsImplMixin.java new file mode 100644 index 00000000000..a441102e6b3 --- /dev/null +++ b/ldap/src/main/java/org/springframework/security/ldap/jackson2/LdapUserDetailsImplMixin.java @@ -0,0 +1,39 @@ +/* + * Copyright 2015-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.ldap.jackson2; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +import org.springframework.security.jackson2.SecurityJackson2Modules; +import org.springframework.security.ldap.userdetails.LdapUserDetailsImpl; + +/** + * This Jackson mixin is used to serialize/deserialize {@link LdapUserDetailsImpl}. + * + * @since 5.7 + * @see LdapJackson2Module + * @see SecurityJackson2Modules + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) +@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +@JsonIgnoreProperties(ignoreUnknown = true) +abstract class LdapUserDetailsImplMixin { + +} diff --git a/ldap/src/main/java/org/springframework/security/ldap/jackson2/PersonMixin.java b/ldap/src/main/java/org/springframework/security/ldap/jackson2/PersonMixin.java new file mode 100644 index 00000000000..a3a0ddebc57 --- /dev/null +++ b/ldap/src/main/java/org/springframework/security/ldap/jackson2/PersonMixin.java @@ -0,0 +1,39 @@ +/* + * Copyright 2015-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.ldap.jackson2; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +import org.springframework.security.jackson2.SecurityJackson2Modules; +import org.springframework.security.ldap.userdetails.Person; + +/** + * This Jackson mixin is used to serialize/deserialize {@link Person}. + * + * @since 5.7 + * @see LdapJackson2Module + * @see SecurityJackson2Modules + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) +@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +@JsonIgnoreProperties(ignoreUnknown = true) +abstract class PersonMixin { + +} diff --git a/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSource.java b/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSource.java index 6fb79ffd4fd..9b5d2998818 100755 --- a/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSource.java +++ b/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSource.java @@ -50,8 +50,7 @@ public DirContext getContext(String principal, String credentials) throws Passwo if (principal.equals(this.userDn)) { return super.getContext(principal, credentials); } - this.logger - .debug(LogMessage.format("Binding as '%s', prior to reconnect as user '%s'", this.userDn, principal)); + this.logger.trace(LogMessage.format("Binding as %s, prior to reconnect as user %s", this.userDn, principal)); // First bind as manager user before rebinding as the specific principal. LdapContext ctx = (LdapContext) super.getContext(this.userDn, this.password); Control[] rctls = { new PasswordPolicyControl(false) }; @@ -63,8 +62,7 @@ public DirContext getContext(String principal, String credentials) throws Passwo catch (javax.naming.NamingException ex) { PasswordPolicyResponseControl ctrl = PasswordPolicyControlExtractor.extractControl(ctx); if (this.logger.isDebugEnabled()) { - this.logger.debug("Failed to obtain context", ex); - this.logger.debug("Password policy response: " + ctrl); + this.logger.debug(LogMessage.format("Failed to bind with %s", ctrl), ex); } LdapUtils.closeContext(ctx); if (ctrl != null && ctrl.isLocked()) { @@ -72,8 +70,7 @@ public DirContext getContext(String principal, String credentials) throws Passwo } throw LdapUtils.convertLdapException(ex); } - this.logger.debug( - LogMessage.of(() -> "PPolicy control returned: " + PasswordPolicyControlExtractor.extractControl(ctx))); + this.logger.debug(LogMessage.of(() -> "Bound with " + PasswordPolicyControlExtractor.extractControl(ctx))); return ctx; } diff --git a/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlExtractor.java b/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlExtractor.java index 79f007e4083..adffca9546c 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlExtractor.java +++ b/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlExtractor.java @@ -43,7 +43,7 @@ public static PasswordPolicyResponseControl extractControl(DirContext dirCtx) { ctrls = ctx.getResponseControls(); } catch (javax.naming.NamingException ex) { - logger.error("Failed to obtain response controls", ex); + logger.trace("Failed to obtain response controls", ex); } for (int i = 0; ctrls != null && i < ctrls.length; i++) { if (ctrls[i] instanceof PasswordPolicyResponseControl) { diff --git a/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyResponseControl.java b/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyResponseControl.java index bb1c8b08988..730b23291aa 100755 --- a/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyResponseControl.java +++ b/ldap/src/main/java/org/springframework/security/ldap/ppolicy/PasswordPolicyResponseControl.java @@ -31,6 +31,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.core.log.LogMessage; import org.springframework.dao.DataRetrievalFailureException; /** @@ -158,19 +159,21 @@ public boolean isLocked() { */ @Override public String toString() { - StringBuilder sb = new StringBuilder("PasswordPolicyResponseControl"); + StringBuilder sb = new StringBuilder(); + sb.append(getClass().getSimpleName()).append(" ["); if (hasError()) { - sb.append(", error: ").append(this.errorStatus.getDefaultMessage()); + sb.append("error=").append(this.errorStatus.getDefaultMessage()).append("; "); } if (this.graceLoginsRemaining != Integer.MAX_VALUE) { - sb.append(", warning: ").append(this.graceLoginsRemaining).append(" grace logins remain"); + sb.append("warning=").append(this.graceLoginsRemaining).append(" grace logins remain; "); } if (this.timeBeforeExpiration != Integer.MAX_VALUE) { - sb.append(", warning: time before expiration is ").append(this.timeBeforeExpiration); + sb.append("warning=time before expiration is ").append(this.timeBeforeExpiration).append("; "); } if (!hasError() && !hasWarning()) { - sb.append(" (no error, no warning)"); + sb.append("(no error, no warning)"); } + sb.append("]"); return sb.toString(); } @@ -192,7 +195,8 @@ public void decode() throws IOException { new ByteArrayInputStream(PasswordPolicyResponseControl.this.encodedValue), bread); int size = seq.size(); if (logger.isDebugEnabled()) { - logger.debug("PasswordPolicyResponse, ASN.1 sequence has " + size + " elements"); + logger.debug(LogMessage.format("Received PasswordPolicyResponse whose ASN.1 sequence has %d elements", + size)); } for (int i = 0; i < seq.size(); i++) { BERTag elt = (BERTag) seq.elementAt(i); diff --git a/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java b/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java index 86c6b4e8e75..c00a0b8c498 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java +++ b/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java @@ -79,8 +79,8 @@ public FilterBasedLdapUserSearch(String searchBase, String searchFilter, BaseLda this.searchBase = searchBase; setSearchSubtree(true); if (searchBase.length() == 0) { - logger.info( - "SearchBase not set. Searches will be performed from the root: " + contextSource.getBaseLdapPath()); + logger.info(LogMessage.format("Searches will be performed from the root %s since SearchBase not set", + contextSource.getBaseLdapPath())); } } @@ -93,11 +93,14 @@ public FilterBasedLdapUserSearch(String searchBase, String searchFilter, BaseLda */ @Override public DirContextOperations searchForUser(String username) { - logger.debug(LogMessage.of(() -> "Searching for user '" + username + "', with user search " + this)); + logger.trace(LogMessage.of(() -> "Searching for user '" + username + "', with " + this)); SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(this.contextSource); template.setSearchControls(this.searchControls); try { - return template.searchForSingleEntry(this.searchBase, this.searchFilter, new String[] { username }); + DirContextOperations operations = template.searchForSingleEntry(this.searchBase, this.searchFilter, + new String[] { username }); + logger.debug(LogMessage.of(() -> "Found user '" + username + "', with " + this)); + return operations; } catch (IncorrectResultSizeDataAccessException ex) { if (ex.getActualSize() == 0) { @@ -151,12 +154,14 @@ public void setReturningAttributes(String[] attrs) { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("[ searchFilter: '").append(this.searchFilter).append("', "); - sb.append("searchBase: '").append(this.searchBase).append("'"); - sb.append(", scope: ").append( - (this.searchControls.getSearchScope() != SearchControls.SUBTREE_SCOPE) ? "single-level, " : "subtree"); - sb.append(", searchTimeLimit: ").append(this.searchControls.getTimeLimit()); - sb.append(", derefLinkFlag: ").append(this.searchControls.getDerefLinkFlag()).append(" ]"); + sb.append(getClass().getSimpleName()).append(" ["); + sb.append("searchFilter=").append(this.searchFilter).append("; "); + sb.append("searchBase=").append(this.searchBase).append("; "); + sb.append("scope=").append( + (this.searchControls.getSearchScope() != SearchControls.SUBTREE_SCOPE) ? "single-level" : "subtree") + .append("; "); + sb.append("searchTimeLimit=").append(this.searchControls.getTimeLimit()).append("; "); + sb.append("derefLinkFlag=").append(this.searchControls.getDerefLinkFlag()).append(" ]"); return sb.toString(); } diff --git a/ldap/src/main/java/org/springframework/security/ldap/userdetails/DefaultLdapAuthoritiesPopulator.java b/ldap/src/main/java/org/springframework/security/ldap/userdetails/DefaultLdapAuthoritiesPopulator.java index 8ef21554c43..f16ba86b280 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/userdetails/DefaultLdapAuthoritiesPopulator.java +++ b/ldap/src/main/java/org/springframework/security/ldap/userdetails/DefaultLdapAuthoritiesPopulator.java @@ -163,10 +163,10 @@ public DefaultLdapAuthoritiesPopulator(ContextSource contextSource, String group getLdapTemplate().setSearchControls(getSearchControls()); this.groupSearchBase = groupSearchBase; if (groupSearchBase == null) { - logger.info("groupSearchBase is null. No group search will be performed."); + logger.info("Will not perform group search since groupSearchBase is null."); } else if (groupSearchBase.length() == 0) { - logger.info("groupSearchBase is empty. Searches will be performed from the context source base"); + logger.info("Will perform group search from the context source base since groupSearchBase is empty."); } this.authorityMapper = (record) -> { String role = record.get(this.groupRoleAttribute).get(0); @@ -199,7 +199,6 @@ protected Set getAdditionalRoles(DirContextOperations user, St @Override public final Collection getGrantedAuthorities(DirContextOperations user, String username) { String userDn = user.getNameInNamespace(); - logger.debug(LogMessage.format("Getting authorities for user %s", userDn)); Set roles = getGroupMembershipRoles(userDn, username); Set extraRoles = getAdditionalRoles(user, username); if (extraRoles != null) { @@ -210,6 +209,7 @@ public final Collection getGrantedAuthorities(DirContextOperat } List result = new ArrayList<>(roles.size()); result.addAll(roles); + logger.debug(LogMessage.format("Retrieved authorities for user %s", userDn)); return result; } @@ -218,12 +218,12 @@ public Set getGroupMembershipRoles(String userDn, String usern return new HashSet<>(); } Set authorities = new HashSet<>(); - logger.debug(LogMessage.of(() -> "Searching for roles for user '" + username + "', DN = " + "'" + userDn - + "', with filter " + this.groupSearchFilter + " in search base '" + getGroupSearchBase() + "'")); + logger.trace(LogMessage.of(() -> "Searching for roles for user " + username + " with DN " + userDn + + " and filter " + this.groupSearchFilter + " in search base " + getGroupSearchBase())); Set>> userRoles = getLdapTemplate().searchForMultipleAttributeValues( getGroupSearchBase(), this.groupSearchFilter, new String[] { userDn, username }, new String[] { this.groupRoleAttribute }); - logger.debug(LogMessage.of(() -> "Roles from search: " + userRoles)); + logger.debug(LogMessage.of(() -> "Found roles from search " + userRoles)); for (Map> role : userRoles) { authorities.add(this.authorityMapper.apply(role)); } diff --git a/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsImpl.java b/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsImpl.java index 29a7323e3db..a0ef3b333ba 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsImpl.java +++ b/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsImpl.java @@ -146,30 +146,16 @@ public int hashCode() { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(super.toString()).append(": "); - sb.append("Dn: ").append(this.dn).append("; "); - sb.append("Username: ").append(this.username).append("; "); - sb.append("Password: [PROTECTED]; "); - sb.append("Enabled: ").append(this.enabled).append("; "); - sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; "); - sb.append("CredentialsNonExpired: ").append(this.credentialsNonExpired).append("; "); - sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; "); - if (this.getAuthorities() != null && !this.getAuthorities().isEmpty()) { - sb.append("Granted Authorities: "); - boolean first = true; - for (Object authority : this.getAuthorities()) { - if (first) { - first = false; - } - else { - sb.append(", "); - } - sb.append(authority.toString()); - } - } - else { - sb.append("Not granted any authorities"); - } + sb.append(getClass().getSimpleName()).append(" ["); + sb.append("Dn=").append(this.dn).append("; "); + sb.append("Username=").append(this.username).append("; "); + sb.append("Password=[PROTECTED]; "); + sb.append("Enabled=").append(this.enabled).append("; "); + sb.append("AccountNonExpired=").append(this.accountNonExpired).append("; "); + sb.append("CredentialsNonExpired=").append(this.credentialsNonExpired).append("; "); + sb.append("AccountNonLocked=").append(this.accountNonLocked).append("; "); + sb.append("Granted Authorities=").append(getAuthorities()); + sb.append("]"); return sb.toString(); } diff --git a/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsMapper.java b/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsMapper.java index 56e724a0755..b44e30a0d87 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsMapper.java +++ b/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsMapper.java @@ -54,7 +54,7 @@ public class LdapUserDetailsMapper implements UserDetailsContextMapper { public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection authorities) { String dn = ctx.getNameInNamespace(); - this.logger.debug(LogMessage.format("Mapping user details from context with DN: %s", dn)); + this.logger.debug(LogMessage.format("Mapping user details from context with DN %s", dn)); LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence(); essence.setDn(dn); Object passwordValue = ctx.getObjectAttribute(this.passwordAttributeName); @@ -67,7 +67,7 @@ public UserDetails mapUserFromContext(DirContextOperations ctx, String username, String[] rolesForAttribute = ctx.getStringAttributes(this.roleAttributes[i]); if (rolesForAttribute == null) { this.logger.debug( - LogMessage.format("Couldn't read role attribute '%s' for user $s", this.roleAttributes[i], dn)); + LogMessage.format("Couldn't read role attribute %s for user %s", this.roleAttributes[i], dn)); continue; } for (String role : rolesForAttribute) { diff --git a/ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java b/ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java index 33d55d7c5b7..b61068ec8f5 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java +++ b/ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java @@ -166,13 +166,13 @@ public Set getGroupMembershipRoles(String userDn, String usern private void performNestedSearch(String userDn, String username, Set authorities, int depth) { if (depth == 0) { // back out of recursion - logger.debug(LogMessage.of(() -> "Search aborted, max depth reached," + " for roles for user '" + username - + "', DN = " + "'" + userDn + "', with filter " + getGroupSearchFilter() + " in search base '" + logger.debug(LogMessage.of(() -> "Aborted search since max depth reached," + " for roles for user '" + + username + " with DN = " + userDn + " and filter " + getGroupSearchFilter() + " in search base '" + getGroupSearchBase() + "'")); return; } - logger.debug(LogMessage.of(() -> "Searching for roles for user '" + username + "', DN = " + "'" + userDn - + "', with filter " + getGroupSearchFilter() + " in search base '" + getGroupSearchBase() + "'")); + logger.trace(LogMessage.of(() -> "Searching for roles for user " + username + " with DN " + userDn + + " and filter " + getGroupSearchFilter() + " in search base " + getGroupSearchBase())); if (getAttributeNames() == null) { setAttributeNames(new HashSet<>()); } @@ -182,7 +182,7 @@ private void performNestedSearch(String userDn, String username, Set>> userRoles = getLdapTemplate().searchForMultipleAttributeValues( getGroupSearchBase(), getGroupSearchFilter(), new String[] { userDn, username }, getAttributeNames().toArray(new String[0])); - logger.debug(LogMessage.format("Roles from search: %s", userRoles)); + logger.debug(LogMessage.format("Found roles from search %s", userRoles)); for (Map> record : userRoles) { boolean circular = false; String dn = record.get(SpringSecurityLdapTemplate.DN_KEY).get(0); diff --git a/ldap/src/test/java/org/springframework/security/ldap/jackson2/InetOrgPersonMixinTests.java b/ldap/src/test/java/org/springframework/security/ldap/jackson2/InetOrgPersonMixinTests.java new file mode 100644 index 00000000000..d9a05e65313 --- /dev/null +++ b/ldap/src/test/java/org/springframework/security/ldap/jackson2/InetOrgPersonMixinTests.java @@ -0,0 +1,196 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.ldap.jackson2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.json.JSONException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; + +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.jackson2.SecurityJackson2Modules; +import org.springframework.security.ldap.userdetails.InetOrgPerson; +import org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +/** + * Tests for {@link InetOrgPersonMixin}. + */ +public class InetOrgPersonMixinTests { + + private static final String USER_PASSWORD = "Password1234"; + + private static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", []]"; + + // @formatter:off + private static final String INET_ORG_PERSON_JSON = "{\n" + + "\"@class\": \"org.springframework.security.ldap.userdetails.InetOrgPerson\"," + + "\"dn\": \"ignored=ignored\"," + + "\"uid\": \"ghengis\"," + + "\"username\": \"ghengis\"," + + "\"password\": \"" + USER_PASSWORD + "\"," + + "\"carLicense\": \"HORS1\"," + + "\"givenName\": \"Ghengis\"," + + "\"destinationIndicator\": \"West\"," + + "\"displayName\": \"Ghengis McCann\"," + + "\"givenName\": \"Ghengis\"," + + "\"homePhone\": \"+467575436521\"," + + "\"initials\": \"G\"," + + "\"employeeNumber\": \"00001\"," + + "\"homePostalAddress\": \"Steppes\"," + + "\"mail\": \"ghengis@mongolia\"," + + "\"mobile\": \"always\"," + + "\"o\": \"Hordes\"," + + "\"ou\": \"Horde1\"," + + "\"postalAddress\": \"On the Move\"," + + "\"postalCode\": \"Changes Frequently\"," + + "\"roomNumber\": \"Yurt 1\"," + + "\"sn\": \"Khan\"," + + "\"street\": \"Westward Avenue\"," + + "\"telephoneNumber\": \"+442075436521\"," + + "\"departmentNumber\": \"5679\"," + + "\"title\": \"T\"," + + "\"cn\": [\"java.util.Arrays$ArrayList\",[\"Ghengis Khan\"]]," + + "\"description\": \"Scary\"," + + "\"accountNonExpired\": true, " + + "\"accountNonLocked\": true, " + + "\"credentialsNonExpired\": true, " + + "\"enabled\": true, " + + "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + "," + + "\"graceLoginsRemaining\": " + Integer.MAX_VALUE + "," + + "\"timeBeforeExpiration\": " + Integer.MAX_VALUE + + "}"; + // @formatter:on + + private ObjectMapper mapper; + + @BeforeEach + public void setup() { + ClassLoader loader = getClass().getClassLoader(); + this.mapper = new ObjectMapper(); + this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); + } + + @Test + public void serializeWhenMixinRegisteredThenSerializes() throws Exception { + InetOrgPersonContextMapper mapper = new InetOrgPersonContextMapper(); + InetOrgPerson p = (InetOrgPerson) mapper.mapUserFromContext(createUserContext(), "ghengis", + AuthorityUtils.NO_AUTHORITIES); + + String json = this.mapper.writeValueAsString(p); + JSONAssert.assertEquals(INET_ORG_PERSON_JSON, json, true); + } + + @Test + public void serializeWhenEraseCredentialInvokedThenUserPasswordIsNull() + throws JsonProcessingException, JSONException { + InetOrgPersonContextMapper mapper = new InetOrgPersonContextMapper(); + InetOrgPerson p = (InetOrgPerson) mapper.mapUserFromContext(createUserContext(), "ghengis", + AuthorityUtils.NO_AUTHORITIES); + p.eraseCredentials(); + String actualJson = this.mapper.writeValueAsString(p); + JSONAssert.assertEquals(INET_ORG_PERSON_JSON.replaceAll("\"" + USER_PASSWORD + "\"", "null"), actualJson, true); + } + + @Test + public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() { + assertThatExceptionOfType(JsonProcessingException.class) + .isThrownBy(() -> new ObjectMapper().readValue(INET_ORG_PERSON_JSON, InetOrgPerson.class)); + } + + @Test + public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception { + InetOrgPersonContextMapper mapper = new InetOrgPersonContextMapper(); + InetOrgPerson expectedAuthentication = (InetOrgPerson) mapper.mapUserFromContext(createUserContext(), "ghengis", + AuthorityUtils.NO_AUTHORITIES); + + InetOrgPerson authentication = this.mapper.readValue(INET_ORG_PERSON_JSON, InetOrgPerson.class); + assertThat(authentication.getAuthorities()).containsExactlyElementsOf(expectedAuthentication.getAuthorities()); + assertThat(authentication.getCarLicense()).isEqualTo(expectedAuthentication.getCarLicense()); + assertThat(authentication.getDepartmentNumber()).isEqualTo(expectedAuthentication.getDepartmentNumber()); + assertThat(authentication.getDestinationIndicator()) + .isEqualTo(expectedAuthentication.getDestinationIndicator()); + assertThat(authentication.getDn()).isEqualTo(expectedAuthentication.getDn()); + assertThat(authentication.getDescription()).isEqualTo(expectedAuthentication.getDescription()); + assertThat(authentication.getDisplayName()).isEqualTo(expectedAuthentication.getDisplayName()); + assertThat(authentication.getUid()).isEqualTo(expectedAuthentication.getUid()); + assertThat(authentication.getUsername()).isEqualTo(expectedAuthentication.getUsername()); + assertThat(authentication.getPassword()).isEqualTo(expectedAuthentication.getPassword()); + assertThat(authentication.getHomePhone()).isEqualTo(expectedAuthentication.getHomePhone()); + assertThat(authentication.getEmployeeNumber()).isEqualTo(expectedAuthentication.getEmployeeNumber()); + assertThat(authentication.getHomePostalAddress()).isEqualTo(expectedAuthentication.getHomePostalAddress()); + assertThat(authentication.getInitials()).isEqualTo(expectedAuthentication.getInitials()); + assertThat(authentication.getMail()).isEqualTo(expectedAuthentication.getMail()); + assertThat(authentication.getMobile()).isEqualTo(expectedAuthentication.getMobile()); + assertThat(authentication.getO()).isEqualTo(expectedAuthentication.getO()); + assertThat(authentication.getOu()).isEqualTo(expectedAuthentication.getOu()); + assertThat(authentication.getPostalAddress()).isEqualTo(expectedAuthentication.getPostalAddress()); + assertThat(authentication.getPostalCode()).isEqualTo(expectedAuthentication.getPostalCode()); + assertThat(authentication.getRoomNumber()).isEqualTo(expectedAuthentication.getRoomNumber()); + assertThat(authentication.getStreet()).isEqualTo(expectedAuthentication.getStreet()); + assertThat(authentication.getSn()).isEqualTo(expectedAuthentication.getSn()); + assertThat(authentication.getTitle()).isEqualTo(expectedAuthentication.getTitle()); + assertThat(authentication.getGivenName()).isEqualTo(expectedAuthentication.getGivenName()); + assertThat(authentication.getTelephoneNumber()).isEqualTo(expectedAuthentication.getTelephoneNumber()); + assertThat(authentication.getGraceLoginsRemaining()) + .isEqualTo(expectedAuthentication.getGraceLoginsRemaining()); + assertThat(authentication.getTimeBeforeExpiration()) + .isEqualTo(expectedAuthentication.getTimeBeforeExpiration()); + assertThat(authentication.isAccountNonExpired()).isEqualTo(expectedAuthentication.isAccountNonExpired()); + assertThat(authentication.isAccountNonLocked()).isEqualTo(expectedAuthentication.isAccountNonLocked()); + assertThat(authentication.isEnabled()).isEqualTo(expectedAuthentication.isEnabled()); + assertThat(authentication.isCredentialsNonExpired()) + .isEqualTo(expectedAuthentication.isCredentialsNonExpired()); + } + + private DirContextAdapter createUserContext() { + DirContextAdapter ctx = new DirContextAdapter(); + ctx.setDn(new DistinguishedName("ignored=ignored")); + ctx.setAttributeValue("uid", "ghengis"); + ctx.setAttributeValue("userPassword", USER_PASSWORD); + ctx.setAttributeValue("carLicense", "HORS1"); + ctx.setAttributeValue("cn", "Ghengis Khan"); + ctx.setAttributeValue("description", "Scary"); + ctx.setAttributeValue("destinationIndicator", "West"); + ctx.setAttributeValue("displayName", "Ghengis McCann"); + ctx.setAttributeValue("givenName", "Ghengis"); + ctx.setAttributeValue("homePhone", "+467575436521"); + ctx.setAttributeValue("initials", "G"); + ctx.setAttributeValue("employeeNumber", "00001"); + ctx.setAttributeValue("homePostalAddress", "Steppes"); + ctx.setAttributeValue("mail", "ghengis@mongolia"); + ctx.setAttributeValue("mobile", "always"); + ctx.setAttributeValue("o", "Hordes"); + ctx.setAttributeValue("ou", "Horde1"); + ctx.setAttributeValue("postalAddress", "On the Move"); + ctx.setAttributeValue("postalCode", "Changes Frequently"); + ctx.setAttributeValue("roomNumber", "Yurt 1"); + ctx.setAttributeValue("sn", "Khan"); + ctx.setAttributeValue("street", "Westward Avenue"); + ctx.setAttributeValue("telephoneNumber", "+442075436521"); + ctx.setAttributeValue("departmentNumber", "5679"); + ctx.setAttributeValue("title", "T"); + return ctx; + } + +} diff --git a/ldap/src/test/java/org/springframework/security/ldap/jackson2/LdapUserDetailsImplMixinTests.java b/ldap/src/test/java/org/springframework/security/ldap/jackson2/LdapUserDetailsImplMixinTests.java new file mode 100644 index 00000000000..755623ba8f0 --- /dev/null +++ b/ldap/src/test/java/org/springframework/security/ldap/jackson2/LdapUserDetailsImplMixinTests.java @@ -0,0 +1,126 @@ +/* + * Copyright 2002-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.ldap.jackson2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.json.JSONException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; + +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.jackson2.SecurityJackson2Modules; +import org.springframework.security.ldap.userdetails.LdapUserDetailsImpl; +import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +/** + * Tests for {@link LdapUserDetailsImplMixin}. + */ +public class LdapUserDetailsImplMixinTests { + + private static final String USER_PASSWORD = "Password1234"; + + private static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", []]"; + + // @formatter:off + private static final String USER_JSON = "{" + + "\"@class\": \"org.springframework.security.ldap.userdetails.LdapUserDetailsImpl\", " + + "\"dn\": \"ignored=ignored\"," + + "\"username\": \"ghengis\"," + + "\"password\": \"" + USER_PASSWORD + "\"," + + "\"accountNonExpired\": true, " + + "\"accountNonLocked\": true, " + + "\"credentialsNonExpired\": true, " + + "\"enabled\": true, " + + "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + "," + + "\"graceLoginsRemaining\": " + Integer.MAX_VALUE + "," + + "\"timeBeforeExpiration\": " + Integer.MAX_VALUE + + "}"; + // @formatter:on + + private ObjectMapper mapper; + + @BeforeEach + public void setup() { + ClassLoader loader = getClass().getClassLoader(); + this.mapper = new ObjectMapper(); + this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); + } + + @Test + public void serializeWhenMixinRegisteredThenSerializes() throws Exception { + LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); + LdapUserDetailsImpl p = (LdapUserDetailsImpl) mapper.mapUserFromContext(createUserContext(), "ghengis", + AuthorityUtils.NO_AUTHORITIES); + + String json = this.mapper.writeValueAsString(p); + JSONAssert.assertEquals(USER_JSON, json, true); + } + + @Test + public void serializeWhenEraseCredentialInvokedThenUserPasswordIsNull() + throws JsonProcessingException, JSONException { + LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); + LdapUserDetailsImpl p = (LdapUserDetailsImpl) mapper.mapUserFromContext(createUserContext(), "ghengis", + AuthorityUtils.NO_AUTHORITIES); + p.eraseCredentials(); + String actualJson = this.mapper.writeValueAsString(p); + JSONAssert.assertEquals(USER_JSON.replaceAll("\"" + USER_PASSWORD + "\"", "null"), actualJson, true); + } + + @Test + public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() { + assertThatExceptionOfType(JsonProcessingException.class) + .isThrownBy(() -> new ObjectMapper().readValue(USER_JSON, LdapUserDetailsImpl.class)); + } + + @Test + public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception { + LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); + LdapUserDetailsImpl expectedAuthentication = (LdapUserDetailsImpl) mapper + .mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); + + LdapUserDetailsImpl authentication = this.mapper.readValue(USER_JSON, LdapUserDetailsImpl.class); + assertThat(authentication.getAuthorities()).containsExactlyElementsOf(expectedAuthentication.getAuthorities()); + assertThat(authentication.getDn()).isEqualTo(expectedAuthentication.getDn()); + assertThat(authentication.getUsername()).isEqualTo(expectedAuthentication.getUsername()); + assertThat(authentication.getPassword()).isEqualTo(expectedAuthentication.getPassword()); + assertThat(authentication.getGraceLoginsRemaining()) + .isEqualTo(expectedAuthentication.getGraceLoginsRemaining()); + assertThat(authentication.getTimeBeforeExpiration()) + .isEqualTo(expectedAuthentication.getTimeBeforeExpiration()); + assertThat(authentication.isAccountNonExpired()).isEqualTo(expectedAuthentication.isAccountNonExpired()); + assertThat(authentication.isAccountNonLocked()).isEqualTo(expectedAuthentication.isAccountNonLocked()); + assertThat(authentication.isEnabled()).isEqualTo(expectedAuthentication.isEnabled()); + assertThat(authentication.isCredentialsNonExpired()) + .isEqualTo(expectedAuthentication.isCredentialsNonExpired()); + } + + private DirContextAdapter createUserContext() { + DirContextAdapter ctx = new DirContextAdapter(); + ctx.setDn(new DistinguishedName("ignored=ignored")); + ctx.setAttributeValue("userPassword", USER_PASSWORD); + return ctx; + } + +} diff --git a/ldap/src/test/java/org/springframework/security/ldap/jackson2/PersonMixinTests.java b/ldap/src/test/java/org/springframework/security/ldap/jackson2/PersonMixinTests.java new file mode 100644 index 00000000000..018058888ef --- /dev/null +++ b/ldap/src/test/java/org/springframework/security/ldap/jackson2/PersonMixinTests.java @@ -0,0 +1,138 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.ldap.jackson2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.json.JSONException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; + +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.jackson2.SecurityJackson2Modules; +import org.springframework.security.ldap.userdetails.Person; +import org.springframework.security.ldap.userdetails.PersonContextMapper; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +/** + * Tests for {@link PersonMixin}. + */ +public class PersonMixinTests { + + private static final String USER_PASSWORD = "Password1234"; + + private static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", []]"; + + // @formatter:off + private static final String PERSON_JSON = "{" + + "\"@class\": \"org.springframework.security.ldap.userdetails.Person\", " + + "\"dn\": \"ignored=ignored\"," + + "\"username\": \"ghengis\"," + + "\"password\": \"" + USER_PASSWORD + "\"," + + "\"givenName\": \"Ghengis\"," + + "\"sn\": \"Khan\"," + + "\"cn\": [\"java.util.Arrays$ArrayList\",[\"Ghengis Khan\"]]," + + "\"description\": \"Scary\"," + + "\"telephoneNumber\": \"+442075436521\"," + + "\"accountNonExpired\": true, " + + "\"accountNonLocked\": true, " + + "\"credentialsNonExpired\": true, " + + "\"enabled\": true, " + + "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + "," + + "\"graceLoginsRemaining\": " + Integer.MAX_VALUE + "," + + "\"timeBeforeExpiration\": " + Integer.MAX_VALUE + + "}"; + // @formatter:on + + private ObjectMapper mapper; + + @BeforeEach + public void setup() { + ClassLoader loader = getClass().getClassLoader(); + this.mapper = new ObjectMapper(); + this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); + } + + @Test + public void serializeWhenMixinRegisteredThenSerializes() throws Exception { + PersonContextMapper mapper = new PersonContextMapper(); + Person p = (Person) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); + + String json = this.mapper.writeValueAsString(p); + JSONAssert.assertEquals(PERSON_JSON, json, true); + } + + @Test + public void serializeWhenEraseCredentialInvokedThenUserPasswordIsNull() + throws JsonProcessingException, JSONException { + PersonContextMapper mapper = new PersonContextMapper(); + Person p = (Person) mapper.mapUserFromContext(createUserContext(), "ghengis", AuthorityUtils.NO_AUTHORITIES); + p.eraseCredentials(); + String actualJson = this.mapper.writeValueAsString(p); + JSONAssert.assertEquals(PERSON_JSON.replaceAll("\"" + USER_PASSWORD + "\"", "null"), actualJson, true); + } + + @Test + public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() { + assertThatExceptionOfType(JsonProcessingException.class) + .isThrownBy(() -> new ObjectMapper().readValue(PERSON_JSON, Person.class)); + } + + @Test + public void deserializeWhenMixinRegisteredThenDeserializes() throws Exception { + PersonContextMapper mapper = new PersonContextMapper(); + Person expectedAuthentication = (Person) mapper.mapUserFromContext(createUserContext(), "ghengis", + AuthorityUtils.NO_AUTHORITIES); + + Person authentication = this.mapper.readValue(PERSON_JSON, Person.class); + assertThat(authentication.getAuthorities()).containsExactlyElementsOf(expectedAuthentication.getAuthorities()); + assertThat(authentication.getDn()).isEqualTo(expectedAuthentication.getDn()); + assertThat(authentication.getDescription()).isEqualTo(expectedAuthentication.getDescription()); + assertThat(authentication.getUsername()).isEqualTo(expectedAuthentication.getUsername()); + assertThat(authentication.getPassword()).isEqualTo(expectedAuthentication.getPassword()); + assertThat(authentication.getSn()).isEqualTo(expectedAuthentication.getSn()); + assertThat(authentication.getGivenName()).isEqualTo(expectedAuthentication.getGivenName()); + assertThat(authentication.getTelephoneNumber()).isEqualTo(expectedAuthentication.getTelephoneNumber()); + assertThat(authentication.getGraceLoginsRemaining()) + .isEqualTo(expectedAuthentication.getGraceLoginsRemaining()); + assertThat(authentication.getTimeBeforeExpiration()) + .isEqualTo(expectedAuthentication.getTimeBeforeExpiration()); + assertThat(authentication.isAccountNonExpired()).isEqualTo(expectedAuthentication.isAccountNonExpired()); + assertThat(authentication.isAccountNonLocked()).isEqualTo(expectedAuthentication.isAccountNonLocked()); + assertThat(authentication.isEnabled()).isEqualTo(expectedAuthentication.isEnabled()); + assertThat(authentication.isCredentialsNonExpired()) + .isEqualTo(expectedAuthentication.isCredentialsNonExpired()); + } + + private DirContextAdapter createUserContext() { + DirContextAdapter ctx = new DirContextAdapter(); + ctx.setDn(new DistinguishedName("ignored=ignored")); + ctx.setAttributeValue("userPassword", USER_PASSWORD); + ctx.setAttributeValue("cn", "Ghengis Khan"); + ctx.setAttributeValue("description", "Scary"); + ctx.setAttributeValue("givenName", "Ghengis"); + ctx.setAttributeValue("sn", "Khan"); + ctx.setAttributeValue("telephoneNumber", "+442075436521"); + return ctx; + } + +} diff --git a/local-antora-playbook.yml b/local-antora-playbook.yml deleted file mode 100644 index 061bad7e96d..00000000000 --- a/local-antora-playbook.yml +++ /dev/null @@ -1,17 +0,0 @@ -site: - title: Spring Security - start_page: security::index.adoc -asciidoc: - attributes: - page-pagination: true -content: - sources: - - url: ./ - branches: [HEAD] - start_path: docs - - url: ../../rwinch/spring-security-docs-generated - branches: [HEAD] -ui: - bundle: - url: https://github.com/rwinch/antora-ui-spring/releases/download/latest/ui-bundle.zip - snapshot: true diff --git a/messaging/spring-security-messaging.gradle b/messaging/spring-security-messaging.gradle index 6556c0e6b00..b5a8e03ec7a 100644 --- a/messaging/spring-security-messaging.gradle +++ b/messaging/spring-security-messaging.gradle @@ -12,7 +12,7 @@ dependencies { optional project(':spring-security-web') optional 'org.springframework:spring-websocket' optional 'io.projectreactor:reactor-core' - optional 'javax.servlet:javax.servlet-api' + optional 'jakarta.servlet:jakarta.servlet-api' testImplementation project(path: ':spring-security-core', configuration: 'tests') testImplementation 'commons-codec:commons-codec' diff --git a/messaging/src/main/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptor.java b/messaging/src/main/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptor.java index 594cfcacba8..b7f959c499d 100644 --- a/messaging/src/main/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptor.java +++ b/messaging/src/main/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptor.java @@ -22,7 +22,7 @@ import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; -import org.springframework.messaging.support.ChannelInterceptorAdapter; +import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.messaging.support.ExecutorChannelInterceptor; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; @@ -40,8 +40,7 @@ * @author Rob Winch * @since 4.0 */ -public final class SecurityContextChannelInterceptor extends ChannelInterceptorAdapter - implements ExecutorChannelInterceptor { +public final class SecurityContextChannelInterceptor implements ExecutorChannelInterceptor, ChannelInterceptor { private static final SecurityContext EMPTY_CONTEXT = SecurityContextHolder.createEmptyContext(); diff --git a/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java b/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java index 059b34bddba..cc2a696662c 100644 --- a/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java +++ b/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java @@ -22,7 +22,7 @@ import org.springframework.messaging.MessageChannel; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageType; -import org.springframework.messaging.support.ChannelInterceptorAdapter; +import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.security.messaging.util.matcher.MessageMatcher; import org.springframework.security.messaging.util.matcher.SimpMessageTypeMatcher; import org.springframework.security.web.csrf.CsrfToken; @@ -30,14 +30,14 @@ import org.springframework.security.web.csrf.MissingCsrfTokenException; /** - * {@link ChannelInterceptorAdapter} that validates that a valid CSRF is included in the - * header of any {@link SimpMessageType#CONNECT} message. The expected {@link CsrfToken} - * is populated by CsrfTokenHandshakeInterceptor. + * {@link ChannelInterceptor} that validates that a valid CSRF is included in the header + * of any {@link SimpMessageType#CONNECT} message. The expected {@link CsrfToken} is + * populated by CsrfTokenHandshakeInterceptor. * * @author Rob Winch * @since 4.0 */ -public final class CsrfChannelInterceptor extends ChannelInterceptorAdapter { +public final class CsrfChannelInterceptor implements ChannelInterceptor { private final MessageMatcher matcher = new SimpMessageTypeMatcher(SimpMessageType.CONNECT); diff --git a/messaging/src/main/java/org/springframework/security/messaging/web/socket/server/CsrfTokenHandshakeInterceptor.java b/messaging/src/main/java/org/springframework/security/messaging/web/socket/server/CsrfTokenHandshakeInterceptor.java index aa40975f2f6..aa936c91fe0 100644 --- a/messaging/src/main/java/org/springframework/security/messaging/web/socket/server/CsrfTokenHandshakeInterceptor.java +++ b/messaging/src/main/java/org/springframework/security/messaging/web/socket/server/CsrfTokenHandshakeInterceptor.java @@ -18,7 +18,7 @@ import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; diff --git a/oauth2/oauth2-client/spring-security-oauth2-client.gradle b/oauth2/oauth2-client/spring-security-oauth2-client.gradle index 3a6b1c1394a..b16fa09bebe 100644 --- a/oauth2/oauth2-client/spring-security-oauth2-client.gradle +++ b/oauth2/oauth2-client/spring-security-oauth2-client.gradle @@ -21,7 +21,6 @@ dependencies { testImplementation 'com.squareup.okhttp3:mockwebserver' testImplementation 'io.projectreactor.netty:reactor-netty' testImplementation 'io.projectreactor:reactor-test' - testImplementation 'io.projectreactor.tools:blockhound' testImplementation 'org.skyscreamer:jsonassert' testImplementation 'io.r2dbc:r2dbc-h2:0.8.4.RELEASE' testImplementation 'io.r2dbc:r2dbc-spi-test:0.8.6.RELEASE' @@ -35,5 +34,5 @@ dependencies { testRuntimeOnly 'org.hsqldb:hsqldb' - provided 'javax.servlet:javax.servlet-api' + provided 'jakarta.servlet:jakarta.servlet-api' } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationFailureHandler.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationFailureHandler.java index 4e6089eab1d..3a246c49fbd 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationFailureHandler.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationFailureHandler.java @@ -40,9 +40,9 @@ public interface OAuth2AuthorizationFailureHandler { * @param principal the {@code Principal} associated with the attempted authorization * @param attributes an immutable {@code Map} of (optional) attributes present under * certain conditions. For example, this might contain a - * {@code javax.servlet.http.HttpServletRequest} and - * {@code javax.servlet.http.HttpServletResponse} if the authorization was performed - * within the context of a {@code javax.servlet.ServletContext}. + * {@code jakarta.servlet.http.HttpServletRequest} and + * {@code jakarta.servlet.http.HttpServletResponse} if the authorization was performed + * within the context of a {@code jakarta.servlet.ServletContext}. */ void onAuthorizationFailure(OAuth2AuthorizationException authorizationException, Authentication principal, Map attributes); diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationSuccessHandler.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationSuccessHandler.java index 7e5e81a3854..c28a388c8bd 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationSuccessHandler.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizationSuccessHandler.java @@ -40,9 +40,9 @@ public interface OAuth2AuthorizationSuccessHandler { * @param principal the {@code Principal} associated with the authorized client * @param attributes an immutable {@code Map} of (optional) attributes present under * certain conditions. For example, this might contain a - * {@code javax.servlet.http.HttpServletRequest} and - * {@code javax.servlet.http.HttpServletResponse} if the authorization was performed - * within the context of a {@code javax.servlet.ServletContext}. + * {@code jakarta.servlet.http.HttpServletRequest} and + * {@code jakarta.servlet.http.HttpServletResponse} if the authorization was performed + * within the context of a {@code jakarta.servlet.ServletContext}. */ void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal, Map attributes); diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilder.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilder.java index fa109dd2aa3..10a048f185f 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilder.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -204,10 +204,12 @@ public PasswordGrantBuilder accessTokenResponseClient( /** * Sets the maximum acceptable clock skew, which is used when checking the access - * token expiry. An access token is considered expired if it's before - * {@code Instant.now(this.clock) - clockSkew}. + * token expiry. An access token is considered expired if + * {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time + * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew * @return the {@link PasswordGrantBuilder} + * @see PasswordOAuth2AuthorizedClientProvider#setClockSkew(Duration) */ public PasswordGrantBuilder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; @@ -275,10 +277,12 @@ public ClientCredentialsGrantBuilder accessTokenResponseClient( /** * Sets the maximum acceptable clock skew, which is used when checking the access - * token expiry. An access token is considered expired if it's before - * {@code Instant.now(this.clock) - clockSkew}. + * token expiry. An access token is considered expired if + * {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time + * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew * @return the {@link ClientCredentialsGrantBuilder} + * @see ClientCredentialsOAuth2AuthorizedClientProvider#setClockSkew(Duration) */ public ClientCredentialsGrantBuilder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; @@ -365,10 +369,12 @@ public RefreshTokenGrantBuilder accessTokenResponseClient( /** * Sets the maximum acceptable clock skew, which is used when checking the access - * token expiry. An access token is considered expired if it's before - * {@code Instant.now(this.clock) - clockSkew}. + * token expiry. An access token is considered expired if + * {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time + * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew * @return the {@link RefreshTokenGrantBuilder} + * @see RefreshTokenOAuth2AuthorizedClientProvider#setClockSkew(Duration) */ public RefreshTokenGrantBuilder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilder.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilder.java index 7b0580571db..c9483fa16be 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilder.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -225,10 +225,12 @@ public ClientCredentialsGrantBuilder accessTokenResponseClient( /** * Sets the maximum acceptable clock skew, which is used when checking the access - * token expiry. An access token is considered expired if it's before - * {@code Instant.now(this.clock) - clockSkew}. + * token expiry. An access token is considered expired if + * {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time + * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew * @return the {@link ClientCredentialsGrantBuilder} + * @see ClientCredentialsReactiveOAuth2AuthorizedClientProvider#setClockSkew(Duration) */ public ClientCredentialsGrantBuilder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; @@ -297,10 +299,12 @@ public PasswordGrantBuilder accessTokenResponseClient( /** * Sets the maximum acceptable clock skew, which is used when checking the access - * token expiry. An access token is considered expired if it's before - * {@code Instant.now(this.clock) - clockSkew}. + * token expiry. An access token is considered expired if + * {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time + * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew * @return the {@link PasswordGrantBuilder} + * @see PasswordReactiveOAuth2AuthorizedClientProvider#setClockSkew(Duration) */ public PasswordGrantBuilder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; @@ -368,10 +372,12 @@ public RefreshTokenGrantBuilder accessTokenResponseClient( /** * Sets the maximum acceptable clock skew, which is used when checking the access - * token expiry. An access token is considered expired if it's before - * {@code Instant.now(this.clock) - clockSkew}. + * token expiry. An access token is considered expired if + * {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time + * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew * @return the {@link RefreshTokenGrantBuilder} + * @see RefreshTokenReactiveOAuth2AuthorizedClientProvider#setClockSkew(Duration) */ public RefreshTokenGrantBuilder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/RemoveAuthorizedClientOAuth2AuthorizationFailureHandler.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/RemoveAuthorizedClientOAuth2AuthorizationFailureHandler.java index 3701e8457ce..d367685e21f 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/RemoveAuthorizedClientOAuth2AuthorizationFailureHandler.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/RemoveAuthorizedClientOAuth2AuthorizationFailureHandler.java @@ -143,9 +143,9 @@ public interface OAuth2AuthorizedClientRemover { * @param principal the End-User {@link Authentication} (Resource Owner) * @param attributes an immutable {@code Map} of (optional) attributes present * under certain conditions. For example, this might contain a - * {@code javax.servlet.http.HttpServletRequest} and - * {@code javax.servlet.http.HttpServletResponse} if the authorization was - * performed within the context of a {@code javax.servlet.ServletContext}. + * {@code jakarta.servlet.http.HttpServletRequest} and + * {@code jakarta.servlet.http.HttpServletResponse} if the authorization was + * performed within the context of a {@code jakarta.servlet.ServletContext}. */ void removeAuthorizedClient(String clientRegistrationId, Authentication principal, Map attributes); diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandler.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandler.java index 3f23c7d5836..5e14fb66a19 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandler.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandler.java @@ -23,10 +23,12 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.converter.HttpMessageConverter; import org.springframework.security.oauth2.core.OAuth2AuthorizationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.http.converter.OAuth2ErrorHttpMessageConverter; +import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.ResponseErrorHandler; @@ -41,7 +43,7 @@ */ public class OAuth2ErrorResponseErrorHandler implements ResponseErrorHandler { - private final OAuth2ErrorHttpMessageConverter oauth2ErrorConverter = new OAuth2ErrorHttpMessageConverter(); + private HttpMessageConverter oauth2ErrorConverter = new OAuth2ErrorHttpMessageConverter(); private final ResponseErrorHandler defaultErrorHandler = new DefaultResponseErrorHandler(); @@ -89,4 +91,15 @@ private BearerTokenError getBearerToken(String wwwAuthenticateHeader) { } } + /** + * Sets the {@link HttpMessageConverter} for an OAuth 2.0 Error. + * @param oauth2ErrorConverter A {@link HttpMessageConverter} for an + * {@link OAuth2Error OAuth 2.0 Error}. + * @since 5.7 + */ + public final void setErrorConverter(HttpMessageConverter oauth2ErrorConverter) { + Assert.notNull(oauth2ErrorConverter, "oauth2ErrorConverter cannot be null"); + this.oauth2ErrorConverter = oauth2ErrorConverter; + } + } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandler.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandler.java index 262e08a2aae..766424f4fe2 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandler.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandler.java @@ -20,8 +20,8 @@ import java.nio.charset.StandardCharsets; import java.util.Collections; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepository.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepository.java index 246f729aa9d..fb0e5d2889f 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepository.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepository.java @@ -16,8 +16,8 @@ package org.springframework.security.oauth2.client.web; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthorizationRequestRepository.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthorizationRequestRepository.java index 90e47929f1e..b10f694b83e 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthorizationRequestRepository.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthorizationRequestRepository.java @@ -16,8 +16,8 @@ package org.springframework.security.oauth2.client.web; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolver.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolver.java index 7e606eae6bd..fc7b8747ab9 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolver.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolver.java @@ -24,7 +24,7 @@ import java.util.Map; import java.util.function.Consumer; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.crypto.keygen.Base64StringKeyGenerator; import org.springframework.security.crypto.keygen.StringKeyGenerator; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManager.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManager.java index 02e41ab33f8..bfe626cfdc6 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManager.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManager.java @@ -21,8 +21,8 @@ import java.util.Map; import java.util.function.Function; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.lang.Nullable; import org.springframework.security.core.Authentication; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepository.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepository.java index fd19d1c2cdb..c1103f98467 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepository.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepository.java @@ -19,9 +19,9 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepository.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepository.java index e0b65a63980..727cab1aa65 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepository.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepository.java @@ -19,9 +19,9 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilter.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilter.java index f8bc3b13b2f..1e41edf85cf 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilter.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilter.java @@ -23,10 +23,10 @@ import java.util.Objects; import java.util.Set; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.AuthenticationManager; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilter.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilter.java index ab8e7c4413a..2bf35d43b63 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilter.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilter.java @@ -18,10 +18,10 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.http.HttpStatus; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestResolver.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestResolver.java index d4c6fda21fa..dd930f6d4e6 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestResolver.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestResolver.java @@ -16,7 +16,7 @@ package org.springframework.security.oauth2.client.web; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizedClientRepository.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizedClientRepository.java index f52993a3d54..50661037764 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizedClientRepository.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizedClientRepository.java @@ -16,8 +16,8 @@ package org.springframework.security.oauth2.client.web; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilter.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilter.java index 9bebb0869c8..a4c3b8d626d 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilter.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilter.java @@ -16,8 +16,8 @@ package org.springframework.security.oauth2.client.web; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AuthenticationManager; @@ -222,6 +222,7 @@ public final void setAuthorizationRequestRepository( * authentication result. * @param authenticationResultConverter the converter for * {@link OAuth2AuthenticationToken}'s + * @since 5.6 */ public final void setAuthenticationResultConverter( Converter authenticationResultConverter) { diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolver.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolver.java index 32247a860a7..951ee9effa0 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolver.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolver.java @@ -16,8 +16,8 @@ package org.springframework.security.oauth2.client.web.method.annotation; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.MethodParameter; import org.springframework.core.annotation.AnnotatedElementUtils; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.java index c2fcadc1c79..712ef7352ee 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.java @@ -24,8 +24,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java index f5a84834949..aed0aad7fa8 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java @@ -23,12 +23,19 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.converter.HttpMessageConverter; import org.springframework.mock.http.MockHttpInputMessage; import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.security.oauth2.core.OAuth2AuthorizationException; +import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.web.client.UnknownHttpStatusCodeException; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; /** * Tests for {@link OAuth2ErrorResponseErrorHandler}. @@ -53,6 +60,26 @@ public void handleErrorWhenErrorResponseBodyThenHandled() { .withMessage("[unauthorized_client] The client is not authorized"); } + @Test + public void handleErrorWhenOAuth2ErrorConverterSetThenCalled() throws IOException { + HttpMessageConverter oauth2ErrorConverter = mock(HttpMessageConverter.class); + this.errorHandler.setErrorConverter(oauth2ErrorConverter); + // @formatter:off + String errorResponse = "{\n" + + " \"errorCode\": \"unauthorized_client\",\n" + + " \"errorSummary\": \"The client is not authorized\"\n" + + "}\n"; + // @formatter:on + MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST); + given(oauth2ErrorConverter.read(any(), any())) + .willReturn(new OAuth2Error("unauthorized_client", "The client is not authorized", null)); + + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.errorHandler.handleError(response)) + .withMessage("[unauthorized_client] The client is not authorized"); + verify(oauth2ErrorConverter).read(eq(OAuth2Error.class), eq(response)); + } + @Test public void handleErrorWhenErrorResponseWwwAuthenticateHeaderThenHandled() { String wwwAuthenticateHeader = "Bearer realm=\"auth-realm\" error=\"insufficient_scope\" error_description=\"The access token expired\""; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java index b5ca968f99a..d270b9c0d67 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java @@ -20,7 +20,7 @@ import java.net.URI; import java.util.Collections; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java index 2a28fea70a4..d7b39ff1d48 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java @@ -20,7 +20,7 @@ import java.net.URI; import java.util.Collections; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java index 5c91205e4a7..58db8b5e509 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java @@ -19,7 +19,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java index 8fe786146fc..868505c5b18 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java @@ -20,8 +20,8 @@ import java.util.Map; import java.util.function.Function; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepositoryTests.java index 1054b29beb0..1af63530677 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepositoryTests.java @@ -18,7 +18,7 @@ import java.util.Map; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java index e822c4b932a..55d3bd793d1 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java @@ -21,10 +21,10 @@ import java.util.Map; import java.util.stream.Collectors; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java index 0df8ea1a03d..e82985de03c 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java @@ -21,11 +21,11 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.FilterChain; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java index d399f3c3dbe..e0bf75ddf73 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java @@ -20,9 +20,9 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java index 1e83a645f94..5f6ec7b1291 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java @@ -20,8 +20,8 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java index d0a0b8e7308..b06e30c6fa0 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java @@ -23,17 +23,15 @@ import java.util.HashSet; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import reactor.blockhound.BlockHound; import reactor.util.context.Context; import org.springframework.http.HttpHeaders; @@ -89,23 +87,6 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests { private MockHttpServletResponse response; - @BeforeAll - public static void setUpBlockingChecks() { - // IMPORTANT: - // Before enabling BlockHound, we need to white-list - // `java.lang.Class.getPackage()`. - // When the JVM loads `java.lang.Package.getSystemPackage()`, it attempts to - // `java.lang.Package.loadManifest()` which is blocking I/O and triggers - // BlockHound to error. - // NOTE: This is an issue with JDK 8. It's been tested on JDK 10 and works fine - // w/o this white-list. - // @formatter:off - BlockHound.builder() - .allowBlockingCallsInside(Class.class.getName(), "getPackage") - .install(); - // @formatter:on - } - @BeforeEach public void setUp() throws Exception { this.clientRegistrationRepository = mock(ClientRegistrationRepository.class); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java index 849a173ebfa..46c7226dad7 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java @@ -28,8 +28,8 @@ import java.util.Optional; import java.util.function.Consumer; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilterTests.java index a326bcc9942..e304ced2dde 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilterTests.java @@ -74,7 +74,7 @@ public void setup() { this.filter = new OAuth2LoginAuthenticationWebFilter(this.authenticationManager, this.authorizedClientRepository); this.webFilterExchange = new WebFilterExchange(MockServerWebExchange.from(MockServerHttpRequest.get("/")), - new DefaultWebFilterChain((exchange) -> exchange.getResponse().setComplete())); + new DefaultWebFilterChain((exchange) -> exchange.getResponse().setComplete(), Collections.emptyList())); given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty()); } diff --git a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtClaimValidator.java b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtClaimValidator.java index 73c13c7dc29..0202815cc20 100644 --- a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtClaimValidator.java +++ b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtClaimValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -54,7 +54,7 @@ public JwtClaimValidator(String claim, Predicate test) { Assert.notNull(test, "test can not be null"); this.claim = claim; this.test = test; - this.error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, "The " + this.claim + " claim is not valid", + this.error = new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, "The " + this.claim + " claim is not valid", "https://tools.ietf.org/html/rfc6750#section-3.1"); } diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java index 430f7078924..a43989c8680 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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,10 +16,14 @@ package org.springframework.security.oauth2.jwt; +import java.util.Collection; +import java.util.Objects; import java.util.function.Predicate; import org.junit.jupiter.api.Test; +import org.springframework.security.oauth2.core.OAuth2Error; +import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import static org.assertj.core.api.Assertions.assertThat; @@ -45,7 +49,9 @@ public void validateWhenClaimPassesTheTestThenReturnsSuccess() { @Test public void validateWhenClaimFailsTheTestThenReturnsFailure() { Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "http://abc").build(); + Collection details = this.validator.validate(jwt).getErrors(); assertThat(this.validator.validate(jwt).getErrors().isEmpty()).isFalse(); + assertThat(details).allMatch((error) -> Objects.equals(error.getErrorCode(), OAuth2ErrorCodes.INVALID_TOKEN)); } @Test diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java index 7f8a093ad3c..72164cf21b7 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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,6 +23,7 @@ import java.util.Collection; import java.util.Collections; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; @@ -64,6 +65,7 @@ public void validateWhenJwtIsExpiredThenErrorMessageIndicatesExpirationTime() { .collect(Collectors.toList()); // @formatter:on assertThat(messages).contains("Jwt expired at " + oneHourAgo); + assertThat(details).allMatch((error) -> Objects.equals(error.getErrorCode(), OAuth2ErrorCodes.INVALID_TOKEN)); } @Test @@ -78,6 +80,7 @@ public void validateWhenJwtIsTooEarlyThenErrorMessageIndicatesNotBeforeTime() { .collect(Collectors.toList()); // @formatter:on assertThat(messages).contains("Jwt used before " + oneHourFromNow); + assertThat(details).allMatch((error) -> Objects.equals(error.getErrorCode(), OAuth2ErrorCodes.INVALID_TOKEN)); } @Test diff --git a/oauth2/oauth2-resource-server/spring-security-oauth2-resource-server.gradle b/oauth2/oauth2-resource-server/spring-security-oauth2-resource-server.gradle index 438bbc8b5d5..69e705766b2 100644 --- a/oauth2/oauth2-resource-server/spring-security-oauth2-resource-server.gradle +++ b/oauth2/oauth2-resource-server/spring-security-oauth2-resource-server.gradle @@ -12,7 +12,7 @@ dependencies { optional 'io.projectreactor:reactor-core' optional 'org.springframework:spring-webflux' - provided 'javax.servlet:javax.servlet-api' + provided 'jakarta.servlet:jakarta.servlet-api' testImplementation project(path: ':spring-security-oauth2-jose', configuration: 'tests') testImplementation 'com.squareup.okhttp3:mockwebserver' diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationToken.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationToken.java index 940ee7b676c..a65f5b34ed1 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationToken.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationToken.java @@ -57,7 +57,7 @@ public BearerTokenAuthenticationToken(String token) { * Bearer * Token * @return the token that proves the caller's authority to perform the - * {@link javax.servlet.http.HttpServletRequest} + * {@link jakarta.servlet.http.HttpServletRequest} */ public String getToken() { return this.token; diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolver.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolver.java index 56b8df7bc31..8c5044b5388 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolver.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolver.java @@ -23,7 +23,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import com.nimbusds.jwt.JWTParser; import org.apache.commons.logging.Log; diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolver.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolver.java index afbfb38f9c4..26aeca6d085 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolver.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolver.java @@ -16,6 +16,7 @@ package org.springframework.security.oauth2.server.resource.authentication; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -186,7 +187,7 @@ public Mono resolve(String issuer) { return this.authenticationManagers.computeIfAbsent(issuer, (k) -> Mono.fromCallable(() -> new JwtReactiveAuthenticationManager(ReactiveJwtDecoders.fromIssuerLocation(k))) .subscribeOn(Schedulers.boundedElastic()) - .cache() + .cache((manager) -> Duration.ofMillis(Long.MAX_VALUE), (ex) -> Duration.ZERO, () -> Duration.ZERO) ); // @formatter:on } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java index f28cdd2c3b4..48711ae40e2 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java @@ -19,8 +19,8 @@ import java.util.LinkedHashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.java index ffa9701ad39..b0d36b116a4 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.java @@ -18,10 +18,10 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.AuthenticationDetailsSource; diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenResolver.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenResolver.java index f7bd2efd3f9..7abd174630b 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenResolver.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenResolver.java @@ -16,7 +16,7 @@ package org.springframework.security.oauth2.server.resource.web; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java index 34073567324..eb93ad5ed5c 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java @@ -19,7 +19,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolver.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolver.java index abbabcd8454..c05551ef6c2 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolver.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolver.java @@ -16,7 +16,7 @@ package org.springframework.security.oauth2.server.resource.web; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.util.Assert; diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java index 043412492f0..5c2422efe43 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java @@ -19,8 +19,8 @@ import java.util.LinkedHashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java index 99ab3933b99..8bc9573eda7 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java @@ -96,6 +96,40 @@ public void resolveWhenUsingTrustedIssuerThenReturnsAuthenticationManager() thro } } + @Test + public void resolveWhednUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.start(); + String issuer = server.url("").toString(); + // @formatter:off + server.enqueue(new MockResponse().setResponseCode(500) + .setHeader("Content-Type", "application/json") + .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer)) + ); + server.enqueue(new MockResponse().setResponseCode(200) + .setHeader("Content-Type", "application/json") + .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer)) + ); + server.enqueue(new MockResponse().setResponseCode(200) + .setHeader("Content-Type", "application/json") + .setBody(JWK_SET) + ); + // @formatter:on + JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), + new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); + jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); + JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( + issuer); + Authentication token = withBearerToken(jws.serialize()); + AuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null); + assertThat(authenticationManager).isNotNull(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> authenticationManager.authenticate(token)); + Authentication authentication = authenticationManager.authenticate(token); + assertThat(authentication.isAuthenticated()).isTrue(); + } + } + @Test public void resolveWhenUsingSameIssuerThenReturnsSameAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java index c13eac86f86..357d95423d6 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java @@ -95,6 +95,34 @@ public void resolveWhenUsingTrustedIssuerThenReturnsAuthenticationManager() thro } } + // gh-10444 + @Test + public void resolveWhednUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception { + try (MockWebServer server = new MockWebServer()) { + String issuer = server.url("").toString(); + // @formatter:off + server.enqueue(new MockResponse().setResponseCode(500).setHeader("Content-Type", "application/json") + .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); + server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") + .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); + server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") + .setBody(JWK_SET)); + // @formatter:on + JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), + new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); + jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); + JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( + issuer); + ReactiveAuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null).block(); + assertThat(authenticationManager).isNotNull(); + Authentication token = withBearerToken(jws.serialize()); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> authenticationManager.authenticate(token).block()); + Authentication authentication = authenticationManager.authenticate(token).block(); + assertThat(authentication.isAuthenticated()).isTrue(); + } + } + @Test public void resolveWhenUsingSameIssuerThenReturnsSameAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java index 418ca85c0a1..e1bc8a65508 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/openid/spring-security-openid.gradle b/openid/spring-security-openid.gradle index 0725b0d0a8b..badd934136d 100644 --- a/openid/spring-security-openid.gradle +++ b/openid/spring-security-openid.gradle @@ -23,7 +23,7 @@ dependencies { api 'org.springframework:spring-core' api 'org.springframework:spring-web' - provided 'javax.servlet:javax.servlet-api' + provided 'jakarta.servlet:jakarta.servlet-api' runtimeOnly 'net.sourceforge.nekohtml:nekohtml' runtimeOnly 'org.apache.httpcomponents:httpclient' diff --git a/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java b/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java index 1316b6bf874..085999f3a9b 100644 --- a/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java +++ b/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java @@ -20,7 +20,7 @@ import java.util.Collections; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationFilter.java b/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationFilter.java index c0c3cffbb8a..915ff464b62 100644 --- a/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationFilter.java +++ b/openid/src/main/java/org/springframework/security/openid/OpenIDAuthenticationFilter.java @@ -27,8 +27,8 @@ import java.util.Map; import java.util.Set; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.openid4java.consumer.ConsumerException; diff --git a/openid/src/main/java/org/springframework/security/openid/OpenIDConsumer.java b/openid/src/main/java/org/springframework/security/openid/OpenIDConsumer.java index 671b960bb51..a58e4ba6e41 100644 --- a/openid/src/main/java/org/springframework/security/openid/OpenIDConsumer.java +++ b/openid/src/main/java/org/springframework/security/openid/OpenIDConsumer.java @@ -16,7 +16,7 @@ package org.springframework.security.openid; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * An interface for OpenID library implementations diff --git a/openid/src/test/java/org/springframework/security/openid/MockOpenIDConsumer.java b/openid/src/test/java/org/springframework/security/openid/MockOpenIDConsumer.java index 8f4cb141bee..a4a142b0b17 100644 --- a/openid/src/test/java/org/springframework/security/openid/MockOpenIDConsumer.java +++ b/openid/src/test/java/org/springframework/security/openid/MockOpenIDConsumer.java @@ -16,7 +16,7 @@ package org.springframework.security.openid; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * @author Robin Bramley, Opsera Ltd diff --git a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java index 678d38bc0a7..54062063a2d 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java @@ -19,9 +19,9 @@ import java.net.URI; import java.util.Collections; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/remoting/spring-security-remoting.gradle b/remoting/spring-security-remoting.gradle deleted file mode 100644 index adbc8baeb31..00000000000 --- a/remoting/spring-security-remoting.gradle +++ /dev/null @@ -1,20 +0,0 @@ -apply plugin: 'io.spring.convention.spring-module' - -dependencies { - management platform(project(":spring-security-dependencies")) - api project(':spring-security-core') - api 'org.springframework:spring-aop' - api 'org.springframework:spring-beans' - api 'org.springframework:spring-context' - api 'org.springframework:spring-core' - api 'org.springframework:spring-web' - - testImplementation project(path: ':spring-security-core', configuration: 'tests') - testImplementation "org.assertj:assertj-core" - testImplementation "org.junit.jupiter:junit-jupiter-api" - testImplementation "org.junit.jupiter:junit-jupiter-params" - testImplementation "org.junit.jupiter:junit-jupiter-engine" - testImplementation "org.mockito:mockito-core" - testImplementation "org.mockito:mockito-junit-jupiter" - testImplementation "org.springframework:spring-test" -} diff --git a/remoting/src/main/java/org/springframework/security/remoting/dns/DnsLookupException.java b/remoting/src/main/java/org/springframework/security/remoting/dns/DnsLookupException.java deleted file mode 100644 index 536bf1817fd..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/dns/DnsLookupException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2009-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.dns; - -/** - * This will be thrown for unknown DNS errors. - * - * @author Mike Wiesner - * @since 3.0 - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public class DnsLookupException extends RuntimeException { - - public DnsLookupException(String msg, Throwable cause) { - super(msg, cause); - } - - public DnsLookupException(String msg) { - super(msg); - } - -} diff --git a/remoting/src/main/java/org/springframework/security/remoting/dns/DnsResolver.java b/remoting/src/main/java/org/springframework/security/remoting/dns/DnsResolver.java deleted file mode 100644 index ae7c19d4191..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/dns/DnsResolver.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2009-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.dns; - -/** - * Helper class for DNS operations. - * - * @author Mike Wiesner - * @since 3.0 - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public interface DnsResolver { - - /** - * Resolves the IP Address (A record) to the specified host name. Throws - * DnsEntryNotFoundException if there is no record. - * @param hostname The hostname for which you need the IP Address - * @return IP Address as a String - * @throws DnsEntryNotFoundException No record found - * @throws DnsLookupException Unknown DNS error - */ - String resolveIpAddress(String hostname) throws DnsEntryNotFoundException, DnsLookupException; - - /** - *

- * Resolves the host name for the specified service in the specified domain - * - *

- * For example, if you need the host name for an LDAP server running in the domain - * springsource.com, you would call resolveServiceEntry("ldap", - * "springsource.com"). - * - *

- * The DNS server needs to provide the service records for this, in the example above, - * it would look like this: - * - *

-	 * _ldap._tcp.springsource.com IN SRV 10 0 88 ldap.springsource.com.
-	 * 
- * - * The method will return the record with highest priority (which means the lowest - * number in the DNS record) and if there are more than one records with the same - * priority, it will return the one with the highest weight. You will find more - * informatione about DNS service records at - * Wikipedia. - * @param serviceType The service type you are searching for, e.g. ldap, kerberos, ... - * @param domain The domain, in which you are searching for the service - * @return The hostname of the service - * @throws DnsEntryNotFoundException No record found - * @throws DnsLookupException Unknown DNS error - */ - String resolveServiceEntry(String serviceType, String domain) throws DnsEntryNotFoundException, DnsLookupException; - - /** - * Resolves the host name for the specified service and then the IP Address for this - * host in one call. - * @param serviceType The service type you are searching for, e.g. ldap, kerberos, ... - * @param domain The domain, in which you are searching for the service - * @return IP Address of the service - * @throws DnsEntryNotFoundException No record found - * @throws DnsLookupException Unknown DNS error - * @see #resolveServiceEntry(String, String) - * @see #resolveIpAddress(String) - */ - String resolveServiceIpAddress(String serviceType, String domain) - throws DnsEntryNotFoundException, DnsLookupException; - -} diff --git a/remoting/src/main/java/org/springframework/security/remoting/dns/InitialContextFactory.java b/remoting/src/main/java/org/springframework/security/remoting/dns/InitialContextFactory.java deleted file mode 100644 index 264fccc4f71..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/dns/InitialContextFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2009-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.dns; - -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; - -/** - * This is used in JndiDnsResolver to get an InitialDirContext for DNS queries. - * - * @author Mike Wiesner - * @since 3.0 - * @see InitialDirContext - * @see DirContext - * @see JndiDnsResolver - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public interface InitialContextFactory { - - /** - * Must return a DirContext which can be used for DNS queries - * @return JNDI DirContext - */ - DirContext getCtx(); - -} diff --git a/remoting/src/main/java/org/springframework/security/remoting/dns/JndiDnsResolver.java b/remoting/src/main/java/org/springframework/security/remoting/dns/JndiDnsResolver.java deleted file mode 100644 index c9024d21bd0..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/dns/JndiDnsResolver.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright 2009-2021 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.dns; - -import java.util.Arrays; -import java.util.Hashtable; - -import javax.naming.Context; -import javax.naming.NameNotFoundException; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; - -/** - * Implementation of DnsResolver which uses JNDI for the DNS queries. - * - * Uses an InitialContextFactory to get the JNDI DirContext. The default - * implementation will just create a new Context with the context factory - * com.sun.jndi.dns.DnsContextFactory - * - * @author Mike Wiesner - * @author Kathryn Newbould - * @since 3.0 - * @see DnsResolver - * @see InitialContextFactory - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public class JndiDnsResolver implements DnsResolver { - - private InitialContextFactory ctxFactory = new DefaultInitialContextFactory(); - - private static final int SERVICE_RECORD_PRIORITY_INDEX = 0; - - private static final int SERVICE_RECORD_WEIGHT_INDEX = 1; - - private static final int SERVICE_RECORD_PORT_INDEX = 2; - - private static final int SERVICE_RECORD_TARGET_INDEX = 3; - - /** - * Allows to inject an own JNDI context factory. - * @param ctxFactory factory to use, when a DirContext is needed - * @see InitialDirContext - * @see DirContext - */ - public void setCtxFactory(InitialContextFactory ctxFactory) { - this.ctxFactory = ctxFactory; - } - - @Override - public String resolveIpAddress(String hostname) { - return resolveIpAddress(hostname, this.ctxFactory.getCtx()); - } - - @Override - public String resolveServiceEntry(String serviceType, String domain) { - return resolveServiceEntry(serviceType, domain, this.ctxFactory.getCtx()).getHostName(); - } - - @Override - public String resolveServiceIpAddress(String serviceType, String domain) { - DirContext ctx = this.ctxFactory.getCtx(); - String hostname = resolveServiceEntry(serviceType, domain, ctx).getHostName(); - return resolveIpAddress(hostname, ctx); - } - - /** - * Resolves the host name for the specified service and then the IP Address and port - * for this host in one call. - * @param serviceType The service type you are searching for, e.g. ldap, kerberos, ... - * @param domain The domain, in which you are searching for the service - * @return IP address and port of the service, formatted [ip_address]:[port] - * @throws DnsEntryNotFoundException No record found - * @throws DnsLookupException Unknown DNS error - * @since 5.6 - * @see #resolveServiceEntry(String, String) - * @see #resolveServiceIpAddress(String, String) - */ - public String resolveServiceIpAddressAndPort(String serviceType, String domain) { - DirContext ctx = this.ctxFactory.getCtx(); - ConnectionInfo hostInfo = resolveServiceEntry(serviceType, domain, ctx); - return resolveIpAddress(hostInfo.getHostName(), ctx) + ":" + hostInfo.getPort(); - } - - // This method is needed, so that we can use only one DirContext for - // resolveServiceIpAddress(). - private String resolveIpAddress(String hostname, DirContext ctx) { - try { - Attribute dnsRecord = lookup(hostname, ctx, "A"); - // There should be only one A record, therefore it is save to return - // only the first. - return dnsRecord.get().toString(); - } - catch (NamingException ex) { - throw new DnsLookupException("DNS lookup failed for: " + hostname, ex); - } - - } - - // This method is needed, so that we can use only one DirContext for - // resolveServiceIpAddress(). - private ConnectionInfo resolveServiceEntry(String serviceType, String domain, DirContext ctx) { - String target = null; - String port = null; - try { - String query = new StringBuilder("_").append(serviceType).append("._tcp.").append(domain).toString(); - Attribute dnsRecord = lookup(query, ctx, "SRV"); - // There are maybe more records defined, we will return the one - // with the highest priority (lowest number) and the highest weight - // (highest number) - int highestPriority = -1; - int highestWeight = -1; - for (NamingEnumeration recordEnum = dnsRecord.getAll(); recordEnum.hasMoreElements();) { - String[] record = recordEnum.next().toString().split(" "); - if (record.length != 4) { - throw new DnsLookupException( - "Wrong service record for query " + query + ": [" + Arrays.toString(record) + "]"); - } - int priority = Integer.parseInt(record[SERVICE_RECORD_PRIORITY_INDEX]); - int weight = Integer.parseInt(record[SERVICE_RECORD_WEIGHT_INDEX]); - // we have a new highest Priority, so forget also the highest weight - if (priority < highestPriority || highestPriority == -1) { - highestPriority = priority; - highestWeight = weight; - target = record[SERVICE_RECORD_TARGET_INDEX].trim(); - port = record[SERVICE_RECORD_PORT_INDEX].trim(); - } - // same priority, but higher weight - if (priority == highestPriority && weight > highestWeight) { - highestWeight = weight; - target = record[SERVICE_RECORD_TARGET_INDEX].trim(); - port = record[SERVICE_RECORD_PORT_INDEX].trim(); - } - } - } - catch (NamingException ex) { - throw new DnsLookupException("DNS lookup failed for service " + serviceType + " at " + domain, ex); - } - // remove the "." at the end - if (target.endsWith(".")) { - target = target.substring(0, target.length() - 1); - } - return new ConnectionInfo(target, port); - } - - private Attribute lookup(String query, DirContext ictx, String recordType) { - try { - Attributes dnsResult = ictx.getAttributes(query, new String[] { recordType }); - return dnsResult.get(recordType); - } - catch (NamingException ex) { - if (ex instanceof NameNotFoundException) { - throw new DnsEntryNotFoundException("DNS entry not found for:" + query, ex); - } - throw new DnsLookupException("DNS lookup failed for: " + query, ex); - } - } - - private static class DefaultInitialContextFactory implements InitialContextFactory { - - @Override - public DirContext getCtx() { - Hashtable env = new Hashtable<>(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); - env.put(Context.PROVIDER_URL, "dns:"); // This is needed for IBM JDK/JRE - try { - return new InitialDirContext(env); - } - catch (NamingException ex) { - throw new DnsLookupException("Cannot create InitialDirContext for DNS lookup", ex); - } - } - - } - - private static class ConnectionInfo { - - private final String hostName; - - private final String port; - - ConnectionInfo(String hostName, String port) { - this.hostName = hostName; - this.port = port; - } - - String getHostName() { - return this.hostName; - } - - String getPort() { - return this.port; - } - - } - -} diff --git a/remoting/src/main/java/org/springframework/security/remoting/dns/package-info.java b/remoting/src/main/java/org/springframework/security/remoting/dns/package-info.java deleted file mode 100644 index 6f8c8a3f9bb..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/dns/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * DNS resolution. - */ -package org.springframework.security.remoting.dns; diff --git a/remoting/src/main/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutor.java b/remoting/src/main/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutor.java deleted file mode 100644 index a7dba3e4ea8..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutor.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.httpinvoker; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.util.Base64; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor; -import org.springframework.security.authentication.AuthenticationTrustResolver; -import org.springframework.security.authentication.AuthenticationTrustResolverImpl; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; - -/** - * Adds BASIC authentication support to SimpleHttpInvokerRequestExecutor. - * - * @author Ben Alex - * @author Rob Winch - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public class AuthenticationSimpleHttpInvokerRequestExecutor extends SimpleHttpInvokerRequestExecutor { - - private static final Log logger = LogFactory.getLog(AuthenticationSimpleHttpInvokerRequestExecutor.class); - - private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); - - /** - * Provided so subclasses can perform additional configuration if required (eg set - * additional request headers for non-security related information etc). - * @param con the HTTP connection to prepare - * @param contentLength the length of the content to send - * - */ - protected void doPrepareConnection(HttpURLConnection con, int contentLength) throws IOException { - } - - /** - * Called every time a HTTP invocation is made. - *

- * Simply allows the parent to setup the connection, and then adds an - * Authorization HTTP header property that will be used for BASIC - * authentication. - *

- *

- * The SecurityContextHolder is used to obtain the relevant principal and - * credentials. - *

- * @param con the HTTP connection to prepare - * @param contentLength the length of the content to send - * @throws IOException if thrown by HttpURLConnection methods - */ - @Override - protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException { - super.prepareConnection(con, contentLength); - - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - - if ((auth != null) && (auth.getName() != null) && (auth.getCredentials() != null) - && !this.trustResolver.isAnonymous(auth)) { - String base64 = auth.getName() + ":" + auth.getCredentials().toString(); - con.setRequestProperty("Authorization", - "Basic " + new String(Base64.getEncoder().encode(base64.getBytes()))); - - if (logger.isDebugEnabled()) { - logger.debug("HttpInvocation now presenting via BASIC authentication SecurityContextHolder-derived: " - + auth.toString()); - } - } - else { - if (logger.isDebugEnabled()) { - logger.debug("Unable to set BASIC authentication header as SecurityContext did not provide " - + "valid Authentication: " + auth); - } - } - - doPrepareConnection(con, contentLength); - } - -} diff --git a/remoting/src/main/java/org/springframework/security/remoting/httpinvoker/package-info.java b/remoting/src/main/java/org/springframework/security/remoting/httpinvoker/package-info.java deleted file mode 100644 index cd052eba4d6..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/httpinvoker/package-info.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Enables use of Spring's HttpInvoker extension points to present the - * principal and credentials located in the - * ContextHolder via BASIC authentication. - *

- * The beans are wired as follows: - * - *

- * <bean id="test" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
- *   <property name="serviceUrl"><value>http://localhost/Test</value></property>
- *   <property name="serviceInterface"><value>test.TargetInterface</value></property>
- *   <property name="httpInvokerRequestExecutor"><ref bean="httpInvokerRequestExecutor"/></property>
- * </bean>
- *
- * <bean id="httpInvokerRequestExecutor"
- *     class="org.springframework.security.core.context.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor"/>
- * 
- */ -package org.springframework.security.remoting.httpinvoker; diff --git a/remoting/src/main/java/org/springframework/security/remoting/package-info.java b/remoting/src/main/java/org/springframework/security/remoting/package-info.java deleted file mode 100644 index 1439310acb2..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Remote client related functionality. - */ -package org.springframework.security.remoting; diff --git a/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocation.java b/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocation.java deleted file mode 100644 index a6f526909ed..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocation.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.rmi; - -import java.lang.reflect.InvocationTargetException; - -import org.aopalliance.intercept.MethodInvocation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.core.log.LogMessage; -import org.springframework.remoting.support.RemoteInvocation; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.SpringSecurityCoreVersion; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; - -/** - * The actual {@code RemoteInvocation} that is passed from the client to the server. - *

- * The principal and credentials information will be extracted from the current security - * context and passed to the server as part of the invocation object. - *

- * To avoid potential serialization-based attacks, this implementation interprets the - * values as {@code String}s and creates a {@code UsernamePasswordAuthenticationToken} on - * the server side to hold them. If a different token type is required you can override - * the {@code createAuthenticationRequest} method. - * - * @author James Monaghan - * @author Ben Alex - * @author Luke Taylor - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public class ContextPropagatingRemoteInvocation extends RemoteInvocation { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - private static final Log logger = LogFactory.getLog(ContextPropagatingRemoteInvocation.class); - - private final String principal; - - private final String credentials; - - /** - * Constructs the object, storing the principal and credentials extracted from the - * client-side security context. - * @param methodInvocation the method to invoke - */ - public ContextPropagatingRemoteInvocation(MethodInvocation methodInvocation) { - super(methodInvocation); - Authentication currentUser = SecurityContextHolder.getContext().getAuthentication(); - if (currentUser != null) { - this.principal = currentUser.getName(); - Object userCredentials = currentUser.getCredentials(); - this.credentials = (userCredentials != null) ? userCredentials.toString() : null; - } - else { - this.credentials = null; - this.principal = null; - } - if (logger.isDebugEnabled()) { - logger.debug("RemoteInvocation now has principal: " + this.principal); - if (this.credentials == null) { - logger.debug("RemoteInvocation now has null credentials."); - } - } - } - - /** - * Invoked on the server-side. - *

- * The transmitted principal and credentials will be used to create an unauthenticated - * {@code Authentication} instance for processing by the - * {@code AuthenticationManager}. - * @param targetObject the target object to apply the invocation to - * @return the invocation result - * @throws NoSuchMethodException if the method name could not be resolved - * @throws IllegalAccessException if the method could not be accessed - * @throws InvocationTargetException if the method invocation resulted in an exception - */ - @Override - public Object invoke(Object targetObject) - throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { - if (this.principal != null) { - Authentication request = createAuthenticationRequest(this.principal, this.credentials); - request.setAuthenticated(false); - SecurityContext context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(request); - SecurityContextHolder.setContext(context); - logger.debug(LogMessage.format("Set SecurityContextHolder to contain: %s", request)); - } - try { - return super.invoke(targetObject); - } - finally { - SecurityContextHolder.clearContext(); - logger.debug("Cleared SecurityContextHolder."); - } - } - - /** - * Creates the server-side authentication request object. - */ - protected Authentication createAuthenticationRequest(String principal, String credentials) { - return new UsernamePasswordAuthenticationToken(principal, credentials); - } - -} diff --git a/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationFactory.java b/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationFactory.java deleted file mode 100644 index 077832a287f..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.rmi; - -import org.aopalliance.intercept.MethodInvocation; - -import org.springframework.remoting.support.RemoteInvocation; -import org.springframework.remoting.support.RemoteInvocationFactory; - -/** - * Called by a client-side instance of - * org.springframework.remoting.rmi.RmiProxyFactoryBean when it wishes to - * create a remote invocation. - *

- * Set an instance of this bean against the above class' - * remoteInvocationFactory property. - *

- * - * @author James Monaghan - * @author Ben Alex - * @deprecated as of 5.6.0 with no replacement - */ -@Deprecated -public class ContextPropagatingRemoteInvocationFactory implements RemoteInvocationFactory { - - @Override - public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) { - return new ContextPropagatingRemoteInvocation(methodInvocation); - } - -} diff --git a/remoting/src/main/java/org/springframework/security/remoting/rmi/package-info.java b/remoting/src/main/java/org/springframework/security/remoting/rmi/package-info.java deleted file mode 100644 index ead4d448637..00000000000 --- a/remoting/src/main/java/org/springframework/security/remoting/rmi/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2002-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Enables use of Spring's RMI remoting extension points to propagate the - * SecurityContextHolder (which should contain an Authentication - * request token) from one JVM to the remote JVM. - *

- * The beans are wired as follows:

- * <bean id="test" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
- *   <property name="serviceUrl"><value>rmi://localhost/Test</value></property>
- *   <property name="serviceInterface"><value>test.TargetInterface</value></property>
- *   <property name="refreshStubOnConnectFailure"><value>true</value></property>
- *   <property name="remoteInvocationFactory"><ref bean="remoteInvocationFactory"/></property>
- * </bean>
- *
- * <bean id="remoteInvocationFactory"
- *     class="org.springframework.security.remoting.rmi.ContextPropagatingRemoteInvocationFactory"/>
- * 
- */ -package org.springframework.security.remoting.rmi; diff --git a/remoting/src/test/java/org/springframework/security/remoting/dns/JndiDnsResolverTests.java b/remoting/src/test/java/org/springframework/security/remoting/dns/JndiDnsResolverTests.java deleted file mode 100644 index 3056c87f77f..00000000000 --- a/remoting/src/test/java/org/springframework/security/remoting/dns/JndiDnsResolverTests.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2009-2021 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.dns; - -import javax.naming.NameNotFoundException; -import javax.naming.NamingException; -import javax.naming.directory.Attributes; -import javax.naming.directory.BasicAttribute; -import javax.naming.directory.BasicAttributes; -import javax.naming.directory.DirContext; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * @author Mike Wiesner - * @since 3.0 - */ -public class JndiDnsResolverTests { - - private JndiDnsResolver dnsResolver; - - private InitialContextFactory contextFactory; - - private DirContext context; - - @BeforeEach - public void setup() { - this.contextFactory = mock(InitialContextFactory.class); - this.context = mock(DirContext.class); - this.dnsResolver = new JndiDnsResolver(); - this.dnsResolver.setCtxFactory(this.contextFactory); - given(this.contextFactory.getCtx()).willReturn(this.context); - } - - @Test - public void testResolveIpAddress() throws Exception { - Attributes records = new BasicAttributes("A", "63.246.7.80"); - given(this.context.getAttributes("www.springsource.com", new String[] { "A" })).willReturn(records); - String ipAddress = this.dnsResolver.resolveIpAddress("www.springsource.com"); - assertThat(ipAddress).isEqualTo("63.246.7.80"); - } - - @Test - public void testResolveIpAddressNotExisting() throws Exception { - given(this.context.getAttributes(any(String.class), any(String[].class))) - .willThrow(new NameNotFoundException("not found")); - assertThatExceptionOfType(DnsEntryNotFoundException.class) - .isThrownBy(() -> this.dnsResolver.resolveIpAddress("notexisting.ansdansdugiuzgguzgioansdiandwq.foo")); - } - - @Test - public void testResolveServiceEntry() throws Exception { - BasicAttributes records = createSrvRecords(); - given(this.context.getAttributes("_ldap._tcp.springsource.com", new String[] { "SRV" })).willReturn(records); - String hostname = this.dnsResolver.resolveServiceEntry("ldap", "springsource.com"); - assertThat(hostname).isEqualTo("kdc.springsource.com"); - } - - @Test - public void testResolveServiceEntryNotExisting() throws Exception { - given(this.context.getAttributes(any(String.class), any(String[].class))) - .willThrow(new NameNotFoundException("not found")); - assertThatExceptionOfType(DnsEntryNotFoundException.class) - .isThrownBy(() -> this.dnsResolver.resolveServiceEntry("wrong", "secpod.de")); - } - - @Test - public void testResolveServiceIpAddress() throws Exception { - BasicAttributes srvRecords = createSrvRecords(); - BasicAttributes aRecords = new BasicAttributes("A", "63.246.7.80"); - given(this.context.getAttributes("_ldap._tcp.springsource.com", new String[] { "SRV" })).willReturn(srvRecords); - given(this.context.getAttributes("kdc.springsource.com", new String[] { "A" })).willReturn(aRecords); - String ipAddress = this.dnsResolver.resolveServiceIpAddress("ldap", "springsource.com"); - assertThat(ipAddress).isEqualTo("63.246.7.80"); - } - - @Test - public void resolveServiceIpAddressAndPortWhenExistsThenReturnsIpAddressAndPort() throws Exception { - BasicAttributes srvRecords = createSrvRecords(); - BasicAttributes aRecords = new BasicAttributes("A", "63.246.7.80"); - given(this.context.getAttributes("_ldap._tcp.springsource.com", new String[] { "SRV" })).willReturn(srvRecords); - given(this.context.getAttributes("kdc.springsource.com", new String[] { "A" })).willReturn(aRecords); - String ipAddressAndPort = this.dnsResolver.resolveServiceIpAddressAndPort("ldap", "springsource.com"); - assertThat(ipAddressAndPort).isEqualTo("63.246.7.80:389"); - } - - @Test - public void testUnknowError() throws Exception { - given(this.context.getAttributes(any(String.class), any(String[].class))) - .willThrow(new NamingException("error")); - assertThatExceptionOfType(DnsLookupException.class).isThrownBy(() -> this.dnsResolver.resolveIpAddress("")); - } - - private BasicAttributes createSrvRecords() { - BasicAttributes records = new BasicAttributes(); - BasicAttribute record = new BasicAttribute("SRV"); - // the structure of the service records is: - // priority weight port hostname - // for more information: https://en.wikipedia.org/wiki/SRV_record - record.add("20 80 389 kdc3.springsource.com."); - record.add("10 70 389 kdc.springsource.com."); - record.add("20 20 389 kdc4.springsource.com."); - record.add("10 30 389 kdc2.springsource.com"); - records.put(record); - return records; - } - -} diff --git a/remoting/src/test/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java b/remoting/src/test/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java deleted file mode 100644 index 859ded84727..00000000000 --- a/remoting/src/test/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.httpinvoker; - -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import org.springframework.security.authentication.AnonymousAuthenticationToken; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.context.SecurityContextHolder; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests {@link AuthenticationSimpleHttpInvokerRequestExecutor}. - * - * @author Ben Alex - * @author Rob Winch - */ -public class AuthenticationSimpleHttpInvokerRequestExecutorTests { - - @AfterEach - public void tearDown() { - SecurityContextHolder.clearContext(); - } - - @Test - public void testNormalOperation() throws Exception { - // Setup client-side context - Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("Aladdin", "open sesame"); - SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication); - // Create a connection and ensure our executor sets its - // properties correctly - AuthenticationSimpleHttpInvokerRequestExecutor executor = new AuthenticationSimpleHttpInvokerRequestExecutor(); - HttpURLConnection conn = new MockHttpURLConnection(new URL("https://localhost/")); - executor.prepareConnection(conn, 10); - // Check connection properties - // See https://tools.ietf.org/html/rfc1945 section 11.1 for example - // we are comparing against - assertThat(conn.getRequestProperty("Authorization")).isEqualTo("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); - } - - @Test - public void testNullContextHolderIsNull() throws Exception { - SecurityContextHolder.getContext().setAuthentication(null); - // Create a connection and ensure our executor sets its - // properties correctly - AuthenticationSimpleHttpInvokerRequestExecutor executor = new AuthenticationSimpleHttpInvokerRequestExecutor(); - HttpURLConnection conn = new MockHttpURLConnection(new URL("https://localhost/")); - executor.prepareConnection(conn, 10); - // Check connection properties (shouldn't be an Authorization header) - assertThat(conn.getRequestProperty("Authorization")).isNull(); - } - - // SEC-1975 - @Test - public void testNullContextHolderWhenAnonymous() throws Exception { - AnonymousAuthenticationToken anonymous = new AnonymousAuthenticationToken("key", "principal", - AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); - SecurityContextHolder.getContext().setAuthentication(anonymous); - // Create a connection and ensure our executor sets its - // properties correctly - AuthenticationSimpleHttpInvokerRequestExecutor executor = new AuthenticationSimpleHttpInvokerRequestExecutor(); - HttpURLConnection conn = new MockHttpURLConnection(new URL("https://localhost/")); - executor.prepareConnection(conn, 10); - // Check connection properties (shouldn't be an Authorization header) - assertThat(conn.getRequestProperty("Authorization")).isNull(); - } - - private class MockHttpURLConnection extends HttpURLConnection { - - private Map requestProperties = new HashMap<>(); - - MockHttpURLConnection(URL u) { - super(u); - } - - @Override - public void connect() { - throw new UnsupportedOperationException("mock not implemented"); - } - - @Override - public void disconnect() { - throw new UnsupportedOperationException("mock not implemented"); - } - - @Override - public String getRequestProperty(String key) { - return this.requestProperties.get(key); - } - - @Override - public void setRequestProperty(String key, String value) { - this.requestProperties.put(key, value); - } - - @Override - public boolean usingProxy() { - throw new UnsupportedOperationException("mock not implemented"); - } - - } - -} diff --git a/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java b/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java deleted file mode 100644 index ed37bc00a9e..00000000000 --- a/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security.remoting.rmi; - -import java.lang.reflect.Method; - -import org.aopalliance.intercept.MethodInvocation; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import org.springframework.security.TargetObject; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.util.SimpleMethodInvocation; -import org.springframework.test.util.ReflectionTestUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests {@link ContextPropagatingRemoteInvocation} and - * {@link ContextPropagatingRemoteInvocationFactory}. - * - * @author Ben Alex - */ -public class ContextPropagatingRemoteInvocationTests { - - @AfterEach - public void tearDown() { - SecurityContextHolder.clearContext(); - } - - private ContextPropagatingRemoteInvocation getRemoteInvocation() throws Exception { - Class clazz = TargetObject.class; - Method method = clazz.getMethod("makeLowerCase", new Class[] { String.class }); - MethodInvocation mi = new SimpleMethodInvocation(new TargetObject(), method, "SOME_STRING"); - ContextPropagatingRemoteInvocationFactory factory = new ContextPropagatingRemoteInvocationFactory(); - return (ContextPropagatingRemoteInvocation) factory.createRemoteInvocation(mi); - } - - @Test - public void testContextIsResetEvenIfExceptionOccurs() throws Exception { - // Setup client-side context - Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("rod", "koala"); - SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication); - ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation(); - // Set up the wrong arguments. - remoteInvocation.setArguments(new Object[] {}); - assertThatIllegalArgumentException() - .isThrownBy(() -> remoteInvocation.invoke(TargetObject.class.newInstance())); - assertThat(SecurityContextHolder.getContext().getAuthentication()) - .withFailMessage("Authentication must be null").isNull(); - } - - @Test - public void testNormalOperation() throws Exception { - // Setup client-side context - Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("rod", "koala"); - SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication); - ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation(); - // Set to null, as ContextPropagatingRemoteInvocation already obtained - // a copy and nulling is necessary to ensure the Context delivered by - // ContextPropagatingRemoteInvocation is used on server-side - SecurityContextHolder.clearContext(); - // The result from invoking the TargetObject should contain the - // Authentication class delivered via the SecurityContextHolder - assertThat(remoteInvocation.invoke(new TargetObject())).isEqualTo( - "some_string org.springframework.security.authentication.UsernamePasswordAuthenticationToken false"); - } - - @Test - public void testNullContextHolderDoesNotCauseInvocationProblems() throws Exception { - SecurityContextHolder.clearContext(); // just to be explicit - ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation(); - SecurityContextHolder.clearContext(); // unnecessary, but for - // explicitness - assertThat(remoteInvocation.invoke(new TargetObject())).isEqualTo("some_string Authentication empty"); - } - - // SEC-1867 - @Test - public void testNullCredentials() throws Exception { - Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("rod", null); - SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication); - ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation(); - assertThat(ReflectionTestUtils.getField(remoteInvocation, "credentials")).isNull(); - } - -} diff --git a/remoting/src/test/resources/logback-test.xml b/remoting/src/test/resources/logback-test.xml deleted file mode 100644 index 2d51ba4180a..00000000000 --- a/remoting/src/test/resources/logback-test.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - diff --git a/saml2/saml2-service-provider/spring-security-saml2-service-provider.gradle b/saml2/saml2-service-provider/spring-security-saml2-service-provider.gradle index 5bcc457a617..c4a893aa2d2 100644 --- a/saml2/saml2-service-provider/spring-security-saml2-service-provider.gradle +++ b/saml2/saml2-service-provider/spring-security-saml2-service-provider.gradle @@ -36,21 +36,29 @@ configurations { } compileOpensaml4MainJava { - sourceCompatibility = '11' - targetCompatibility = '11' + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 } dependencies { management platform(project(":spring-security-dependencies")) api project(':spring-security-web') api "org.opensaml:opensaml-core" - api "org.opensaml:opensaml-saml-api" - api "org.opensaml:opensaml-saml-impl" + api ("org.opensaml:opensaml-saml-api") { + exclude group: 'commons-logging', module: 'commons-logging' + } + api ("org.opensaml:opensaml-saml-impl") { + exclude group: 'commons-logging', module: 'commons-logging' + } opensaml4MainImplementation "org.opensaml:opensaml-core:4.1.0" - opensaml4MainImplementation "org.opensaml:opensaml-saml-api:4.1.0" - opensaml4MainImplementation "org.opensaml:opensaml-saml-impl:4.1.0" + opensaml4MainImplementation ("org.opensaml:opensaml-saml-api:4.1.0") { + exclude group: 'commons-logging', module: 'commons-logging' + } + opensaml4MainImplementation ("org.opensaml:opensaml-saml-impl:4.1.0") { + exclude group: 'commons-logging', module: 'commons-logging' + } - provided 'javax.servlet:javax.servlet-api' + provided 'jakarta.servlet:jakarta.servlet-api' testImplementation 'com.squareup.okhttp3:mockwebserver' testImplementation "org.assertj:assertj-core" diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlVerificationUtils.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlVerificationUtils.java index 5b8d0295874..68eb33d1c38 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlVerificationUtils.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlVerificationUtils.java @@ -22,7 +22,7 @@ import java.util.HashSet; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import net.shibboleth.utilities.java.support.resolver.CriteriaSet; import org.opensaml.core.criterion.EntityIdCriterion; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolver.java index 1f0d5c19af1..731b9c8cf80 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -31,6 +31,7 @@ import org.opensaml.saml.saml2.metadata.AssertionConsumerService; import org.opensaml.saml.saml2.metadata.EntityDescriptor; import org.opensaml.saml.saml2.metadata.KeyDescriptor; +import org.opensaml.saml.saml2.metadata.NameIDFormat; import org.opensaml.saml.saml2.metadata.SPSSODescriptor; import org.opensaml.saml.saml2.metadata.SingleLogoutService; import org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller; @@ -86,7 +87,12 @@ private SPSSODescriptor buildSpSsoDescriptor(RelyingPartyRegistration registrati spSsoDescriptor.getKeyDescriptors() .addAll(buildKeys(registration.getDecryptionX509Credentials(), UsageType.ENCRYPTION)); spSsoDescriptor.getAssertionConsumerServices().add(buildAssertionConsumerService(registration)); - spSsoDescriptor.getSingleLogoutServices().add(buildSingleLogoutService(registration)); + if (registration.getSingleLogoutServiceLocation() != null) { + spSsoDescriptor.getSingleLogoutServices().add(buildSingleLogoutService(registration)); + } + if (registration.getNameIdFormat() != null) { + spSsoDescriptor.getNameIDFormats().add(buildNameIDFormat(registration)); + } return spSsoDescriptor; } @@ -133,6 +139,12 @@ private SingleLogoutService buildSingleLogoutService(RelyingPartyRegistration re return singleLogoutService; } + private NameIDFormat buildNameIDFormat(RelyingPartyRegistration registration) { + NameIDFormat nameIdFormat = build(NameIDFormat.DEFAULT_ELEMENT_NAME); + nameIdFormat.setFormat(registration.getNameIdFormat()); + return nameIdFormat; + } + @SuppressWarnings("unchecked") private T build(QName elementName) { XMLObjectBuilder builder = XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(elementName); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.java index d07a3664f8a..ab1ce03f6b6 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.java @@ -87,6 +87,8 @@ public final class RelyingPartyRegistration { private final Saml2MessageBinding singleLogoutServiceBinding; + private final String nameIdFormat; + private final ProviderDetails providerDetails; private final List credentials; @@ -98,7 +100,7 @@ public final class RelyingPartyRegistration { private RelyingPartyRegistration(String registrationId, String entityId, String assertionConsumerServiceLocation, Saml2MessageBinding assertionConsumerServiceBinding, String singleLogoutServiceLocation, String singleLogoutServiceResponseLocation, Saml2MessageBinding singleLogoutServiceBinding, - ProviderDetails providerDetails, + ProviderDetails providerDetails, String nameIdFormat, Collection credentials, Collection decryptionX509Credentials, Collection signingX509Credentials) { @@ -106,6 +108,8 @@ private RelyingPartyRegistration(String registrationId, String entityId, String Assert.hasText(entityId, "entityId cannot be empty"); Assert.hasText(assertionConsumerServiceLocation, "assertionConsumerServiceLocation cannot be empty"); Assert.notNull(assertionConsumerServiceBinding, "assertionConsumerServiceBinding cannot be null"); + Assert.isTrue(singleLogoutServiceLocation == null || singleLogoutServiceBinding != null, + "singleLogoutServiceBinding cannot be null when singleLogoutServiceLocation is set"); Assert.notNull(providerDetails, "providerDetails cannot be null"); Assert.notEmpty(credentials, "credentials cannot be empty"); for (org.springframework.security.saml2.credentials.Saml2X509Credential c : credentials) { @@ -129,6 +133,7 @@ private RelyingPartyRegistration(String registrationId, String entityId, String this.singleLogoutServiceLocation = singleLogoutServiceLocation; this.singleLogoutServiceResponseLocation = singleLogoutServiceResponseLocation; this.singleLogoutServiceBinding = singleLogoutServiceBinding; + this.nameIdFormat = nameIdFormat; this.providerDetails = providerDetails; this.credentials = Collections.unmodifiableList(new LinkedList<>(credentials)); this.decryptionX509Credentials = Collections.unmodifiableList(new LinkedList<>(decryptionX509Credentials)); @@ -234,6 +239,15 @@ public String getSingleLogoutServiceResponseLocation() { return this.singleLogoutServiceResponseLocation; } + /** + * Get the NameID format. + * @return the NameID format + * @since 5.7 + */ + public String getNameIdFormat() { + return this.nameIdFormat; + } + /** * Get the {@link Collection} of decryption {@link Saml2X509Credential}s associated * with this relying party @@ -424,6 +438,7 @@ public static Builder withRelyingPartyRegistration(RelyingPartyRegistration regi .singleLogoutServiceLocation(registration.getSingleLogoutServiceLocation()) .singleLogoutServiceResponseLocation(registration.getSingleLogoutServiceResponseLocation()) .singleLogoutServiceBinding(registration.getSingleLogoutServiceBinding()) + .nameIdFormat(registration.getNameIdFormat()) .assertingPartyDetails((assertingParty) -> assertingParty .entityId(registration.getAssertingPartyDetails().getEntityId()) .wantAuthnRequestsSigned(registration.getAssertingPartyDetails().getWantAuthnRequestsSigned()) @@ -1012,12 +1027,14 @@ public static final class Builder { private Saml2MessageBinding assertionConsumerServiceBinding = Saml2MessageBinding.POST; - private String singleLogoutServiceLocation = "{baseUrl}/logout/saml2/slo"; + private String singleLogoutServiceLocation; private String singleLogoutServiceResponseLocation; private Saml2MessageBinding singleLogoutServiceBinding = Saml2MessageBinding.POST; + private String nameIdFormat = null; + private ProviderDetails.Builder providerDetails = new ProviderDetails.Builder(); private Collection credentials = new HashSet<>(); @@ -1173,6 +1190,17 @@ public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceRes return this; } + /** + * Set the NameID format + * @param nameIdFormat + * @return the {@link Builder} for further configuration + * @since 5.7 + */ + public Builder nameIdFormat(String nameIdFormat) { + this.nameIdFormat = nameIdFormat; + return this; + } + /** * Apply this {@link Consumer} to further configure the Asserting Party details * @param assertingPartyDetails The {@link Consumer} to apply @@ -1321,7 +1349,7 @@ public RelyingPartyRegistration build() { return new RelyingPartyRegistration(this.registrationId, this.entityId, this.assertionConsumerServiceLocation, this.assertionConsumerServiceBinding, this.singleLogoutServiceLocation, this.singleLogoutServiceResponseLocation, - this.singleLogoutServiceBinding, this.providerDetails.build(), this.credentials, + this.singleLogoutServiceBinding, this.providerDetails.build(), this.nameIdFormat, this.credentials, this.decryptionX509Credentials, this.signingX509Credentials); } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilter.java index 0d5a018c361..708af40cb6e 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilter.java @@ -16,8 +16,8 @@ package org.springframework.security.saml2.provider.service.servlet.filter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilter.java index 8eea145fe37..1d47d544e1e 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilter.java @@ -19,10 +19,10 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.opensaml.core.Version; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java index cc5f77c318d..6bcd6fcb086 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java @@ -20,7 +20,7 @@ import java.util.Map; import java.util.function.Function; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolver.java index 0a72ea5e7c9..0eeb10cb9e8 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolver.java @@ -16,7 +16,7 @@ package org.springframework.security.saml2.provider.service.web; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/HttpSessionSaml2AuthenticationRequestRepository.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/HttpSessionSaml2AuthenticationRequestRepository.java index 3727b22105c..56a3e03c80f 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/HttpSessionSaml2AuthenticationRequestRepository.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/HttpSessionSaml2AuthenticationRequestRepository.java @@ -16,9 +16,9 @@ package org.springframework.security.saml2.provider.service.web; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/RelyingPartyRegistrationResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/RelyingPartyRegistrationResolver.java index d9e5e0eb14f..bb78a8e72ca 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/RelyingPartyRegistrationResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/RelyingPartyRegistrationResolver.java @@ -16,7 +16,7 @@ package org.springframework.security.saml2.provider.service.web; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationRequestContextResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationRequestContextResolver.java index 233d93b23d4..5b3ec081f10 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationRequestContextResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationRequestContextResolver.java @@ -16,7 +16,7 @@ package org.springframework.security.saml2.provider.service.web; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestContext; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationRequestRepository.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationRequestRepository.java index 585a8ae90a9..98a7157f387 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationRequestRepository.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationRequestRepository.java @@ -16,8 +16,8 @@ package org.springframework.security.saml2.provider.service.web; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java index b100957d78b..a4ac1eadd40 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java @@ -22,7 +22,7 @@ import java.util.zip.Inflater; import java.util.zip.InflaterOutputStream; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.codec.CodecPolicy; import org.apache.commons.codec.binary.Base64; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilter.java index ccb2f74fdbb..492388bd288 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilter.java @@ -20,10 +20,10 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpHeaders; @@ -36,7 +36,7 @@ import org.springframework.web.filter.OncePerRequestFilter; /** - * A {@link javax.servlet.Filter} that returns the metadata for a Relying Party + * A {@link jakarta.servlet.Filter} that returns the metadata for a Relying Party * * @author Jakub Kubrynski * @author Josh Cummings diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/HttpSessionLogoutRequestRepository.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/HttpSessionLogoutRequestRepository.java index 79e4e45293e..2f41cc1002d 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/HttpSessionLogoutRequestRepository.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/HttpSessionLogoutRequestRepository.java @@ -18,9 +18,9 @@ import java.security.MessageDigest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.security.crypto.codec.Utf8; import org.springframework.security.saml2.core.Saml2ParameterNames; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java index 5a5e64c6e37..a4b39ce84d5 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java @@ -20,7 +20,7 @@ import java.util.UUID; import java.util.function.BiConsumer; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.apache.commons.logging.Log; @@ -111,6 +111,9 @@ Saml2LogoutRequest resolve(HttpServletRequest request, Authentication authentica if (registration == null) { return null; } + if (registration.getAssertingPartyDetails().getSingleLogoutServiceLocation() == null) { + return null; + } LogoutRequest logoutRequest = this.logoutRequestBuilder.buildObject(); logoutRequest.setDestination(registration.getAssertingPartyDetails().getSingleLogoutServiceLocation()); Issuer issuer = this.issuerBuilder.buildObject(); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java index 935fb1febf5..1714033e5d4 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java @@ -21,7 +21,7 @@ import java.util.UUID; import java.util.function.BiConsumer; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import net.shibboleth.utilities.java.support.xml.ParserPool; import net.shibboleth.utilities.java.support.xml.SerializeSupport; @@ -132,6 +132,9 @@ Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentic if (registration == null) { return null; } + if (registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation() == null) { + return null; + } String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST); byte[] b = Saml2Utils.samlDecode(serialized); LogoutRequest logoutRequest = parse(inflateIfRequired(registration, b)); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.java index 99e88c9ae86..3689f4fb5bd 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.java @@ -20,10 +20,10 @@ import java.nio.charset.StandardCharsets; import java.util.function.Function; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -120,6 +120,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } + if (registration.getSingleLogoutServiceLocation() == null) { + this.logger.trace( + "Did not process logout request since RelyingPartyRegistration has not been configured with a logout request endpoint"); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + return; + } if (!isCorrectBinding(request, registration)) { this.logger.trace("Did not process logout request since used incorrect binding"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestRepository.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestRepository.java index f977ce84b84..d3d82e0ea8b 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestRepository.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestRepository.java @@ -16,8 +16,8 @@ package org.springframework.security.saml2.provider.service.web.authentication.logout; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestResolver.java index d4b5e4e3b27..c0a8d850fa1 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestResolver.java @@ -16,7 +16,7 @@ package org.springframework.security.saml2.provider.service.web.authentication.logout; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilter.java index 83b4c8eccd4..9f169f9e1c9 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilter.java @@ -18,10 +18,10 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -120,6 +120,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response.sendError(HttpServletResponse.SC_BAD_REQUEST, error.toString()); return; } + if (registration.getSingleLogoutServiceResponseLocation() == null) { + this.logger.trace( + "Did not process logout response since RelyingPartyRegistration has not been configured with a logout response endpoint"); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + return; + } if (!isCorrectBinding(request, registration)) { this.logger.trace("Did not process logout request since used incorrect binding"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseResolver.java index a47b39f8eb0..84cf038af9b 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseResolver.java @@ -16,7 +16,7 @@ package org.springframework.security.saml2.provider.service.web.authentication.logout; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2RelyingPartyInitiatedLogoutSuccessHandler.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2RelyingPartyInitiatedLogoutSuccessHandler.java index 8d8b1f204f6..ff6d7020fec 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2RelyingPartyInitiatedLogoutSuccessHandler.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2RelyingPartyInitiatedLogoutSuccessHandler.java @@ -20,8 +20,8 @@ import java.nio.charset.StandardCharsets; import java.util.function.Function; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/saml2/saml2-service-provider/src/opensaml3Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutRequestResolver.java b/saml2/saml2-service-provider/src/opensaml3Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutRequestResolver.java index 7469c0a778f..5e3e37c9a42 100644 --- a/saml2/saml2-service-provider/src/opensaml3Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutRequestResolver.java +++ b/saml2/saml2-service-provider/src/opensaml3Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutRequestResolver.java @@ -19,7 +19,7 @@ import java.time.Clock; import java.util.function.Consumer; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.joda.time.DateTime; import org.opensaml.saml.saml2.core.LogoutRequest; diff --git a/saml2/saml2-service-provider/src/opensaml3Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutResponseResolver.java b/saml2/saml2-service-provider/src/opensaml3Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutResponseResolver.java index aded12b4286..49941bc93e3 100644 --- a/saml2/saml2-service-provider/src/opensaml3Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutResponseResolver.java +++ b/saml2/saml2-service-provider/src/opensaml3Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutResponseResolver.java @@ -19,7 +19,7 @@ import java.time.Clock; import java.util.function.Consumer; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.joda.time.DateTime; import org.opensaml.saml.saml2.core.LogoutResponse; diff --git a/saml2/saml2-service-provider/src/opensaml3Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutRequestResolverTests.java b/saml2/saml2-service-provider/src/opensaml3Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutRequestResolverTests.java index 99e5d225b1a..a61b0d33dca 100644 --- a/saml2/saml2-service-provider/src/opensaml3Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutRequestResolverTests.java +++ b/saml2/saml2-service-provider/src/opensaml3Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutRequestResolverTests.java @@ -16,7 +16,7 @@ package org.springframework.security.saml2.provider.service.web.authentication.logout; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; @@ -47,7 +47,9 @@ public void resolveWhenCustomParametersConsumerThenUses() { this.relyingPartyRegistrationResolver); logoutRequestResolver.setParametersConsumer((parameters) -> parameters.getLogoutRequest().setID("myid")); HttpServletRequest request = new MockHttpServletRequest(); - RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); + RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() + .assertingPartyDetails((party) -> party.singleLogoutServiceLocation("https://ap.example.com/logout")) + .build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutRequest logoutRequest = logoutRequestResolver.resolve(request, authentication); diff --git a/saml2/saml2-service-provider/src/opensaml3Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutResponseResolverTests.java b/saml2/saml2-service-provider/src/opensaml3Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutResponseResolverTests.java index 2e5a4a0a435..628d2401e44 100644 --- a/saml2/saml2-service-provider/src/opensaml3Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutResponseResolverTests.java +++ b/saml2/saml2-service-provider/src/opensaml3Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml3LogoutResponseResolverTests.java @@ -53,7 +53,10 @@ public void resolveWhenCustomParametersConsumerThenUses() { Consumer parametersConsumer = mock(Consumer.class); logoutResponseResolver.setParametersConsumer(parametersConsumer); MockHttpServletRequest request = new MockHttpServletRequest(); - RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); + RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() + .assertingPartyDetails( + (party) -> party.singleLogoutServiceResponseLocation("https://ap.example.com/logout")) + .build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); request.setParameter(Saml2ParameterNames.SAML_REQUEST, diff --git a/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationRequestFactory.java b/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationRequestFactory.java index dcfa1cfdbc1..ec02ca2a064 100644 --- a/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationRequestFactory.java +++ b/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -27,8 +27,10 @@ import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.saml2.core.AuthnRequest; import org.opensaml.saml.saml2.core.Issuer; +import org.opensaml.saml.saml2.core.NameIDPolicy; import org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder; import org.opensaml.saml.saml2.core.impl.IssuerBuilder; +import org.opensaml.saml.saml2.core.impl.NameIDPolicyBuilder; import org.springframework.core.convert.converter.Converter; import org.springframework.security.saml2.core.OpenSamlInitializationService; @@ -56,6 +58,8 @@ public final class OpenSaml4AuthenticationRequestFactory implements Saml2Authent private final IssuerBuilder issuerBuilder; + private final NameIDPolicyBuilder nameIdPolicyBuilder; + private Clock clock = Clock.systemUTC(); private Converter authenticationRequestContextConverter; @@ -69,6 +73,8 @@ public OpenSaml4AuthenticationRequestFactory() { this.authnRequestBuilder = (AuthnRequestBuilder) registry.getBuilderFactory() .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME); this.issuerBuilder = (IssuerBuilder) registry.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME); + this.nameIdPolicyBuilder = (NameIDPolicyBuilder) registry.getBuilderFactory() + .getBuilder(NameIDPolicy.DEFAULT_ELEMENT_NAME); } /** @@ -152,6 +158,9 @@ private AuthnRequest createAuthnRequest(Saml2AuthenticationRequestContext contex auth.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI); } auth.setProtocolBinding(protocolBinding); + if (auth.getNameIDPolicy() == null) { + setNameIdPolicy(auth, context.getRelyingPartyRegistration()); + } Issuer iss = this.issuerBuilder.buildObject(); iss.setValue(issuer); auth.setIssuer(iss); @@ -160,6 +169,15 @@ private AuthnRequest createAuthnRequest(Saml2AuthenticationRequestContext contex return auth; } + private void setNameIdPolicy(AuthnRequest authnRequest, RelyingPartyRegistration registration) { + if (!StringUtils.hasText(registration.getNameIdFormat())) { + return; + } + NameIDPolicy nameIdPolicy = this.nameIdPolicyBuilder.buildObject(); + nameIdPolicy.setFormat(registration.getNameIdFormat()); + authnRequest.setNameIDPolicy(nameIdPolicy); + } + /** * Set the strategy for building an {@link AuthnRequest} from a given context * @param authenticationRequestContextConverter the conversion strategy to use diff --git a/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolver.java b/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolver.java index 13409e4cdb1..7919e1eb2ad 100644 --- a/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolver.java +++ b/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolver.java @@ -20,7 +20,7 @@ import java.time.Instant; import java.util.function.Consumer; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.opensaml.saml.saml2.core.LogoutRequest; diff --git a/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.java b/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.java index e90b2b177c3..9121d72ad82 100644 --- a/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.java +++ b/saml2/saml2-service-provider/src/opensaml4Main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.java @@ -20,7 +20,7 @@ import java.time.Instant; import java.util.function.Consumer; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.opensaml.saml.saml2.core.LogoutResponse; diff --git a/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationRequestFactoryTests.java b/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationRequestFactoryTests.java index 84c415ebe56..0aced67097b 100644 --- a/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationRequestFactoryTests.java +++ b/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationRequestFactoryTests.java @@ -242,6 +242,18 @@ public void createRedirectAuthenticationRequestWhenSHA1SignRequestThenSignatureI assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); } + @Test + public void createAuthenticationRequestWhenSetNameIDPolicyThenReturnsCorrectNameIDPolicy() { + RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().nameIdFormat("format").build(); + this.context = this.contextBuilder.relayState("Relay State Value").relyingPartyRegistration(registration) + .build(); + AuthnRequest authn = getAuthNRequest(Saml2MessageBinding.POST); + assertThat(authn.getNameIDPolicy()).isNotNull(); + assertThat(authn.getNameIDPolicy().getAllowCreate()).isFalse(); + assertThat(authn.getNameIDPolicy().getFormat()).isEqualTo("format"); + assertThat(authn.getNameIDPolicy().getSPNameQualifier()).isNull(); + } + private AuthnRequest authnRequest() { AuthnRequest authnRequest = TestOpenSamlObjects.authnRequest(); authnRequest.setIssueInstant(Instant.now()); diff --git a/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolverTests.java b/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolverTests.java index 6ea35b47161..abc06484618 100644 --- a/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolverTests.java +++ b/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolverTests.java @@ -16,7 +16,7 @@ package org.springframework.security.saml2.provider.service.web.authentication.logout; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; @@ -47,7 +47,9 @@ public void resolveWhenCustomParametersConsumerThenUses() { this.relyingPartyRegistrationResolver); logoutRequestResolver.setParametersConsumer((parameters) -> parameters.getLogoutRequest().setID("myid")); HttpServletRequest request = new MockHttpServletRequest(); - RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); + RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() + .assertingPartyDetails((party) -> party.singleLogoutServiceLocation("https://ap.example.com/logout")) + .build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutRequest logoutRequest = logoutRequestResolver.resolve(request, authentication); diff --git a/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolverTests.java b/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolverTests.java index 7353318fb90..20d18018578 100644 --- a/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolverTests.java +++ b/saml2/saml2-service-provider/src/opensaml4Test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolverTests.java @@ -53,7 +53,10 @@ public void resolveWhenCustomParametersConsumerThenUses() { Consumer parametersConsumer = mock(Consumer.class); logoutResponseResolver.setParametersConsumer(parametersConsumer); MockHttpServletRequest request = new MockHttpServletRequest(); - RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); + RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() + .assertingPartyDetails( + (party) -> party.singleLogoutServiceResponseLocation("https://ap.example.com/logout")) + .build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); request.setParameter(Saml2ParameterNames.SAML_REQUEST, diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolverTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolverTests.java index d42fc875be6..f5e6e445602 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolverTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,4 +61,22 @@ public void resolveWhenRelyingPartyNoCredentialsThenMetadataMatches() { .contains("ResponseLocation=\"https://rp.example.org/logout/saml2/response\""); } + @Test + public void resolveWhenRelyingPartyNameIDFormatThenMetadataMatches() { + RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.full().nameIdFormat("format") + .build(); + OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); + String metadata = openSamlMetadataResolver.resolve(relyingPartyRegistration); + assertThat(metadata).contains("format"); + } + + @Test + public void resolveWhenRelyingPartyNoLogoutThenMetadataMatches() { + RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.full() + .singleLogoutServiceLocation(null).nameIdFormat("format").build(); + OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); + String metadata = openSamlMetadataResolver.resolve(relyingPartyRegistration); + assertThat(metadata).doesNotContain("ResponseLocation"); + } + } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java index d25d4b981c0..63e9d58505a 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java @@ -28,6 +28,7 @@ public class RelyingPartyRegistrationTests { @Test public void withRelyingPartyRegistrationWorks() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() + .nameIdFormat("format") .assertingPartyDetails((a) -> a.singleSignOnServiceBinding(Saml2MessageBinding.POST)) .assertingPartyDetails((a) -> a.wantAuthnRequestsSigned(false)) .assertingPartyDetails((a) -> a.signingAlgorithms((algs) -> algs.add("alg"))) @@ -74,6 +75,7 @@ private void compareRegistrations(RelyingPartyRegistration registration, Relying .isEqualTo(registration.getAssertingPartyDetails().getVerificationX509Credentials()); assertThat(copy.getAssertingPartyDetails().getSigningAlgorithms()) .isEqualTo(registration.getAssertingPartyDetails().getSigningAlgorithms()); + assertThat(copy.getNameIdFormat()).isEqualTo(registration.getNameIdFormat()); } @Test diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java index b95bf41d9bc..845e5ea656a 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java @@ -16,7 +16,7 @@ package org.springframework.security.saml2.provider.service.servlet.filter; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java index 5ddd7168ed6..7d109e327f3 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java @@ -19,7 +19,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java index 02b46929618..10908a2a67e 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java @@ -19,7 +19,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java index 0f40eebdf33..f8f021e7a25 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java @@ -19,7 +19,7 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolverTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolverTests.java index 7604e262f54..d386fefddc5 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolverTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolverTests.java @@ -21,7 +21,7 @@ import java.util.ArrayList; import java.util.HashMap; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilterTests.java index 2f08d6c122d..bb604c47759 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilterTests.java @@ -153,4 +153,20 @@ public void doFilterWhenValidationFailsThen401() throws Exception { verifyNoInteractions(this.logoutHandler); } + @Test + public void doFilterWhenNoRelyingPartyLogoutThen401() throws Exception { + Authentication authentication = new TestingAuthenticationToken("user", "password"); + SecurityContextHolder.getContext().setAuthentication(authentication); + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); + request.setServletPath("/logout/saml2/slo"); + request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); + MockHttpServletResponse response = new MockHttpServletResponse(); + RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().singleLogoutServiceLocation(null) + .build(); + given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); + this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); + assertThat(response.getStatus()).isEqualTo(401); + verifyNoInteractions(this.logoutHandler); + } + } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilterTests.java index 2a86a06a26c..b201e52a05a 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilterTests.java @@ -37,6 +37,7 @@ import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; @@ -151,4 +152,23 @@ public void doFilterWhenValidatorFailsThenStops() throws Exception { verifyNoInteractions(this.logoutSuccessHandler); } + @Test + public void doFilterWhenNoRelyingPartyLogoutThen401() throws Exception { + Authentication authentication = new TestingAuthenticationToken("user", "password"); + SecurityContextHolder.getContext().setAuthentication(authentication); + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); + request.setServletPath("/logout/saml2/slo"); + request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response"); + MockHttpServletResponse response = new MockHttpServletResponse(); + RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().singleLogoutServiceLocation(null) + .singleLogoutServiceResponseLocation(null).build(); + given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); + Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) + .samlRequest("request").build(); + given(this.logoutRequestRepository.removeLogoutRequest(request, response)).willReturn(logoutRequest); + this.logoutResponseProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); + assertThat(response.getStatus()).isEqualTo(401); + verifyNoInteractions(this.logoutSuccessHandler); + } + } diff --git a/settings.gradle b/settings.gradle index a73b597502b..9a1d44a4600 100644 --- a/settings.gradle +++ b/settings.gradle @@ -6,12 +6,10 @@ pluginManagement { } plugins { - id "com.gradle.enterprise" version "3.6.1" + id "com.gradle.enterprise" version "3.7.2" id "io.spring.ge.conventions" version "0.0.7" } -enableFeaturePreview("VERSION_ORDERING_V2") - dependencyResolutionManagement { repositories { mavenCentral() diff --git a/taglibs/spring-security-taglibs.gradle b/taglibs/spring-security-taglibs.gradle index a45ad37f12a..587e83ffa7f 100644 --- a/taglibs/spring-security-taglibs.gradle +++ b/taglibs/spring-security-taglibs.gradle @@ -12,10 +12,10 @@ dependencies { api 'org.springframework:spring-expression' api 'org.springframework:spring-web' - provided 'javax.servlet.jsp:javax.servlet.jsp-api' - provided 'javax.servlet:javax.servlet-api' + provided 'jakarta.servlet.jsp:jakarta.servlet.jsp-api' + provided 'jakarta.servlet:jakarta.servlet-api' - testRuntimeOnly 'javax.servlet.jsp.jstl:javax.servlet.jsp.jstl-api' + testRuntimeOnly 'jakarta.servlet.jsp.jstl:jakarta.servlet.jsp.jstl-api' testImplementation "org.assertj:assertj-core" testImplementation "org.junit.jupiter:junit-jupiter-api" diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/TagLibConfig.java b/taglibs/src/main/java/org/springframework/security/taglibs/TagLibConfig.java index 64083a679a8..445f7bfaefc 100644 --- a/taglibs/src/main/java/org/springframework/security/taglibs/TagLibConfig.java +++ b/taglibs/src/main/java/org/springframework/security/taglibs/TagLibConfig.java @@ -16,7 +16,7 @@ package org.springframework.security.taglibs; -import javax.servlet.jsp.tagext.Tag; +import jakarta.servlet.jsp.tagext.Tag; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java index 95fb17928f4..9216d6f6779 100644 --- a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java +++ b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java @@ -19,10 +19,10 @@ import java.io.IOException; import java.util.Map; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.context.ApplicationContext; import org.springframework.core.GenericTypeResolver; diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AccessControlListTag.java b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AccessControlListTag.java index 16904672a63..1914ce5147a 100644 --- a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AccessControlListTag.java +++ b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AccessControlListTag.java @@ -20,11 +20,11 @@ import java.util.List; import java.util.Map; -import javax.servlet.ServletContext; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.PageContext; -import javax.servlet.jsp.tagext.Tag; -import javax.servlet.jsp.tagext.TagSupport; +import jakarta.servlet.ServletContext; +import jakarta.servlet.jsp.JspException; +import jakarta.servlet.jsp.PageContext; +import jakarta.servlet.jsp.tagext.Tag; +import jakarta.servlet.jsp.tagext.TagSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AuthenticationTag.java b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AuthenticationTag.java index d7fd43627c7..3d7cd31da16 100644 --- a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AuthenticationTag.java +++ b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AuthenticationTag.java @@ -18,10 +18,10 @@ import java.io.IOException; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.PageContext; -import javax.servlet.jsp.tagext.Tag; -import javax.servlet.jsp.tagext.TagSupport; +import jakarta.servlet.jsp.JspException; +import jakarta.servlet.jsp.PageContext; +import jakarta.servlet.jsp.tagext.Tag; +import jakarta.servlet.jsp.tagext.TagSupport; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.BeansException; @@ -32,8 +32,8 @@ import org.springframework.web.util.TagUtils; /** - * An {@link javax.servlet.jsp.tagext.Tag} implementation that allows convenient access to - * the current Authentication object. + * An {@link jakarta.servlet.jsp.tagext.Tag} implementation that allows convenient access + * to the current Authentication object. *

* Whilst JSPs can access the SecurityContext directly, this tag avoids * handling null conditions. diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/authz/JspAuthorizeTag.java b/taglibs/src/main/java/org/springframework/security/taglibs/authz/JspAuthorizeTag.java index e5b4cedb78b..be0c0b70d63 100644 --- a/taglibs/src/main/java/org/springframework/security/taglibs/authz/JspAuthorizeTag.java +++ b/taglibs/src/main/java/org/springframework/security/taglibs/authz/JspAuthorizeTag.java @@ -19,12 +19,12 @@ import java.io.IOException; import java.util.List; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.PageContext; -import javax.servlet.jsp.tagext.Tag; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.jsp.JspException; +import jakarta.servlet.jsp.PageContext; +import jakarta.servlet.jsp.tagext.Tag; import org.springframework.expression.BeanResolver; import org.springframework.expression.ConstructorResolver; diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/csrf/AbstractCsrfTag.java b/taglibs/src/main/java/org/springframework/security/taglibs/csrf/AbstractCsrfTag.java index d9ad9145d29..5878e086d5a 100644 --- a/taglibs/src/main/java/org/springframework/security/taglibs/csrf/AbstractCsrfTag.java +++ b/taglibs/src/main/java/org/springframework/security/taglibs/csrf/AbstractCsrfTag.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.TagSupport; +import jakarta.servlet.jsp.JspException; +import jakarta.servlet.jsp.tagext.TagSupport; import org.springframework.security.web.csrf.CsrfToken; diff --git a/taglibs/src/main/resources/META-INF/security.tld b/taglibs/src/main/resources/META-INF/security.tld index b14bac5ab4c..0ae747b7df4 100644 --- a/taglibs/src/main/resources/META-INF/security.tld +++ b/taglibs/src/main/resources/META-INF/security.tld @@ -20,7 +20,7 @@ version="2.0"> Spring Security Authorization Tag Library - 5.6 + 6.0 security http://www.springframework.org/security/tags diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTagTests.java index 12addcc94ee..0bc9653147b 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTagTests.java @@ -19,9 +19,9 @@ import java.io.IOException; import java.util.Collections; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AccessControlListTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AccessControlListTagTests.java index 2c319d5e5ce..fc00a5b2626 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AccessControlListTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AccessControlListTagTests.java @@ -19,8 +19,8 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.ServletContext; -import javax.servlet.jsp.tagext.Tag; +import jakarta.servlet.ServletContext; +import jakarta.servlet.jsp.tagext.Tag; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthenticationTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthenticationTagTests.java index dd53eabfa18..82cb281a302 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthenticationTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthenticationTagTests.java @@ -16,8 +16,8 @@ package org.springframework.security.taglibs.authz; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.Tag; +import jakarta.servlet.jsp.JspException; +import jakarta.servlet.jsp.tagext.Tag; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java index aa64b505b58..b740336b21a 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java @@ -16,8 +16,8 @@ package org.springframework.security.taglibs.authz; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.Tag; +import jakarta.servlet.jsp.JspException; +import jakarta.servlet.jsp.tagext.Tag; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java index 60522e600ef..09ca9633833 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java @@ -18,8 +18,8 @@ import java.io.UnsupportedEncodingException; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.Tag; +import jakarta.servlet.jsp.JspException; +import jakarta.servlet.jsp.tagext.Tag; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/test/spring-security-test.gradle b/test/spring-security-test.gradle index e5b977dda55..92b38684381 100644 --- a/test/spring-security-test.gradle +++ b/test/spring-security-test.gradle @@ -15,13 +15,13 @@ dependencies { optional 'org.springframework:spring-webmvc' optional 'org.springframework:spring-webflux' - provided 'javax.servlet:javax.servlet-api' + provided 'jakarta.servlet:jakarta.servlet-api' testImplementation project(path : ':spring-security-config', configuration : 'tests') testImplementation 'com.fasterxml.jackson.core:jackson-databind' testImplementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' testImplementation 'io.projectreactor:reactor-test' - testImplementation 'javax.xml.bind:jaxb-api' + testImplementation 'jakarta.xml.bind:jakarta.xml.bind-api' testImplementation "org.assertj:assertj-core" testImplementation "org.junit.jupiter:junit-jupiter-api" testImplementation "org.junit.jupiter:junit-jupiter-params" diff --git a/test/src/main/java/org/springframework/security/test/context/TestSecurityContextHolder.java b/test/src/main/java/org/springframework/security/test/context/TestSecurityContextHolder.java index f62938d4994..1eac0476709 100644 --- a/test/src/main/java/org/springframework/security/test/context/TestSecurityContextHolder.java +++ b/test/src/main/java/org/springframework/security/test/context/TestSecurityContextHolder.java @@ -16,7 +16,7 @@ package org.springframework.security.test.context; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; diff --git a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuilders.java b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuilders.java index 58058b45377..a0544f89e81 100644 --- a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuilders.java +++ b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuilders.java @@ -16,7 +16,7 @@ package org.springframework.security.test.web.servlet.request; -import javax.servlet.ServletContext; +import jakarta.servlet.ServletContext; import org.springframework.beans.Mergeable; import org.springframework.http.MediaType; diff --git a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java index 4d140655f59..86c44f86d4d 100644 --- a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java +++ b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java @@ -37,9 +37,9 @@ import java.util.function.Supplier; import java.util.stream.Collectors; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import com.nimbusds.oauth2.sdk.util.StringUtils; @@ -470,7 +470,7 @@ private X509RequestPostProcessor(X509Certificate... certificates) { @Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { - request.setAttribute("javax.servlet.request.X509Certificate", this.certificates); + request.setAttribute("jakarta.servlet.request.X509Certificate", this.certificates); return request; } diff --git a/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurer.java b/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurer.java index 98173963c1e..be16107e034 100644 --- a/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurer.java +++ b/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurer.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.springframework.security.config.BeanIds; import org.springframework.test.web.servlet.request.RequestPostProcessor; @@ -54,8 +54,8 @@ final class SecurityMockMvcConfigurer extends MockMvcConfigurerAdapter { } /** - * Creates a new instance with the provided {@link javax.servlet.Filter} - * @param springSecurityFilterChain the {@link javax.servlet.Filter} to use + * Creates a new instance with the provided {@link jakarta.servlet.Filter} + * @param springSecurityFilterChain the {@link jakarta.servlet.Filter} to use */ SecurityMockMvcConfigurer(Filter springSecurityFilterChain) { this.delegateFilter = new DelegateFilter(springSecurityFilterChain); diff --git a/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurers.java b/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurers.java index 07332b3244e..d6e7f440518 100644 --- a/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurers.java +++ b/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurers.java @@ -16,7 +16,7 @@ package org.springframework.security.test.web.servlet.setup; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.springframework.test.web.servlet.setup.MockMvcConfigurer; import org.springframework.util.Assert; diff --git a/test/src/main/java/org/springframework/security/test/web/support/WebTestUtils.java b/test/src/main/java/org/springframework/security/test/web/support/WebTestUtils.java index 8f9a79f51dc..8fe7a31ffa7 100644 --- a/test/src/main/java/org/springframework/security/test/web/support/WebTestUtils.java +++ b/test/src/main/java/org/springframework/security/test/web/support/WebTestUtils.java @@ -18,9 +18,9 @@ import java.util.List; -import javax.servlet.Filter; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.Filter; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.security.config.BeanIds; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationTests.java index 924d086f66c..17b8436146d 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationTests.java @@ -16,7 +16,7 @@ package org.springframework.security.test.web.servlet.request; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCertificateTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCertificateTests.java index c6edafd37ea..63924093cda 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCertificateTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCertificateTests.java @@ -46,7 +46,7 @@ public void setup() { public void x509SingleCertificate() { MockHttpServletRequest postProcessedRequest = x509(this.certificate).postProcessRequest(this.request); X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest - .getAttribute("javax.servlet.request.X509Certificate"); + .getAttribute("jakarta.servlet.request.X509Certificate"); assertThat(certificates).containsOnly(this.certificate); } @@ -54,7 +54,7 @@ public void x509SingleCertificate() { public void x509ResourceName() throws Exception { MockHttpServletRequest postProcessedRequest = x509("rod.cer").postProcessRequest(this.request); X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest - .getAttribute("javax.servlet.request.X509Certificate"); + .getAttribute("jakarta.servlet.request.X509Certificate"); assertThat(certificates).hasSize(1); assertThat(certificates[0].getSubjectDN().getName()) .isEqualTo("CN=rod, OU=Spring Security, O=Spring Framework"); diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCsrfTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCsrfTests.java index 9b7240c94d8..c26e079e34b 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCsrfTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCsrfTests.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java index e21d6ed5574..ad5cee4bbf2 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsJwtTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsJwtTests.java index be4975be47d..07a7b81079f 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsJwtTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsJwtTests.java @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java index 2d556581778..c9c7aa991cd 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java @@ -16,7 +16,7 @@ package org.springframework.security.test.web.servlet.request; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsSecurityContextTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsSecurityContextTests.java index afc8165b25e..db99a2a94dc 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsSecurityContextTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsSecurityContextTests.java @@ -16,7 +16,7 @@ package org.springframework.security.test.web.servlet.request; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextStatelessTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextStatelessTests.java index 7a919c27c6a..f9514b64b5a 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextStatelessTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextStatelessTests.java @@ -16,7 +16,7 @@ package org.springframework.security.test.web.servlet.request; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextTests.java index a3c2f7966fb..056934feb09 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextTests.java @@ -16,7 +16,7 @@ package org.springframework.security.test.web.servlet.request; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserDetailsTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserDetailsTests.java index bbd7c98c979..66fbad1c5f5 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserDetailsTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserDetailsTests.java @@ -16,7 +16,7 @@ package org.springframework.security.test.web.servlet.request; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java index f7e877d59ca..919f57aff1c 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java index f4cfabe2610..667cce15108 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java @@ -16,8 +16,8 @@ package org.springframework.security.test.web.servlet.setup; -import javax.servlet.Filter; -import javax.servlet.ServletContext; +import jakarta.servlet.Filter; +import jakarta.servlet.ServletContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurersTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurersTests.java index 5c964ec6ebb..36e53f335d7 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurersTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurersTests.java @@ -16,7 +16,7 @@ package org.springframework.security.test.web.servlet.setup; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/web/spring-security-web.gradle b/web/spring-security-web.gradle index ad2279b46e1..81a4e8116f5 100644 --- a/web/spring-security-web.gradle +++ b/web/spring-security-web.gradle @@ -17,12 +17,12 @@ dependencies { optional 'org.springframework:spring-webflux' optional 'org.springframework:spring-webmvc' - provided 'javax.servlet:javax.servlet-api' + provided 'jakarta.servlet:jakarta.servlet-api' testImplementation project(path: ':spring-security-core', configuration: 'tests') testImplementation 'commons-codec:commons-codec' testImplementation 'io.projectreactor:reactor-test' - testImplementation 'javax.xml.bind:jaxb-api' + testImplementation 'jakarta.xml.bind:jakarta.xml.bind-api' testImplementation 'org.hamcrest:hamcrest' testImplementation 'org.mockito:mockito-core' testImplementation 'org.mockito:mockito-inline' diff --git a/web/src/main/java/org/springframework/security/web/AuthenticationEntryPoint.java b/web/src/main/java/org/springframework/security/web/AuthenticationEntryPoint.java index ef59b284530..18c7657c2f0 100644 --- a/web/src/main/java/org/springframework/security/web/AuthenticationEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/AuthenticationEntryPoint.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.access.ExceptionTranslationFilter; diff --git a/web/src/main/java/org/springframework/security/web/DefaultRedirectStrategy.java b/web/src/main/java/org/springframework/security/web/DefaultRedirectStrategy.java index 61c16a3789e..fd764e34f77 100644 --- a/web/src/main/java/org/springframework/security/web/DefaultRedirectStrategy.java +++ b/web/src/main/java/org/springframework/security/web/DefaultRedirectStrategy.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/DefaultSecurityFilterChain.java b/web/src/main/java/org/springframework/security/web/DefaultSecurityFilterChain.java index 1961bf84fd6..fb0e2b53eea 100644 --- a/web/src/main/java/org/springframework/security/web/DefaultSecurityFilterChain.java +++ b/web/src/main/java/org/springframework/security/web/DefaultSecurityFilterChain.java @@ -20,8 +20,8 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.Filter; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.Filter; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/FilterChainProxy.java b/web/src/main/java/org/springframework/security/web/FilterChainProxy.java index 5b2d4392283..2a562fcf8cf 100644 --- a/web/src/main/java/org/springframework/security/web/FilterChainProxy.java +++ b/web/src/main/java/org/springframework/security/web/FilterChainProxy.java @@ -21,13 +21,13 @@ import java.util.Collections; import java.util.List; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -97,7 +97,7 @@ *

* {@code FilterChainProxy} respects normal handling of {@code Filter}s that elect not to * call - * {@link javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)} + * {@link jakarta.servlet.Filter#doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain)} * , in that the remainder of the original or {@code FilterChainProxy}-declared filter * chain will not be called. * diff --git a/web/src/main/java/org/springframework/security/web/FilterInvocation.java b/web/src/main/java/org/springframework/security/web/FilterInvocation.java index 2b848fb50e9..91631b2bf69 100644 --- a/web/src/main/java/org/springframework/security/web/FilterInvocation.java +++ b/web/src/main/java/org/springframework/security/web/FilterInvocation.java @@ -28,13 +28,13 @@ import java.util.LinkedHashMap; import java.util.Map; -import javax.servlet.FilterChain; -import javax.servlet.ServletContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.security.web.util.UrlUtils; diff --git a/web/src/main/java/org/springframework/security/web/PortResolver.java b/web/src/main/java/org/springframework/security/web/PortResolver.java index b83cfc976cc..501b1b43296 100644 --- a/web/src/main/java/org/springframework/security/web/PortResolver.java +++ b/web/src/main/java/org/springframework/security/web/PortResolver.java @@ -16,7 +16,7 @@ package org.springframework.security.web; -import javax.servlet.ServletRequest; +import jakarta.servlet.ServletRequest; /** * A PortResolver determines the port a web request was received on. diff --git a/web/src/main/java/org/springframework/security/web/PortResolverImpl.java b/web/src/main/java/org/springframework/security/web/PortResolverImpl.java index faa01d83c3f..94c200e216a 100644 --- a/web/src/main/java/org/springframework/security/web/PortResolverImpl.java +++ b/web/src/main/java/org/springframework/security/web/PortResolverImpl.java @@ -16,7 +16,7 @@ package org.springframework.security.web; -import javax.servlet.ServletRequest; +import jakarta.servlet.ServletRequest; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/RedirectStrategy.java b/web/src/main/java/org/springframework/security/web/RedirectStrategy.java index 8dc718a46d7..bd75edb722b 100644 --- a/web/src/main/java/org/springframework/security/web/RedirectStrategy.java +++ b/web/src/main/java/org/springframework/security/web/RedirectStrategy.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** * Encapsulates the redirection logic for all classes in the framework which perform diff --git a/web/src/main/java/org/springframework/security/web/RequestMatcherRedirectFilter.java b/web/src/main/java/org/springframework/security/web/RequestMatcherRedirectFilter.java index 9971ba9034f..d3247035449 100644 --- a/web/src/main/java/org/springframework/security/web/RequestMatcherRedirectFilter.java +++ b/web/src/main/java/org/springframework/security/web/RequestMatcherRedirectFilter.java @@ -18,10 +18,10 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/SecurityFilterChain.java b/web/src/main/java/org/springframework/security/web/SecurityFilterChain.java index bc919ef91b7..fb87b7bae8e 100644 --- a/web/src/main/java/org/springframework/security/web/SecurityFilterChain.java +++ b/web/src/main/java/org/springframework/security/web/SecurityFilterChain.java @@ -18,8 +18,8 @@ import java.util.List; -import javax.servlet.Filter; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.Filter; +import jakarta.servlet.http.HttpServletRequest; /** * Defines a filter chain which is capable of being matched against an diff --git a/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandler.java b/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandler.java index 8c4495ca6ff..53fa3aec605 100644 --- a/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandler.java +++ b/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; diff --git a/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandlerImpl.java b/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandlerImpl.java index 8139d0b2af8..e35d3b6fae7 100644 --- a/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandlerImpl.java +++ b/web/src/main/java/org/springframework/security/web/access/AccessDeniedHandlerImpl.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/access/AuthorizationManagerWebInvocationPrivilegeEvaluator.java b/web/src/main/java/org/springframework/security/web/access/AuthorizationManagerWebInvocationPrivilegeEvaluator.java new file mode 100644 index 00000000000..e5a6369eeb5 --- /dev/null +++ b/web/src/main/java/org/springframework/security/web/access/AuthorizationManagerWebInvocationPrivilegeEvaluator.java @@ -0,0 +1,57 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.access; + +import jakarta.servlet.http.HttpServletRequest; + +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.FilterInvocation; +import org.springframework.util.Assert; + +/** + * An implementation of {@link WebInvocationPrivilegeEvaluator} which delegates the checks + * to an instance of {@link AuthorizationManager} + * + * @author Marcus Da Coregio + * @since 5.7 + */ +public final class AuthorizationManagerWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator { + + private final AuthorizationManager authorizationManager; + + public AuthorizationManagerWebInvocationPrivilegeEvaluator( + AuthorizationManager authorizationManager) { + Assert.notNull(authorizationManager, "authorizationManager cannot be null"); + this.authorizationManager = authorizationManager; + } + + @Override + public boolean isAllowed(String uri, Authentication authentication) { + return isAllowed(null, uri, null, authentication); + } + + @Override + public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) { + FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method); + AuthorizationDecision decision = this.authorizationManager.check(() -> authentication, + filterInvocation.getHttpRequest()); + return decision != null && decision.isGranted(); + } + +} diff --git a/web/src/main/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluator.java b/web/src/main/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluator.java index 0563636dd5b..9b64bb6d159 100644 --- a/web/src/main/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluator.java +++ b/web/src/main/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluator.java @@ -18,7 +18,7 @@ import java.util.Collection; -import javax.servlet.ServletContext; +import jakarta.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/access/DelegatingAccessDeniedHandler.java b/web/src/main/java/org/springframework/security/web/access/DelegatingAccessDeniedHandler.java index 9e5fc8d3fa1..7349ee6d790 100644 --- a/web/src/main/java/org/springframework/security/web/access/DelegatingAccessDeniedHandler.java +++ b/web/src/main/java/org/springframework/security/web/access/DelegatingAccessDeniedHandler.java @@ -20,9 +20,9 @@ import java.util.LinkedHashMap; import java.util.Map.Entry; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java b/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java index 7b96e40d792..d870e856293 100644 --- a/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java +++ b/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; diff --git a/web/src/main/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandler.java b/web/src/main/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandler.java index 65f8c1abacc..aea6e2fb28c 100644 --- a/web/src/main/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandler.java +++ b/web/src/main/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandler.java @@ -20,9 +20,9 @@ import java.util.LinkedHashMap; import java.util.Map.Entry; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.util.matcher.RequestMatcher; diff --git a/web/src/main/java/org/springframework/security/web/access/RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.java b/web/src/main/java/org/springframework/security/web/access/RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.java new file mode 100644 index 00000000000..75de7201ca6 --- /dev/null +++ b/web/src/main/java/org/springframework/security/web/access/RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.java @@ -0,0 +1,122 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.access; + +import java.util.Collections; +import java.util.List; + +import jakarta.servlet.http.HttpServletRequest; + +import org.springframework.security.core.Authentication; +import org.springframework.security.web.FilterInvocation; +import org.springframework.security.web.util.matcher.RequestMatcherEntry; +import org.springframework.util.Assert; + +/** + * A {@link WebInvocationPrivilegeEvaluator} which delegates to a list of + * {@link WebInvocationPrivilegeEvaluator} based on a + * {@link org.springframework.security.web.util.matcher.RequestMatcher} evaluation + * + * @author Marcus Da Coregio + * @since 5.7 + */ +public final class RequestMatcherDelegatingWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator { + + private final List>> delegates; + + public RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( + List>> requestMatcherPrivilegeEvaluatorsEntries) { + Assert.notNull(requestMatcherPrivilegeEvaluatorsEntries, "requestMatcherPrivilegeEvaluators cannot be null"); + for (RequestMatcherEntry> entry : requestMatcherPrivilegeEvaluatorsEntries) { + Assert.notNull(entry.getRequestMatcher(), "requestMatcher cannot be null"); + Assert.notNull(entry.getEntry(), "webInvocationPrivilegeEvaluators cannot be null"); + } + this.delegates = requestMatcherPrivilegeEvaluatorsEntries; + } + + /** + * Determines whether the user represented by the supplied Authentication + * object is allowed to invoke the supplied URI. + *

+ * Uses the provided URI in the + * {@link org.springframework.security.web.util.matcher.RequestMatcher#matches(HttpServletRequest)} + * for every {@code RequestMatcher} configured. If no {@code RequestMatcher} is + * matched, or if there is not an available {@code WebInvocationPrivilegeEvaluator}, + * returns {@code true}. + * @param uri the URI excluding the context path (a default context path setting will + * be used) + * @return true if access is allowed, false if denied + */ + @Override + public boolean isAllowed(String uri, Authentication authentication) { + List privilegeEvaluators = getDelegate(null, uri, null); + if (privilegeEvaluators.isEmpty()) { + return true; + } + for (WebInvocationPrivilegeEvaluator evaluator : privilegeEvaluators) { + boolean isAllowed = evaluator.isAllowed(uri, authentication); + if (!isAllowed) { + return false; + } + } + return true; + } + + /** + * Determines whether the user represented by the supplied Authentication + * object is allowed to invoke the supplied URI. + *

+ * Uses the provided URI in the + * {@link org.springframework.security.web.util.matcher.RequestMatcher#matches(HttpServletRequest)} + * for every {@code RequestMatcher} configured. If no {@code RequestMatcher} is + * matched, or if there is not an available {@code WebInvocationPrivilegeEvaluator}, + * returns {@code true}. + * @param uri the URI excluding the context path (a default context path setting will + * be used) + * @param contextPath the context path (may be null, in which case a default value + * will be used). + * @param method the HTTP method (or null, for any method) + * @param authentication the Authentication instance whose authorities should + * be used in evaluation whether access should be granted. + * @return true if access is allowed, false if denied + */ + @Override + public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) { + List privilegeEvaluators = getDelegate(contextPath, uri, method); + if (privilegeEvaluators.isEmpty()) { + return true; + } + for (WebInvocationPrivilegeEvaluator evaluator : privilegeEvaluators) { + boolean isAllowed = evaluator.isAllowed(contextPath, uri, method, authentication); + if (!isAllowed) { + return false; + } + } + return true; + } + + private List getDelegate(String contextPath, String uri, String method) { + FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method); + for (RequestMatcherEntry> delegate : this.delegates) { + if (delegate.getRequestMatcher().matches(filterInvocation.getHttpRequest())) { + return delegate.getEntry(); + } + } + return Collections.emptyList(); + } + +} diff --git a/web/src/main/java/org/springframework/security/web/access/channel/AbstractRetryEntryPoint.java b/web/src/main/java/org/springframework/security/web/access/channel/AbstractRetryEntryPoint.java index 81fd2279b46..a2496e00afc 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/AbstractRetryEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/AbstractRetryEntryPoint.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManager.java b/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManager.java index a2bf53d11a1..3dace42b1e1 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManager.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManager.java @@ -19,7 +19,7 @@ import java.io.IOException; import java.util.Collection; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; diff --git a/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImpl.java b/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImpl.java index 5f6e05b29b1..5685c650666 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImpl.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImpl.java @@ -21,7 +21,7 @@ import java.util.Collection; import java.util.List; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import org.springframework.beans.factory.InitializingBean; import org.springframework.security.access.ConfigAttribute; diff --git a/web/src/main/java/org/springframework/security/web/access/channel/ChannelEntryPoint.java b/web/src/main/java/org/springframework/security/web/access/channel/ChannelEntryPoint.java index f3e09d3beb9..f5149055bf1 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/ChannelEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/ChannelEntryPoint.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** * May be used by a {@link ChannelProcessor} to launch a web channel. diff --git a/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessingFilter.java b/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessingFilter.java index b9dc1acb3e7..1f4fd2a7832 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessingFilter.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessingFilter.java @@ -21,12 +21,12 @@ import java.util.HashSet; import java.util.Set; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.access.ConfigAttribute; diff --git a/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessor.java b/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessor.java index 19cb406f357..07e27769c45 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessor.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessor.java @@ -19,7 +19,7 @@ import java.io.IOException; import java.util.Collection; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; diff --git a/web/src/main/java/org/springframework/security/web/access/channel/InsecureChannelProcessor.java b/web/src/main/java/org/springframework/security/web/access/channel/InsecureChannelProcessor.java index 3c214f73d7b..dbf23df6995 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/InsecureChannelProcessor.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/InsecureChannelProcessor.java @@ -19,7 +19,7 @@ import java.io.IOException; import java.util.Collection; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import org.springframework.beans.factory.InitializingBean; import org.springframework.security.access.ConfigAttribute; diff --git a/web/src/main/java/org/springframework/security/web/access/channel/SecureChannelProcessor.java b/web/src/main/java/org/springframework/security/web/access/channel/SecureChannelProcessor.java index 507bd679063..bc3dd8805dc 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/SecureChannelProcessor.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/SecureChannelProcessor.java @@ -19,7 +19,7 @@ import java.io.IOException; import java.util.Collection; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import org.springframework.beans.factory.InitializingBean; import org.springframework.security.access.ConfigAttribute; diff --git a/web/src/main/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessor.java b/web/src/main/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessor.java index b15a7c02ffa..6223c958ab0 100644 --- a/web/src/main/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessor.java +++ b/web/src/main/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessor.java @@ -18,7 +18,7 @@ import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.expression.EvaluationContext; import org.springframework.security.web.FilterInvocation; diff --git a/web/src/main/java/org/springframework/security/web/access/expression/ExpressionBasedFilterInvocationSecurityMetadataSource.java b/web/src/main/java/org/springframework/security/web/access/expression/ExpressionBasedFilterInvocationSecurityMetadataSource.java index 840a4a0b43a..932cea9d51f 100644 --- a/web/src/main/java/org/springframework/security/web/access/expression/ExpressionBasedFilterInvocationSecurityMetadataSource.java +++ b/web/src/main/java/org/springframework/security/web/access/expression/ExpressionBasedFilterInvocationSecurityMetadataSource.java @@ -22,7 +22,7 @@ import java.util.Map; import java.util.function.BiConsumer; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/access/expression/WebSecurityExpressionRoot.java b/web/src/main/java/org/springframework/security/web/access/expression/WebSecurityExpressionRoot.java index 91bc2df290b..e5027ebf2c4 100644 --- a/web/src/main/java/org/springframework/security/web/access/expression/WebSecurityExpressionRoot.java +++ b/web/src/main/java/org/springframework/security/web/access/expression/WebSecurityExpressionRoot.java @@ -16,7 +16,7 @@ package org.springframework.security.web.access.expression; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.access.expression.SecurityExpressionRoot; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/access/intercept/AuthorizationFilter.java b/web/src/main/java/org/springframework/security/web/access/intercept/AuthorizationFilter.java index 37b65ab0fbc..929e4cb8d03 100644 --- a/web/src/main/java/org/springframework/security/web/access/intercept/AuthorizationFilter.java +++ b/web/src/main/java/org/springframework/security/web/access/intercept/AuthorizationFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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,10 +18,10 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authorization.AuthorizationManager; @@ -67,4 +67,12 @@ private Authentication getAuthentication() { return authentication; } + /** + * Gets the {@link AuthorizationManager} used by this filter + * @return the {@link AuthorizationManager} + */ + public AuthorizationManager getAuthorizationManager() { + return this.authorizationManager; + } + } diff --git a/web/src/main/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSource.java b/web/src/main/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSource.java index 06ac758497d..61fa5b9dae1 100644 --- a/web/src/main/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSource.java +++ b/web/src/main/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSource.java @@ -22,7 +22,7 @@ import java.util.Map; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.java b/web/src/main/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.java index 1472a1a05e8..80148744a24 100644 --- a/web/src/main/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.java +++ b/web/src/main/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; diff --git a/web/src/main/java/org/springframework/security/web/access/intercept/RequestAuthorizationContext.java b/web/src/main/java/org/springframework/security/web/access/intercept/RequestAuthorizationContext.java index c285922d55f..97e6652b339 100644 --- a/web/src/main/java/org/springframework/security/web/access/intercept/RequestAuthorizationContext.java +++ b/web/src/main/java/org/springframework/security/web/access/intercept/RequestAuthorizationContext.java @@ -19,7 +19,7 @@ import java.util.Collections; import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * An {@link HttpServletRequest} authorization context. diff --git a/web/src/main/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManager.java b/web/src/main/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManager.java index b1c6378914f..3dd874dbc9e 100644 --- a/web/src/main/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManager.java +++ b/web/src/main/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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,9 +18,10 @@ import java.util.LinkedHashMap; import java.util.Map; +import java.util.function.Consumer; import java.util.function.Supplier; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -112,6 +113,21 @@ public Builder add(RequestMatcher matcher, AuthorizationManager>> mappingsConsumer) { + Assert.notNull(mappingsConsumer, "mappingsConsumer cannot be null"); + mappingsConsumer.accept(this.mappings); + return this; + } + /** * Creates a {@link RequestMatcherDelegatingAuthorizationManager} instance. * @return the {@link RequestMatcherDelegatingAuthorizationManager} instance diff --git a/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java index 933463c98ca..c90c8bb5690 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; diff --git a/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationTargetUrlRequestHandler.java b/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationTargetUrlRequestHandler.java index 1e10dbd2326..2289660fe16 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationTargetUrlRequestHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationTargetUrlRequestHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java index 341c8c16e11..3b1c6288425 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java @@ -19,11 +19,11 @@ import java.io.IOException; import java.util.List; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.log.LogMessage; diff --git a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationConverter.java b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationConverter.java index 63a144a0202..b8075b4bd68 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationConverter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationConverter.java @@ -16,7 +16,7 @@ package org.springframework.security.web.authentication; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationEntryPointFailureHandler.java b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationEntryPointFailureHandler.java index 0c6040f0997..0e1b8fbbc07 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationEntryPointFailureHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationEntryPointFailureHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; diff --git a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFailureHandler.java b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFailureHandler.java index ba4d23d1bc2..f31e589962c 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFailureHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFailureHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.core.AuthenticationException; diff --git a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFilter.java index fc42828a1d3..43a7b04d794 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFilter.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; diff --git a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationSuccessHandler.java b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationSuccessHandler.java index dc59b82f522..c40c5c4ad0e 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AuthenticationSuccessHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AuthenticationSuccessHandler.java @@ -18,10 +18,10 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPoint.java b/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPoint.java index d67dbf604f6..487e701166a 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPoint.java @@ -19,9 +19,9 @@ import java.io.IOException; import java.util.LinkedHashMap; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandler.java b/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandler.java index 4891c1ea83e..dee70fa430a 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandler.java @@ -20,9 +20,9 @@ import java.util.LinkedHashMap; import java.util.Map; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/authentication/ExceptionMappingAuthenticationFailureHandler.java b/web/src/main/java/org/springframework/security/web/authentication/ExceptionMappingAuthenticationFailureHandler.java index 5a619000f36..2bb72088c61 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/ExceptionMappingAuthenticationFailureHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/ExceptionMappingAuthenticationFailureHandler.java @@ -20,9 +20,9 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.util.UrlUtils; diff --git a/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationFailureHandler.java b/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationFailureHandler.java index 9071ea289e1..64268c2c715 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationFailureHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationFailureHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.WebAttributes; diff --git a/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationSuccessHandler.java b/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationSuccessHandler.java index 1e2ca60ef48..fb500eae67c 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationSuccessHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/ForwardAuthenticationSuccessHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.UrlUtils; diff --git a/web/src/main/java/org/springframework/security/web/authentication/Http403ForbiddenEntryPoint.java b/web/src/main/java/org/springframework/security/web/authentication/Http403ForbiddenEntryPoint.java index 216654945c4..2291414e305 100755 --- a/web/src/main/java/org/springframework/security/web/authentication/Http403ForbiddenEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/authentication/Http403ForbiddenEntryPoint.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/HttpStatusEntryPoint.java b/web/src/main/java/org/springframework/security/web/authentication/HttpStatusEntryPoint.java index a62e01e18e6..1168b7c93c3 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/HttpStatusEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/authentication/HttpStatusEntryPoint.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; diff --git a/web/src/main/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.java b/web/src/main/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.java index 08de9369c05..11be793f269 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.java @@ -18,10 +18,10 @@ import java.io.IOException; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/NullRememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/NullRememberMeServices.java index c6b1189e3d7..afccdaca3f5 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/NullRememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/NullRememberMeServices.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/RememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/RememberMeServices.java index a90c829db5e..b53cb0ffaf4 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/RememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/RememberMeServices.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandler.java b/web/src/main/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandler.java index 9118b86e90f..89235ab271c 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.java b/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.java index 96e327d22c2..2d204fdbc72 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.java @@ -18,10 +18,10 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandler.java b/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandler.java index b8ac058cd82..b87657dce9c 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandler.java @@ -18,10 +18,10 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.security.core.Authentication; import org.springframework.security.web.WebAttributes; diff --git a/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java index e1a444594fb..4b9b16b9038 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.lang.Nullable; import org.springframework.security.authentication.AuthenticationManager; diff --git a/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetails.java b/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetails.java index 34586abd46c..61c26dd982e 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetails.java +++ b/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetails.java @@ -18,8 +18,8 @@ import java.io.Serializable; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; import org.springframework.security.core.SpringSecurityCoreVersion; diff --git a/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetailsSource.java b/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetailsSource.java index 96d62c0c0c3..bf1946e7943 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetailsSource.java +++ b/web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetailsSource.java @@ -16,7 +16,7 @@ package org.springframework.security.web.authentication; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authentication.AuthenticationDetailsSource; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandler.java index b092d80cf66..f63dae083a9 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandler.java @@ -19,8 +19,8 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandler.java index 1ed2590024b..09b07c8bc41 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandler.java @@ -20,9 +20,9 @@ import java.util.List; import java.util.function.Function; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandler.java index 7632f57db7b..8fb550c743b 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandler.java @@ -20,9 +20,9 @@ import java.util.LinkedHashMap; import java.util.Map; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.matcher.RequestMatcher; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/ForwardLogoutSuccessHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/ForwardLogoutSuccessHandler.java index 90073995ca5..b1fa8aa4dec 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/ForwardLogoutSuccessHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/ForwardLogoutSuccessHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.UrlUtils; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/HeaderWriterLogoutHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/HeaderWriterLogoutHandler.java index cc5ce0309c2..f91f798b7f7 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/HeaderWriterLogoutHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/HeaderWriterLogoutHandler.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication.logout; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.header.HeaderWriter; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandler.java index 4cc71a856a4..9eab29e5418 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandler.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutFilter.java b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutFilter.java index 0c70eb0eb9c..9f987e91972 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutFilter.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutHandler.java index 4551d588a39..7e78ca2bb5b 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutHandler.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication.logout; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessEventPublishingLogoutHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessEventPublishingLogoutHandler.java index e33e15cfafd..216689bf226 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessEventPublishingLogoutHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessEventPublishingLogoutHandler.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication.logout; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessHandler.java index dfbedca5e0b..a40b913a685 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutSuccessHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.java index 1e84ab64ebc..de690e97df0 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.java @@ -16,9 +16,9 @@ package org.springframework.security.web.authentication.logout; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.java b/web/src/main/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.java index 08c4a20960e..bbc7e260781 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler; diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilter.java index 574e95de826..ebc45501efc 100755 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilter.java @@ -18,13 +18,13 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.java index f9534b5a907..5f5fa256946 100755 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.java @@ -21,7 +21,7 @@ import java.util.Collections; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityCoreVersion; diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilter.java index 6d9176a2306..f791bad0cfa 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilter.java @@ -16,7 +16,7 @@ package org.springframework.security.web.authentication.preauth; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestHeaderAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestHeaderAuthenticationFilter.java index 4f5fbee3f55..4817826bad9 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestHeaderAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/RequestHeaderAuthenticationFilter.java @@ -16,7 +16,7 @@ package org.springframework.security.web.authentication.preauth; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java index 4fbd010402f..efa29a316e3 100755 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java @@ -21,7 +21,7 @@ import java.util.Collections; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -68,9 +68,9 @@ public void afterPropertiesSet() { /** * Obtains the list of user roles based on the current user's JEE roles. The - * {@link javax.servlet.http.HttpServletRequest#isUserInRole(String)} method is called - * for each of the values in the {@code j2eeMappableRoles} set to determine if that - * role should be assigned to the user. + * {@link jakarta.servlet.http.HttpServletRequest#isUserInRole(String)} method is + * called for each of the values in the {@code j2eeMappableRoles} set to determine if + * that role should be assigned to the user. * @param request the request which should be used to extract the user's roles. * @return The subset of {@code j2eeMappableRoles} which applies to the current user * making the request. diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilter.java index 6d5a5dfa52a..2f67c744743 100755 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilter.java @@ -16,7 +16,7 @@ package org.springframework.security.web.authentication.preauth.j2ee; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.core.log.LogMessage; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilter.java index e58ee0b182e..6e34658e82f 100755 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilter.java @@ -16,7 +16,7 @@ package org.springframework.security.web.authentication.preauth.websphere; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.core.log.LogMessage; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedWebAuthenticationDetailsSource.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedWebAuthenticationDetailsSource.java index 5f52f928f6c..23823293dfe 100755 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedWebAuthenticationDetailsSource.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedWebAuthenticationDetailsSource.java @@ -19,7 +19,7 @@ import java.util.Collection; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/X509AuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/X509AuthenticationFilter.java index 1692df44d08..c49cc6ab2f6 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/X509AuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/X509AuthenticationFilter.java @@ -18,7 +18,7 @@ import java.security.cert.X509Certificate; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.core.log.LogMessage; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; @@ -42,7 +42,7 @@ protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { } private X509Certificate extractClientCertificate(HttpServletRequest request) { - X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); + X509Certificate[] certs = (X509Certificate[]) request.getAttribute("jakarta.servlet.request.X509Certificate"); if (certs != null && certs.length > 0) { this.logger.debug(LogMessage.format("X.509 client authentication certificate:%s", certs[0])); return certs[0]; diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/package-info.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/package-info.java index d45ff765457..9df5b2b9b56 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/package-info.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/x509/package-info.java @@ -16,7 +16,7 @@ /** * X.509 client certificate authentication support. Hooks into the certificate exposed by - * the servlet container through the {@code javax.servlet.request.X509Certificate} + * the servlet container through the {@code jakarta.servlet.request.X509Certificate} * property. */ package org.springframework.security.web.authentication.preauth.x509; diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java index 693d7f1e39e..a1786ea4405 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java @@ -22,9 +22,9 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.java index 9914275ca27..38ce40e0a3a 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.java @@ -21,8 +21,8 @@ import java.util.Base64; import java.util.Date; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter.java index d8573c0d70b..000fef5e5c8 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java index 2facda2bc17..ddd7d3cb9ba 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java @@ -21,8 +21,8 @@ import java.util.Arrays; import java.util.Date; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/AbstractSessionFixationProtectionStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/AbstractSessionFixationProtectionStrategy.java index 3f7183b5a7b..b25dedc414b 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/session/AbstractSessionFixationProtectionStrategy.java +++ b/web/src/main/java/org/springframework/security/web/authentication/session/AbstractSessionFixationProtectionStrategy.java @@ -16,9 +16,9 @@ package org.springframework.security.web.authentication.session; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/ChangeSessionIdAuthenticationStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/ChangeSessionIdAuthenticationStrategy.java index 1f382181408..5903cb19c91 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/session/ChangeSessionIdAuthenticationStrategy.java +++ b/web/src/main/java/org/springframework/security/web/authentication/session/ChangeSessionIdAuthenticationStrategy.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication.session; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; /** * Uses {@code HttpServletRequest.changeSessionId()} to protect against session fixation diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategy.java index 7473201df87..4af02d72d85 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategy.java +++ b/web/src/main/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategy.java @@ -18,9 +18,9 @@ import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategy.java index c35a80c5264..eac2f82f4e8 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategy.java +++ b/web/src/main/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategy.java @@ -19,9 +19,9 @@ import java.util.Comparator; import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/NullAuthenticatedSessionStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/NullAuthenticatedSessionStrategy.java index 5af14ee24aa..1b766804afe 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/session/NullAuthenticatedSessionStrategy.java +++ b/web/src/main/java/org/springframework/security/web/authentication/session/NullAuthenticatedSessionStrategy.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication.session; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/RegisterSessionAuthenticationStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/RegisterSessionAuthenticationStrategy.java index 99723e02aea..4a9e093a8fd 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/session/RegisterSessionAuthenticationStrategy.java +++ b/web/src/main/java/org/springframework/security/web/authentication/session/RegisterSessionAuthenticationStrategy.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication.session; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.session.SessionRegistry; diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/SessionAuthenticationStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/SessionAuthenticationStrategy.java index dfdcf762797..00e13dafc1b 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/session/SessionAuthenticationStrategy.java +++ b/web/src/main/java/org/springframework/security/web/authentication/session/SessionAuthenticationStrategy.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication.session; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionStrategy.java index 842ba85b776..6e6aa73e823 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionStrategy.java +++ b/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionStrategy.java @@ -20,8 +20,8 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; import org.springframework.core.log.LogMessage; diff --git a/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java b/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java index cd716fbfe5a..256f2e7d43e 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java @@ -21,12 +21,12 @@ import java.util.Collection; import java.util.List; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationEventPublisher; diff --git a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java index 06f0955c658..d8750baf690 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java @@ -22,13 +22,13 @@ import java.util.Map; import java.util.function.Function; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.WebAttributes; diff --git a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilter.java index 22811d01cf0..40a1ab84fcb 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilter.java @@ -21,10 +21,10 @@ import java.util.Map; import java.util.function.Function; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; diff --git a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java index 2e39a676245..25cd4d095d3 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java @@ -20,7 +20,7 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.security.authentication.AuthenticationDetailsSource; diff --git a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.java b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.java index e67ecba1993..e4ca009c9f6 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.HttpStatus; diff --git a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java index 9d639adf151..82c0d617ffa 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java @@ -19,10 +19,10 @@ import java.io.IOException; import java.nio.charset.Charset; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.AnonymousAuthenticationToken; diff --git a/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPoint.java b/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPoint.java index ac547cabb5d..1ed7054e545 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPoint.java @@ -19,8 +19,8 @@ import java.io.IOException; import java.util.Base64; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilter.java index 21efe4f5f8e..70a25379fe5 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilter.java @@ -20,12 +20,12 @@ import java.util.Base64; import java.util.Map; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializer.java b/web/src/main/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializer.java index 2df5c7a2eb2..5bed087e011 100644 --- a/web/src/main/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializer.java +++ b/web/src/main/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializer.java @@ -20,11 +20,11 @@ import java.util.EnumSet; import java.util.Set; -import javax.servlet.DispatcherType; -import javax.servlet.Filter; -import javax.servlet.FilterRegistration.Dynamic; -import javax.servlet.ServletContext; -import javax.servlet.SessionTrackingMode; +import jakarta.servlet.DispatcherType; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterRegistration.Dynamic; +import jakarta.servlet.ServletContext; +import jakarta.servlet.SessionTrackingMode; import org.springframework.context.ApplicationContext; import org.springframework.core.Conventions; diff --git a/web/src/main/java/org/springframework/security/web/context/HttpRequestResponseHolder.java b/web/src/main/java/org/springframework/security/web/context/HttpRequestResponseHolder.java index d2e68ad8173..c5b2f08edc2 100644 --- a/web/src/main/java/org/springframework/security/web/context/HttpRequestResponseHolder.java +++ b/web/src/main/java/org/springframework/security/web/context/HttpRequestResponseHolder.java @@ -16,8 +16,8 @@ package org.springframework.security.web.context; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** * Used to pass the incoming request to diff --git a/web/src/main/java/org/springframework/security/web/context/HttpSessionSecurityContextRepository.java b/web/src/main/java/org/springframework/security/web/context/HttpSessionSecurityContextRepository.java index 756db58a566..a5818d6abfa 100644 --- a/web/src/main/java/org/springframework/security/web/context/HttpSessionSecurityContextRepository.java +++ b/web/src/main/java/org/springframework/security/web/context/HttpSessionSecurityContextRepository.java @@ -16,13 +16,13 @@ package org.springframework.security.web.context; -import javax.servlet.AsyncContext; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.AsyncContext; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -233,6 +233,9 @@ public void setSpringSecurityContextKey(String springSecurityContextKey) { } private boolean isTransientAuthentication(Authentication authentication) { + if (authentication == null) { + return false; + } return AnnotationUtils.getAnnotation(authentication.getClass(), Transient.class) != null; } @@ -327,6 +330,9 @@ final class SaveToSessionResponseWrapper extends SaveContextOnUpdateOrErrorRespo @Override protected void saveContext(SecurityContext context) { final Authentication authentication = context.getAuthentication(); + if (isTransientAuthentication(authentication)) { + return; + } HttpSession httpSession = this.request.getSession(false); String springSecurityContextKey = HttpSessionSecurityContextRepository.this.springSecurityContextKey; // See SEC-776 @@ -348,7 +354,7 @@ protected void saveContext(SecurityContext context) { } return; } - httpSession = (httpSession != null) ? httpSession : createNewSessionIfAllowed(context, authentication); + httpSession = (httpSession != null) ? httpSession : createNewSessionIfAllowed(context); // If HttpSession exists, store current SecurityContext but only if it has // actually changed in this thread (see SEC-37, SEC-1307, SEC-1528) if (httpSession != null) { @@ -369,10 +375,7 @@ private boolean contextChanged(SecurityContext context) { || context.getAuthentication() != this.authBeforeExecution; } - private HttpSession createNewSessionIfAllowed(SecurityContext context, Authentication authentication) { - if (isTransientAuthentication(authentication)) { - return null; - } + private HttpSession createNewSessionIfAllowed(SecurityContext context) { if (this.httpSessionExistedAtStartOfRequest) { this.logger.debug("HttpSession is now null, but was not null at start of request; " + "session was invalidated, so do not create a new session"); diff --git a/web/src/main/java/org/springframework/security/web/context/NullSecurityContextRepository.java b/web/src/main/java/org/springframework/security/web/context/NullSecurityContextRepository.java index bd8563a3d03..697ce743ddc 100644 --- a/web/src/main/java/org/springframework/security/web/context/NullSecurityContextRepository.java +++ b/web/src/main/java/org/springframework/security/web/context/NullSecurityContextRepository.java @@ -16,8 +16,8 @@ package org.springframework.security.web.context; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; diff --git a/web/src/main/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapper.java b/web/src/main/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapper.java index 4fb534a5655..81bb453ac2e 100644 --- a/web/src/main/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapper.java +++ b/web/src/main/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapper.java @@ -16,7 +16,7 @@ package org.springframework.security.web.context; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; diff --git a/web/src/main/java/org/springframework/security/web/context/SecurityContextPersistenceFilter.java b/web/src/main/java/org/springframework/security/web/context/SecurityContextPersistenceFilter.java index 9a369a2161e..6300a02a266 100644 --- a/web/src/main/java/org/springframework/security/web/context/SecurityContextPersistenceFilter.java +++ b/web/src/main/java/org/springframework/security/web/context/SecurityContextPersistenceFilter.java @@ -18,13 +18,13 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.core.log.LogMessage; import org.springframework.security.core.context.SecurityContext; diff --git a/web/src/main/java/org/springframework/security/web/context/SecurityContextRepository.java b/web/src/main/java/org/springframework/security/web/context/SecurityContextRepository.java index 506dda8e38f..1039e60c98f 100644 --- a/web/src/main/java/org/springframework/security/web/context/SecurityContextRepository.java +++ b/web/src/main/java/org/springframework/security/web/context/SecurityContextRepository.java @@ -16,8 +16,8 @@ package org.springframework.security.web.context; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.context.SecurityContext; diff --git a/web/src/main/java/org/springframework/security/web/context/request/async/SecurityContextCallableProcessingInterceptor.java b/web/src/main/java/org/springframework/security/web/context/request/async/SecurityContextCallableProcessingInterceptor.java index bb54c2cc9da..8bb52766619 100644 --- a/web/src/main/java/org/springframework/security/web/context/request/async/SecurityContextCallableProcessingInterceptor.java +++ b/web/src/main/java/org/springframework/security/web/context/request/async/SecurityContextCallableProcessingInterceptor.java @@ -23,7 +23,6 @@ import org.springframework.util.Assert; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.async.CallableProcessingInterceptor; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; /** *

@@ -40,7 +39,7 @@ * @author Rob Winch * @since 3.2 */ -public final class SecurityContextCallableProcessingInterceptor extends CallableProcessingInterceptorAdapter { +public final class SecurityContextCallableProcessingInterceptor implements CallableProcessingInterceptor { private volatile SecurityContext securityContext; diff --git a/web/src/main/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilter.java b/web/src/main/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilter.java index dbe0c65f4c5..4b8df31f027 100644 --- a/web/src/main/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilter.java +++ b/web/src/main/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilter.java @@ -19,10 +19,10 @@ import java.io.IOException; import java.util.concurrent.Callable; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.context.SecurityContext; import org.springframework.web.context.request.async.WebAsyncManager; diff --git a/web/src/main/java/org/springframework/security/web/context/support/SecurityWebApplicationContextUtils.java b/web/src/main/java/org/springframework/security/web/context/support/SecurityWebApplicationContextUtils.java index d168bc31bc8..f5a7d6894ad 100644 --- a/web/src/main/java/org/springframework/security/web/context/support/SecurityWebApplicationContextUtils.java +++ b/web/src/main/java/org/springframework/security/web/context/support/SecurityWebApplicationContextUtils.java @@ -16,7 +16,7 @@ package org.springframework.security.web.context.support; -import javax.servlet.ServletContext; +import jakarta.servlet.ServletContext; import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; diff --git a/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java b/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java index 80f036e7d85..62075e0d063 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java +++ b/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java @@ -18,10 +18,10 @@ import java.util.UUID; -import javax.servlet.ServletRequest; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.util.Assert; import org.springframework.util.StringUtils; diff --git a/web/src/main/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategy.java b/web/src/main/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategy.java index f6a19a266d7..78a813c0e3f 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategy.java +++ b/web/src/main/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategy.java @@ -16,8 +16,8 @@ package org.springframework.security.web.csrf; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/csrf/CsrfFilter.java b/web/src/main/java/org/springframework/security/web/csrf/CsrfFilter.java index 8490c508dac..53a244d6b09 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/CsrfFilter.java +++ b/web/src/main/java/org/springframework/security/web/csrf/CsrfFilter.java @@ -21,11 +21,11 @@ import java.util.Arrays; import java.util.HashSet; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/csrf/CsrfLogoutHandler.java b/web/src/main/java/org/springframework/security/web/csrf/CsrfLogoutHandler.java index c3b60909970..3ca7d98fc24 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/CsrfLogoutHandler.java +++ b/web/src/main/java/org/springframework/security/web/csrf/CsrfLogoutHandler.java @@ -16,8 +16,8 @@ package org.springframework.security.web.csrf; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; @@ -46,8 +46,8 @@ public CsrfLogoutHandler(CsrfTokenRepository csrfTokenRepository) { /** * Clears the {@link CsrfToken} * - * @see org.springframework.security.web.authentication.logout.LogoutHandler#logout(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse, + * @see org.springframework.security.web.authentication.logout.LogoutHandler#logout(jakarta.servlet.http.HttpServletRequest, + * jakarta.servlet.http.HttpServletResponse, * org.springframework.security.core.Authentication) */ @Override diff --git a/web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRepository.java b/web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRepository.java index bc20131685e..3fcdd01607a 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRepository.java +++ b/web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRepository.java @@ -16,9 +16,9 @@ package org.springframework.security.web.csrf; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; /** * An API to allow changing the method in which the expected {@link CsrfToken} is diff --git a/web/src/main/java/org/springframework/security/web/csrf/HttpSessionCsrfTokenRepository.java b/web/src/main/java/org/springframework/security/web/csrf/HttpSessionCsrfTokenRepository.java index 70c701b60e4..802dcc2c064 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/HttpSessionCsrfTokenRepository.java +++ b/web/src/main/java/org/springframework/security/web/csrf/HttpSessionCsrfTokenRepository.java @@ -18,9 +18,9 @@ import java.util.UUID; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/csrf/InvalidCsrfTokenException.java b/web/src/main/java/org/springframework/security/web/csrf/InvalidCsrfTokenException.java index 135ba3831fb..0c57e5a604d 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/InvalidCsrfTokenException.java +++ b/web/src/main/java/org/springframework/security/web/csrf/InvalidCsrfTokenException.java @@ -16,7 +16,7 @@ package org.springframework.security.web.csrf; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * Thrown when an expected {@link CsrfToken} exists, but it does not match the value diff --git a/web/src/main/java/org/springframework/security/web/csrf/LazyCsrfTokenRepository.java b/web/src/main/java/org/springframework/security/web/csrf/LazyCsrfTokenRepository.java index b0f4263f2a1..d5c0c211904 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/LazyCsrfTokenRepository.java +++ b/web/src/main/java/org/springframework/security/web/csrf/LazyCsrfTokenRepository.java @@ -16,8 +16,8 @@ package org.springframework.security.web.csrf; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/debug/DebugFilter.java b/web/src/main/java/org/springframework/security/web/debug/DebugFilter.java index a25b7927ace..47d80e6da97 100644 --- a/web/src/main/java/org/springframework/security/web/debug/DebugFilter.java +++ b/web/src/main/java/org/springframework/security/web/debug/DebugFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2021 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. @@ -20,16 +20,16 @@ import java.util.Enumeration; import java.util.List; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.SecurityFilterChain; @@ -151,6 +151,10 @@ public void init(FilterConfig filterConfig) { public void destroy() { } + public FilterChainProxy getFilterChainProxy() { + return this.filterChainProxy; + } + static class DebugRequestWrapper extends HttpServletRequestWrapper { private static final Logger logger = new Logger(); diff --git a/web/src/main/java/org/springframework/security/web/firewall/DefaultHttpFirewall.java b/web/src/main/java/org/springframework/security/web/firewall/DefaultHttpFirewall.java index aec01583a58..1bed1d74c24 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/DefaultHttpFirewall.java +++ b/web/src/main/java/org/springframework/security/web/firewall/DefaultHttpFirewall.java @@ -16,8 +16,8 @@ package org.springframework.security.web.firewall; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** *

diff --git a/web/src/main/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandler.java b/web/src/main/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandler.java index 5c4cc314c63..27d7c3328db 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandler.java +++ b/web/src/main/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** * Default implementation of {@link RequestRejectedHandler} that simply rethrows the diff --git a/web/src/main/java/org/springframework/security/web/firewall/FirewalledRequest.java b/web/src/main/java/org/springframework/security/web/firewall/FirewalledRequest.java index 396a19aa947..fddf44aceaa 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/FirewalledRequest.java +++ b/web/src/main/java/org/springframework/security/web/firewall/FirewalledRequest.java @@ -16,8 +16,8 @@ package org.springframework.security.web.firewall; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; /** * Request wrapper which is returned by the {@code HttpFirewall} interface. diff --git a/web/src/main/java/org/springframework/security/web/firewall/FirewalledResponse.java b/web/src/main/java/org/springframework/security/web/firewall/FirewalledResponse.java index 0f0bca9b1cc..e5d34ff197e 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/FirewalledResponse.java +++ b/web/src/main/java/org/springframework/security/web/firewall/FirewalledResponse.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponseWrapper; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/firewall/HttpFirewall.java b/web/src/main/java/org/springframework/security/web/firewall/HttpFirewall.java index e6c3d6ab904..3b962300a7a 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/HttpFirewall.java +++ b/web/src/main/java/org/springframework/security/web/firewall/HttpFirewall.java @@ -16,8 +16,8 @@ package org.springframework.security.web.firewall; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** * Interface which can be used to reject potentially dangerous requests and/or wrap them diff --git a/web/src/main/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandler.java b/web/src/main/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandler.java index 36a9df93e2e..608e54c8589 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandler.java +++ b/web/src/main/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandler.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/firewall/RequestRejectedHandler.java b/web/src/main/java/org/springframework/security/web/firewall/RequestRejectedHandler.java index 5fa1a5ce312..dba6a51f30b 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/RequestRejectedHandler.java +++ b/web/src/main/java/org/springframework/security/web/firewall/RequestRejectedHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** * Used by {@link org.springframework.security.web.FilterChainProxy} to handle an diff --git a/web/src/main/java/org/springframework/security/web/firewall/RequestWrapper.java b/web/src/main/java/org/springframework/security/web/firewall/RequestWrapper.java index 80a41a0a828..78de1494382 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/RequestWrapper.java +++ b/web/src/main/java/org/springframework/security/web/firewall/RequestWrapper.java @@ -19,11 +19,11 @@ import java.io.IOException; import java.util.StringTokenizer; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; /** * Request wrapper which ensures values of {@code servletPath} and {@code pathInfo} are diff --git a/web/src/main/java/org/springframework/security/web/firewall/StrictHttpFirewall.java b/web/src/main/java/org/springframework/security/web/firewall/StrictHttpFirewall.java index 282184b3b38..2869627a9e3 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/StrictHttpFirewall.java +++ b/web/src/main/java/org/springframework/security/web/firewall/StrictHttpFirewall.java @@ -27,8 +27,8 @@ import java.util.function.Predicate; import java.util.regex.Pattern; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpMethod; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/header/Header.java b/web/src/main/java/org/springframework/security/web/header/Header.java index 2356914712f..84586f23b3b 100644 --- a/web/src/main/java/org/springframework/security/web/header/Header.java +++ b/web/src/main/java/org/springframework/security/web/header/Header.java @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/header/HeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/HeaderWriter.java index e844d734838..68cd541c0f6 100644 --- a/web/src/main/java/org/springframework/security/web/header/HeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/HeaderWriter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.header; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** * Contract for writing headers to a {@link HttpServletResponse} diff --git a/web/src/main/java/org/springframework/security/web/header/HeaderWriterFilter.java b/web/src/main/java/org/springframework/security/web/header/HeaderWriterFilter.java index 2608431b3be..3c6ad93eccf 100644 --- a/web/src/main/java/org/springframework/security/web/header/HeaderWriterFilter.java +++ b/web/src/main/java/org/springframework/security/web/header/HeaderWriterFilter.java @@ -19,14 +19,14 @@ import java.io.IOException; import java.util.List; -import javax.servlet.FilterChain; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.util.OnCommittedResponseWrapper; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/CacheControlHeadersWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/CacheControlHeadersWriter.java index 88f78dc6aad..f7359de803b 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/CacheControlHeadersWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/CacheControlHeadersWriter.java @@ -19,8 +19,8 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.security.web.header.Header; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriter.java index db3c4be2eb4..2a20b8fb188 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.header.writers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/CompositeHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/CompositeHeaderWriter.java index 4f2b9f41850..20b7369a31e 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/CompositeHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/CompositeHeaderWriter.java @@ -18,8 +18,8 @@ import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/ContentSecurityPolicyHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/ContentSecurityPolicyHeaderWriter.java index 5de10d04b87..ed2445a72fa 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/ContentSecurityPolicyHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/ContentSecurityPolicyHeaderWriter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.header.writers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; @@ -112,8 +112,8 @@ public ContentSecurityPolicyHeaderWriter(String policyDirectives) { } /** - * @see org.springframework.security.web.header.HeaderWriter#writeHeaders(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse) + * @see org.springframework.security.web.header.HeaderWriter#writeHeaders(jakarta.servlet.http.HttpServletRequest, + * jakarta.servlet.http.HttpServletResponse) */ @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { diff --git a/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginEmbedderPolicyHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginEmbedderPolicyHeaderWriter.java new file mode 100644 index 00000000000..d7e2a6dde58 --- /dev/null +++ b/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginEmbedderPolicyHeaderWriter.java @@ -0,0 +1,84 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.header.writers; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.springframework.security.web.header.HeaderWriter; +import org.springframework.util.Assert; + +/** + * Inserts Cross-Origin-Embedder-Policy header. + * + * @author Marcus Da Coregio + * @since 5.7 + * @see + * Cross-Origin-Embedder-Policy + */ +public final class CrossOriginEmbedderPolicyHeaderWriter implements HeaderWriter { + + private static final String EMBEDDER_POLICY = "Cross-Origin-Embedder-Policy"; + + private CrossOriginEmbedderPolicy policy; + + /** + * Sets the {@link CrossOriginEmbedderPolicy} value to be used in the + * {@code Cross-Origin-Embedder-Policy} header + * @param embedderPolicy the {@link CrossOriginEmbedderPolicy} to use + */ + public void setPolicy(CrossOriginEmbedderPolicy embedderPolicy) { + Assert.notNull(embedderPolicy, "embedderPolicy cannot be null"); + this.policy = embedderPolicy; + } + + @Override + public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { + if (this.policy != null && !response.containsHeader(EMBEDDER_POLICY)) { + response.addHeader(EMBEDDER_POLICY, this.policy.getPolicy()); + } + } + + public enum CrossOriginEmbedderPolicy { + + UNSAFE_NONE("unsafe-none"), + + REQUIRE_CORP("require-corp"); + + private final String policy; + + CrossOriginEmbedderPolicy(String policy) { + this.policy = policy; + } + + public String getPolicy() { + return this.policy; + } + + public static CrossOriginEmbedderPolicy from(String embedderPolicy) { + for (CrossOriginEmbedderPolicy policy : values()) { + if (policy.getPolicy().equals(embedderPolicy)) { + return policy; + } + } + return null; + } + + } + +} diff --git a/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginOpenerPolicyHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginOpenerPolicyHeaderWriter.java new file mode 100644 index 00000000000..33e89ea99a6 --- /dev/null +++ b/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginOpenerPolicyHeaderWriter.java @@ -0,0 +1,86 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.header.writers; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.springframework.security.web.header.HeaderWriter; +import org.springframework.util.Assert; + +/** + * Inserts the Cross-Origin-Opener-Policy header + * + * @author Marcus Da Coregio + * @since 5.7 + * @see + * Cross-Origin-Opener-Policy + */ +public final class CrossOriginOpenerPolicyHeaderWriter implements HeaderWriter { + + private static final String OPENER_POLICY = "Cross-Origin-Opener-Policy"; + + private CrossOriginOpenerPolicy policy; + + /** + * Sets the {@link CrossOriginOpenerPolicy} value to be used in the + * {@code Cross-Origin-Opener-Policy} header + * @param openerPolicy the {@link CrossOriginOpenerPolicy} to use + */ + public void setPolicy(CrossOriginOpenerPolicy openerPolicy) { + Assert.notNull(openerPolicy, "openerPolicy cannot be null"); + this.policy = openerPolicy; + } + + @Override + public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { + if (this.policy != null && !response.containsHeader(OPENER_POLICY)) { + response.addHeader(OPENER_POLICY, this.policy.getPolicy()); + } + } + + public enum CrossOriginOpenerPolicy { + + UNSAFE_NONE("unsafe-none"), + + SAME_ORIGIN_ALLOW_POPUPS("same-origin-allow-popups"), + + SAME_ORIGIN("same-origin"); + + private final String policy; + + CrossOriginOpenerPolicy(String policy) { + this.policy = policy; + } + + public String getPolicy() { + return this.policy; + } + + public static CrossOriginOpenerPolicy from(String openerPolicy) { + for (CrossOriginOpenerPolicy policy : values()) { + if (policy.getPolicy().equals(openerPolicy)) { + return policy; + } + } + return null; + } + + } + +} diff --git a/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginResourcePolicyHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginResourcePolicyHeaderWriter.java new file mode 100644 index 00000000000..54fe2d74f81 --- /dev/null +++ b/web/src/main/java/org/springframework/security/web/header/writers/CrossOriginResourcePolicyHeaderWriter.java @@ -0,0 +1,86 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.header.writers; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.springframework.security.web.header.HeaderWriter; +import org.springframework.util.Assert; + +/** + * Inserts Cross-Origin-Resource-Policy header + * + * @author Marcus Da Coregio + * @since 5.7 + * @see + * Cross-Origin-Resource-Policy + */ +public final class CrossOriginResourcePolicyHeaderWriter implements HeaderWriter { + + private static final String RESOURCE_POLICY = "Cross-Origin-Resource-Policy"; + + private CrossOriginResourcePolicy policy; + + /** + * Sets the {@link CrossOriginResourcePolicy} value to be used in the + * {@code Cross-Origin-Resource-Policy} header + * @param resourcePolicy the {@link CrossOriginResourcePolicy} to use + */ + public void setPolicy(CrossOriginResourcePolicy resourcePolicy) { + Assert.notNull(resourcePolicy, "resourcePolicy cannot be null"); + this.policy = resourcePolicy; + } + + @Override + public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { + if (this.policy != null && !response.containsHeader(RESOURCE_POLICY)) { + response.addHeader(RESOURCE_POLICY, this.policy.getPolicy()); + } + } + + public enum CrossOriginResourcePolicy { + + SAME_SITE("same-site"), + + SAME_ORIGIN("same-origin"), + + CROSS_ORIGIN("cross-origin"); + + private final String policy; + + CrossOriginResourcePolicy(String policy) { + this.policy = policy; + } + + public String getPolicy() { + return this.policy; + } + + public static CrossOriginResourcePolicy from(String resourcePolicy) { + for (CrossOriginResourcePolicy policy : values()) { + if (policy.getPolicy().equals(resourcePolicy)) { + return policy; + } + } + return null; + } + + } + +} diff --git a/web/src/main/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriter.java index d30cecc5f22..9d1f9a115c5 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.header.writers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.security.web.util.matcher.RequestMatcher; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriter.java index 3929c3df521..fe8c891eee4 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.header.writers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/HpkpHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/HpkpHeaderWriter.java index 0422f525c72..ad2739613a8 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/HpkpHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/HpkpHeaderWriter.java @@ -21,8 +21,8 @@ import java.util.LinkedHashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/HstsHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/HstsHeaderWriter.java index c4ee432a516..10cf9877111 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/HstsHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/HstsHeaderWriter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.header.writers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/PermissionsPolicyHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/PermissionsPolicyHeaderWriter.java index aaefc3d9ca6..4067177e627 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/PermissionsPolicyHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/PermissionsPolicyHeaderWriter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.header.writers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/ReferrerPolicyHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/ReferrerPolicyHeaderWriter.java index eab56fc3895..2daf98283aa 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/ReferrerPolicyHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/ReferrerPolicyHeaderWriter.java @@ -20,8 +20,8 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/StaticHeadersWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/StaticHeadersWriter.java index bec4a5d5da3..f1d4dfe7f33 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/StaticHeadersWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/StaticHeadersWriter.java @@ -19,8 +19,8 @@ import java.util.Collections; import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.Header; import org.springframework.security.web.header.HeaderWriter; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/XXssProtectionHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/XXssProtectionHeaderWriter.java index a5a72d1384b..e6eab3f7694 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/XXssProtectionHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/XXssProtectionHeaderWriter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.header.writers; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AbstractRequestParameterAllowFromStrategy.java b/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AbstractRequestParameterAllowFromStrategy.java index 104a6cb2349..bf27ff69fcd 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AbstractRequestParameterAllowFromStrategy.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AbstractRequestParameterAllowFromStrategy.java @@ -16,7 +16,7 @@ package org.springframework.security.web.header.writers.frameoptions; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AllowFromStrategy.java b/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AllowFromStrategy.java index 8c9a2373b50..e48fe2ac8e9 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AllowFromStrategy.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/AllowFromStrategy.java @@ -16,7 +16,7 @@ package org.springframework.security.web.header.writers.frameoptions; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * Strategy interfaces used by the {@code FrameOptionsHeaderWriter} to determine the diff --git a/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/StaticAllowFromStrategy.java b/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/StaticAllowFromStrategy.java index 11ae4f091fd..8b7cd4792e6 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/StaticAllowFromStrategy.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/StaticAllowFromStrategy.java @@ -18,7 +18,7 @@ import java.net.URI; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * Simple implementation of the {@code AllowFromStrategy} diff --git a/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/XFrameOptionsHeaderWriter.java b/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/XFrameOptionsHeaderWriter.java index 9cecae5cc47..a3c3f8ad779 100644 --- a/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/XFrameOptionsHeaderWriter.java +++ b/web/src/main/java/org/springframework/security/web/header/writers/frameoptions/XFrameOptionsHeaderWriter.java @@ -16,8 +16,8 @@ package org.springframework.security.web.header.writers.frameoptions; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilter.java b/web/src/main/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilter.java index b340512a671..a66d1ce3c32 100644 --- a/web/src/main/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilter.java +++ b/web/src/main/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilter.java @@ -22,10 +22,11 @@ import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.jaas.JaasAuthenticationToken; diff --git a/web/src/main/java/org/springframework/security/web/jackson2/CookieDeserializer.java b/web/src/main/java/org/springframework/security/web/jackson2/CookieDeserializer.java index 4b0c3a41f2d..0b034b5490a 100644 --- a/web/src/main/java/org/springframework/security/web/jackson2/CookieDeserializer.java +++ b/web/src/main/java/org/springframework/security/web/jackson2/CookieDeserializer.java @@ -18,7 +18,7 @@ import java.io.IOException; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/web/src/main/java/org/springframework/security/web/jackson2/CookieMixin.java b/web/src/main/java/org/springframework/security/web/jackson2/CookieMixin.java index 4d0c42c4211..2938e796435 100644 --- a/web/src/main/java/org/springframework/security/web/jackson2/CookieMixin.java +++ b/web/src/main/java/org/springframework/security/web/jackson2/CookieMixin.java @@ -21,7 +21,7 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** - * Mixin class to serialize/deserialize {@link javax.servlet.http.Cookie} + * Mixin class to serialize/deserialize {@link jakarta.servlet.http.Cookie} * *

  *     ObjectMapper mapper = new ObjectMapper();
diff --git a/web/src/main/java/org/springframework/security/web/jackson2/WebServletJackson2Module.java b/web/src/main/java/org/springframework/security/web/jackson2/WebServletJackson2Module.java
index 7a91aebf3f8..07bd2c3e00d 100644
--- a/web/src/main/java/org/springframework/security/web/jackson2/WebServletJackson2Module.java
+++ b/web/src/main/java/org/springframework/security/web/jackson2/WebServletJackson2Module.java
@@ -16,7 +16,7 @@
 
 package org.springframework.security.web.jackson2;
 
-import javax.servlet.http.Cookie;
+import jakarta.servlet.http.Cookie;
 
 import com.fasterxml.jackson.core.Version;
 import com.fasterxml.jackson.databind.module.SimpleModule;
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/CookieRequestCache.java b/web/src/main/java/org/springframework/security/web/savedrequest/CookieRequestCache.java
index 9999cc2ee76..d540ca98caa 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/CookieRequestCache.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/CookieRequestCache.java
@@ -18,9 +18,9 @@
 
 import java.util.Base64;
 
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.Cookie;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/DefaultSavedRequest.java b/web/src/main/java/org/springframework/security/web/savedrequest/DefaultSavedRequest.java
index ea2358293f6..2a3c99865b6 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/DefaultSavedRequest.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/DefaultSavedRequest.java
@@ -25,8 +25,8 @@
 import java.util.Map;
 import java.util.TreeMap;
 
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.Cookie;
+import jakarta.servlet.http.HttpServletRequest;
 
 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
 import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
@@ -61,6 +61,8 @@
  */
 public class DefaultSavedRequest implements SavedRequest {
 
+	private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
+
 	protected static final Log logger = LogFactory.getLog(DefaultSavedRequest.class);
 
 	private static final String HEADER_IF_NONE_MATCH = "If-None-Match";
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/HttpSessionRequestCache.java b/web/src/main/java/org/springframework/security/web/savedrequest/HttpSessionRequestCache.java
index af5d414550f..574ffb4ba18 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/HttpSessionRequestCache.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/HttpSessionRequestCache.java
@@ -16,9 +16,9 @@
 
 package org.springframework.security.web.savedrequest;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpSession;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/NullRequestCache.java b/web/src/main/java/org/springframework/security/web/savedrequest/NullRequestCache.java
index 51064839054..9557dc179e1 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/NullRequestCache.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/NullRequestCache.java
@@ -16,8 +16,8 @@
 
 package org.springframework.security.web.savedrequest;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
 
 /**
  * Null implementation of RequestCache. Typically used when creation of a session
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/RequestCache.java b/web/src/main/java/org/springframework/security/web/savedrequest/RequestCache.java
index 0746dbfbf62..427b81dc475 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/RequestCache.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/RequestCache.java
@@ -16,8 +16,8 @@
 
 package org.springframework.security.web.savedrequest;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
 
 /**
  * Implements "saved request" logic, allowing a single request to be retrieved and
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java b/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java
index 74b769c1ee9..ccb65ed980a 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java
@@ -18,12 +18,12 @@
 
 import java.io.IOException;
 
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
 
 import org.springframework.util.Assert;
 import org.springframework.web.filter.GenericFilterBean;
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/SavedCookie.java b/web/src/main/java/org/springframework/security/web/savedrequest/SavedCookie.java
index 9357e98fbed..36ec72c3afa 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/SavedCookie.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/SavedCookie.java
@@ -18,7 +18,7 @@
 
 import java.io.Serializable;
 
-import javax.servlet.http.Cookie;
+import jakarta.servlet.http.Cookie;
 
 /**
  * Stores off the values of a cookie in a serializable holder
@@ -27,6 +27,8 @@
  */
 public class SavedCookie implements Serializable {
 
+	private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
+
 	private final java.lang.String name;
 
 	private final java.lang.String value;
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequest.java b/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequest.java
index 6a2984c7329..0207c4fffb4 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequest.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequest.java
@@ -21,7 +21,7 @@
 import java.util.Locale;
 import java.util.Map;
 
-import javax.servlet.http.Cookie;
+import jakarta.servlet.http.Cookie;
 
 /**
  * Encapsulates the functionality required of a cached request for both an authentication
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapper.java b/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapper.java
index dfd47266753..204abd60125 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapper.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapper.java
@@ -28,8 +28,8 @@
 import java.util.Set;
 import java.util.TimeZone;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequestWrapper;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/SimpleSavedRequest.java b/web/src/main/java/org/springframework/security/web/savedrequest/SimpleSavedRequest.java
index 431f037703d..e1595ea6bdc 100644
--- a/web/src/main/java/org/springframework/security/web/savedrequest/SimpleSavedRequest.java
+++ b/web/src/main/java/org/springframework/security/web/savedrequest/SimpleSavedRequest.java
@@ -23,7 +23,7 @@
 import java.util.Locale;
 import java.util.Map;
 
-import javax.servlet.http.Cookie;
+import jakarta.servlet.http.Cookie;
 
 import org.springframework.util.Assert;
 
diff --git a/web/src/main/java/org/springframework/security/web/server/WebFilterChainProxy.java b/web/src/main/java/org/springframework/security/web/server/WebFilterChainProxy.java
index f4654ab25fd..33704a096fb 100644
--- a/web/src/main/java/org/springframework/security/web/server/WebFilterChainProxy.java
+++ b/web/src/main/java/org/springframework/security/web/server/WebFilterChainProxy.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2017 the original author or authors.
+ * Copyright 2002-2021 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.
@@ -26,7 +26,6 @@
 import org.springframework.web.server.WebFilter;
 import org.springframework.web.server.WebFilterChain;
 import org.springframework.web.server.handler.DefaultWebFilterChain;
-import org.springframework.web.server.handler.FilteringWebHandler;
 
 /**
  * Used to delegate to a List of {@link SecurityWebFilterChain} instances.
@@ -52,7 +51,7 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) {
 				.filterWhen((securityWebFilterChain) -> securityWebFilterChain.matches(exchange)).next()
 				.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
 				.flatMap((securityWebFilterChain) -> securityWebFilterChain.getWebFilters().collectList())
-				.map((filters) -> new FilteringWebHandler(chain::filter, filters)).map(DefaultWebFilterChain::new)
+				.map((filters) -> new DefaultWebFilterChain(chain::filter, filters))
 				.flatMap((securedChain) -> securedChain.filter(exchange));
 	}
 
diff --git a/web/src/main/java/org/springframework/security/web/server/authorization/IpAddressReactiveAuthorizationManager.java b/web/src/main/java/org/springframework/security/web/server/authorization/IpAddressReactiveAuthorizationManager.java
new file mode 100644
index 00000000000..5b814a52761
--- /dev/null
+++ b/web/src/main/java/org/springframework/security/web/server/authorization/IpAddressReactiveAuthorizationManager.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2002-2021 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.security.web.server.authorization;
+
+import reactor.core.publisher.Mono;
+
+import org.springframework.security.authorization.AuthorizationDecision;
+import org.springframework.security.authorization.ReactiveAuthorizationManager;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.server.util.matcher.IpAddressServerWebExchangeMatcher;
+import org.springframework.util.Assert;
+
+/**
+ * A {@link ReactiveAuthorizationManager}, that determines if the current request contains
+ * the specified address or range of addresses
+ *
+ * @author Guirong Hu
+ * @since 5.7
+ */
+public final class IpAddressReactiveAuthorizationManager implements ReactiveAuthorizationManager {
+
+	private final IpAddressServerWebExchangeMatcher ipAddressExchangeMatcher;
+
+	IpAddressReactiveAuthorizationManager(String ipAddress) {
+		this.ipAddressExchangeMatcher = new IpAddressServerWebExchangeMatcher(ipAddress);
+	}
+
+	@Override
+	public Mono check(Mono authentication, AuthorizationContext context) {
+		return Mono.just(context.getExchange()).flatMap(this.ipAddressExchangeMatcher::matches)
+				.map((matchResult) -> new AuthorizationDecision(matchResult.isMatch()));
+	}
+
+	/**
+	 * Creates an instance of {@link IpAddressReactiveAuthorizationManager} with the
+	 * provided IP address.
+	 * @param ipAddress the address or range of addresses from which the request must
+	 * @return the new instance
+	 */
+	public static IpAddressReactiveAuthorizationManager hasIpAddress(String ipAddress) {
+		Assert.notNull(ipAddress, "This IP address is required; it must not be null");
+		return new IpAddressReactiveAuthorizationManager(ipAddress);
+	}
+
+}
diff --git a/web/src/main/java/org/springframework/security/web/server/csrf/WebSessionServerCsrfTokenRepository.java b/web/src/main/java/org/springframework/security/web/server/csrf/WebSessionServerCsrfTokenRepository.java
index e2a9a81adaf..266697639f9 100644
--- a/web/src/main/java/org/springframework/security/web/server/csrf/WebSessionServerCsrfTokenRepository.java
+++ b/web/src/main/java/org/springframework/security/web/server/csrf/WebSessionServerCsrfTokenRepository.java
@@ -19,8 +19,8 @@
 import java.util.Map;
 import java.util.UUID;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpSession;
 
 import reactor.core.publisher.Mono;
 import reactor.core.scheduler.Schedulers;
diff --git a/web/src/main/java/org/springframework/security/web/server/header/CrossOriginEmbedderPolicyServerHttpHeadersWriter.java b/web/src/main/java/org/springframework/security/web/server/header/CrossOriginEmbedderPolicyServerHttpHeadersWriter.java
new file mode 100644
index 00000000000..17446845dde
--- /dev/null
+++ b/web/src/main/java/org/springframework/security/web/server/header/CrossOriginEmbedderPolicyServerHttpHeadersWriter.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2002-2021 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.security.web.server.header;
+
+import reactor.core.publisher.Mono;
+
+import org.springframework.util.Assert;
+import org.springframework.web.server.ServerWebExchange;
+
+/**
+ * Inserts Cross-Origin-Embedder-Policy headers.
+ *
+ * @author Marcus Da Coregio
+ * @since 5.7
+ * @see 
+ * Cross-Origin-Embedder-Policy
+ */
+public final class CrossOriginEmbedderPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter {
+
+	public static final String EMBEDDER_POLICY = "Cross-Origin-Embedder-Policy";
+
+	private ServerHttpHeadersWriter delegate;
+
+	/**
+	 * Sets the {@link CrossOriginEmbedderPolicy} value to be used in the
+	 * {@code Cross-Origin-Embedder-Policy} header
+	 * @param embedderPolicy the {@link CrossOriginEmbedderPolicy} to use
+	 */
+	public void setPolicy(CrossOriginEmbedderPolicy embedderPolicy) {
+		Assert.notNull(embedderPolicy, "embedderPolicy cannot be null");
+		this.delegate = createDelegate(embedderPolicy);
+	}
+
+	@Override
+	public Mono writeHttpHeaders(ServerWebExchange exchange) {
+		return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty();
+	}
+
+	private static ServerHttpHeadersWriter createDelegate(CrossOriginEmbedderPolicy embedderPolicy) {
+		StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder();
+		builder.header(EMBEDDER_POLICY, embedderPolicy.getPolicy());
+		return builder.build();
+	}
+
+	public enum CrossOriginEmbedderPolicy {
+
+		UNSAFE_NONE("unsafe-none"),
+
+		REQUIRE_CORP("require-corp");
+
+		private final String policy;
+
+		CrossOriginEmbedderPolicy(String policy) {
+			this.policy = policy;
+		}
+
+		public String getPolicy() {
+			return this.policy;
+		}
+
+	}
+
+}
diff --git a/web/src/main/java/org/springframework/security/web/server/header/CrossOriginOpenerPolicyServerHttpHeadersWriter.java b/web/src/main/java/org/springframework/security/web/server/header/CrossOriginOpenerPolicyServerHttpHeadersWriter.java
new file mode 100644
index 00000000000..d02add2320e
--- /dev/null
+++ b/web/src/main/java/org/springframework/security/web/server/header/CrossOriginOpenerPolicyServerHttpHeadersWriter.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2002-2021 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.security.web.server.header;
+
+import reactor.core.publisher.Mono;
+
+import org.springframework.util.Assert;
+import org.springframework.web.server.ServerWebExchange;
+
+/**
+ * Inserts Cross-Origin-Opener-Policy header.
+ *
+ * @author Marcus Da Coregio
+ * @since 5.7
+ * @see 
+ * Cross-Origin-Opener-Policy
+ */
+public final class CrossOriginOpenerPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter {
+
+	public static final String OPENER_POLICY = "Cross-Origin-Opener-Policy";
+
+	private ServerHttpHeadersWriter delegate;
+
+	/**
+	 * Sets the {@link CrossOriginOpenerPolicy} value to be used in the
+	 * {@code Cross-Origin-Opener-Policy} header
+	 * @param openerPolicy the {@link CrossOriginOpenerPolicy} to use
+	 */
+	public void setPolicy(CrossOriginOpenerPolicy openerPolicy) {
+		Assert.notNull(openerPolicy, "openerPolicy cannot be null");
+		this.delegate = createDelegate(openerPolicy);
+	}
+
+	@Override
+	public Mono writeHttpHeaders(ServerWebExchange exchange) {
+		return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty();
+	}
+
+	private static ServerHttpHeadersWriter createDelegate(CrossOriginOpenerPolicy openerPolicy) {
+		StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder();
+		builder.header(OPENER_POLICY, openerPolicy.getPolicy());
+		return builder.build();
+	}
+
+	public enum CrossOriginOpenerPolicy {
+
+		UNSAFE_NONE("unsafe-none"),
+
+		SAME_ORIGIN_ALLOW_POPUPS("same-origin-allow-popups"),
+
+		SAME_ORIGIN("same-origin");
+
+		private final String policy;
+
+		CrossOriginOpenerPolicy(String policy) {
+			this.policy = policy;
+		}
+
+		public String getPolicy() {
+			return this.policy;
+		}
+
+	}
+
+}
diff --git a/web/src/main/java/org/springframework/security/web/server/header/CrossOriginResourcePolicyServerHttpHeadersWriter.java b/web/src/main/java/org/springframework/security/web/server/header/CrossOriginResourcePolicyServerHttpHeadersWriter.java
new file mode 100644
index 00000000000..dff25749441
--- /dev/null
+++ b/web/src/main/java/org/springframework/security/web/server/header/CrossOriginResourcePolicyServerHttpHeadersWriter.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2002-2021 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.security.web.server.header;
+
+import reactor.core.publisher.Mono;
+
+import org.springframework.util.Assert;
+import org.springframework.web.server.ServerWebExchange;
+
+/**
+ * Inserts Cross-Origin-Resource-Policy headers.
+ *
+ * @author Marcus Da Coregio
+ * @since 5.7
+ * @see 
+ * Cross-Origin-Resource-Policy
+ */
+public final class CrossOriginResourcePolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter {
+
+	public static final String RESOURCE_POLICY = "Cross-Origin-Resource-Policy";
+
+	private ServerHttpHeadersWriter delegate;
+
+	/**
+	 * Sets the {@link CrossOriginResourcePolicy} value to be used in the
+	 * {@code Cross-Origin-Embedder-Policy} header
+	 * @param resourcePolicy the {@link CrossOriginResourcePolicy} to use
+	 */
+	public void setPolicy(CrossOriginResourcePolicy resourcePolicy) {
+		Assert.notNull(resourcePolicy, "resourcePolicy cannot be null");
+		this.delegate = createDelegate(resourcePolicy);
+	}
+
+	@Override
+	public Mono writeHttpHeaders(ServerWebExchange exchange) {
+		return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty();
+	}
+
+	private static ServerHttpHeadersWriter createDelegate(CrossOriginResourcePolicy resourcePolicy) {
+		StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder();
+		builder.header(RESOURCE_POLICY, resourcePolicy.getPolicy());
+		return builder.build();
+	}
+
+	public enum CrossOriginResourcePolicy {
+
+		SAME_SITE("same-site"),
+
+		SAME_ORIGIN("same-origin"),
+
+		CROSS_ORIGIN("cross-origin");
+
+		private final String policy;
+
+		CrossOriginResourcePolicy(String policy) {
+			this.policy = policy;
+		}
+
+		public String getPolicy() {
+			return this.policy;
+		}
+
+	}
+
+}
diff --git a/web/src/main/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriter.java b/web/src/main/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriter.java
index 1f636f5cd33..fb3d3c4d774 100644
--- a/web/src/main/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriter.java
+++ b/web/src/main/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriter.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2018 the original author or authors.
+ * Copyright 2002-2021 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.
@@ -17,7 +17,6 @@
 package org.springframework.security.web.server.header;
 
 import java.util.Arrays;
-import java.util.Collections;
 
 import reactor.core.publisher.Mono;
 
@@ -41,8 +40,16 @@ public StaticServerHttpHeadersWriter(HttpHeaders headersToAdd) {
 	@Override
 	public Mono writeHttpHeaders(ServerWebExchange exchange) {
 		HttpHeaders headers = exchange.getResponse().getHeaders();
-		boolean containsOneHeaderToAdd = Collections.disjoint(headers.keySet(), this.headersToAdd.keySet());
-		if (containsOneHeaderToAdd) {
+		// Note: We need to ensure that the following algorithm compares headers
+		// case insensitively, which should be true of headers.containsKey().
+		boolean containsNoHeadersToAdd = true;
+		for (String headerName : this.headersToAdd.keySet()) {
+			if (headers.containsKey(headerName)) {
+				containsNoHeadersToAdd = false;
+				break;
+			}
+		}
+		if (containsNoHeadersToAdd) {
 			this.headersToAdd.forEach(headers::put);
 		}
 		return Mono.empty();
diff --git a/web/src/main/java/org/springframework/security/web/server/util/matcher/IpAddressServerWebExchangeMatcher.java b/web/src/main/java/org/springframework/security/web/server/util/matcher/IpAddressServerWebExchangeMatcher.java
new file mode 100644
index 00000000000..5bf439a5e02
--- /dev/null
+++ b/web/src/main/java/org/springframework/security/web/server/util/matcher/IpAddressServerWebExchangeMatcher.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2002-2021 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.security.web.server.util.matcher;
+
+import reactor.core.publisher.Mono;
+
+import org.springframework.security.web.util.matcher.IpAddressMatcher;
+import org.springframework.util.Assert;
+import org.springframework.web.server.ServerWebExchange;
+
+/**
+ * Matches a request based on IP Address or subnet mask matching against the remote
+ * address.
+ *
+ * @author Guirong Hu
+ * @since 5.7
+ */
+public final class IpAddressServerWebExchangeMatcher implements ServerWebExchangeMatcher {
+
+	private final IpAddressMatcher ipAddressMatcher;
+
+	/**
+	 * Takes a specific IP address or a range specified using the IP/Netmask (e.g.
+	 * 192.168.1.0/24 or 202.24.0.0/14).
+	 * @param ipAddress the address or range of addresses from which the request must
+	 * come.
+	 */
+	public IpAddressServerWebExchangeMatcher(String ipAddress) {
+		Assert.hasText(ipAddress, "IP address cannot be empty");
+		this.ipAddressMatcher = new IpAddressMatcher(ipAddress);
+	}
+
+	@Override
+	public Mono matches(ServerWebExchange exchange) {
+		// @formatter:off
+		return Mono.justOrEmpty(exchange.getRequest().getRemoteAddress())
+				.map((remoteAddress) -> remoteAddress.getAddress().getHostAddress())
+				.map(this.ipAddressMatcher::matches)
+				.flatMap((matches) -> matches ? MatchResult.match() : MatchResult.notMatch())
+				.switchIfEmpty(MatchResult.notMatch());
+		// @formatter:on
+	}
+
+	@Override
+	public String toString() {
+		return "IpAddressServerWebExchangeMatcher{ipAddressMatcher=" + this.ipAddressMatcher + '}';
+	}
+
+}
diff --git a/web/src/main/java/org/springframework/security/web/servlet/support/csrf/CsrfRequestDataValueProcessor.java b/web/src/main/java/org/springframework/security/web/servlet/support/csrf/CsrfRequestDataValueProcessor.java
index 1ea18dbe784..84b25b69292 100644
--- a/web/src/main/java/org/springframework/security/web/servlet/support/csrf/CsrfRequestDataValueProcessor.java
+++ b/web/src/main/java/org/springframework/security/web/servlet/support/csrf/CsrfRequestDataValueProcessor.java
@@ -21,7 +21,7 @@
 import java.util.Map;
 import java.util.regex.Pattern;
 
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
 
 import org.springframework.security.web.csrf.CsrfToken;
 import org.springframework.web.servlet.support.RequestDataValueProcessor;
diff --git a/web/src/main/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.java b/web/src/main/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.java
index 70c96faba56..542b3b639fa 100644
--- a/web/src/main/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.java
+++ b/web/src/main/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.java
@@ -18,7 +18,7 @@
 
 import java.util.Map;
 
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
 
 import org.springframework.http.HttpMethod;
 import org.springframework.security.web.util.matcher.RequestMatcher;
diff --git a/web/src/main/java/org/springframework/security/web/servletapi/HttpServlet3RequestFactory.java b/web/src/main/java/org/springframework/security/web/servletapi/HttpServlet3RequestFactory.java
index 51113ac551a..2acfb4f75bc 100644
--- a/web/src/main/java/org/springframework/security/web/servletapi/HttpServlet3RequestFactory.java
+++ b/web/src/main/java/org/springframework/security/web/servletapi/HttpServlet3RequestFactory.java
@@ -19,19 +19,20 @@
 import java.io.IOException;
 import java.util.List;
 
-import javax.servlet.AsyncContext;
-import javax.servlet.AsyncListener;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.AsyncContext;
+import jakarta.servlet.AsyncListener;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
 import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
+import org.springframework.security.authentication.AuthenticationDetailsSource;
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.authentication.AuthenticationTrustResolver;
 import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
@@ -42,6 +43,7 @@
 import org.springframework.security.core.context.SecurityContext;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.web.AuthenticationEntryPoint;
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
 import org.springframework.security.web.authentication.logout.LogoutHandler;
 import org.springframework.util.Assert;
 import org.springframework.util.CollectionUtils;
@@ -79,6 +81,8 @@ final class HttpServlet3RequestFactory implements HttpServletRequestFactory {
 
 	private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
 
+	private final AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource();
+
 	private AuthenticationEntryPoint authenticationEntryPoint;
 
 	private AuthenticationManager authenticationManager;
@@ -233,7 +237,11 @@ public void login(String username, String password) throws ServletException {
 		private Authentication getAuthentication(AuthenticationManager authManager, String username, String password)
 				throws ServletException {
 			try {
-				return authManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
+				UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username,
+						password);
+				Object details = HttpServlet3RequestFactory.this.authenticationDetailsSource.buildDetails(this);
+				authentication.setDetails(details);
+				return authManager.authenticate(authentication);
 			}
 			catch (AuthenticationException ex) {
 				SecurityContextHolder.clearContext();
diff --git a/web/src/main/java/org/springframework/security/web/servletapi/HttpServletRequestFactory.java b/web/src/main/java/org/springframework/security/web/servletapi/HttpServletRequestFactory.java
index e6d430d1ba7..bd7baad7fff 100644
--- a/web/src/main/java/org/springframework/security/web/servletapi/HttpServletRequestFactory.java
+++ b/web/src/main/java/org/springframework/security/web/servletapi/HttpServletRequestFactory.java
@@ -16,8 +16,8 @@
 
 package org.springframework.security.web.servletapi;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
 
 /**
  * Internal interface for creating a {@link HttpServletRequest}.
diff --git a/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilter.java b/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilter.java
index 2b6238e1392..eeb4f4de826 100644
--- a/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilter.java
+++ b/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilter.java
@@ -19,13 +19,13 @@
 import java.io.IOException;
 import java.util.List;
 
-import javax.servlet.AsyncContext;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.AsyncContext;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
 
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.authentication.AuthenticationTrustResolver;
diff --git a/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapper.java b/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapper.java
index 612c73893a6..e2057add22c 100644
--- a/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapper.java
+++ b/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapper.java
@@ -19,8 +19,8 @@
 import java.security.Principal;
 import java.util.Collection;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequestWrapper;
 
 import org.springframework.security.authentication.AbstractAuthenticationToken;
 import org.springframework.security.authentication.AuthenticationTrustResolver;
diff --git a/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java b/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java
index 57d5928ec09..473dc63ed89 100644
--- a/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java
+++ b/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java
@@ -19,13 +19,13 @@
 import java.io.IOException;
 import java.util.List;
 
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpSession;
 
 import org.springframework.core.log.LogMessage;
 import org.springframework.security.core.Authentication;
diff --git a/web/src/main/java/org/springframework/security/web/session/HttpSessionCreatedEvent.java b/web/src/main/java/org/springframework/security/web/session/HttpSessionCreatedEvent.java
index f9fe0d9721b..15dcfff296a 100644
--- a/web/src/main/java/org/springframework/security/web/session/HttpSessionCreatedEvent.java
+++ b/web/src/main/java/org/springframework/security/web/session/HttpSessionCreatedEvent.java
@@ -16,7 +16,7 @@
 
 package org.springframework.security.web.session;
 
-import javax.servlet.http.HttpSession;
+import jakarta.servlet.http.HttpSession;
 
 import org.springframework.security.core.session.SessionCreationEvent;
 
diff --git a/web/src/main/java/org/springframework/security/web/session/HttpSessionDestroyedEvent.java b/web/src/main/java/org/springframework/security/web/session/HttpSessionDestroyedEvent.java
index ec06003d64c..944dd3c202d 100644
--- a/web/src/main/java/org/springframework/security/web/session/HttpSessionDestroyedEvent.java
+++ b/web/src/main/java/org/springframework/security/web/session/HttpSessionDestroyedEvent.java
@@ -20,7 +20,7 @@
 import java.util.Enumeration;
 import java.util.List;
 
-import javax.servlet.http.HttpSession;
+import jakarta.servlet.http.HttpSession;
 
 import org.springframework.security.core.context.SecurityContext;
 import org.springframework.security.core.session.SessionDestroyedEvent;
diff --git a/web/src/main/java/org/springframework/security/web/session/HttpSessionEventPublisher.java b/web/src/main/java/org/springframework/security/web/session/HttpSessionEventPublisher.java
index 146922129a0..f136208feae 100644
--- a/web/src/main/java/org/springframework/security/web/session/HttpSessionEventPublisher.java
+++ b/web/src/main/java/org/springframework/security/web/session/HttpSessionEventPublisher.java
@@ -16,11 +16,11 @@
 
 package org.springframework.security.web.session;
 
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpSession;
-import javax.servlet.http.HttpSessionEvent;
-import javax.servlet.http.HttpSessionIdListener;
-import javax.servlet.http.HttpSessionListener;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.http.HttpSession;
+import jakarta.servlet.http.HttpSessionEvent;
+import jakarta.servlet.http.HttpSessionIdListener;
+import jakarta.servlet.http.HttpSessionListener;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -40,9 +40,9 @@
  * 
* * Publishes HttpSessionApplicationEvents to the Spring Root - * WebApplicationContext. Maps javax.servlet.http.HttpSessionListener.sessionCreated() to - * {@link HttpSessionCreatedEvent}. Maps - * javax.servlet.http.HttpSessionListener.sessionDestroyed() to + * WebApplicationContext. Maps jakarta.servlet.http.HttpSessionListener.sessionCreated() + * to {@link HttpSessionCreatedEvent}. Maps + * jakarta.servlet.http.HttpSessionListener.sessionDestroyed() to * {@link HttpSessionDestroyedEvent}. * * @author Ray Krueger diff --git a/web/src/main/java/org/springframework/security/web/session/HttpSessionIdChangedEvent.java b/web/src/main/java/org/springframework/security/web/session/HttpSessionIdChangedEvent.java index 1d075c8a980..1320c1bb50d 100644 --- a/web/src/main/java/org/springframework/security/web/session/HttpSessionIdChangedEvent.java +++ b/web/src/main/java/org/springframework/security/web/session/HttpSessionIdChangedEvent.java @@ -16,7 +16,7 @@ package org.springframework.security.web.session; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import org.springframework.security.core.session.SessionIdChangedEvent; diff --git a/web/src/main/java/org/springframework/security/web/session/InvalidSessionAccessDeniedHandler.java b/web/src/main/java/org/springframework/security/web/session/InvalidSessionAccessDeniedHandler.java index 64540da7b07..5efbd94a216 100644 --- a/web/src/main/java/org/springframework/security/web/session/InvalidSessionAccessDeniedHandler.java +++ b/web/src/main/java/org/springframework/security/web/session/InvalidSessionAccessDeniedHandler.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; diff --git a/web/src/main/java/org/springframework/security/web/session/InvalidSessionStrategy.java b/web/src/main/java/org/springframework/security/web/session/InvalidSessionStrategy.java index 5919279c7a0..75276468d75 100644 --- a/web/src/main/java/org/springframework/security/web/session/InvalidSessionStrategy.java +++ b/web/src/main/java/org/springframework/security/web/session/InvalidSessionStrategy.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; /** * Determines the behaviour of the {@code SessionManagementFilter} when an invalid session diff --git a/web/src/main/java/org/springframework/security/web/session/RequestedUrlRedirectInvalidSessionStrategy.java b/web/src/main/java/org/springframework/security/web/session/RequestedUrlRedirectInvalidSessionStrategy.java index 9d023701fff..c7a0a5296f6 100644 --- a/web/src/main/java/org/springframework/security/web/session/RequestedUrlRedirectInvalidSessionStrategy.java +++ b/web/src/main/java/org/springframework/security/web/session/RequestedUrlRedirectInvalidSessionStrategy.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredEvent.java b/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredEvent.java index c23c882d192..925f5a04400 100644 --- a/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredEvent.java +++ b/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredEvent.java @@ -16,8 +16,8 @@ package org.springframework.security.web.session; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationEvent; import org.springframework.security.core.session.SessionInformation; diff --git a/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredStrategy.java b/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredStrategy.java index 29a5b59d719..a6ec0395ac4 100644 --- a/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredStrategy.java +++ b/web/src/main/java/org/springframework/security/web/session/SessionInformationExpiredStrategy.java @@ -18,7 +18,7 @@ import java.io.IOException; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; /** * Determines the behaviour of the {@code ConcurrentSessionFilter} when an expired session diff --git a/web/src/main/java/org/springframework/security/web/session/SessionManagementFilter.java b/web/src/main/java/org/springframework/security/web/session/SessionManagementFilter.java index 658b9ddb766..3cae4cf4d19 100644 --- a/web/src/main/java/org/springframework/security/web/session/SessionManagementFilter.java +++ b/web/src/main/java/org/springframework/security/web/session/SessionManagementFilter.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.AuthenticationTrustResolver; diff --git a/web/src/main/java/org/springframework/security/web/session/SimpleRedirectInvalidSessionStrategy.java b/web/src/main/java/org/springframework/security/web/session/SimpleRedirectInvalidSessionStrategy.java index 35db022e9e8..d38595ba053 100644 --- a/web/src/main/java/org/springframework/security/web/session/SimpleRedirectInvalidSessionStrategy.java +++ b/web/src/main/java/org/springframework/security/web/session/SimpleRedirectInvalidSessionStrategy.java @@ -18,8 +18,8 @@ import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/util/OnCommittedResponseWrapper.java b/web/src/main/java/org/springframework/security/web/util/OnCommittedResponseWrapper.java index 6cd63e0e4cc..196b153242f 100644 --- a/web/src/main/java/org/springframework/security/web/util/OnCommittedResponseWrapper.java +++ b/web/src/main/java/org/springframework/security/web/util/OnCommittedResponseWrapper.java @@ -20,14 +20,14 @@ import java.io.PrintWriter; import java.util.Locale; -import javax.servlet.ServletOutputStream; -import javax.servlet.WriteListener; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.WriteListener; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponseWrapper; /** * Base class for response wrappers which encapsulate the logic for handling an event when - * the {@link javax.servlet.http.HttpServletResponse} is committed. + * the {@link jakarta.servlet.http.HttpServletResponse} is committed. * * @author Rob Winch * @since 4.0.2 @@ -84,8 +84,8 @@ private void setContentLength(long len) { /** * Invoke this method to disable invoking * {@link OnCommittedResponseWrapper#onResponseCommitted()} when the - * {@link javax.servlet.http.HttpServletResponse} is committed. This can be useful in - * the event that Async Web Requests are made. + * {@link jakarta.servlet.http.HttpServletResponse} is committed. This can be useful + * in the event that Async Web Requests are made. */ protected void disableOnResponseCommitted() { this.disableOnCommitted = true; @@ -101,8 +101,8 @@ protected boolean isDisableOnResponseCommitted() { } /** - * Implement the logic for handling the {@link javax.servlet.http.HttpServletResponse} - * being committed + * Implement the logic for handling the + * {@link jakarta.servlet.http.HttpServletResponse} being committed */ protected abstract void onResponseCommitted(); @@ -498,8 +498,9 @@ public PrintWriter append(char c) { /** * Ensures{@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before * calling methods that commit the response. We delegate all methods to the original - * {@link javax.servlet.ServletOutputStream} to ensure that the behavior is as close - * to the original {@link javax.servlet.ServletOutputStream} as possible. See SEC-2039 + * {@link jakarta.servlet.ServletOutputStream} to ensure that the behavior is as close + * to the original {@link jakarta.servlet.ServletOutputStream} as possible. See + * SEC-2039 * * @author Rob Winch */ diff --git a/web/src/main/java/org/springframework/security/web/util/UrlUtils.java b/web/src/main/java/org/springframework/security/web/util/UrlUtils.java index 98f4bbf5c8d..e1346a86b7e 100644 --- a/web/src/main/java/org/springframework/security/web/util/UrlUtils.java +++ b/web/src/main/java/org/springframework/security/web/util/UrlUtils.java @@ -18,7 +18,7 @@ import java.util.regex.Pattern; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * Provides static methods for composing URLs. diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/AndRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/AndRequestMatcher.java index 07682a183f5..eed80e507f5 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/AndRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/AndRequestMatcher.java @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/AntPathRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/AntPathRequestMatcher.java index 49aed044786..30563b0ac7d 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/AntPathRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/AntPathRequestMatcher.java @@ -19,7 +19,7 @@ import java.util.Collections; import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpMethod; import org.springframework.util.AntPathMatcher; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/AnyRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/AnyRequestMatcher.java index 52a818cc5d1..159ea45872b 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/AnyRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/AnyRequestMatcher.java @@ -16,7 +16,7 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * Matches any supplied request. diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcher.java index 617fc956fdf..9b0b5ba184a 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcher.java @@ -16,8 +16,8 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.DispatcherType; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.DispatcherType; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpMethod; import org.springframework.lang.Nullable; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcher.java index f3ce9d70a60..53091a136b9 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcher.java @@ -16,7 +16,7 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcherContext.java b/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcherContext.java index d6988b32846..bd0f2a01ae1 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcherContext.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/ELRequestMatcherContext.java @@ -16,7 +16,7 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.util.StringUtils; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java index 2666905c6a2..a0e9409e631 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java @@ -19,7 +19,7 @@ import java.net.InetAddress; import java.net.UnknownHostException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.util.Assert; import org.springframework.util.StringUtils; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcher.java index 6aa80140a64..1ff6be2452d 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcher.java @@ -22,7 +22,7 @@ import java.util.List; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/NegatedRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/NegatedRequestMatcher.java index 3f5e92c6b88..a7eb791443a 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/NegatedRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/NegatedRequestMatcher.java @@ -16,7 +16,7 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/OrRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/OrRequestMatcher.java index 92a2e2eb784..6234a1af7ea 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/OrRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/OrRequestMatcher.java @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/RegexRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/RegexRequestMatcher.java index 9264b56f213..e93b99f9340 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/RegexRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/RegexRequestMatcher.java @@ -18,7 +18,7 @@ import java.util.regex.Pattern; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/RequestHeaderRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/RequestHeaderRequestMatcher.java index 8b476f37bc0..9f1bbfcc018 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/RequestHeaderRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/RequestHeaderRequestMatcher.java @@ -16,7 +16,7 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.util.Assert; diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcher.java index 0d3fccf6f9b..e6b223d977d 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcher.java @@ -19,7 +19,7 @@ import java.util.Collections; import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * Simple strategy to match an HttpServletRequest. diff --git a/remoting/src/main/java/org/springframework/security/remoting/dns/DnsEntryNotFoundException.java b/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcherEntry.java similarity index 50% rename from remoting/src/main/java/org/springframework/security/remoting/dns/DnsEntryNotFoundException.java rename to web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcherEntry.java index 4606bbe6171..ea83cc7ac12 100644 --- a/remoting/src/main/java/org/springframework/security/remoting/dns/DnsEntryNotFoundException.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/RequestMatcherEntry.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2016 the original author or authors. + * Copyright 2002-2021 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. @@ -14,26 +14,31 @@ * limitations under the License. */ -package org.springframework.security.remoting.dns; +package org.springframework.security.web.util.matcher; /** - * This will be thrown if no entry matches the specified DNS query. + * A rich object for associating a {@link RequestMatcher} to another object. * - * @author Mike Wiesner - * @since 3.0 - * @deprecated as of 5.6.0 with no replacement + * @author Marcus Da Coregio + * @since 5.7 */ -@Deprecated -public class DnsEntryNotFoundException extends DnsLookupException { +public class RequestMatcherEntry { - private static final long serialVersionUID = -947232730426775162L; + private final RequestMatcher requestMatcher; - public DnsEntryNotFoundException(String msg) { - super(msg); + private final T entry; + + public RequestMatcherEntry(RequestMatcher requestMatcher, T entry) { + this.requestMatcher = requestMatcher; + this.entry = entry; + } + + public RequestMatcher getRequestMatcher() { + return this.requestMatcher; } - public DnsEntryNotFoundException(String msg, Throwable cause) { - super(msg, cause); + public T getEntry() { + return this.entry; } } diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/RequestVariablesExtractor.java b/web/src/main/java/org/springframework/security/web/util/matcher/RequestVariablesExtractor.java index 5c9fcb9675b..309c6ddd082 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/RequestVariablesExtractor.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/RequestVariablesExtractor.java @@ -18,7 +18,7 @@ import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * An interface for extracting URI variables from the {@link HttpServletRequest}. diff --git a/web/src/test/java/org/springframework/security/MockFilterConfig.java b/web/src/test/java/org/springframework/security/MockFilterConfig.java index 5a2e9b0a325..8f80bf20f3f 100644 --- a/web/src/test/java/org/springframework/security/MockFilterConfig.java +++ b/web/src/test/java/org/springframework/security/MockFilterConfig.java @@ -20,8 +20,8 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletContext; /** * @author Ben Alex diff --git a/web/src/test/java/org/springframework/security/MockPortResolver.java b/web/src/test/java/org/springframework/security/MockPortResolver.java index 65e774af018..10ea448b463 100644 --- a/web/src/test/java/org/springframework/security/MockPortResolver.java +++ b/web/src/test/java/org/springframework/security/MockPortResolver.java @@ -16,7 +16,7 @@ package org.springframework.security; -import javax.servlet.ServletRequest; +import jakarta.servlet.ServletRequest; import org.springframework.security.web.PortResolver; diff --git a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java index 59db2f705fb..398f639b8ac 100644 --- a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java +++ b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java @@ -20,12 +20,12 @@ import java.util.Collections; import java.util.List; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/FilterInvocationTests.java b/web/src/test/java/org/springframework/security/web/FilterInvocationTests.java index 2d1941f3c8c..0066e0c10c3 100644 --- a/web/src/test/java/org/springframework/security/web/FilterInvocationTests.java +++ b/web/src/test/java/org/springframework/security/web/FilterInvocationTests.java @@ -16,9 +16,9 @@ package org.springframework.security.web; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/RequestMatcherRedirectFilterTests.java b/web/src/test/java/org/springframework/security/web/RequestMatcherRedirectFilterTests.java index 5603f00a2f1..2ed3a72cdb0 100644 --- a/web/src/test/java/org/springframework/security/web/RequestMatcherRedirectFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/RequestMatcherRedirectFilterTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/AuthorizationManagerWebInvocationPrivilegeEvaluatorTests.java b/web/src/test/java/org/springframework/security/web/access/AuthorizationManagerWebInvocationPrivilegeEvaluatorTests.java new file mode 100644 index 00000000000..9e24dd490fe --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/access/AuthorizationManagerWebInvocationPrivilegeEvaluatorTests.java @@ -0,0 +1,68 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.access; + +import jakarta.servlet.http.HttpServletRequest; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.security.authentication.TestAuthentication; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.AuthorizationManager; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class AuthorizationManagerWebInvocationPrivilegeEvaluatorTests { + + @InjectMocks + private AuthorizationManagerWebInvocationPrivilegeEvaluator privilegeEvaluator; + + @Mock + private AuthorizationManager authorizationManager; + + @Test + void constructorWhenAuthorizationManagerNullThenIllegalArgument() { + assertThatIllegalArgumentException() + .isThrownBy(() -> new AuthorizationManagerWebInvocationPrivilegeEvaluator(null)) + .withMessage("authorizationManager cannot be null"); + } + + @Test + void isAllowedWhenAuthorizationManagerAllowsThenAllowedTrue() { + given(this.authorizationManager.check(any(), any())).willReturn(new AuthorizationDecision(true)); + boolean allowed = this.privilegeEvaluator.isAllowed("/test", TestAuthentication.authenticatedUser()); + assertThat(allowed).isTrue(); + verify(this.authorizationManager).check(any(), any()); + } + + @Test + void isAllowedWhenAuthorizationManagerDeniesAllowedFalse() { + given(this.authorizationManager.check(any(), any())).willReturn(new AuthorizationDecision(false)); + boolean allowed = this.privilegeEvaluator.isAllowed("/test", TestAuthentication.authenticatedUser()); + assertThat(allowed).isFalse(); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/access/DelegatingAccessDeniedHandlerTests.java b/web/src/test/java/org/springframework/security/web/access/DelegatingAccessDeniedHandlerTests.java index 9e93d66ded8..646718c650e 100644 --- a/web/src/test/java/org/springframework/security/web/access/DelegatingAccessDeniedHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/access/DelegatingAccessDeniedHandlerTests.java @@ -18,8 +18,8 @@ import java.util.LinkedHashMap; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java index 9fd08885400..c3c81de1867 100644 --- a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java @@ -19,11 +19,11 @@ import java.io.IOException; import java.util.Locale; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandlerTests.java b/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandlerTests.java index bf24389b19c..078f41fa5df 100644 --- a/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandlerTests.java @@ -18,7 +18,7 @@ import java.util.LinkedHashMap; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingWebInvocationPrivilegeEvaluatorTests.java b/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingWebInvocationPrivilegeEvaluatorTests.java new file mode 100644 index 00000000000..95feee1b568 --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingWebInvocationPrivilegeEvaluatorTests.java @@ -0,0 +1,179 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.access; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.util.matcher.RequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcherEntry; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Tests for {@link RequestMatcherDelegatingWebInvocationPrivilegeEvaluator} + * + * @author Marcus Da Coregio + */ +class RequestMatcherDelegatingWebInvocationPrivilegeEvaluatorTests { + + private final RequestMatcher alwaysMatch = mock(RequestMatcher.class); + + private final RequestMatcher alwaysDeny = mock(RequestMatcher.class); + + private final String uri = "/test"; + + private final Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER"); + + @BeforeEach + void setup() { + given(this.alwaysMatch.matches(any())).willReturn(true); + given(this.alwaysDeny.matches(any())).willReturn(false); + } + + @Test + void isAllowedWhenDelegatesEmptyThenAllowed() { + RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( + Collections.emptyList()); + assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); + } + + @Test + void isAllowedWhenNotMatchThenAllowed() { + RequestMatcherEntry> notMatch = new RequestMatcherEntry<>(this.alwaysDeny, + Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysAllow())); + RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( + Collections.singletonList(notMatch)); + assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); + verify(notMatch.getRequestMatcher()).matches(any()); + } + + @Test + void isAllowedWhenPrivilegeEvaluatorAllowThenAllowedTrue() { + RequestMatcherEntry> delegate = new RequestMatcherEntry<>( + this.alwaysMatch, Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysAllow())); + RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( + Collections.singletonList(delegate)); + assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); + } + + @Test + void isAllowedWhenPrivilegeEvaluatorDenyThenAllowedFalse() { + RequestMatcherEntry> delegate = new RequestMatcherEntry<>( + this.alwaysMatch, Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysDeny())); + RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( + Collections.singletonList(delegate)); + assertThat(delegating.isAllowed(this.uri, this.authentication)).isFalse(); + } + + @Test + void isAllowedWhenNotMatchThenMatchThenOnlySecondDelegateInvoked() { + RequestMatcherEntry> notMatchDelegate = new RequestMatcherEntry<>( + this.alwaysDeny, Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysAllow())); + RequestMatcherEntry> matchDelegate = new RequestMatcherEntry<>( + this.alwaysMatch, Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysAllow())); + RequestMatcherEntry> spyNotMatchDelegate = spy(notMatchDelegate); + RequestMatcherEntry> spyMatchDelegate = spy(matchDelegate); + + RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( + Arrays.asList(notMatchDelegate, spyMatchDelegate)); + assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); + verify(spyNotMatchDelegate.getRequestMatcher()).matches(any()); + verify(spyNotMatchDelegate, never()).getEntry(); + verify(spyMatchDelegate.getRequestMatcher()).matches(any()); + verify(spyMatchDelegate, times(2)).getEntry(); // 2 times, one for constructor and + // other one in isAllowed + } + + @Test + void isAllowedWhenDelegatePrivilegeEvaluatorsEmptyThenAllowedTrue() { + RequestMatcherEntry> delegate = new RequestMatcherEntry<>( + this.alwaysMatch, Collections.emptyList()); + RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( + Collections.singletonList(delegate)); + assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); + } + + @Test + void isAllowedWhenFirstDelegateDenyThenDoNotInvokeOthers() { + WebInvocationPrivilegeEvaluator deny = TestWebInvocationPrivilegeEvaluator.alwaysDeny(); + WebInvocationPrivilegeEvaluator allow = TestWebInvocationPrivilegeEvaluator.alwaysAllow(); + WebInvocationPrivilegeEvaluator spyDeny = spy(deny); + WebInvocationPrivilegeEvaluator spyAllow = spy(allow); + RequestMatcherEntry> delegate = new RequestMatcherEntry<>( + this.alwaysMatch, Arrays.asList(spyDeny, spyAllow)); + + RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( + Collections.singletonList(delegate)); + + assertThat(delegating.isAllowed(this.uri, this.authentication)).isFalse(); + verify(spyDeny).isAllowed(any(), any()); + verifyNoInteractions(spyAllow); + } + + @Test + void isAllowedWhenDifferentArgumentsThenCallSpecificIsAllowedInDelegate() { + WebInvocationPrivilegeEvaluator deny = TestWebInvocationPrivilegeEvaluator.alwaysDeny(); + WebInvocationPrivilegeEvaluator spyDeny = spy(deny); + RequestMatcherEntry> delegate = new RequestMatcherEntry<>( + this.alwaysMatch, Collections.singletonList(spyDeny)); + + RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( + Collections.singletonList(delegate)); + + assertThat(delegating.isAllowed(this.uri, this.authentication)).isFalse(); + assertThat(delegating.isAllowed("/cp", this.uri, "GET", this.authentication)).isFalse(); + verify(spyDeny).isAllowed(any(), any()); + verify(spyDeny).isAllowed(any(), any(), any(), any()); + verifyNoMoreInteractions(spyDeny); + } + + @Test + void constructorWhenPrivilegeEvaluatorsNullThenException() { + RequestMatcherEntry> entry = new RequestMatcherEntry<>(this.alwaysMatch, + null); + assertThatIllegalArgumentException().isThrownBy( + () -> new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(Collections.singletonList(entry))) + .withMessageContaining("webInvocationPrivilegeEvaluators cannot be null"); + } + + @Test + void constructorWhenRequestMatcherNullThenException() { + RequestMatcherEntry> entry = new RequestMatcherEntry<>(null, + Collections.singletonList(mock(WebInvocationPrivilegeEvaluator.class))); + assertThatIllegalArgumentException().isThrownBy( + () -> new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(Collections.singletonList(entry))) + .withMessageContaining("requestMatcher cannot be null"); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/access/TestWebInvocationPrivilegeEvaluator.java b/web/src/test/java/org/springframework/security/web/access/TestWebInvocationPrivilegeEvaluator.java new file mode 100644 index 00000000000..54ab666cd52 --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/access/TestWebInvocationPrivilegeEvaluator.java @@ -0,0 +1,66 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.access; + +import org.springframework.security.core.Authentication; + +public final class TestWebInvocationPrivilegeEvaluator { + + private static final AlwaysAllowWebInvocationPrivilegeEvaluator ALWAYS_ALLOW = new AlwaysAllowWebInvocationPrivilegeEvaluator(); + + private static final AlwaysDenyWebInvocationPrivilegeEvaluator ALWAYS_DENY = new AlwaysDenyWebInvocationPrivilegeEvaluator(); + + private TestWebInvocationPrivilegeEvaluator() { + } + + public static WebInvocationPrivilegeEvaluator alwaysAllow() { + return ALWAYS_ALLOW; + } + + public static WebInvocationPrivilegeEvaluator alwaysDeny() { + return ALWAYS_DENY; + } + + private static class AlwaysAllowWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator { + + @Override + public boolean isAllowed(String uri, Authentication authentication) { + return true; + } + + @Override + public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) { + return true; + } + + } + + private static class AlwaysDenyWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator { + + @Override + public boolean isAllowed(String uri, Authentication authentication) { + return false; + } + + @Override + public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) { + return false; + } + + } + +} diff --git a/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java b/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java index 20fd436a966..785e71f118b 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java @@ -22,7 +22,7 @@ import java.util.List; import java.util.Vector; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/channel/ChannelProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/access/channel/ChannelProcessingFilterTests.java index d2f10d6333e..5a24d45928f 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/ChannelProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/ChannelProcessingFilterTests.java @@ -19,7 +19,7 @@ import java.io.IOException; import java.util.Collection; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java b/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java index fabc67814e9..bd213da46ef 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.access.channel; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java b/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java index 46f0cb7fdc7..01191c53db2 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.access.channel; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessorTests.java b/web/src/test/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessorTests.java index fad49c48d58..373e742e4ad 100644 --- a/web/src/test/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessorTests.java @@ -19,7 +19,7 @@ import java.util.Collections; import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java b/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java index 80c5a82291c..e471d634ed1 100644 --- a/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java @@ -18,9 +18,9 @@ import java.util.ArrayList; -import javax.servlet.FilterChain; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.aopalliance.intercept.MethodInvocation; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/expression/WebSecurityExpressionRootTests.java b/web/src/test/java/org/springframework/security/web/access/expression/WebSecurityExpressionRootTests.java index 85574abc080..17bc7388670 100644 --- a/web/src/test/java/org/springframework/security/web/access/expression/WebSecurityExpressionRootTests.java +++ b/web/src/test/java/org/springframework/security/web/access/expression/WebSecurityExpressionRootTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.access.expression; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/access/intercept/AuthorizationFilterTests.java b/web/src/test/java/org/springframework/security/web/access/intercept/AuthorizationFilterTests.java index b2b22c5666d..46680fac478 100644 --- a/web/src/test/java/org/springframework/security/web/access/intercept/AuthorizationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/intercept/AuthorizationFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ import java.util.function.Supplier; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -125,4 +125,11 @@ public void filterWhenAuthenticationNullThenAuthenticationCredentialsNotFoundExc verifyNoInteractions(mockFilterChain); } + @Test + public void getAuthorizationManager() { + AuthorizationManager authorizationManager = mock(AuthorizationManager.class); + AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager); + assertThat(authorizationFilter.getAuthorizationManager()).isSameAs(authorizationManager); + } + } diff --git a/web/src/test/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSourceTests.java b/web/src/test/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSourceTests.java index 01c368e286b..2a90dcb2108 100644 --- a/web/src/test/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSourceTests.java +++ b/web/src/test/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSourceTests.java @@ -19,7 +19,7 @@ import java.util.Collection; import java.util.LinkedHashMap; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; @@ -32,7 +32,6 @@ import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -88,11 +87,6 @@ public void lookupRequiringExactMatchWithAdditionalSlashesIsSuccessful() { // sign).isEqualTo(def) } - @Test - public void unknownHttpMethodIsRejected() { - assertThatIllegalArgumentException().isThrownBy(() -> createFids("/someAdminPage.html**", "UNKNOWN")); - } - @Test public void httpMethodLookupSucceeds() { createFids("/somepage**", "GET"); diff --git a/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java b/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java index ee6ce48ddc3..ded5a395d20 100644 --- a/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java @@ -16,9 +16,9 @@ package org.springframework.security.web.access.intercept; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManagerTests.java b/web/src/test/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManagerTests.java index 829866340a1..952132522b1 100644 --- a/web/src/test/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManagerTests.java +++ b/web/src/test/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManagerTests.java @@ -22,9 +22,11 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.authorization.AuthorityAuthorizationManager; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.core.Authentication; import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; +import org.springframework.security.web.util.matcher.AnyRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -83,4 +85,40 @@ public void checkWhenMultipleMappingsConfiguredThenDelegatesMatchingManager() { assertThat(abstain).isNull(); } + @Test + public void checkWhenMultipleMappingsConfiguredWithConsumerThenDelegatesMatchingManager() { + RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder() + .mappings((m) -> { + m.put(new MvcRequestMatcher(null, "/grant"), (a, o) -> new AuthorizationDecision(true)); + m.put(AnyRequestMatcher.INSTANCE, AuthorityAuthorizationManager.hasRole("ADMIN")); + m.put(new MvcRequestMatcher(null, "/deny"), (a, o) -> new AuthorizationDecision(false)); + m.put(new MvcRequestMatcher(null, "/afterAny"), (a, o) -> new AuthorizationDecision(true)); + }).build(); + + Supplier authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_USER"); + + AuthorizationDecision grant = manager.check(authentication, new MockHttpServletRequest(null, "/grant")); + assertThat(grant).isNotNull(); + assertThat(grant.isGranted()).isTrue(); + + AuthorizationDecision deny = manager.check(authentication, new MockHttpServletRequest(null, "/deny")); + assertThat(deny).isNotNull(); + assertThat(deny.isGranted()).isFalse(); + + AuthorizationDecision afterAny = manager.check(authentication, new MockHttpServletRequest(null, "/afterAny")); + assertThat(afterAny).isNotNull(); + assertThat(afterAny.isGranted()).isFalse(); + + AuthorizationDecision unmapped = manager.check(authentication, new MockHttpServletRequest(null, "/unmapped")); + assertThat(unmapped).isNotNull(); + assertThat(unmapped.isGranted()).isFalse(); + } + + @Test + public void addWhenMappingsConsumerNullThenException() { + assertThatIllegalArgumentException() + .isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder().mappings(null).build()) + .withMessage("mappingsConsumer cannot be null"); + } + } diff --git a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java index c41c12eab80..b9948c435f3 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java @@ -16,12 +16,12 @@ package org.springframework.security.web.authentication; -import javax.servlet.FilterChain; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.junit.jupiter.api.AfterEach; diff --git a/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java index e8cef30504b..a50cc4639ae 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java @@ -18,12 +18,12 @@ import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java index a8a97eebb10..cd737d9b7a5 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java @@ -16,11 +16,11 @@ package org.springframework.security.web.authentication; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java index 97fbfda4066..d5b4ed29e0e 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java @@ -19,9 +19,9 @@ import java.util.Collections; import java.util.Locale; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointContextTests.java b/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointContextTests.java index 9e7d85270b7..b9ac59940c1 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointContextTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointContextTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.authentication; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTests.java index 761fe90bd42..678e4d31eac 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTests.java @@ -18,7 +18,7 @@ import java.util.LinkedHashMap; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandlerTests.java index 857be3a115a..7d5080b2801 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandlerTests.java @@ -18,8 +18,8 @@ import java.util.LinkedHashMap; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java index 6bc04f2eaf0..83f7d51e94b 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java @@ -19,8 +19,8 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.mockito.InOrder; diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandlerTests.java index c5b6c6e8305..a6a9c864074 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandlerTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.authentication.logout; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandlerTests.java index 36c5879dc0d..ea34fd01dfb 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandlerTests.java @@ -18,7 +18,7 @@ import java.util.LinkedHashMap; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java index d32323c4e72..1c81209c75a 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java @@ -16,9 +16,9 @@ package org.springframework.security.web.authentication.preauth; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java index 096c5315b35..e7d54ba4a84 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java @@ -18,7 +18,7 @@ import java.io.IOException; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java index 0be25f5c264..c6a2ef7d177 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java @@ -21,7 +21,7 @@ import java.util.List; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java index 3e7275f1b7f..186346ca234 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java @@ -22,7 +22,7 @@ import java.util.List; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java index 91edaf4d140..1aa89b1065d 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java @@ -20,7 +20,7 @@ import java.util.HashSet; import java.util.Set; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java index d5a9e1a8d20..1a73bc66134 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.authentication.preauth.websphere; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java index a8912f326a3..7de3bef577a 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java @@ -16,9 +16,9 @@ package org.springframework.security.web.authentication.rememberme; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java index b79ef32f09a..7d8a8219584 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java @@ -19,7 +19,7 @@ import java.util.Date; import java.util.concurrent.TimeUnit; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java index de778a94fd4..8d036b7388d 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java @@ -16,9 +16,9 @@ package org.springframework.security.web.authentication.rememberme; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java index bc1aa888c10..871503f9732 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java @@ -18,7 +18,7 @@ import java.util.Date; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; diff --git a/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java b/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java index 2aaab5a6395..c36df8beb6a 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java @@ -19,8 +19,8 @@ import java.util.Arrays; import java.util.Collections; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java index 1c9f5eaef45..d483c4fddc6 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java @@ -19,7 +19,7 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.FilterChain; +import jakarta.servlet.FilterChain; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverterTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverterTests.java index 744f32993a2..784f1fb969c 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverterTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.authentication.www; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Base64; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java index 13b265b8e00..420f6086365 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java @@ -18,10 +18,10 @@ import java.nio.charset.StandardCharsets; -import javax.servlet.FilterChain; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.junit.jupiter.api.AfterEach; diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java index 6168db71433..f0f6e9a08f8 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java @@ -19,10 +19,10 @@ import java.io.IOException; import java.util.Map; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; diff --git a/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java b/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java index a29ef1cab76..a92bffac0b4 100644 --- a/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java @@ -19,8 +19,8 @@ import java.util.Date; import java.util.List; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java b/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java index 8475a2433de..5dfb003b40b 100644 --- a/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java +++ b/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java @@ -22,11 +22,11 @@ import java.util.HashSet; import java.util.Set; -import javax.servlet.DispatcherType; -import javax.servlet.Filter; -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; -import javax.servlet.SessionTrackingMode; +import jakarta.servlet.DispatcherType; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterRegistration; +import jakarta.servlet.ServletContext; +import jakarta.servlet.SessionTrackingMode; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; diff --git a/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java b/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java index cfbe0f332f4..add6c00e8c7 100644 --- a/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java +++ b/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java @@ -21,16 +21,17 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -import javax.servlet.Filter; -import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.servlet.http.HttpSession; +import java.util.Collections; + +import jakarta.servlet.Filter; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponseWrapper; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -614,6 +615,21 @@ public void saveContextWhenTransientAuthenticationSubclassThenSkipped() { assertThat(session).isNull(); } + @Test + public void saveContextWhenTransientAuthenticationAndSessionExistsThenSkipped() { + HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.getSession(); // ensure the session exists + MockHttpServletResponse response = new MockHttpServletResponse(); + HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); + SecurityContext context = repo.loadContext(holder); + SomeTransientAuthentication authentication = new SomeTransientAuthentication(); + context.setAuthentication(authentication); + repo.saveContext(context, holder.getRequest(), holder.getResponse()); + MockHttpSession session = (MockHttpSession) request.getSession(false); + assertThat(Collections.list(session.getAttributeNames())).isEmpty(); + } + @Test public void saveContextWhenTransientAuthenticationWithCustomAnnotationThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); diff --git a/web/src/test/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapperTests.java b/web/src/test/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapperTests.java index 4c1b5f37982..9b5b2d5b5fa 100644 --- a/web/src/test/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapperTests.java +++ b/web/src/test/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapperTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.context; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java index 8ef48d12b2b..a3a87c1f034 100644 --- a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java @@ -18,9 +18,9 @@ import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java b/web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java index d2aab149693..8cdf41f5f46 100644 --- a/web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java @@ -19,8 +19,8 @@ import java.util.concurrent.Callable; import java.util.concurrent.ThreadFactory; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -35,7 +35,7 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.async.AsyncWebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; @@ -90,7 +90,7 @@ public void clearSecurityContext() { @Test public void doFilterInternalRegistersSecurityContextCallableProcessor() throws Exception { SecurityContextHolder.setContext(this.securityContext); - this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() { + this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptor() { @Override public void postProcess(NativeWebRequest request, Callable task, Object concurrentResult) { assertThat(SecurityContextHolder.getContext()) @@ -107,7 +107,7 @@ public void postProcess(NativeWebRequest request, Callable task, Object c @Test public void doFilterInternalRegistersSecurityContextCallableProcessorContextUpdated() throws Exception { SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); - this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() { + this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptor() { @Override public void postProcess(NativeWebRequest request, Callable task, Object concurrentResult) { assertThat(SecurityContextHolder.getContext()) diff --git a/web/src/test/java/org/springframework/security/web/csrf/CookieCsrfTokenRepositoryTests.java b/web/src/test/java/org/springframework/security/web/csrf/CookieCsrfTokenRepositoryTests.java index 3b08d4318f9..90b33b4b165 100644 --- a/web/src/test/java/org/springframework/security/web/csrf/CookieCsrfTokenRepositoryTests.java +++ b/web/src/test/java/org/springframework/security/web/csrf/CookieCsrfTokenRepositoryTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.csrf; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategyTests.java b/web/src/test/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategyTests.java index a949e3a3958..e2f70abbd1b 100644 --- a/web/src/test/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategyTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.csrf; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/csrf/CsrfFilterTests.java b/web/src/test/java/org/springframework/security/web/csrf/CsrfFilterTests.java index b4244f228d7..91136b14a54 100644 --- a/web/src/test/java/org/springframework/security/web/csrf/CsrfFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/csrf/CsrfFilterTests.java @@ -19,10 +19,10 @@ import java.io.IOException; import java.util.Arrays; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.assertj.core.api.AbstractObjectAssert; import org.assertj.core.api.ObjectAssert; diff --git a/web/src/test/java/org/springframework/security/web/csrf/LazyCsrfTokenRepositoryTests.java b/web/src/test/java/org/springframework/security/web/csrf/LazyCsrfTokenRepositoryTests.java index 5ad35258d4c..40a19297a5f 100644 --- a/web/src/test/java/org/springframework/security/web/csrf/LazyCsrfTokenRepositoryTests.java +++ b/web/src/test/java/org/springframework/security/web/csrf/LazyCsrfTokenRepositoryTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.csrf; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/debug/DebugFilterTests.java b/web/src/test/java/org/springframework/security/web/debug/DebugFilterTests.java index 309b2454e1b..48fd8f95b2e 100644 --- a/web/src/test/java/org/springframework/security/web/debug/DebugFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/debug/DebugFilterTests.java @@ -18,10 +18,10 @@ import java.util.Collections; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandlerTests.java b/web/src/test/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandlerTests.java index 1e668eb8b5a..d9eec85c938 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandlerTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.firewall; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java b/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java index dedf238ad72..2f2f2622d9e 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.firewall; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandlerTests.java b/web/src/test/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandlerTests.java index 49b28796ef5..0590e8162d6 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandlerTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.firewall; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/firewall/RequestWrapperTests.java b/web/src/test/java/org/springframework/security/web/firewall/RequestWrapperTests.java index 4d1bd3f46f8..1e3d538c566 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/RequestWrapperTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/RequestWrapperTests.java @@ -19,9 +19,9 @@ import java.util.LinkedHashMap; import java.util.Map; -import javax.servlet.RequestDispatcher; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java b/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java index ce461e34015..92bbc2ea414 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/header/HeaderWriterFilterTests.java b/web/src/test/java/org/springframework/security/web/header/HeaderWriterFilterTests.java index 712e03e01c1..7841bce5603 100644 --- a/web/src/test/java/org/springframework/security/web/header/HeaderWriterFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/header/HeaderWriterFilterTests.java @@ -21,8 +21,8 @@ import java.util.Collections; import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/web/src/test/java/org/springframework/security/web/header/writers/CompositeHeaderWriterTests.java b/web/src/test/java/org/springframework/security/web/header/writers/CompositeHeaderWriterTests.java index f1ef36b15a5..1060198e2a9 100644 --- a/web/src/test/java/org/springframework/security/web/header/writers/CompositeHeaderWriterTests.java +++ b/web/src/test/java/org/springframework/security/web/header/writers/CompositeHeaderWriterTests.java @@ -19,8 +19,8 @@ import java.util.Arrays; import java.util.Collections; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginEmbedderPolicyHeaderWriterTests.java b/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginEmbedderPolicyHeaderWriterTests.java new file mode 100644 index 00000000000..0b90c57dea3 --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginEmbedderPolicyHeaderWriterTests.java @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.header.writers; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +class CrossOriginEmbedderPolicyHeaderWriterTests { + + private static final String EMBEDDER_HEADER_NAME = "Cross-Origin-Embedder-Policy"; + + private CrossOriginEmbedderPolicyHeaderWriter writer; + + private MockHttpServletRequest request; + + private MockHttpServletResponse response; + + @BeforeEach + void setup() { + this.writer = new CrossOriginEmbedderPolicyHeaderWriter(); + this.request = new MockHttpServletRequest(); + this.response = new MockHttpServletResponse(); + } + + @Test + void setEmbedderPolicyWhenNullEmbedderPolicyThenThrowsIllegalArgument() { + assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) + .withMessage("embedderPolicy cannot be null"); + } + + @Test + void writeHeadersWhenDefaultValuesThenDontWriteHeaders() { + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeaderNames()).hasSize(0); + } + + @Test + void writeHeadersWhenResponseHeaderExistsThenDontOverride() { + this.response.addHeader(EMBEDDER_HEADER_NAME, "require-corp"); + this.writer.setPolicy(CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.UNSAFE_NONE); + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeader(EMBEDDER_HEADER_NAME)).isEqualTo("require-corp"); + } + + @Test + void writeHeadersWhenSetHeaderValuesThenWrites() { + this.writer.setPolicy(CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP); + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeader(EMBEDDER_HEADER_NAME)).isEqualTo("require-corp"); + } + + @Test + void writeHeadersWhenSetEmbedderPolicyThenWritesEmbedderPolicy() { + this.writer.setPolicy(CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.UNSAFE_NONE); + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeaderNames()).hasSize(1); + assertThat(this.response.getHeader(EMBEDDER_HEADER_NAME)).isEqualTo("unsafe-none"); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginOpenerPolicyHeaderWriterTests.java b/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginOpenerPolicyHeaderWriterTests.java new file mode 100644 index 00000000000..863351bb8b1 --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginOpenerPolicyHeaderWriterTests.java @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.header.writers; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +class CrossOriginOpenerPolicyHeaderWriterTests { + + private static final String OPENER_HEADER_NAME = "Cross-Origin-Opener-Policy"; + + private CrossOriginOpenerPolicyHeaderWriter writer; + + private MockHttpServletRequest request; + + private MockHttpServletResponse response; + + @BeforeEach + void setup() { + this.writer = new CrossOriginOpenerPolicyHeaderWriter(); + this.request = new MockHttpServletRequest(); + this.response = new MockHttpServletResponse(); + } + + @Test + void setOpenerPolicyWhenNullOpenerPolicyThenThrowsIllegalArgument() { + assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) + .withMessage("openerPolicy cannot be null"); + } + + @Test + void writeHeadersWhenDefaultValuesThenDontWriteHeaders() { + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeaderNames()).hasSize(0); + } + + @Test + void writeHeadersWhenResponseHeaderExistsThenDontOverride() { + this.response.addHeader(OPENER_HEADER_NAME, "same-origin"); + this.writer.setPolicy(CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS); + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeader(OPENER_HEADER_NAME)).isEqualTo("same-origin"); + } + + @Test + void writeHeadersWhenSetHeaderValuesThenWrites() { + this.writer.setPolicy(CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS); + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeader(OPENER_HEADER_NAME)).isEqualTo("same-origin-allow-popups"); + } + + @Test + void writeHeadersWhenSetOpenerPolicyThenWritesOpenerPolicy() { + this.writer.setPolicy(CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS); + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeaderNames()).hasSize(1); + assertThat(this.response.getHeader(OPENER_HEADER_NAME)).isEqualTo("same-origin-allow-popups"); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginResourcePolicyHeaderWriterTests.java b/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginResourcePolicyHeaderWriterTests.java new file mode 100644 index 00000000000..14b8f04a031 --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginResourcePolicyHeaderWriterTests.java @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.header.writers; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +class CrossOriginResourcePolicyHeaderWriterTests { + + private static final String RESOURCE_HEADER_NAME = "Cross-Origin-Resource-Policy"; + + private CrossOriginResourcePolicyHeaderWriter writer; + + private MockHttpServletRequest request; + + private MockHttpServletResponse response; + + @BeforeEach + void setup() { + this.writer = new CrossOriginResourcePolicyHeaderWriter(); + this.request = new MockHttpServletRequest(); + this.response = new MockHttpServletResponse(); + } + + @Test + void setResourcePolicyWhenNullThenThrowsIllegalArgument() { + assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) + .withMessage("resourcePolicy cannot be null"); + } + + @Test + void writeHeadersWhenDefaultValuesThenDontWriteHeaders() { + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeaderNames()).hasSize(0); + } + + @Test + void writeHeadersWhenResponseHeaderExistsThenDontOverride() { + this.response.addHeader(RESOURCE_HEADER_NAME, "same-site"); + this.writer.setPolicy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.CROSS_ORIGIN); + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeader(RESOURCE_HEADER_NAME)).isEqualTo("same-site"); + } + + @Test + void writeHeadersWhenSetHeaderValuesThenWrites() { + this.writer.setPolicy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.SAME_ORIGIN); + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeader(RESOURCE_HEADER_NAME)).isEqualTo("same-origin"); + } + + @Test + void writeHeadersWhenSetResourcePolicyThenWritesResourcePolicy() { + this.writer.setPolicy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.SAME_SITE); + this.writer.writeHeaders(this.request, this.response); + assertThat(this.response.getHeaderNames()).hasSize(1); + assertThat(this.response.getHeader(RESOURCE_HEADER_NAME)).isEqualTo("same-site"); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java b/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java index f1709d31921..d6efb55b747 100644 --- a/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java @@ -31,9 +31,10 @@ import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; + +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/web/src/test/java/org/springframework/security/web/jackson2/CookieMixinTests.java b/web/src/test/java/org/springframework/security/web/jackson2/CookieMixinTests.java index 41bc753d3bc..c946e27ed91 100644 --- a/web/src/test/java/org/springframework/security/web/jackson2/CookieMixinTests.java +++ b/web/src/test/java/org/springframework/security/web/jackson2/CookieMixinTests.java @@ -18,7 +18,7 @@ import java.io.IOException; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import com.fasterxml.jackson.core.JsonProcessingException; import org.json.JSONException; @@ -35,7 +35,7 @@ public class CookieMixinTests extends AbstractMixinTests { // @formatter:off private static final String COOKIE_JSON = "{" - + "\"@class\": \"javax.servlet.http.Cookie\", " + + "\"@class\": \"jakarta.servlet.http.Cookie\", " + "\"name\": \"demo\", " + "\"value\": \"cookie1\"," + "\"comment\": null, " diff --git a/web/src/test/java/org/springframework/security/web/jackson2/DefaultSavedRequestMixinTests.java b/web/src/test/java/org/springframework/security/web/jackson2/DefaultSavedRequestMixinTests.java index 3ef5f37fecd..b136c8c8795 100644 --- a/web/src/test/java/org/springframework/security/web/jackson2/DefaultSavedRequestMixinTests.java +++ b/web/src/test/java/org/springframework/security/web/jackson2/DefaultSavedRequestMixinTests.java @@ -20,9 +20,9 @@ import java.util.Collections; import java.util.Locale; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; import org.json.JSONException; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/jackson2/SavedCookieMixinTests.java b/web/src/test/java/org/springframework/security/web/jackson2/SavedCookieMixinTests.java index 06f4bbfa9ca..b72848e49fb 100644 --- a/web/src/test/java/org/springframework/security/web/jackson2/SavedCookieMixinTests.java +++ b/web/src/test/java/org/springframework/security/web/jackson2/SavedCookieMixinTests.java @@ -20,7 +20,7 @@ import java.util.ArrayList; import java.util.List; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/CookieRequestCacheTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/CookieRequestCacheTests.java index 320a2731815..be35465789a 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/CookieRequestCacheTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/CookieRequestCacheTests.java @@ -18,8 +18,8 @@ import java.util.Base64; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java index 05600271148..36ed7f21df4 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java @@ -21,9 +21,9 @@ import java.util.Locale; import java.util.Map; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilterTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilterTests.java index fc2184a5048..8e50b6336e6 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilterTests.java @@ -18,7 +18,7 @@ import java.util.Base64; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/SavedCookieTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/SavedCookieTests.java index 1f7901b069d..ec391fa20ac 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/SavedCookieTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/SavedCookieTests.java @@ -18,7 +18,7 @@ import java.io.Serializable; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapperTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapperTests.java index 4f53239f66e..e7fc56bd858 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapperTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapperTests.java @@ -21,7 +21,7 @@ import java.util.Enumeration; import java.util.Locale; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/SimpleSavedRequestTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/SimpleSavedRequestTests.java index 2484589ba14..71522b4b2f4 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/SimpleSavedRequestTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/SimpleSavedRequestTests.java @@ -22,7 +22,7 @@ import java.util.Locale; import java.util.Map; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandlerTests.java index 499cdb2e2d5..720b2575371 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandlerTests.java @@ -16,6 +16,8 @@ package org.springframework.security.web.server.authentication; +import java.util.Collections; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; @@ -95,7 +97,7 @@ public void setRedirectStrategyWhenNullThenException() { private WebFilterExchange createExchange() { return new WebFilterExchange(MockServerWebExchange.from(MockServerHttpRequest.get("/").build()), - new DefaultWebFilterChain((e) -> Mono.empty())); + new DefaultWebFilterChain((e) -> Mono.empty(), Collections.emptyList())); } } diff --git a/web/src/test/java/org/springframework/security/web/server/authorization/IpAddressReactiveAuthorizationManagerTests.java b/web/src/test/java/org/springframework/security/web/server/authorization/IpAddressReactiveAuthorizationManagerTests.java new file mode 100644 index 00000000000..5b42423e2c9 --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/server/authorization/IpAddressReactiveAuthorizationManagerTests.java @@ -0,0 +1,75 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.server.authorization; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; + +import org.junit.jupiter.api.Test; + +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests for {@link IpAddressReactiveAuthorizationManager} + * + * @author Guirong Hu + */ +public class IpAddressReactiveAuthorizationManagerTests { + + @Test + public void checkWhenHasIpv6AddressThenReturnTrue() throws UnknownHostException { + IpAddressReactiveAuthorizationManager v6manager = IpAddressReactiveAuthorizationManager + .hasIpAddress("fe80::21f:5bff:fe33:bd68"); + boolean granted = v6manager.check(null, context("fe80::21f:5bff:fe33:bd68")).block().isGranted(); + assertThat(granted).isTrue(); + } + + @Test + public void checkWhenHasIpv6AddressThenReturnFalse() throws UnknownHostException { + IpAddressReactiveAuthorizationManager v6manager = IpAddressReactiveAuthorizationManager + .hasIpAddress("fe80::21f:5bff:fe33:bd68"); + boolean granted = v6manager.check(null, context("fe80::1c9a:7cfd:29a8:a91e")).block().isGranted(); + assertThat(granted).isFalse(); + } + + @Test + public void checkWhenHasIpv4AddressThenReturnTrue() throws UnknownHostException { + IpAddressReactiveAuthorizationManager v4manager = IpAddressReactiveAuthorizationManager + .hasIpAddress("192.168.1.104"); + boolean granted = v4manager.check(null, context("192.168.1.104")).block().isGranted(); + assertThat(granted).isTrue(); + } + + @Test + public void checkWhenHasIpv4AddressThenReturnFalse() throws UnknownHostException { + IpAddressReactiveAuthorizationManager v4manager = IpAddressReactiveAuthorizationManager + .hasIpAddress("192.168.1.104"); + boolean granted = v4manager.check(null, context("192.168.100.15")).block().isGranted(); + assertThat(granted).isFalse(); + } + + private static AuthorizationContext context(String ipAddress) throws UnknownHostException { + MockServerWebExchange exchange = MockServerWebExchange.builder(MockServerHttpRequest.get("/") + .remoteAddress(new InetSocketAddress(InetAddress.getByName(ipAddress), 8080))).build(); + return new AuthorizationContext(exchange); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java index 7f3e6a3f1fa..6b342c22b56 100644 --- a/web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java @@ -16,6 +16,8 @@ package org.springframework.security.web.server.context; +import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -109,7 +111,8 @@ public void filterWhenMainContextThenDoesNotOverride() { given(this.repository.load(any())).willReturn(this.securityContext.mono()); String contextKey = "main"; WebFilter mainContextWebFilter = (e, c) -> c.filter(e).subscriberContext(Context.of(contextKey, true)); - WebFilterChain chain = new DefaultWebFilterChain((e) -> Mono.empty(), mainContextWebFilter, this.filter); + WebFilterChain chain = new DefaultWebFilterChain((e) -> Mono.empty(), + List.of(mainContextWebFilter, this.filter)); Mono filter = chain.filter(MockServerWebExchange.from(this.exchange.build())); StepVerifier.create(filter).expectAccessibleContext().hasKey(contextKey).then().verifyComplete(); } diff --git a/web/src/test/java/org/springframework/security/web/server/context/SecurityContextServerWebExchangeWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/context/SecurityContextServerWebExchangeWebFilterTests.java index bcf3d2bba47..f42a30ee466 100644 --- a/web/src/test/java/org/springframework/security/web/server/context/SecurityContextServerWebExchangeWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/context/SecurityContextServerWebExchangeWebFilterTests.java @@ -16,6 +16,8 @@ package org.springframework.security.web.server.context; +import java.util.Collections; + import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -48,7 +50,8 @@ public void filterWhenExistingContextAndPrincipalNotNullThenContextPopulated() { .filter(this.exchange, new DefaultWebFilterChain((e) -> e.getPrincipal() .doOnSuccess((contextPrincipal) -> assertThat(contextPrincipal).isEqualTo(this.principal)) .flatMap((contextPrincipal) -> Mono.subscriberContext()) - .doOnSuccess((context) -> assertThat(context.get("foo")).isEqualTo("bar")).then())) + .doOnSuccess((context) -> assertThat(context.get("foo")).isEqualTo("bar")).then(), + Collections.emptyList())) .subscriberContext((context) -> context.put("foo", "bar")) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.principal)); StepVerifier.create(result).verifyComplete(); @@ -61,7 +64,7 @@ public void filterWhenPrincipalNotNullThenContextPopulated() { new DefaultWebFilterChain((e) -> e.getPrincipal() .doOnSuccess( (contextPrincipal) -> assertThat(contextPrincipal).isEqualTo(this.principal)) - .then())) + .then(), Collections.emptyList())) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.principal)); StepVerifier.create(result).verifyComplete(); } @@ -73,7 +76,7 @@ public void filterWhenPrincipalNullThenContextEmpty() { new DefaultWebFilterChain((e) -> e.getPrincipal().defaultIfEmpty(defaultAuthentication) .doOnSuccess( (contextPrincipal) -> assertThat(contextPrincipal).isEqualTo(defaultAuthentication)) - .then())); + .then(), Collections.emptyList())); StepVerifier.create(result).verifyComplete(); } diff --git a/web/src/test/java/org/springframework/security/web/server/header/CrossOriginEmbedderPolicyServerHttpHeadersWriterTests.java b/web/src/test/java/org/springframework/security/web/server/header/CrossOriginEmbedderPolicyServerHttpHeadersWriterTests.java new file mode 100644 index 00000000000..b4e99336fc2 --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/server/header/CrossOriginEmbedderPolicyServerHttpHeadersWriterTests.java @@ -0,0 +1,76 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.server.header; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.springframework.http.HttpHeaders; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.ServerWebExchange; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +class CrossOriginEmbedderPolicyServerHttpHeadersWriterTests { + + private ServerWebExchange exchange; + + private CrossOriginEmbedderPolicyServerHttpHeadersWriter writer; + + @BeforeEach + void setup() { + this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); + this.writer = new CrossOriginEmbedderPolicyServerHttpHeadersWriter(); + } + + @Test + void setEmbedderPolicyWhenNullEmbedderPolicyThenThrowsIllegalArgument() { + assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) + .withMessage("embedderPolicy cannot be null"); + } + + @Test + void writeHeadersWhenNoValuesThenDoesNotWriteHeaders() { + this.writer.writeHttpHeaders(this.exchange); + HttpHeaders headers = this.exchange.getResponse().getHeaders(); + assertThat(headers).isEmpty(); + } + + @Test + void writeHeadersWhenResponseHeaderExistsThenDontOverride() { + this.exchange.getResponse().getHeaders().add(CrossOriginEmbedderPolicyServerHttpHeadersWriter.EMBEDDER_POLICY, + "require-corp"); + this.writer.writeHttpHeaders(this.exchange); + HttpHeaders headers = this.exchange.getResponse().getHeaders(); + assertThat(headers).hasSize(1); + assertThat(headers.get(CrossOriginEmbedderPolicyServerHttpHeadersWriter.EMBEDDER_POLICY)) + .containsOnly("require-corp"); + } + + @Test + void writeHeadersWhenSetHeaderValuesThenWrites() { + this.writer.setPolicy(CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP); + this.writer.writeHttpHeaders(this.exchange); + HttpHeaders headers = this.exchange.getResponse().getHeaders(); + assertThat(headers).hasSize(1); + assertThat(headers.get(CrossOriginEmbedderPolicyServerHttpHeadersWriter.EMBEDDER_POLICY)) + .containsOnly("require-corp"); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/server/header/CrossOriginOpenerPolicyServerHttpHeadersWriterTests.java b/web/src/test/java/org/springframework/security/web/server/header/CrossOriginOpenerPolicyServerHttpHeadersWriterTests.java new file mode 100644 index 00000000000..0159665b4ef --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/server/header/CrossOriginOpenerPolicyServerHttpHeadersWriterTests.java @@ -0,0 +1,77 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.server.header; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.springframework.http.HttpHeaders; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.ServerWebExchange; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +class CrossOriginOpenerPolicyServerHttpHeadersWriterTests { + + private ServerWebExchange exchange; + + private CrossOriginOpenerPolicyServerHttpHeadersWriter writer; + + @BeforeEach + void setup() { + this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); + this.writer = new CrossOriginOpenerPolicyServerHttpHeadersWriter(); + } + + @Test + void setOpenerPolicyWhenNullOpenerPolicyThenThrowsIllegalArgument() { + assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) + .withMessage("openerPolicy cannot be null"); + } + + @Test + void writeHeadersWhenNoValuesThenDoesNotWriteHeaders() { + this.writer.writeHttpHeaders(this.exchange); + HttpHeaders headers = this.exchange.getResponse().getHeaders(); + assertThat(headers).isEmpty(); + } + + @Test + void writeHeadersWhenResponseHeaderExistsThenDontOverride() { + this.exchange.getResponse().getHeaders().add(CrossOriginOpenerPolicyServerHttpHeadersWriter.OPENER_POLICY, + "same-origin"); + this.writer.writeHttpHeaders(this.exchange); + HttpHeaders headers = this.exchange.getResponse().getHeaders(); + assertThat(headers).hasSize(1); + assertThat(headers.get(CrossOriginOpenerPolicyServerHttpHeadersWriter.OPENER_POLICY)) + .containsOnly("same-origin"); + } + + @Test + void writeHeadersWhenSetHeaderValuesThenWrites() { + this.writer.setPolicy( + CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS); + this.writer.writeHttpHeaders(this.exchange); + HttpHeaders headers = this.exchange.getResponse().getHeaders(); + assertThat(headers).hasSize(1); + assertThat(headers.get(CrossOriginOpenerPolicyServerHttpHeadersWriter.OPENER_POLICY)) + .containsOnly("same-origin-allow-popups"); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/server/header/CrossOriginResourcePolicyServerHttpHeadersWriterTests.java b/web/src/test/java/org/springframework/security/web/server/header/CrossOriginResourcePolicyServerHttpHeadersWriterTests.java new file mode 100644 index 00000000000..a3ba9a2ec9f --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/server/header/CrossOriginResourcePolicyServerHttpHeadersWriterTests.java @@ -0,0 +1,76 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.server.header; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.springframework.http.HttpHeaders; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.ServerWebExchange; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +class CrossOriginResourcePolicyServerHttpHeadersWriterTests { + + private ServerWebExchange exchange; + + private CrossOriginResourcePolicyServerHttpHeadersWriter writer; + + @BeforeEach + void setup() { + this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); + this.writer = new CrossOriginResourcePolicyServerHttpHeadersWriter(); + } + + @Test + void setResourcePolicyWhenNullThenThrowsIllegalArgument() { + assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) + .withMessage("resourcePolicy cannot be null"); + } + + @Test + void writeHeadersWhenNoValuesThenDoesNotWriteHeaders() { + this.writer.writeHttpHeaders(this.exchange); + HttpHeaders headers = this.exchange.getResponse().getHeaders(); + assertThat(headers).isEmpty(); + } + + @Test + void writeHeadersWhenResponseHeaderExistsThenDontOverride() { + this.exchange.getResponse().getHeaders().add(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY, + "same-origin"); + this.writer.writeHttpHeaders(this.exchange); + HttpHeaders headers = this.exchange.getResponse().getHeaders(); + assertThat(headers).hasSize(1); + assertThat(headers.get(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY)) + .containsOnly("same-origin"); + } + + @Test + void writeHeadersWhenSetHeaderValuesThenWrites() { + this.writer.setPolicy(CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN); + this.writer.writeHttpHeaders(this.exchange); + HttpHeaders headers = this.exchange.getResponse().getHeaders(); + assertThat(headers).hasSize(1); + assertThat(headers.get(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY)) + .containsOnly("same-origin"); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriterTests.java b/web/src/test/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriterTests.java index e411ee745bc..604d20d56db 100644 --- a/web/src/test/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 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,11 +16,14 @@ package org.springframework.security.web.server.header; +import java.util.Locale; + import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; @@ -56,6 +59,24 @@ public void writeHeadersWhenSingleHeaderAndHeaderWrittenThenSuccess() { .containsOnly(headerValue); } + // gh-10557 + @Test + public void writeHeadersWhenHeaderWrittenWithDifferentCaseThenDoesNotWriteHeaders() { + String headerName = HttpHeaders.CACHE_CONTROL.toLowerCase(Locale.ROOT); + String headerValue = "max-age=120"; + this.headers.set(headerName, headerValue); + // Note: This test inverts which collection uses case sensitive headers, + // due to the fact that gh-10557 reports NettyHeadersAdapter as the + // response headers implementation, which is not accessible here. + HttpHeaders caseSensitiveHeaders = new HttpHeaders(new LinkedMultiValueMap<>()); + caseSensitiveHeaders.set(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE); + caseSensitiveHeaders.set(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE); + caseSensitiveHeaders.set(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE); + this.writer = new StaticServerHttpHeadersWriter(caseSensitiveHeaders); + this.writer.writeHttpHeaders(this.exchange); + assertThat(this.headers.get(headerName)).containsOnly(headerValue); + } + @Test public void writeHeadersWhenMultiHeaderThenWritesAllHeaders() { this.writer = StaticServerHttpHeadersWriter.builder() diff --git a/web/src/test/java/org/springframework/security/web/server/util/matcher/IpAddressServerWebExchangeMatcherTests.java b/web/src/test/java/org/springframework/security/web/server/util/matcher/IpAddressServerWebExchangeMatcherTests.java new file mode 100644 index 00000000000..3c26dfdfd93 --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/server/util/matcher/IpAddressServerWebExchangeMatcherTests.java @@ -0,0 +1,126 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.server.util.matcher; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.ServerWebExchange; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +/** + * Tests for {@link IpAddressServerWebExchangeMatcher} + * + * @author Guirong Hu + */ +@ExtendWith(MockitoExtension.class) +public class IpAddressServerWebExchangeMatcherTests { + + @Test + public void matchesWhenIpv6RangeAndIpv6AddressThenTrue() throws UnknownHostException { + ServerWebExchange ipv6Exchange = exchange("fe80::21f:5bff:fe33:bd68"); + ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("fe80::21f:5bff:fe33:bd68") + .matches(ipv6Exchange).block(); + assertThat(matches.isMatch()).isTrue(); + } + + @Test + public void matchesWhenIpv6RangeAndIpv4AddressThenFalse() throws UnknownHostException { + ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); + ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("fe80::21f:5bff:fe33:bd68") + .matches(ipv4Exchange).block(); + assertThat(matches.isMatch()).isFalse(); + } + + @Test + public void matchesWhenIpv4RangeAndIpv4AddressThenTrue() throws UnknownHostException { + ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); + ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("192.168.1.104") + .matches(ipv4Exchange).block(); + assertThat(matches.isMatch()).isTrue(); + } + + @Test + public void matchesWhenIpv4SubnetAndIpv4AddressThenTrue() throws UnknownHostException { + ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); + IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("192.168.1.0/24"); + assertThat(matcher.matches(ipv4Exchange).block().isMatch()).isTrue(); + } + + @Test + public void matchesWhenIpv4SubnetAndIpv4AddressThenFalse() throws UnknownHostException { + ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); + IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("192.168.1.128/25"); + assertThat(matcher.matches(ipv4Exchange).block().isMatch()).isFalse(); + } + + @Test + public void matchesWhenIpv6SubnetAndIpv6AddressThenTrue() throws UnknownHostException { + ServerWebExchange ipv6Exchange = exchange("2001:DB8:0:FFFF:FFFF:FFFF:FFFF:FFFF"); + IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("2001:DB8::/48"); + assertThat(matcher.matches(ipv6Exchange).block().isMatch()).isTrue(); + } + + @Test + public void matchesWhenIpv6SubnetAndIpv6AddressThenFalse() throws UnknownHostException { + ServerWebExchange ipv6Exchange = exchange("2001:DB8:1:0:0:0:0:0"); + IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("2001:DB8::/48"); + assertThat(matcher.matches(ipv6Exchange).block().isMatch()).isFalse(); + } + + @Test + public void matchesWhenZeroMaskAndAnythingThenTrue() throws UnknownHostException { + IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("0.0.0.0/0"); + assertThat(matcher.matches(exchange("123.4.5.6")).block().isMatch()).isTrue(); + assertThat(matcher.matches(exchange("192.168.0.159")).block().isMatch()).isTrue(); + matcher = new IpAddressServerWebExchangeMatcher("192.168.0.159/0"); + assertThat(matcher.matches(exchange("123.4.5.6")).block().isMatch()).isTrue(); + assertThat(matcher.matches(exchange("192.168.0.159")).block().isMatch()).isTrue(); + } + + @Test + public void constructorWhenIpv4AddressMaskTooLongThenIllegalArgumentException() { + String ipv4AddressWithTooLongMask = "192.168.1.104/33"; + assertThatIllegalArgumentException() + .isThrownBy(() -> new IpAddressServerWebExchangeMatcher(ipv4AddressWithTooLongMask)) + .withMessage(String.format("IP address %s is too short for bitmask of length %d", "192.168.1.104", 33)); + } + + @Test + public void constructorWhenIpv6AddressMaskTooLongThenIllegalArgumentException() { + String ipv6AddressWithTooLongMask = "fe80::21f:5bff:fe33:bd68/129"; + assertThatIllegalArgumentException() + .isThrownBy(() -> new IpAddressServerWebExchangeMatcher(ipv6AddressWithTooLongMask)) + .withMessage(String.format("IP address %s is too short for bitmask of length %d", + "fe80::21f:5bff:fe33:bd68", 129)); + } + + private static ServerWebExchange exchange(String ipAddress) throws UnknownHostException { + return MockServerWebExchange.builder(MockServerHttpRequest.get("/") + .remoteAddress(new InetSocketAddress(InetAddress.getByName(ipAddress), 8080))).build(); + } + +} diff --git a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java index 5e81db0a107..f1ea9c41828 100644 --- a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited + * Copyright 2004, 2005, 2006, 2021 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ import java.util.Arrays; import java.util.List; -import javax.servlet.AsyncContext; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.AsyncContext; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -36,6 +36,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockHttpSession; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.TestingAuthenticationToken; @@ -45,12 +46,14 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -217,6 +220,27 @@ public void loginNullAuthenticationManagerFail() throws Exception { verifyZeroInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler); } + @Test + public void loginWhenHttpServletRequestHasAuthenticationDetailsThenAuthenticationRequestHasDetails() + throws Exception { + String ipAddress = "10.0.0.100"; + String sessionId = "session-id"; + given(this.request.getRemoteAddr()).willReturn(ipAddress); + given(this.request.getSession(anyBoolean())).willReturn(new MockHttpSession(null, sessionId)); + wrappedRequest().login("username", "password"); + + ArgumentCaptor authenticationCaptor = ArgumentCaptor + .forClass(UsernamePasswordAuthenticationToken.class); + verify(this.authenticationManager).authenticate(authenticationCaptor.capture()); + + UsernamePasswordAuthenticationToken authenticationRequest = authenticationCaptor.getValue(); + assertThat(authenticationRequest.getDetails()).isInstanceOf(WebAuthenticationDetails.class); + + WebAuthenticationDetails details = (WebAuthenticationDetails) authenticationRequest.getDetails(); + assertThat(details.getRemoteAddress()).isEqualTo(ipAddress); + assertThat(details.getSessionId()).isEqualTo(sessionId); + } + @Test public void logout() throws Exception { TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); diff --git a/web/src/test/java/org/springframework/security/web/session/DefaultSessionAuthenticationStrategyTests.java b/web/src/test/java/org/springframework/security/web/session/DefaultSessionAuthenticationStrategyTests.java index 58f651411a2..278122549a2 100644 --- a/web/src/test/java/org/springframework/security/web/session/DefaultSessionAuthenticationStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/session/DefaultSessionAuthenticationStrategyTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.session; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; diff --git a/web/src/test/java/org/springframework/security/web/session/HttpSessionEventPublisherTests.java b/web/src/test/java/org/springframework/security/web/session/HttpSessionEventPublisherTests.java index 7bdbfc7a7d4..c18b3bebd1d 100644 --- a/web/src/test/java/org/springframework/security/web/session/HttpSessionEventPublisherTests.java +++ b/web/src/test/java/org/springframework/security/web/session/HttpSessionEventPublisherTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.session; -import javax.servlet.http.HttpSessionEvent; +import jakarta.servlet.http.HttpSessionEvent; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java b/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java index b76367aa383..3bed72ead2b 100644 --- a/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java @@ -16,9 +16,9 @@ package org.springframework.security.web.session; -import javax.servlet.FilterChain; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java b/web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java index 82a6cab8069..97acfee56fb 100644 --- a/web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java +++ b/web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java @@ -20,8 +20,8 @@ import java.io.PrintWriter; import java.util.Locale; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/AndRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/AndRequestMatcherTests.java index a53e569c18a..5b8705d9265 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/AndRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/AndRequestMatcherTests.java @@ -20,7 +20,7 @@ import java.util.Collections; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/AntPathRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/AntPathRequestMatcherTests.java index 50469478902..73a192c72b4 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/AntPathRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/AntPathRequestMatcherTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcherTests.java index 509912d50d2..516904b9541 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcherTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.DispatcherType; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.DispatcherType; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/NegatedRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/NegatedRequestMatcherTests.java index 5192dcd9cc1..e8cbcba3651 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/NegatedRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/NegatedRequestMatcherTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/OrRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/OrRequestMatcherTests.java index 37314e174c6..f5f9ff36136 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/OrRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/OrRequestMatcherTests.java @@ -20,7 +20,7 @@ import java.util.Collections; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/RegexRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/RegexRequestMatcherTests.java index 3a87bdc5f94..1af91610b8e 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/RegexRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/RegexRequestMatcherTests.java @@ -16,7 +16,7 @@ package org.springframework.security.web.util.matcher; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/RequestMatcherEntryTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/RequestMatcherEntryTests.java new file mode 100644 index 00000000000..b293b68caaa --- /dev/null +++ b/web/src/test/java/org/springframework/security/web/util/matcher/RequestMatcherEntryTests.java @@ -0,0 +1,41 @@ +/* + * Copyright 2002-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.util.matcher; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +class RequestMatcherEntryTests { + + @Test + void constructWhenGetRequestMatcherAndEntryThenSameRequestMatcherAndEntry() { + RequestMatcher requestMatcher = mock(RequestMatcher.class); + RequestMatcherEntry entry = new RequestMatcherEntry<>(requestMatcher, "entry"); + assertThat(entry.getRequestMatcher()).isSameAs(requestMatcher); + assertThat(entry.getEntry()).isEqualTo("entry"); + } + + @Test + void constructWhenNullValuesThenNullValues() { + RequestMatcherEntry entry = new RequestMatcherEntry<>(null, null); + assertThat(entry.getRequestMatcher()).isNull(); + assertThat(entry.getEntry()).isNull(); + } + +}