Compare commits
125 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 87e2071b17 | |||
| 2686af0c4d | |||
| f66a5bab99 | |||
| 7da99acca7 | |||
| 0cf95dbf61 | |||
| 39c43159f4 | |||
| be0c2bd44c | |||
| 67f262199a | |||
| 0a022a348c | |||
| afec90c8e8 | |||
| 9806674481 | |||
| b29772269f | |||
| c7ccba66c7 | |||
| a6599f9874 | |||
| 9f581850a1 | |||
| 6e13927b48 | |||
| cead207c5b | |||
| 9e22d40264 | |||
| c54a191042 | |||
| 0da2e5a33e | |||
| 08b84502e3 | |||
| 6bacf21c76 | |||
| fe8f56e41c | |||
| f402679996 | |||
| 708af21576 | |||
| dbcff3f1af | |||
| 57b27cacdf | |||
| ed0cc16bb6 | |||
| e87fae40df | |||
| 32d25e8f23 | |||
| 0c63c7f611 | |||
| 9656f79afe | |||
| dc5e1eae1d | |||
| 81723fca9a | |||
| ac32095bc8 | |||
| 3aedeea676 | |||
| 25390ab618 | |||
| 30206b6d0c | |||
| 3e22c1e8de | |||
| 78b5c3e124 | |||
| 8d60ec32bd | |||
| 1345cb7960 | |||
| 73104daa7f | |||
| 9a71837fc7 | |||
| e7a06fe4d4 | |||
| 2205fc9aaf | |||
| 629299d6ee | |||
| d71a051fd3 | |||
| 064e4e03ce | |||
| 43916836e5 | |||
| 8f6f6ab423 | |||
| 498772d7f6 | |||
| 898791b584 | |||
| 13530d5eba | |||
| d67c11cfbd | |||
| 720809ff7d | |||
| a81c0459e2 | |||
| a387f401b7 | |||
| 9bd04ed0e0 | |||
| 5f26daedcb | |||
| b472a06848 | |||
| 312b758b3a | |||
| 68cec50bad | |||
| 04692d9ee8 | |||
| 8cfb6a4cdc | |||
| e1e61a9bd1 | |||
| ce90bcc6fc | |||
| 1c6dc1aaac | |||
| 2279f9fd39 | |||
| c053f6f0c6 | |||
| d8db849400 | |||
| df4411fb48 | |||
| e834543eed | |||
| 783f674704 | |||
| 933debebeb | |||
| 2629fb2061 | |||
| 77c337bac4 | |||
| 4e3517e03a | |||
| b47420f8a2 | |||
| 7250abc185 | |||
| d47e3e8cd8 | |||
| 45683349a4 | |||
| 9ac286e8ea | |||
| 06e58e4c34 | |||
| 590e9e23d9 | |||
| 79f1cf799d | |||
| bcc1cfc28a | |||
| adeadae92b | |||
| aa8b691ee3 | |||
| 663f5cf76b | |||
| 0ac554ee3e | |||
| 8ccc03fdb6 | |||
| f9b6d173ab | |||
| 55c374da32 | |||
| 5c88b95af5 | |||
| 69b17f3d3f | |||
| c1002ff745 | |||
| 71703dc371 | |||
| 90b37d6d07 | |||
| 73cb9862ad | |||
| ce5aa9e694 | |||
| f8e39336cb | |||
| a53cbb838b | |||
| 8287289bcb | |||
| 40699dc3b7 | |||
| 68b052218a | |||
| 7c54c0e4fa | |||
| 62ede47d86 | |||
| 1eefd433b6 | |||
| c3174179a3 | |||
| 6b19728c54 | |||
| 7efa275abc | |||
| 35ad1f857e | |||
| cdac708051 | |||
| 219faf29d4 | |||
| b6f3cb71e6 | |||
| 7a937fc900 | |||
| 734dc98e50 | |||
| 4c5bf3bdf5 | |||
| af233a2a00 | |||
| b438bc5384 | |||
| f4915890cc | |||
| 06c15035fd | |||
| ed0369ac71 | |||
| ce5570bb06 |
@@ -1,20 +0,0 @@
|
||||
name: Rebuild Search Index
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 10 * * *' # Once per day at 10am UTC
|
||||
workflow_dispatch:
|
||||
permissions: read-all
|
||||
jobs:
|
||||
build:
|
||||
if: github.repository_owner == 'spring-projects'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
ref: docs-build
|
||||
fetch-depth: 1
|
||||
- name: Dispatch
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_ACTIONS_REPO_TOKEN }}
|
||||
run: gh workflow run rebuild-search-index.yml -r $(git rev-parse --abbrev-ref HEAD)
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"java.import.gradle.enabled": false
|
||||
}
|
||||
@@ -9,7 +9,6 @@ buildscript {
|
||||
classpath "com.netflix.nebula:nebula-project-plugin:8.2.0"
|
||||
}
|
||||
repositories {
|
||||
maven { url 'https://repo.spring.io/plugins-snapshot' }
|
||||
maven { url 'https://plugins.gradle.org/m2/' }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ sourceCompatibility = JavaVersion.VERSION_17
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
mavenCentral()
|
||||
maven { url 'https://repo.spring.io/plugins-release/' }
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
@@ -87,7 +86,7 @@ dependencies {
|
||||
implementation localGroovy()
|
||||
|
||||
implementation 'io.github.gradle-nexus:publish-plugin:1.1.0'
|
||||
implementation 'io.projectreactor:reactor-core:3.5.5'
|
||||
implementation 'io.projectreactor:reactor-core:3.5.7'
|
||||
implementation 'org.gretty:gretty:3.0.9'
|
||||
implementation 'com.apollographql.apollo:apollo-runtime:2.4.5'
|
||||
implementation 'com.github.ben-manes:gradle-versions-plugin:0.38.0'
|
||||
@@ -99,7 +98,7 @@ dependencies {
|
||||
implementation 'org.jfrog.buildinfo:build-info-extractor-gradle:4.29.0'
|
||||
implementation 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.7.1'
|
||||
|
||||
testImplementation platform('org.junit:junit-bom:5.9.2')
|
||||
testImplementation platform('org.junit:junit-bom:5.9.3')
|
||||
testImplementation "org.junit.jupiter:junit-jupiter-api"
|
||||
testImplementation "org.junit.jupiter:junit-jupiter-params"
|
||||
testImplementation "org.junit.jupiter:junit-jupiter-engine"
|
||||
|
||||
@@ -54,6 +54,7 @@ public abstract class AbstractSpringJavaPlugin implements Plugin<Project> {
|
||||
pluginManager.apply("io.spring.convention.javadoc-options");
|
||||
pluginManager.apply("io.spring.convention.checkstyle");
|
||||
pluginManager.apply(CopyPropertiesPlugin);
|
||||
pluginManager.apply("io.spring.convention.eclipse");
|
||||
|
||||
project.jar {
|
||||
manifest.attributes["Created-By"] =
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 2023 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 io.spring.gradle.convention
|
||||
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.plugins.ide.eclipse.EclipsePlugin
|
||||
|
||||
/**
|
||||
* Plugin to tweak .classpath settings so that eclipse/sts/vscode can
|
||||
* be imported cleanly.
|
||||
*
|
||||
* @author Janne Valkealahti
|
||||
*/
|
||||
class EclipsePlugin implements Plugin<Project> {
|
||||
|
||||
@Override
|
||||
void apply(Project project) {
|
||||
project.plugins.apply(EclipsePlugin)
|
||||
|
||||
project.eclipse {
|
||||
classpath {
|
||||
file {
|
||||
whenMerged {
|
||||
// for aspects gradle eclipse integration wrongly creates lib entries for
|
||||
// aspects/build/classes/java/main and aspects/build/resources/main which
|
||||
// never has anything. eclipse/sts don't care, vscode language server
|
||||
// complains about missing folders. So remove those from a .classpath
|
||||
entries.removeAll {
|
||||
entry -> entry.kind == 'lib' && (entry.path.contains('aspects/build/classes/java/main') || entry.path.contains('aspects/build/resources/main'))
|
||||
}
|
||||
// there are cycles and then dependencies between projects main sources and
|
||||
// test sources. Looks like gradle eclipse integration is getting confused.
|
||||
// thus just relax rules so that projects always sees everything from
|
||||
// dependant project.
|
||||
entries
|
||||
.findAll { entry -> entry instanceof org.gradle.plugins.ide.eclipse.model.ProjectDependency }
|
||||
.each {
|
||||
it.entryAttributes['without_test_code'] = 'false'
|
||||
it.entryAttributes['test'] = 'false'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
jdt {
|
||||
file {
|
||||
withProperties { properties ->
|
||||
// there are cycles and then dependencies between projects main sources and
|
||||
// test sources. Relax those from error to warning
|
||||
properties['org.eclipse.jdt.core.circularClasspath'] = 'warning'
|
||||
properties['org.eclipse.jdt.core.incompleteClasspath'] = 'warning'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
package io.spring.gradle.convention
|
||||
|
||||
import org.gradle.api.plugins.JavaPlugin
|
||||
import org.gradle.api.tasks.bundling.Zip
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.plugins.JavaPlugin
|
||||
import org.gradle.api.tasks.bundling.Zip
|
||||
|
||||
public class SchemaZipPlugin implements Plugin<Project> {
|
||||
|
||||
@@ -37,6 +37,15 @@ public class SchemaZipPlugin implements Plugin<Project> {
|
||||
from xsdFile.path
|
||||
}
|
||||
}
|
||||
File symlink = module.sourceSets.main.resources.find {
|
||||
it.path.endsWith('org/springframework/security/config/spring-security.xsd')
|
||||
}
|
||||
if (symlink != null) {
|
||||
schemaZip.into('security') {
|
||||
duplicatesStrategy 'exclude'
|
||||
from symlink.path
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
implementation-class=io.spring.gradle.convention.EclipsePlugin
|
||||
@@ -68,6 +68,7 @@ dependencies {
|
||||
testImplementation 'ldapsdk:ldapsdk:4.1'
|
||||
testImplementation('net.sourceforge.htmlunit:htmlunit') {
|
||||
exclude group: 'commons-logging', module: 'commons-logging'
|
||||
exclude group: 'xml-apis', module: 'xml-apis'
|
||||
}
|
||||
testImplementation "org.apache.directory.server:apacheds-core"
|
||||
testImplementation "org.apache.directory.server:apacheds-core-entry"
|
||||
@@ -83,6 +84,7 @@ dependencies {
|
||||
testImplementation "org.mockito:mockito-inline"
|
||||
testImplementation('org.seleniumhq.selenium:htmlunit-driver') {
|
||||
exclude group: 'commons-logging', module: 'commons-logging'
|
||||
exclude group: 'xml-apis', module: 'xml-apis'
|
||||
}
|
||||
testImplementation('org.seleniumhq.selenium:selenium-java') {
|
||||
exclude group: 'commons-logging', module: 'commons-logging'
|
||||
|
||||
+6
@@ -221,6 +221,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
|
||||
if (configs == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
removeFromConfigurersAddedInInitializing(clazz);
|
||||
return new ArrayList<>(configs);
|
||||
}
|
||||
|
||||
@@ -253,11 +254,16 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
|
||||
if (configs == null) {
|
||||
return null;
|
||||
}
|
||||
removeFromConfigurersAddedInInitializing(clazz);
|
||||
Assert.state(configs.size() == 1,
|
||||
() -> "Only one configurer expected for type " + clazz + ", but got " + configs);
|
||||
return (C) configs.get(0);
|
||||
}
|
||||
|
||||
private <C extends SecurityConfigurer<O, B>> void removeFromConfigurersAddedInInitializing(Class<C> clazz) {
|
||||
this.configurersAddedInInitializing.removeIf(clazz::isInstance);
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the {@link ObjectPostProcessor} to use.
|
||||
* @param objectPostProcessor the {@link ObjectPostProcessor} to use. Cannot be null
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
* Copyright 2002-2023 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.
|
||||
@@ -46,7 +46,7 @@ final class Jsr250MethodSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
static Advisor jsr250AuthorizationMethodInterceptor(ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
Advisor jsr250AuthorizationMethodInterceptor(ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
ObjectProvider<SecurityContextHolderStrategy> strategyProvider,
|
||||
ObjectProvider<ObservationRegistry> registryProvider) {
|
||||
Jsr250AuthorizationManager jsr250 = new Jsr250AuthorizationManager();
|
||||
|
||||
+5
-6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -52,7 +52,7 @@ final class PrePostMethodSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
static Advisor preFilterAuthorizationMethodInterceptor(ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
Advisor preFilterAuthorizationMethodInterceptor(ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
ObjectProvider<MethodSecurityExpressionHandler> expressionHandlerProvider,
|
||||
ObjectProvider<SecurityContextHolderStrategy> strategyProvider, ApplicationContext context) {
|
||||
PreFilterAuthorizationMethodInterceptor preFilter = new PreFilterAuthorizationMethodInterceptor();
|
||||
@@ -64,7 +64,7 @@ final class PrePostMethodSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
static Advisor preAuthorizeAuthorizationMethodInterceptor(ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
Advisor preAuthorizeAuthorizationMethodInterceptor(ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
ObjectProvider<MethodSecurityExpressionHandler> expressionHandlerProvider,
|
||||
ObjectProvider<SecurityContextHolderStrategy> strategyProvider,
|
||||
ObjectProvider<AuthorizationEventPublisher> eventPublisherProvider,
|
||||
@@ -81,8 +81,7 @@ final class PrePostMethodSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
static Advisor postAuthorizeAuthorizationMethodInterceptor(
|
||||
ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
Advisor postAuthorizeAuthorizationMethodInterceptor(ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
ObjectProvider<MethodSecurityExpressionHandler> expressionHandlerProvider,
|
||||
ObjectProvider<SecurityContextHolderStrategy> strategyProvider,
|
||||
ObjectProvider<AuthorizationEventPublisher> eventPublisherProvider,
|
||||
@@ -99,7 +98,7 @@ final class PrePostMethodSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
static Advisor postFilterAuthorizationMethodInterceptor(ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
Advisor postFilterAuthorizationMethodInterceptor(ObjectProvider<GrantedAuthorityDefaults> defaultsProvider,
|
||||
ObjectProvider<MethodSecurityExpressionHandler> expressionHandlerProvider,
|
||||
ObjectProvider<SecurityContextHolderStrategy> strategyProvider, ApplicationContext context) {
|
||||
PostFilterAuthorizationMethodInterceptor postFilter = new PostFilterAuthorizationMethodInterceptor();
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
* Copyright 2002-2023 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.
|
||||
@@ -46,7 +46,7 @@ final class SecuredMethodSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
static Advisor securedAuthorizationMethodInterceptor(ObjectProvider<SecurityContextHolderStrategy> strategyProvider,
|
||||
Advisor securedAuthorizationMethodInterceptor(ObjectProvider<SecurityContextHolderStrategy> strategyProvider,
|
||||
ObjectProvider<ObservationRegistry> registryProvider) {
|
||||
SecuredAuthorizationManager secured = new SecuredAuthorizationManager();
|
||||
SecurityContextHolderStrategy strategy = strategyProvider
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
spring-security-6.0.xsd
|
||||
+45
@@ -30,6 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
@@ -83,6 +84,24 @@ public class AbstractConfiguredSecurityBuilderTests {
|
||||
verify(DelegateSecurityConfigurer.CONFIGURER).configure(this.builder);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildWhenConfigurerAppliesAndRemoveAnotherConfigurerThenNotConfigured() throws Exception {
|
||||
ApplyAndRemoveSecurityConfigurer.CONFIGURER = mock(SecurityConfigurer.class);
|
||||
this.builder.apply(new ApplyAndRemoveSecurityConfigurer());
|
||||
this.builder.build();
|
||||
verify(ApplyAndRemoveSecurityConfigurer.CONFIGURER, never()).init(this.builder);
|
||||
verify(ApplyAndRemoveSecurityConfigurer.CONFIGURER, never()).configure(this.builder);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildWhenConfigurerAppliesAndRemoveAnotherConfigurersThenNotConfigured() throws Exception {
|
||||
ApplyAndRemoveAllSecurityConfigurer.CONFIGURER = mock(SecurityConfigurer.class);
|
||||
this.builder.apply(new ApplyAndRemoveAllSecurityConfigurer());
|
||||
this.builder.build();
|
||||
verify(ApplyAndRemoveAllSecurityConfigurer.CONFIGURER, never()).init(this.builder);
|
||||
verify(ApplyAndRemoveAllSecurityConfigurer.CONFIGURER, never()).configure(this.builder);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getConfigurerWhenMultipleConfigurersThenThrowIllegalStateException() throws Exception {
|
||||
TestConfiguredSecurityBuilder builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class),
|
||||
@@ -130,6 +149,32 @@ public class AbstractConfiguredSecurityBuilderTests {
|
||||
assertThat(builder.getConfigurers(DelegateSecurityConfigurer.class)).hasSize(2);
|
||||
}
|
||||
|
||||
private static class ApplyAndRemoveSecurityConfigurer
|
||||
extends SecurityConfigurerAdapter<Object, TestConfiguredSecurityBuilder> {
|
||||
|
||||
private static SecurityConfigurer<Object, TestConfiguredSecurityBuilder> CONFIGURER;
|
||||
|
||||
@Override
|
||||
public void init(TestConfiguredSecurityBuilder builder) throws Exception {
|
||||
builder.apply(CONFIGURER);
|
||||
builder.removeConfigurer(CONFIGURER.getClass());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class ApplyAndRemoveAllSecurityConfigurer
|
||||
extends SecurityConfigurerAdapter<Object, TestConfiguredSecurityBuilder> {
|
||||
|
||||
private static SecurityConfigurer<Object, TestConfiguredSecurityBuilder> CONFIGURER;
|
||||
|
||||
@Override
|
||||
public void init(TestConfiguredSecurityBuilder builder) throws Exception {
|
||||
builder.apply(CONFIGURER);
|
||||
builder.removeConfigurers(CONFIGURER.getClass());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class DelegateSecurityConfigurer
|
||||
extends SecurityConfigurerAdapter<Object, TestConfiguredSecurityBuilder> {
|
||||
|
||||
|
||||
+39
@@ -23,6 +23,7 @@ import java.util.concurrent.Callable;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.micrometer.observation.ObservationRegistry;
|
||||
import jakarta.servlet.Filter;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -50,6 +51,7 @@ import org.springframework.security.config.annotation.SecurityContextChangedList
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.AnonymousConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
|
||||
import org.springframework.security.config.test.SpringTestContext;
|
||||
import org.springframework.security.config.test.SpringTestContextExtension;
|
||||
import org.springframework.security.core.Authentication;
|
||||
@@ -61,6 +63,8 @@ import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.test.web.servlet.RequestCacheResultMatcher;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter;
|
||||
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
@@ -336,6 +340,16 @@ public class HttpSecurityConfigurationTests {
|
||||
this.mockMvc.perform(get("/"));
|
||||
}
|
||||
|
||||
// gh-13203
|
||||
@Test
|
||||
public void disableConfigurerWhenAppliedByAnotherConfigurerThenNotApplied() {
|
||||
this.spring.register(ApplyCustomDslConfig.class).autowire();
|
||||
SecurityFilterChain filterChain = this.spring.getContext().getBean(SecurityFilterChain.class);
|
||||
List<Filter> filters = filterChain.getFilters();
|
||||
assertThat(filters).doesNotHaveAnyElementsOfTypes(DefaultLoginPageGeneratingFilter.class,
|
||||
DefaultLogoutPageGeneratingFilter.class);
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class NameController {
|
||||
|
||||
@@ -575,6 +589,31 @@ public class HttpSecurityConfigurationTests {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
static class ApplyCustomDslConfig {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.apply(CustomDsl.customDsl());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class CustomDsl extends AbstractHttpConfigurer<CustomDsl, HttpSecurity> {
|
||||
|
||||
@Override
|
||||
public void init(HttpSecurity http) throws Exception {
|
||||
http.formLogin(FormLoginConfigurer::disable);
|
||||
}
|
||||
|
||||
static CustomDsl customDsl() {
|
||||
return new CustomDsl();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class DefaultConfigurer extends AbstractHttpConfigurer<DefaultConfigurer, HttpSecurity> {
|
||||
|
||||
boolean init;
|
||||
|
||||
+28
@@ -319,6 +319,34 @@ public class Saml2LogoutConfigurerTests {
|
||||
verify(getBean(LogoutHandler.class)).logout(any(), any(), any());
|
||||
}
|
||||
|
||||
// gh-12346
|
||||
@Test
|
||||
public void saml2LogoutRequestWhenLowercaseEncodingAndDifferentQueryParamOrderThenLogsOutAndSendsLogoutResponse()
|
||||
throws Exception {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
String apLogoutRequest = "nZFNa4QwEIb/iuQeP6K7dYO6FKQg2B622x56G3WwgiY2E8v239fqCksPPfSWIXmfNw+THC9D73yi\r\n"
|
||||
+ "oU6rlAWuzxxUtW461abs5fzAY3bMEoKhF6Msdasne8KPCck6c1KRXK9SNhklNVBHUsGAJG0tn+8f\r\n"
|
||||
+ "SylcX45GW13rnjn5HOwU2KXt3dqRpOeZ0cULDGOPrjat1y8t3gL2zFrGnCJPWXkKcR8KCHY8xmrP\r\n"
|
||||
+ "Iz868OpOVLwO4wohggagmd8STVgosqBsyoQvBPd3XITnIJaRL8PYjcThjTmvm/f8SXa1lEvY3Nr9\r\n"
|
||||
+ "LQdEaH6EWAYjR2U7+8W7JvFucRv8aY4X+b/g03zaoCsmu46/FpN9Aw==";
|
||||
String apLogoutRequestRelayState = "d118dbd5-3853-4268-b3e5-c40fc033fa2f";
|
||||
String apLogoutRequestSignature = "VZ7rWa5u3hIX60fAQs/gBQZWDP2BAIlCMMrNrTHafoKKj0uXWnuITYLuL8NdsWmyQN0+fqWW4X05+BqiLpL80jHLmQR5RVqqL1EtVv1SpPUna938lgz2sOliuYmfQNj4Bmd+Z5G1K6QhbVrtfb7TQHURjUafzfRm8+jGz3dPjVBrn/rD/umfGoSn6RuWngugcMNL4U0A+JcEh1NSfSYNVz7y+MqlW1UhX2kF86rm97ERCrxay7Gh/bI2f3fJPJ1r+EyLjzrDUkqw5cva3rVlFgEQouMVu35lUJn7SFompW8oTxkI23oc/t+AGZqaBupNITNdjyGCBpfukZ69EZrj8g==";
|
||||
DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user",
|
||||
Collections.emptyMap());
|
||||
principal.setRelyingPartyRegistrationId("get");
|
||||
Saml2Authentication user = new Saml2Authentication(principal, "response",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
MvcResult result = this.mvc
|
||||
.perform(get("/logout/saml2/slo").param("SAMLRequest", apLogoutRequest)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg).param("RelayState", apLogoutRequestRelayState)
|
||||
.param("Signature", apLogoutRequestSignature)
|
||||
.with(new SamlQueryStringRequestPostProcessor(true)).with(authentication(user)))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
String location = result.getResponse().getHeader("Location");
|
||||
assertThat(location).startsWith("https://ap.example.org/logout/saml2/response");
|
||||
verify(getBean(LogoutHandler.class)).logout(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saml2LogoutRequestWhenNoRegistrationThen400() throws Exception {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
|
||||
+2
-2
@@ -150,8 +150,8 @@ public class XsdDocumentedTests {
|
||||
.getParentFile()
|
||||
.list((dir, name) -> name.endsWith(".xsd"));
|
||||
// @formatter:on
|
||||
assertThat(schemas.length).isEqualTo(21)
|
||||
.withFailMessage("the count is equal to 21, if not then schemaDocument needs updating");
|
||||
assertThat(schemas.length).isEqualTo(22)
|
||||
.withFailMessage("the count is equal to 22, if not then schemaDocument needs updating");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+9
-10
@@ -9,21 +9,21 @@ javaPlatform {
|
||||
dependencies {
|
||||
api platform("org.springframework:spring-framework-bom:$springFrameworkVersion")
|
||||
api platform("io.projectreactor:reactor-bom:$reactorVersion")
|
||||
api platform("io.rsocket:rsocket-bom:1.1.3")
|
||||
api platform("org.junit:junit-bom:5.9.2")
|
||||
api platform("io.rsocket:rsocket-bom:1.1.4")
|
||||
api platform("org.junit:junit-bom:5.9.3")
|
||||
api platform("org.mockito:mockito-bom:4.8.1")
|
||||
api platform("org.springframework.data:spring-data-bom:2022.0.5")
|
||||
api platform("org.springframework.data:spring-data-bom:2022.0.7")
|
||||
api platform("org.jetbrains.kotlin:kotlin-bom:$kotlinVersion")
|
||||
api platform("org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.6.4")
|
||||
api platform("com.fasterxml.jackson:jackson-bom:2.14.2")
|
||||
api platform("com.fasterxml.jackson:jackson-bom:2.14.3")
|
||||
constraints {
|
||||
api "ch.qos.logback:logback-classic:1.4.6"
|
||||
api "ch.qos.logback:logback-classic:1.4.8"
|
||||
api "com.google.inject:guice:3.0"
|
||||
api "com.nimbusds:nimbus-jose-jwt:9.24.4"
|
||||
api "com.nimbusds:oauth2-oidc-sdk:9.43.1"
|
||||
api "com.nimbusds:oauth2-oidc-sdk:9.43.3"
|
||||
api "com.squareup.okhttp3:mockwebserver:3.14.9"
|
||||
api "com.squareup.okhttp3:okhttp:3.14.9"
|
||||
api "com.unboundid:unboundid-ldapsdk:6.0.8"
|
||||
api "com.unboundid:unboundid-ldapsdk:6.0.9"
|
||||
api "commons-collections:commons-collections:3.2.2"
|
||||
api "io.mockk:mockk:1.13.5"
|
||||
api "io.micrometer:micrometer-observation:$micrometerVersion"
|
||||
@@ -38,7 +38,6 @@ dependencies {
|
||||
api "jakarta.websocket:jakarta.websocket-client-api:2.1.0"
|
||||
api "ldapsdk:ldapsdk:4.1"
|
||||
api "net.sourceforge.htmlunit:htmlunit:2.66.0"
|
||||
api "net.sourceforge.nekohtml:nekohtml:1.9.22"
|
||||
api "org.apache.directory.server:apacheds-core-entry:1.5.5"
|
||||
api "org.apache.directory.server:apacheds-core:1.5.5"
|
||||
api "org.apache.directory.server:apacheds-protocol-ldap:1.5.5"
|
||||
@@ -56,7 +55,7 @@ dependencies {
|
||||
api "jakarta.persistence:jakarta.persistence-api:3.1.0"
|
||||
api "org.hamcrest:hamcrest:2.2"
|
||||
api "org.hibernate.orm:hibernate-core:6.1.7.Final"
|
||||
api "org.hsqldb:hsqldb:2.7.1"
|
||||
api "org.hsqldb:hsqldb:2.7.2"
|
||||
api "org.jasig.cas.client:cas-client-core:3.6.4"
|
||||
api "org.opensaml:opensaml-core:$openSamlVersion"
|
||||
api "org.opensaml:opensaml-saml-api:$openSamlVersion"
|
||||
@@ -68,7 +67,7 @@ dependencies {
|
||||
api "org.skyscreamer:jsonassert:1.5.1"
|
||||
api "org.slf4j:log4j-over-slf4j:1.7.36"
|
||||
api "org.slf4j:slf4j-api:2.0.7"
|
||||
api "org.springframework.ldap:spring-ldap-core:3.0.2"
|
||||
api "org.springframework.ldap:spring-ldap-core:3.0.4"
|
||||
api "org.synchronoss.cloud:nio-multipart-parser:1.1.0"
|
||||
api 'org.apache.maven.resolver:maven-resolver-connector-basic:1.8.2'
|
||||
api 'org.apache.maven.resolver:maven-resolver-impl:1.8.2'
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
name: ROOT
|
||||
name: security
|
||||
version: true
|
||||
title: Documentation
|
||||
title: Spring Security
|
||||
nav:
|
||||
- modules/ROOT/nav.adoc
|
||||
ext:
|
||||
|
||||
@@ -125,6 +125,7 @@
|
||||
**** 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/proxy-server.adoc[Proxy Server Configuration]
|
||||
*** xref:servlet/appendix/faq.adoc[FAQ]
|
||||
* xref:reactive/index.adoc[Reactive Applications]
|
||||
** xref:reactive/getting-started.adoc[Getting Started]
|
||||
@@ -164,3 +165,5 @@
|
||||
**** xref:reactive/test/web/csrf.adoc[Testing CSRF]
|
||||
**** xref:reactive/test/web/oauth2.adoc[Testing OAuth 2.0]
|
||||
** xref:reactive/configuration/webflux.adoc[WebFlux Security]
|
||||
* xref:native-image/index.adoc[GraalVM Native Image Support]
|
||||
** xref:native-image/method-security.adoc[Method Security]
|
||||
|
||||
@@ -67,26 +67,31 @@ Instead Spring Security introduces `DelegatingPasswordEncoder`, which solves all
|
||||
You can easily construct an instance of `DelegatingPasswordEncoder` by using `PasswordEncoderFactories`:
|
||||
|
||||
.Create Default DelegatingPasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
PasswordEncoder passwordEncoder =
|
||||
PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val passwordEncoder: PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Alternatively, you can create your own custom instance:
|
||||
|
||||
.Create Custom DelegatingPasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
String idForEncode = "bcrypt";
|
||||
@@ -105,7 +110,8 @@ PasswordEncoder passwordEncoder =
|
||||
new DelegatingPasswordEncoder(idForEncode, encoders);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val idForEncode = "bcrypt"
|
||||
@@ -122,7 +128,7 @@ encoders["sha256"] = StandardPasswordEncoder()
|
||||
|
||||
val passwordEncoder: PasswordEncoder = DelegatingPasswordEncoder(idForEncode, encoders)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[authentication-password-storage-dpe-format]]
|
||||
=== Password Storage Format
|
||||
@@ -130,12 +136,10 @@ val passwordEncoder: PasswordEncoder = DelegatingPasswordEncoder(idForEncode, en
|
||||
The general format for a password is:
|
||||
|
||||
.DelegatingPasswordEncoder Storage Format
|
||||
====
|
||||
[source,text,attrs="-attributes"]
|
||||
----
|
||||
{id}encodedPassword
|
||||
----
|
||||
====
|
||||
|
||||
`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 `}`.
|
||||
@@ -144,7 +148,6 @@ For example, the following might be a list of passwords encoded using different
|
||||
All of the original passwords are `password`.
|
||||
|
||||
.DelegatingPasswordEncoder Encoded Passwords Example
|
||||
====
|
||||
[source,text,attrs="-attributes"]
|
||||
----
|
||||
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG // <1>
|
||||
@@ -153,7 +156,6 @@ All of the original passwords are `password`.
|
||||
{scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc= // <4>
|
||||
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0 // <5>
|
||||
----
|
||||
====
|
||||
|
||||
<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`
|
||||
@@ -182,12 +184,10 @@ In the `DelegatingPasswordEncoder` we constructed earlier, that means that the r
|
||||
The end result looks like the following example:
|
||||
|
||||
.DelegatingPasswordEncoder Encode Example
|
||||
====
|
||||
[source,text,attrs="-attributes"]
|
||||
----
|
||||
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
|
||||
----
|
||||
====
|
||||
|
||||
[[authentication-password-storage-dpe-matching]]
|
||||
=== Password Matching
|
||||
@@ -209,8 +209,10 @@ If you are putting together a demo or a sample, it is a bit cumbersome to take t
|
||||
There are convenience mechanisms to make this easier, but this is still not intended for production.
|
||||
|
||||
.withDefaultPasswordEncoder Example
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",attrs="-attributes"]
|
||||
----
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
@@ -222,7 +224,8 @@ System.out.println(user.getPassword());
|
||||
// {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
val user = User.withDefaultPasswordEncoder()
|
||||
@@ -233,13 +236,15 @@ val user = User.withDefaultPasswordEncoder()
|
||||
println(user.password)
|
||||
// {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If you are creating multiple users, you can also reuse the builder:
|
||||
|
||||
.withDefaultPasswordEncoder Reusing the Builder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
UserBuilder users = User.withDefaultPasswordEncoder();
|
||||
@@ -255,7 +260,8 @@ UserDetails admin = users
|
||||
.build();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val users = User.withDefaultPasswordEncoder()
|
||||
@@ -270,7 +276,7 @@ val admin = users
|
||||
.roles("USER", "ADMIN")
|
||||
.build()
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
This does hash the password that is stored, but the passwords are still exposed in memory and in the compiled source code.
|
||||
Therefore, it is still not considered secure for a production environment.
|
||||
@@ -284,26 +290,22 @@ The easiest way to properly encode your password is to use the https://docs.spri
|
||||
For example, the following example encodes the password of `password` for use with <<authentication-password-storage-dpe>>:
|
||||
|
||||
.Spring Boot CLI encodepassword Example
|
||||
====
|
||||
[source,attrs="-attributes"]
|
||||
----
|
||||
spring encodepassword password
|
||||
{bcrypt}$2a$10$X5wFBtLrL/kHcmrOGGTrGufsBX8CJ0WpQpF3pgeuxBB/H73BK1DW6
|
||||
----
|
||||
====
|
||||
|
||||
[[authentication-password-storage-dpe-troubleshoot]]
|
||||
=== Troubleshooting
|
||||
|
||||
The following error occurs when one of the passwords that are stored has no `id`, as described in <<authentication-password-storage-dpe-format>>.
|
||||
|
||||
====
|
||||
----
|
||||
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 it is to figure out how your passwords are currently being stored and explicitly provide the correct `PasswordEncoder`.
|
||||
|
||||
@@ -312,20 +314,16 @@ If you are migrating from Spring Security 4.2.x, you can revert to the previous
|
||||
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, see the Javadoc for
|
||||
https://docs.spring.io/spring-security/site/docs/5.0.x/api/org/springframework/security/crypto/factory/PasswordEncoderFactories.html[`PasswordEncoderFactories`].
|
||||
@@ -340,8 +338,10 @@ The default implementation of `BCryptPasswordEncoder` uses strength 10 as mentio
|
||||
tune and test the strength parameter on your own system so that it takes roughly 1 second to verify a password.
|
||||
|
||||
.BCryptPasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Create an encoder with strength 16
|
||||
@@ -350,7 +350,8 @@ String result = encoder.encode("myPassword");
|
||||
assertTrue(encoder.matches("myPassword", result));
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
// Create an encoder with strength 16
|
||||
@@ -358,7 +359,7 @@ val encoder = BCryptPasswordEncoder(16)
|
||||
val result: String = encoder.encode("myPassword")
|
||||
assertTrue(encoder.matches("myPassword", result))
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[authentication-password-storage-argon2]]
|
||||
== Argon2PasswordEncoder
|
||||
@@ -370,8 +371,10 @@ Like other adaptive one-way functions, it should be tuned to take about 1 second
|
||||
The current implementation of the `Argon2PasswordEncoder` requires BouncyCastle.
|
||||
|
||||
.Argon2PasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Create an encoder with all the defaults
|
||||
@@ -380,7 +383,8 @@ String result = encoder.encode("myPassword");
|
||||
assertTrue(encoder.matches("myPassword", result));
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
// Create an encoder with all the defaults
|
||||
@@ -388,7 +392,7 @@ val encoder = Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8()
|
||||
val result: String = encoder.encode("myPassword")
|
||||
assertTrue(encoder.matches("myPassword", result))
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[authentication-password-storage-pbkdf2]]
|
||||
== Pbkdf2PasswordEncoder
|
||||
@@ -399,8 +403,10 @@ Like other adaptive one-way functions, it should be tuned to take about 1 second
|
||||
This algorithm is a good choice when FIPS certification is required.
|
||||
|
||||
.Pbkdf2PasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Create an encoder with all the defaults
|
||||
@@ -409,7 +415,8 @@ String result = encoder.encode("myPassword");
|
||||
assertTrue(encoder.matches("myPassword", result));
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
// Create an encoder with all the defaults
|
||||
@@ -417,7 +424,7 @@ val encoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()
|
||||
val result: String = encoder.encode("myPassword")
|
||||
assertTrue(encoder.matches("myPassword", result))
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[authentication-password-storage-scrypt]]
|
||||
== SCryptPasswordEncoder
|
||||
@@ -427,8 +434,10 @@ To defeat password cracking on custom hardware, scrypt is a deliberately slow al
|
||||
Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system.
|
||||
|
||||
.SCryptPasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Create an encoder with all the defaults
|
||||
@@ -437,7 +446,8 @@ String result = encoder.encode("myPassword");
|
||||
assertTrue(encoder.matches("myPassword", result));
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
// Create an encoder with all the defaults
|
||||
@@ -445,7 +455,7 @@ val encoder = SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8()
|
||||
val result: String = encoder.encode("myPassword")
|
||||
assertTrue(encoder.matches("myPassword", result))
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[authentication-password-storage-other]]
|
||||
== Other ``PasswordEncoder``s
|
||||
@@ -470,8 +480,10 @@ You should instead migrate to using `DelegatingPasswordEncoder` to support secur
|
||||
====
|
||||
|
||||
.NoOpPasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -480,14 +492,16 @@ public static NoOpPasswordEncoder passwordEncoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<b:bean id="passwordEncoder"
|
||||
class="org.springframework.security.crypto.password.NoOpPasswordEncoder" factory-method="getInstance"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -495,7 +509,7 @@ fun passwordEncoder(): PasswordEncoder {
|
||||
return NoOpPasswordEncoder.getInstance();
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -513,36 +527,42 @@ You can configure Spring Security to provide this discovery endpoint.
|
||||
For example, if the change password endpoint in your application is `/change-password`, then you can configure Spring Security like so:
|
||||
|
||||
.Default Change Password Endpoint
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
http
|
||||
.passwordManagement(Customizer.withDefaults())
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:password-management/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
http {
|
||||
passwordManagement { }
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Then, when a password manager navigates to `/.well-known/change-password` then Spring Security will redirect your endpoint, `/change-password`.
|
||||
|
||||
Or, if your endpoint is something other than `/change-password`, you can also specify that like so:
|
||||
|
||||
.Change Password Endpoint
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
http
|
||||
@@ -551,13 +571,15 @@ http
|
||||
)
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:password-management change-password-page="/update-password"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
http {
|
||||
@@ -566,6 +588,6 @@ http {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
With the above configuration, when a password manager navigates to `/.well-known/change-password`, then Spring Security will redirect to `/update-password`.
|
||||
|
||||
@@ -25,7 +25,6 @@ Assume that your bank's website provides a form that allows transferring money f
|
||||
For example, the transfer form might look like:
|
||||
|
||||
.Transfer form
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<form method="post"
|
||||
@@ -40,12 +39,10 @@ For example, the transfer form might look like:
|
||||
value="Transfer"/>
|
||||
</form>
|
||||
----
|
||||
====
|
||||
|
||||
The corresponding HTTP request might look like:
|
||||
|
||||
.Transfer HTTP request
|
||||
====
|
||||
[source]
|
||||
----
|
||||
POST /transfer HTTP/1.1
|
||||
@@ -55,13 +52,11 @@ Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
amount=100.00&routingNumber=1234&account=9876
|
||||
----
|
||||
====
|
||||
|
||||
Now pretend you authenticate to your bank's website and then, without logging out, visit an evil website.
|
||||
The evil website contains an HTML page with the following form:
|
||||
|
||||
.Evil transfer form
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<form method="post"
|
||||
@@ -79,7 +74,6 @@ The evil website contains an HTML page with the following form:
|
||||
value="Win Money!"/>
|
||||
</form>
|
||||
----
|
||||
====
|
||||
|
||||
You like to win money, so you click on the submit button.
|
||||
In the process, you have unintentionally transferred $100 to a malicious user.
|
||||
@@ -134,7 +128,6 @@ Assume that the actual CSRF token is required to be in an HTTP parameter named `
|
||||
Our application's transfer form would look like:
|
||||
|
||||
.Synchronizer Token Form
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<form method="post"
|
||||
@@ -152,7 +145,6 @@ Our application's transfer form would look like:
|
||||
value="Transfer"/>
|
||||
</form>
|
||||
----
|
||||
====
|
||||
|
||||
The form now contains a hidden input with the value of the CSRF token.
|
||||
External sites cannot read the CSRF token since the same origin policy ensures the evil site cannot read the response.
|
||||
@@ -160,7 +152,6 @@ External sites cannot read the CSRF token since the same origin policy ensures t
|
||||
The corresponding HTTP request to transfer money would look like this:
|
||||
|
||||
.Synchronizer Token request
|
||||
====
|
||||
[source]
|
||||
----
|
||||
POST /transfer HTTP/1.1
|
||||
@@ -170,7 +161,6 @@ Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
amount=100.00&routingNumber=1234&account=9876&_csrf=4bfd1575-3ad1-4d21-96c7-4ef2d9f86721
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
You will notice that the HTTP request now contains the `_csrf` parameter with a secure random value.
|
||||
@@ -191,12 +181,10 @@ Spring Framework's https://docs.spring.io/spring-framework/docs/current/javadoc-
|
||||
An example, of an HTTP response header with the `SameSite` attribute might look like:
|
||||
|
||||
.SameSite HTTP response
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Set-Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly; SameSite=Lax
|
||||
----
|
||||
====
|
||||
|
||||
Valid values for the `SameSite` attribute are:
|
||||
|
||||
@@ -245,7 +233,6 @@ However, you must be very careful, as there are CSRF exploits that can impact JS
|
||||
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
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<form action="https://bank.example.com/transfer" method="post" enctype="text/plain">
|
||||
@@ -254,13 +241,11 @@ For example, a malicious user can create a http://blog.opensecurityresearch.com/
|
||||
value="Win Money!"/>
|
||||
</form>
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
This produces the following JSON structure
|
||||
|
||||
.CSRF with JSON request
|
||||
====
|
||||
[source,javascript]
|
||||
----
|
||||
{ "amount": 100,
|
||||
@@ -269,13 +254,11 @@ This produces the following JSON structure
|
||||
"ignore_me": "=test"
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
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
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<form action="https://bank.example.com/transfer.json" method="post" enctype="text/plain">
|
||||
@@ -284,7 +267,6 @@ Depending on the setup, a Spring MVC application that validates the Content-Type
|
||||
value="Win Money!"/>
|
||||
</form>
|
||||
----
|
||||
====
|
||||
|
||||
[[csrf-when-stateless]]
|
||||
=== CSRF and Stateless Browser Applications
|
||||
@@ -394,7 +376,6 @@ 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
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<form action="/process"
|
||||
@@ -405,7 +386,6 @@ For example, the following form can treat the HTTP method as a `delete` rather t
|
||||
value="delete"/>
|
||||
</form>
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
Overriding the HTTP method occurs in a filter.
|
||||
|
||||
@@ -24,7 +24,6 @@ Spring Security provides a default set of security related HTTP response headers
|
||||
The default for Spring Security is to include the following headers:
|
||||
|
||||
.Default Security HTTP Response Headers
|
||||
====
|
||||
[source,http]
|
||||
----
|
||||
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
|
||||
@@ -35,7 +34,6 @@ Strict-Transport-Security: max-age=31536000 ; includeSubDomains
|
||||
X-Frame-Options: DENY
|
||||
X-XSS-Protection: 0
|
||||
----
|
||||
====
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -65,14 +63,12 @@ If a user authenticates to view sensitive information and then logs out, we do n
|
||||
The cache control headers that are sent by default are:
|
||||
|
||||
.Default Cache Control HTTP Response Headers
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
|
||||
Pragma: no-cache
|
||||
Expires: 0
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
@@ -105,12 +101,10 @@ A malicious user might create a http://webblaze.cs.berkeley.edu/papers/barth-cab
|
||||
By default, Spring Security disables content sniffing by adding the following header to HTTP responses:
|
||||
|
||||
.nosniff HTTP Response Header
|
||||
====
|
||||
[source,http]
|
||||
----
|
||||
X-Content-Type-Options: nosniff
|
||||
----
|
||||
====
|
||||
|
||||
[[headers-hsts]]
|
||||
== HTTP Strict Transport Security (HSTS)
|
||||
@@ -140,12 +134,10 @@ For example, Spring Security's default behavior is to add the following header,
|
||||
|
||||
|
||||
.Strict Transport Security HTTP Response Header
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Strict-Transport-Security: max-age=31536000 ; includeSubDomains ; preload
|
||||
----
|
||||
====
|
||||
|
||||
The optional `includeSubDomains` directive instructs the browser that subdomains (such as `secure.mybank.example.com`) should also be treated as an HSTS domain.
|
||||
|
||||
@@ -193,12 +185,10 @@ While not perfect, the frame breaking code is the best you can do for the legacy
|
||||
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 by using with the following header:
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
X-Frame-Options: DENY
|
||||
----
|
||||
====
|
||||
|
||||
[[headers-xss-protection]]
|
||||
== X-XSS-Protection
|
||||
@@ -213,12 +203,10 @@ The filter has been deprecated in major browsers, and https://cheatsheetseries.o
|
||||
|
||||
By default, Spring Security blocks the content by using the following header:
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
X-XSS-Protection: 0
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
[[headers-csp]]
|
||||
@@ -250,12 +238,10 @@ A security policy contains a set of security policy directives, each responsible
|
||||
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
|
||||
====
|
||||
[source]
|
||||
----
|
||||
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 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.
|
||||
@@ -263,12 +249,10 @@ Additionally, if the https://www.w3.org/TR/CSP2/#directive-report-uri[report-uri
|
||||
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
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Content-Security-Policy: script-src https://trustedscripts.example.com; report-uri /csp-report-endpoint/
|
||||
----
|
||||
====
|
||||
|
||||
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/.
|
||||
|
||||
@@ -279,12 +263,10 @@ When a policy is deemed effective, it can be enforced by using the `Content-Secu
|
||||
Given the following response header, the policy declares that scripts can be loaded from one of two possible sources.
|
||||
|
||||
.Content Security Policy Report Only
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Content-Security-Policy-Report-Only: script-src 'self' https://trustedscripts.example.com; report-uri /csp-report-endpoint/
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
|
||||
@@ -311,12 +293,10 @@ page the user was on.
|
||||
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
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Referrer-Policy: same-origin
|
||||
----
|
||||
====
|
||||
|
||||
The Referrer-Policy response header instructs the browser to let the destination knows the source where the user was previously.
|
||||
|
||||
@@ -331,12 +311,10 @@ See the relevant sections to see how to configure both xref:servlet/exploits/hea
|
||||
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
|
||||
====
|
||||
[source]
|
||||
----
|
||||
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.
|
||||
These policies restrict what APIs the site can access or modify the browser's default behavior for certain features.
|
||||
@@ -353,12 +331,10 @@ See the relevant sections to see how to configure both xref:servlet/exploits/hea
|
||||
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
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Permissions-Policy: geolocation=(self)
|
||||
----
|
||||
====
|
||||
|
||||
With Permissions 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.
|
||||
@@ -374,12 +350,10 @@ See the relevant sections to see how to configure both xref:servlet/exploits/hea
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -14,8 +14,10 @@ It wraps a delegate `Runnable` in order to initialize the `SecurityContextHolder
|
||||
It then invokes the delegate Runnable ensuring to clear the `SecurityContextHolder` afterwards.
|
||||
The `DelegatingSecurityContextRunnable` looks something like this:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public void run() {
|
||||
@@ -28,7 +30,8 @@ try {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
fun run() {
|
||||
@@ -40,7 +43,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.
|
||||
@@ -48,8 +51,10 @@ For example, you might have used Spring Security's xref:servlet/appendix/namespa
|
||||
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:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Runnable originalRunnable = new Runnable() {
|
||||
@@ -65,7 +70,8 @@ DelegatingSecurityContextRunnable wrappedRunnable =
|
||||
new Thread(wrappedRunnable).start();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val originalRunnable = Runnable {
|
||||
@@ -76,7 +82,7 @@ val wrappedRunnable = DelegatingSecurityContextRunnable(originalRunnable, contex
|
||||
|
||||
Thread(wrappedRunnable).start()
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The code above performs the following steps:
|
||||
|
||||
@@ -90,8 +96,10 @@ Since it is quite common to create a `DelegatingSecurityContextRunnable` with th
|
||||
The following code is the same as the code above:
|
||||
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Runnable originalRunnable = new Runnable() {
|
||||
@@ -106,7 +114,8 @@ DelegatingSecurityContextRunnable wrappedRunnable =
|
||||
new Thread(wrappedRunnable).start();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val originalRunnable = Runnable {
|
||||
@@ -117,7 +126,7 @@ val wrappedRunnable = DelegatingSecurityContextRunnable(originalRunnable)
|
||||
|
||||
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.
|
||||
@@ -131,8 +140,10 @@ The design of `DelegatingSecurityContextExecutor` is very similar to that of `De
|
||||
You can see an example of how it might be used below:
|
||||
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
@@ -154,7 +165,8 @@ public void run() {
|
||||
executor.execute(originalRunnable);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val context: SecurityContext = SecurityContextHolder.createEmptyContext()
|
||||
@@ -171,7 +183,7 @@ val originalRunnable = Runnable {
|
||||
|
||||
executor.execute(originalRunnable)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The code performs the following steps:
|
||||
|
||||
@@ -185,8 +197,10 @@ In this instance, the same `SecurityContext` will be used for every Runnable sub
|
||||
This is nice if we are running background tasks that need to be run by a user with elevated privileges.
|
||||
* At this point you may be asking 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`.
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Autowired
|
||||
@@ -202,7 +216,8 @@ executor.execute(originalRunnable);
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Autowired
|
||||
@@ -215,7 +230,7 @@ fun submitRunnable() {
|
||||
executor.execute(originalRunnable)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Now our code is unaware that the `SecurityContext` is being propagated to the `Thread`, then the `originalRunnable` is run, and then the `SecurityContextHolder` is cleared out.
|
||||
In this example, the same user is being used to run each thread.
|
||||
@@ -224,8 +239,10 @@ This can be done by removing the `SecurityContext` argument from our `Delegating
|
||||
For example:
|
||||
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
SimpleAsyncTaskExecutor delegateExecutor = new SimpleAsyncTaskExecutor();
|
||||
@@ -233,13 +250,14 @@ DelegatingSecurityContextExecutor executor =
|
||||
new DelegatingSecurityContextExecutor(delegateExecutor);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val delegateExecutor = SimpleAsyncTaskExecutor()
|
||||
val executor = DelegatingSecurityContextExecutor(delegateExecutor)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Now anytime `executor.execute(Runnable)` is executed 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.
|
||||
|
||||
@@ -23,19 +23,22 @@ Both `BytesEncryptor` and `TextEncryptor` are interfaces. `BytesEncryptor` has m
|
||||
You can use the `Encryptors.stronger` factory method to construct a `BytesEncryptor`:
|
||||
|
||||
.BytesEncryptor
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Encryptors.stronger("password", "salt");
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
Encryptors.stronger("password", "salt")
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The `stronger` encryption method creates an encryptor by using 256-bit AES encryption with
|
||||
Galois Counter Mode (GCM).
|
||||
@@ -49,19 +52,22 @@ The provided salt should be in hex-encoded String form, be random, and be at lea
|
||||
You can generate such a salt by using a `KeyGenerator`:
|
||||
|
||||
.Generating a key
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
String salt = KeyGenerators.string().generateKey(); // generates a random 8-byte salt that is then hex-encoded
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val salt = KeyGenerators.string().generateKey() // generates a random 8-byte salt that is then hex-encoded
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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
|
||||
@@ -73,19 +79,22 @@ For a more secure alternative, use `Encryptors.stronger`.
|
||||
You can use the `Encryptors.text` factory method to construct a standard TextEncryptor:
|
||||
|
||||
.TextEncryptor
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Encryptors.text("password", "salt");
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
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 a database.
|
||||
@@ -101,81 +110,92 @@ You can also construct a {security-api-url}org/springframework/security/crypto/k
|
||||
You can use the `KeyGenerators.secureRandom` factory methods to generate a `BytesKeyGenerator` backed by a `SecureRandom` instance:
|
||||
|
||||
.BytesKeyGenerator
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
BytesKeyGenerator generator = KeyGenerators.secureRandom();
|
||||
byte[] key = generator.generateKey();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val generator = KeyGenerators.secureRandom()
|
||||
val key = generator.generateKey()
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The default key length is 8 bytes.
|
||||
A `KeyGenerators.secureRandom` variant provides control over the key length:
|
||||
|
||||
.KeyGenerators.secureRandom
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
KeyGenerators.secureRandom(16);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
KeyGenerators.secureRandom(16)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Use the `KeyGenerators.shared` factory method to construct a BytesKeyGenerator that always returns the same key on every invocation:
|
||||
|
||||
.KeyGenerators.shared
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
KeyGenerators.shared(16);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
KeyGenerators.shared(16)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
=== StringKeyGenerator
|
||||
You can use the `KeyGenerators.string` factory method to construct an 8-byte, `SecureRandom` `KeyGenerator` that hex-encodes each key as a `String`:
|
||||
|
||||
.StringKeyGenerator
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
KeyGenerators.string();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
KeyGenerators.string()
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[spring-security-crypto-passwordencoders]]
|
||||
== Password Encoding
|
||||
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 {
|
||||
@@ -188,7 +208,6 @@ public interface PasswordEncoder {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The `matches` method returns true if the `rawPassword`, once encoded, equals the `encodedPassword`.
|
||||
This method is designed to support password-based authentication schemes.
|
||||
@@ -202,8 +221,10 @@ You can change this value in your deployed system without affecting existing pas
|
||||
The following example uses the `BCryptPasswordEncoder`:
|
||||
|
||||
.BCryptPasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
|
||||
@@ -213,7 +234,8 @@ String result = encoder.encode("myPassword");
|
||||
assertTrue(encoder.matches("myPassword", result));
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
|
||||
@@ -222,7 +244,7 @@ val encoder = BCryptPasswordEncoder(16)
|
||||
val result: String = encoder.encode("myPassword")
|
||||
assertTrue(encoder.matches("myPassword", result))
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The `Pbkdf2PasswordEncoder` implementation uses PBKDF2 algorithm to hash the passwords.
|
||||
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.
|
||||
@@ -230,8 +252,10 @@ The following system uses the `Pbkdf2PasswordEncoder`:
|
||||
|
||||
|
||||
.Pbkdf2PasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Create an encoder with all the defaults
|
||||
@@ -240,7 +264,8 @@ String result = encoder.encode("myPassword");
|
||||
assertTrue(encoder.matches("myPassword", result));
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
// Create an encoder with all the defaults
|
||||
@@ -248,4 +273,4 @@ val encoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()
|
||||
val result: String = encoder.encode("myPassword")
|
||||
assertTrue(encoder.matches("myPassword", result))
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -10,8 +10,10 @@ It is not only useful but necessary to include the user in the queries to suppor
|
||||
To use this support, add `org.springframework.security:spring-security-data` dependency and provide a bean of type `SecurityEvaluationContextExtension`.
|
||||
In Java Configuration, this would look like:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -20,7 +22,8 @@ public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -28,7 +31,7 @@ fun securityEvaluationContextExtension(): SecurityEvaluationContextExtension {
|
||||
return SecurityEvaluationContextExtension()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
In XML Configuration, this would look like:
|
||||
|
||||
@@ -43,8 +46,10 @@ In XML Configuration, this would look like:
|
||||
Now Spring Security can be used within your queries.
|
||||
For example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Repository
|
||||
@@ -54,7 +59,8 @@ public interface MessageRepository extends PagingAndSortingRepository<Message,Lo
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Repository
|
||||
@@ -63,7 +69,7 @@ interface MessageRepository : PagingAndSortingRepository<Message?, Long?> {
|
||||
fun findInbox(pageable: Pageable?): Page<Message?>?
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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.
|
||||
|
||||
@@ -6,8 +6,10 @@ This can improve the performance of serializing Spring Security related classes
|
||||
|
||||
To use it, register the `SecurityJackson2Modules.getModules(ClassLoader)` with `ObjectMapper` (https://github.com/FasterXML/jackson-databind[jackson-databind]):
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
@@ -21,7 +23,8 @@ SecurityContext context = new SecurityContextImpl();
|
||||
String json = mapper.writeValueAsString(context);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val mapper = ObjectMapper()
|
||||
@@ -34,7 +37,7 @@ val context: SecurityContext = SecurityContextImpl()
|
||||
// ...
|
||||
val json: String = mapper.writeValueAsString(context)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
|
||||
@@ -29,7 +29,6 @@ Alternatively, you can manually add the starter, as the following example shows:
|
||||
|
||||
|
||||
.pom.xml
|
||||
====
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<dependencies>
|
||||
@@ -40,13 +39,11 @@ Alternatively, you can manually add the starter, as the following example shows:
|
||||
</dependency>
|
||||
</dependencies>
|
||||
----
|
||||
====
|
||||
|
||||
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 can do so by providing a Maven property:
|
||||
|
||||
.pom.xml
|
||||
====
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<properties>
|
||||
@@ -54,14 +51,12 @@ If you wish to override the Spring Security version, you can do so by providing
|
||||
<spring-security.version>{spring-security-version}</spring-security.version>
|
||||
</properties>
|
||||
----
|
||||
====
|
||||
|
||||
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:
|
||||
|
||||
.pom.xml
|
||||
====
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<properties>
|
||||
@@ -69,7 +64,6 @@ You can do so by adding a Maven property:
|
||||
<spring.version>{spring-core-version}</spring.version>
|
||||
</properties>
|
||||
----
|
||||
====
|
||||
|
||||
If you use additional features (such as LDAP, OAuth 2, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies].
|
||||
|
||||
@@ -79,7 +73,6 @@ If you use additional features (such as LDAP, OAuth 2, and others), you need to
|
||||
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
|
||||
====
|
||||
[source,xml,ubs="verbatim,attributes"]
|
||||
----
|
||||
<dependencyManagement>
|
||||
@@ -95,12 +88,10 @@ When you use Spring Security without Spring Boot, the preferred way is to use Sp
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
----
|
||||
====
|
||||
|
||||
A minimal Spring Security Maven set of dependencies typically looks like the following example:
|
||||
|
||||
.pom.xml
|
||||
====
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<dependencies>
|
||||
@@ -115,7 +106,6 @@ A minimal Spring Security Maven set of dependencies typically looks like the fol
|
||||
</dependency>
|
||||
</dependencies>
|
||||
----
|
||||
====
|
||||
|
||||
If you use additional features (such as LDAP, OAuth 2, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies].
|
||||
|
||||
@@ -124,7 +114,6 @@ Many users are likely to run afoul of the fact that Spring Security's transitive
|
||||
The easiest way to resolve this is to use the `spring-framework-bom` within the `<dependencyManagement>` section of your `pom.xml`:
|
||||
|
||||
.pom.xml
|
||||
====
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<dependencyManagement>
|
||||
@@ -140,7 +129,6 @@ The easiest way to resolve this is to use the `spring-framework-bom` within the
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
----
|
||||
====
|
||||
|
||||
The preceding example ensures that all the transitive dependencies of Spring Security use the Spring {spring-core-version} modules.
|
||||
|
||||
@@ -157,7 +145,6 @@ All GA releases (that is, versions ending in .RELEASE) are deployed to Maven Cen
|
||||
If you use a SNAPSHOT version, you need to ensure that you have the Spring Snapshot repository defined:
|
||||
|
||||
.pom.xml
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<repositories>
|
||||
@@ -169,12 +156,10 @@ If you use a SNAPSHOT version, you need to ensure that you have the Spring Snaps
|
||||
</repository>
|
||||
</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:
|
||||
|
||||
.pom.xml
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<repositories>
|
||||
@@ -186,7 +171,6 @@ If you use a milestone or release candidate version, you need to ensure that you
|
||||
</repository>
|
||||
</repositories>
|
||||
----
|
||||
====
|
||||
|
||||
[[getting-gradle]]
|
||||
== Gradle
|
||||
@@ -203,7 +187,6 @@ The simplest and preferred method to use the starter is to use https://docs.spri
|
||||
Alternatively, you can manually add the starter:
|
||||
|
||||
.build.gradle
|
||||
====
|
||||
[source,groovy]
|
||||
[subs="verbatim,attributes"]
|
||||
----
|
||||
@@ -211,32 +194,27 @@ dependencies {
|
||||
compile "org.springframework.boot:spring-boot-starter-security"
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
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 can do so by providing a Gradle property:
|
||||
|
||||
.build.gradle
|
||||
====
|
||||
[source,groovy]
|
||||
[subs="verbatim,attributes"]
|
||||
----
|
||||
ext['spring-security.version']='{spring-security-version}'
|
||||
----
|
||||
====
|
||||
|
||||
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:
|
||||
|
||||
.build.gradle
|
||||
====
|
||||
[source,groovy]
|
||||
[subs="verbatim,attributes"]
|
||||
----
|
||||
ext['spring.version']='{spring-core-version}'
|
||||
----
|
||||
====
|
||||
|
||||
If you use additional features (such as LDAP, OAuth 2, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies].
|
||||
|
||||
@@ -246,7 +224,6 @@ When you use Spring Security without Spring Boot, the preferred way is to use Sp
|
||||
You can do so by using the https://github.com/spring-gradle-plugins/dependency-management-plugin[Dependency Management Plugin]:
|
||||
|
||||
.build.gradle
|
||||
====
|
||||
[source,groovy]
|
||||
[subs="verbatim,attributes"]
|
||||
----
|
||||
@@ -260,12 +237,10 @@ dependencyManagement {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
A minimal Spring Security Maven set of dependencies typically looks like the following:
|
||||
|
||||
.build.gradle
|
||||
====
|
||||
[source,groovy]
|
||||
[subs="verbatim,attributes"]
|
||||
----
|
||||
@@ -274,7 +249,6 @@ dependencies {
|
||||
compile "org.springframework.security:spring-security-config"
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
If you use additional features (such as LDAP, OAuth 2, and others), you need to also include the appropriate xref:modules.adoc#modules[Project Modules and Dependencies].
|
||||
|
||||
@@ -284,7 +258,6 @@ The easiest way to resolve this is to use the `spring-framework-bom` within your
|
||||
You can do so by using the https://github.com/spring-gradle-plugins/dependency-management-plugin[Dependency Management Plugin]:
|
||||
|
||||
.build.gradle
|
||||
====
|
||||
[source,groovy]
|
||||
[subs="verbatim,attributes"]
|
||||
----
|
||||
@@ -298,7 +271,6 @@ dependencyManagement {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The preceding example ensures that all the transitive dependencies of Spring Security use the Spring {spring-core-version} modules.
|
||||
|
||||
@@ -307,35 +279,29 @@ The preceding example ensures that all the transitive dependencies of Spring Sec
|
||||
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
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
If you use a SNAPSHOT version, you need to ensure that you have the Spring Snapshot repository defined:
|
||||
|
||||
.build.gradle
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
repositories {
|
||||
maven { url 'https://repo.spring.io/snapshot' }
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
If you use a milestone or release candidate version, you need to ensure that you have the Spring Milestone repository defined:
|
||||
|
||||
.build.gradle
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
repositories {
|
||||
maven { url 'https://repo.spring.io/milestone' }
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
@@ -7,35 +7,41 @@ If you have already performed the xref:migration/index.adoc[initial migration st
|
||||
In 6.0, `@EnableReactiveMethodSecurity` defaults `useAuthorizationManager` to `true`.
|
||||
So, to complete migration, {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.html[`@EnableReactiveMethodSecurity`] remove the `useAuthorizationManager` attribute:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@EnableReactiveMethodSecurity(useAuthorizationManager = true)
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@EnableReactiveMethodSecurity(useAuthorizationManager = true)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
changes to:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@EnableReactiveMethodSecurity
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@EnableReactiveMethodSecurity
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
== Propagate ``AuthenticationServiceException``s
|
||||
|
||||
@@ -44,8 +50,10 @@ Because ``AuthenticationServiceException``s represent a server-side error instea
|
||||
|
||||
So, if you opted into this behavior by setting `rethrowAuthenticationServiceException` too `true`, you can now remove it like so:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
AuthenticationFailureHandler bearerFailureHandler = new ServerAuthenticationEntryPointFailureHandler(bearerEntryPoint);
|
||||
@@ -54,7 +62,8 @@ AuthenticationFailureHandler basicFailureHandler = new ServerAuthenticationEntry
|
||||
basicFailureHandler.setRethrowAuthenticationServiceException(true);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val bearerFailureHandler: AuthenticationFailureHandler = ServerAuthenticationEntryPointFailureHandler(bearerEntryPoint)
|
||||
@@ -62,25 +71,28 @@ bearerFailureHandler.setRethrowAuthenticationServiceException(true)
|
||||
val basicFailureHandler: AuthenticationFailureHandler = ServerAuthenticationEntryPointFailureHandler(basicEntryPoint)
|
||||
basicFailureHandler.setRethrowAuthenticationServiceException(true)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
changes to:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
AuthenticationFailureHandler bearerFailureHandler = new ServerAuthenticationEntryPointFailureHandler(bearerEntryPoint);
|
||||
AuthenticationFailureHandler basicFailureHandler = new ServerAuthenticationEntryPointFailureHandler(basicEntryPoint);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val bearerFailureHandler: AuthenticationFailureHandler = ServerAuthenticationEntryPointFailureHandler(bearerEntryPoint)
|
||||
val basicFailureHandler: AuthenticationFailureHandler = ServerAuthenticationEntryPointFailureHandler(basicEntryPoint)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
|
||||
@@ -4,13 +4,15 @@ The following steps relate to how to finish migrating authentication support.
|
||||
|
||||
== Propagate ``AuthenticationServiceException``s
|
||||
|
||||
{security-api-url}org/springframework/security/web/authentication/AuthenticationFilter.html[`AuthenticationFilter`] propagates {security-api-url}org/springframework/security/authentication/AuthenticationServiceException.html[``AuthenticationServiceException``]s to the {security-api-url}org/springframework/security/authentication/AuthenticationEntryPoint.html[`AuthenticationEntryPoint`].
|
||||
{security-api-url}org/springframework/security/web/authentication/AuthenticationFilter.html[`AuthenticationFilter`] propagates {security-api-url}org/springframework/security/authentication/AuthenticationServiceException.html[``AuthenticationServiceException``]s to the {security-api-url}org/springframework/security/web/AuthenticationEntryPoint.html[`AuthenticationEntryPoint`].
|
||||
Because ``AuthenticationServiceException``s represent a server-side error instead of a client-side error, in 6.0, this changes to propagate them to the container.
|
||||
|
||||
So, if you opted into this behavior by setting `rethrowAuthenticationServiceException` to `true`, you can now remove it like so:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
AuthenticationFilter authenticationFilter = new AuthenticationFilter(...);
|
||||
@@ -19,16 +21,18 @@ handler.setRethrowAuthenticationServiceException(true);
|
||||
authenticationFilter.setAuthenticationFailureHandler(handler);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val authenticationFilter: AuthenticationFilter = new AuthenticationFilter(...)
|
||||
val handler: AuthenticationEntryPointFailureHandler = new AuthenticationEntryPointFailureHandler(...)
|
||||
val authenticationFilter: AuthenticationFilter = AuthenticationFilter(...)
|
||||
val handler: AuthenticationEntryPointFailureHandler = AuthenticationEntryPointFailureHandler(...)
|
||||
handler.setRethrowAuthenticationServiceException(true)
|
||||
authenticationFilter.setAuthenticationFailureHandler(handler)
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<bean id="authenticationFilter" class="org.springframework.security.web.authentication.AuthenticationFilter">
|
||||
@@ -40,12 +44,14 @@ authenticationFilter.setAuthenticationFailureHandler(handler)
|
||||
<property name="rethrowAuthenticationServiceException" value="true"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
changes to:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
AuthenticationFilter authenticationFilter = new AuthenticationFilter(...);
|
||||
@@ -53,15 +59,17 @@ AuthenticationEntryPointFailureHandler handler = new AuthenticationEntryPointFai
|
||||
authenticationFilter.setAuthenticationFailureHandler(handler);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val authenticationFilter: AuthenticationFilter = new AuthenticationFilter(...)
|
||||
val handler: AuthenticationEntryPointFailureHandler = new AuthenticationEntryPointFailureHandler(...)
|
||||
val authenticationFilter: AuthenticationFilter = AuthenticationFilter(...)
|
||||
val handler: AuthenticationEntryPointFailureHandler = AuthenticationEntryPointFailureHandler(...)
|
||||
authenticationFilter.setAuthenticationFailureHandler(handler)
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<bean id="authenticationFilter" class="org.springframework.security.web.authentication.AuthenticationFilter">
|
||||
@@ -73,7 +81,7 @@ authenticationFilter.setAuthenticationFailureHandler(handler)
|
||||
<!-- ... -->
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-opt-in-sha256-rememberme]]
|
||||
== Use SHA-256 in Remember Me
|
||||
@@ -83,8 +91,10 @@ To complete the migration, any default values can be removed.
|
||||
|
||||
For example, if you opted in to the 6.0 default for `encodingAlgorithm` and `matchingAlgorithm` like so:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -108,7 +118,9 @@ public class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
.XML
|
||||
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -122,12 +134,14 @@ public class SecurityConfig {
|
||||
<property name="encodingAlgorithm" value="SHA256"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
then the defaults can be removed:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -148,7 +162,9 @@ public class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
.XML
|
||||
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -160,7 +176,7 @@ public class SecurityConfig {
|
||||
<property name="key" value="springRocks"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
== Default authorities for oauth2Login()
|
||||
|
||||
|
||||
@@ -13,23 +13,27 @@ So, to complete migration, remove any `websocket-message-broker@use-authorizatio
|
||||
|
||||
For example:
|
||||
|
||||
====
|
||||
.Xml
|
||||
[tabs]
|
||||
======
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="primary"]
|
||||
----
|
||||
<websocket-message-broker use-authorization-manager="true"/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
changes to:
|
||||
|
||||
====
|
||||
.Xml
|
||||
[tabs]
|
||||
======
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="primary"]
|
||||
----
|
||||
<websocket-message-broker/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
There are no further migrations steps for Java or Kotlin for this feature.
|
||||
|
||||
@@ -41,8 +45,10 @@ So, to complete migration, any defaults values can be removed.
|
||||
|
||||
For example, if you opted in to the 6.0 default for `filter-all-dispatcher-types` or `authorizeHttpRequests#filterAllDispatcherTypes` like so:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
http
|
||||
@@ -52,7 +58,8 @@ http
|
||||
)
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,java,role="secondary"]
|
||||
----
|
||||
http {
|
||||
@@ -63,17 +70,20 @@ http {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http use-authorization-manager="true" filter-all-dispatcher-types="true"/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
then the defaults may be removed:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
http
|
||||
@@ -82,7 +92,8 @@ http
|
||||
)
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,java,role="secondary"]
|
||||
----
|
||||
http {
|
||||
@@ -92,12 +103,13 @@ http {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
= GraalVM Native Image Support
|
||||
|
||||
Spring Boot 3.0 provides https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.introducing-graalvm-native-images[support for generating native images with GraalVM].
|
||||
Spring Security integrates with that support and provides its features ready for native images.
|
||||
|
||||
However, as mentioned in the https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.introducing-graalvm-native-images.understanding-aot-processing.hint-file-generation[Spring Boot documentation], there are some cases where we need to provide hints to be used by GraalVM.
|
||||
|
||||
This section aims to provide guidance in some Spring Security features that likely need to have additional hints provided by the application.
|
||||
@@ -0,0 +1,77 @@
|
||||
[[native-image-method-security]]
|
||||
= Method Security in GraalVM Native Image
|
||||
|
||||
Although xref:servlet/authorization/method-security.adoc[Method Security] is supported in GraalVM Native Image, there are some use cases that need additional hints provided by the application.
|
||||
|
||||
== Using `@PreAuthorize` and `@PostAuthorize` Annotations
|
||||
|
||||
Using `@PreAuthorize` and `@PostAuthorize` annotations require additional hints if you have a custom implementation of `UserDetails` or `Authentication` classes.
|
||||
|
||||
Let's take an example where you have a custom implementation of `UserDetails` class as follows and that implementation is returned by your `UserDetailsService`:
|
||||
|
||||
.Custom Implementation of UserDetails
|
||||
[source,java]
|
||||
----
|
||||
public class CustomUserDetails implements UserDetails {
|
||||
|
||||
private final String username;
|
||||
|
||||
private final String password;
|
||||
|
||||
private final Collection<? extends GrantedAuthority> authorities;
|
||||
|
||||
public boolean isAdmin() {
|
||||
return this.authorities.contains(new SimpleGrantedAuthority("ROLE_ADMIN"));
|
||||
}
|
||||
|
||||
// constructors, getters and setters
|
||||
}
|
||||
----
|
||||
|
||||
And you want to use the `isAdmin()` method inside a `@PreAuthorize` annotation as follows:
|
||||
|
||||
.Using isAdmin() to secure a method
|
||||
[source,java]
|
||||
----
|
||||
@PreAuthorize("principal?.isAdmin()")
|
||||
public String hello() {
|
||||
return "Hello!";
|
||||
}
|
||||
----
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
Remember that you need to xref:servlet/authorization/method-security.adoc#jc-enable-method-security[add `@EnableMethodSecurity` annotation] to your configuration class to enable method security annotations.
|
||||
====
|
||||
|
||||
If you https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.developing-your-first-application[run the native image] of your application with the above configuration, you will get an error similar to the following when trying to invoke the `hello()` method:
|
||||
|
||||
[source]
|
||||
----
|
||||
failed: java.lang.IllegalArgumentException: Failed to evaluate expression 'principal?.isAdmin()' with root cause
|
||||
org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method isAdmin() cannot be found on type com.mypackage.CustomUserDetails
|
||||
----
|
||||
|
||||
Which means that the `isAdmin()` method cannot be found on the `CustomUserDetails` class.
|
||||
This is because Spring Security uses reflection to invoke the `isAdmin()` method and GraalVM Native Image does not support reflection by default.
|
||||
|
||||
To fix this issue, you need to give hints to GraalVM Native Image to allow reflection on the `CustomUserDetails#isAdmin()` method.
|
||||
We can do that by providing a https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.advanced.custom-hints[custom hint].
|
||||
In this example we are going to use {spring-framework-reference-url}core.html#core.aot.hints.register-reflection-for-binding[the `@RegisterReflectionForBinding` annotation].
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
You might need to register all your classes that you want to use in your `@PreAuthorize` and `@PostAuthorize` annotations.
|
||||
====
|
||||
|
||||
.Using @RegisterReflectionForBinding
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
@RegisterReflectionForBinding(CustomUserDetails.class)
|
||||
public class MyConfiguration {
|
||||
//...
|
||||
}
|
||||
----
|
||||
|
||||
And that's it, now you can run the native image of your application and it should work as expected.
|
||||
@@ -11,7 +11,10 @@ This will:
|
||||
Often, you will want to also invalidate the session on logout.
|
||||
To achieve this, you can add the `WebSessionServerLogoutHandler` to your logout configuration, like so:
|
||||
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -28,7 +31,8 @@ SecurityWebFilterChain http(ServerHttpSecurity http) throws Exception {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -47,3 +51,4 @@ fun http(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
======
|
||||
|
||||
@@ -5,8 +5,10 @@ Similar to xref:servlet/authentication/x509.adoc#servlet-x509[Servlet X.509 auth
|
||||
|
||||
The following example shows a reactive x509 security configuration:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -20,7 +22,8 @@ public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -33,14 +36,16 @@ fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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 following example demonstrates how these defaults can be overridden:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -67,7 +72,8 @@ public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -89,7 +95,7 @@ fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -6,8 +6,10 @@ By default, Spring Security’s authorization will require all requests to be au
|
||||
The explicit configuration looks like:
|
||||
|
||||
.All Requests Require Authenticated User
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -22,7 +24,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -36,14 +39,16 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
We can configure Spring Security to have different rules by adding more rules in order of precedence.
|
||||
|
||||
.Multiple Authorize Requests Rules
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
import static org.springframework.security.authorization.AuthorityReactiveAuthorizationManager.hasRole;
|
||||
@@ -68,7 +73,8 @@ SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -88,7 +94,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
<1> There are multiple authorization rules specified.
|
||||
Each rule is considered in the order they were declared.
|
||||
|
||||
@@ -32,8 +32,10 @@ For earlier versions, please read about similar support with <<jc-enable-reactiv
|
||||
For example, the following would enable Spring Security's `@PreAuthorize` annotation:
|
||||
|
||||
.Method Security Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@EnableReactiveMethodSecurity(useAuthorizationManager=true)
|
||||
@@ -41,15 +43,17 @@ public 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 various method interceptors, like `AuthorizationManagerBeforeReactiveMethodInterceptor`, for it to make the actual decision:
|
||||
|
||||
.Method Security Annotation Usage
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public interface BankService {
|
||||
@@ -63,7 +67,7 @@ public interface BankService {
|
||||
Mono<Account> post(Account account, Double amount);
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
In this case `hasRole` refers to the method found in `SecurityExpressionRoot` that gets invoked by the SpEL evaluation engine.
|
||||
|
||||
@@ -71,8 +75,10 @@ In this case `hasRole` refers to the method found in `SecurityExpressionRoot` th
|
||||
A bean like that might look something like this:
|
||||
|
||||
.Method Security Reactive Boolean Expression
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -80,20 +86,22 @@ public Function<Account, Mono<Boolean>> func() {
|
||||
return (account) -> Mono.defer(() -> Mono.just(account.getId().equals(12)));
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
=== Customizing Authorization
|
||||
|
||||
Spring Security's `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` ship with rich expression-based support.
|
||||
|
||||
[[jc-reactive-method-security-custom-granted-authority-defaults]]
|
||||
|
||||
[[jc-reactive-method-security-custom-granted-authority-defaults]]
|
||||
Also, for role-based authorization, Spring Security adds a default `ROLE_` prefix, which is uses when evaluating expressions like `hasRole`.
|
||||
You can configure the authorization rules to use a different prefix by exposing a `GrantedAuthorityDefaults` bean, like so:
|
||||
|
||||
.Custom MethodSecurityExpressionHandler
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -101,7 +109,7 @@ static GrantedAuthorityDefaults grantedAuthorityDefaults() {
|
||||
return new GrantedAuthorityDefaults("MYPREFIX_");
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[TIP]
|
||||
====
|
||||
@@ -124,8 +132,10 @@ If that authorization denies access, the value is not returned, and an `AccessDe
|
||||
To recreate what adding `@EnableReactiveMethodSecurity(useAuthorizationManager=true)` does by default, you would publish the following configuration:
|
||||
|
||||
.Full Pre-post Method Security Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -160,15 +170,17 @@ class MethodSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Notice that Spring Security's method security is built using Spring AOP.
|
||||
So, interceptors are invoked based on the order specified.
|
||||
This can be customized by calling `setOrder` on the interceptor instances like so:
|
||||
|
||||
.Publish Custom Advisor
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -179,13 +191,15 @@ Advisor postFilterAuthorizationMethodInterceptor() {
|
||||
return interceptor;
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You may want to only support `@PreAuthorize` in your application, in which case you can do the following:
|
||||
|
||||
.Only @PreAuthorize Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -202,7 +216,7 @@ class MethodSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Or, you may have a custom before-method `ReactiveAuthorizationManager` that you want to add to the list.
|
||||
|
||||
@@ -211,9 +225,11 @@ In this case, you will need to tell Spring Security both the `ReactiveAuthorizat
|
||||
Thus, you can configure Spring Security to invoke your `ReactiveAuthorizationManager` in between `@PreAuthorize` and `@PostAuthorize` like so:
|
||||
|
||||
.Custom Before Advisor
|
||||
====
|
||||
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@EnableReactiveMethodSecurity(useAuthorizationManager=true)
|
||||
@@ -230,7 +246,7 @@ class MethodSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[TIP]
|
||||
====
|
||||
@@ -243,8 +259,10 @@ After-method authorization is generally concerned with analysing the return valu
|
||||
For example, you might have a method that confirms that the account requested actually belongs to the logged-in user like so:
|
||||
|
||||
.@PostAuthorize example
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public interface BankService {
|
||||
@@ -254,7 +272,7 @@ public interface BankService {
|
||||
Mono<Account> readAccount(Long id);
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can supply your own `AuthorizationMethodInterceptor` to customize how access to the return value is evaluated.
|
||||
|
||||
@@ -262,8 +280,10 @@ For example, if you have your own custom annotation, you can configure it like s
|
||||
|
||||
|
||||
.Custom After Advisor
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@EnableReactiveMethodSecurity(useAuthorizationManager=true)
|
||||
@@ -278,7 +298,7 @@ class MethodSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
and it will be invoked after the `@PostAuthorize` interceptor.
|
||||
|
||||
@@ -291,8 +311,10 @@ When intercepting coroutines, only the first interceptor participates.
|
||||
If any other interceptors are present and come after Spring Security's method security interceptor, https://github.com/spring-projects/spring-framework/issues/22462[they will be skipped].
|
||||
====
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
|
||||
@@ -309,7 +331,8 @@ StepVerifier.create(messageByUsername)
|
||||
.verifyComplete();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val authentication: Authentication = TestingAuthenticationToken("user", "password", "ROLE_USER")
|
||||
@@ -324,12 +347,14 @@ StepVerifier.create(messageByUsername)
|
||||
.expectNext("Hi user")
|
||||
.verifyComplete()
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Where `this::findMessageByUsername` is defined as:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Mono<String> findMessageByUsername(String username) {
|
||||
@@ -337,19 +362,22 @@ Mono<String> findMessageByUsername(String username) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
fun findMessageByUsername(username: String): Mono<String> {
|
||||
return Mono.just("Hi $username")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The following minimal method security configures method security in reactive applications:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -371,7 +399,8 @@ public class SecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -392,12 +421,14 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Consider the following class:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Component
|
||||
@@ -409,7 +440,8 @@ public class HelloWorldMessageService {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Component
|
||||
@@ -420,12 +452,14 @@ class HelloWorldMessageService {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Alternatively, the following class uses Kotlin coroutines:
|
||||
|
||||
====
|
||||
.Kotlin
|
||||
[tabs]
|
||||
======
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="primary"]
|
||||
----
|
||||
@Component
|
||||
@@ -437,7 +471,7 @@ class HelloWorldMessageService {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` ensures that `findByMessage` is invoked only by a user with the `ADMIN` role.
|
||||
@@ -447,8 +481,10 @@ 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:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -484,7 +520,8 @@ public class SecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -516,6 +553,6 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method].
|
||||
|
||||
@@ -14,8 +14,10 @@ A few sample applications demonstrate the code:
|
||||
The following listing shows a minimal WebFlux Security configuration:
|
||||
|
||||
.Minimal WebFlux Security Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
-----
|
||||
@Configuration
|
||||
@@ -34,7 +36,8 @@ public class HelloWebfluxSecurityConfig {
|
||||
}
|
||||
-----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
-----
|
||||
@Configuration
|
||||
@@ -52,7 +55,7 @@ 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 login page and a default logout page, sets up security related HTTP headers, adds CSRF protection, and more.
|
||||
|
||||
@@ -61,8 +64,10 @@ This configuration provides form and HTTP basic authentication, sets up authoriz
|
||||
The following page shows an explicit version of the minimal WebFlux Security configuration:
|
||||
|
||||
.Explicit WebFlux Security Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
-----
|
||||
@Configuration
|
||||
@@ -92,7 +97,8 @@ public class HelloWebfluxSecurityConfig {
|
||||
}
|
||||
-----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
-----
|
||||
import org.springframework.security.config.web.server.invoke
|
||||
@@ -123,7 +129,7 @@ class HelloWebfluxSecurityConfig {
|
||||
}
|
||||
}
|
||||
-----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
Make sure that you import the `invoke` function in your Kotlin class, sometimes the IDE will not auto-import it causing compilation issues.
|
||||
@@ -140,8 +146,10 @@ You can configure multiple `SecurityWebFilterChain` instances to separate config
|
||||
|
||||
For example, you can isolate configuration for URLs that start with `/api`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -179,7 +187,8 @@ static class MultiSecurityHttpConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
import org.springframework.security.config.web.server.invoke
|
||||
@@ -219,13 +228,13 @@ 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 selects one `SecurityWebFilterChain` `@Bean` for each request.
|
||||
It matches the requests in order by the `securityMatcher` definition.
|
||||
|
||||
@@ -35,8 +35,10 @@ These defaults come from https://docs.angularjs.org/api/ng/service/$http#cross-s
|
||||
You can configure `CookieServerCsrfTokenRepository` in Java Configuration:
|
||||
|
||||
.Store CSRF Token in a Cookie
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
-----
|
||||
@Bean
|
||||
@@ -48,7 +50,8 @@ public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http)
|
||||
}
|
||||
-----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
-----
|
||||
@Bean
|
||||
@@ -61,7 +64,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
-----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -78,8 +81,10 @@ However, you can disable CSRF protection if it xref:features/exploits/csrf.adoc#
|
||||
The Java configuration below will disable CSRF protection.
|
||||
|
||||
.Disable CSRF Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -91,7 +96,8 @@ public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http)
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
-----
|
||||
@Bean
|
||||
@@ -104,7 +110,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
-----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-csrf-configure-request-handler]]
|
||||
==== Configure ServerCsrfTokenRequestHandler
|
||||
@@ -117,8 +123,10 @@ As of 6.0, the default implementation is `XorServerCsrfTokenRequestAttributeHand
|
||||
If you wish to disable BREACH protection of the `CsrfToken` and revert to the 5.8 default, you can configure `ServerCsrfTokenRequestAttributeHandler` using the following Java configuration:
|
||||
|
||||
.Disable BREACH protection
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
-----
|
||||
@Bean
|
||||
@@ -132,7 +140,8 @@ public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http)
|
||||
}
|
||||
-----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
-----
|
||||
@Bean
|
||||
@@ -145,7 +154,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
-----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-csrf-include]]
|
||||
=== Include the CSRF Token
|
||||
@@ -161,8 +170,10 @@ If your view technology does not provide a simple way to subscribe to the `Mono<
|
||||
The following example places the `CsrfToken` on the default attribute name (`_csrf`) used by Spring Security's <<webflux-csrf-include-form-auto,CsrfRequestDataValueProcessor>> to automatically include the CSRF token as a hidden input:
|
||||
|
||||
.`CsrfToken` as `@ModelAttribute`
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@ControllerAdvice
|
||||
@@ -176,7 +187,8 @@ public class SecurityControllerAdvice {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@ControllerAdvice
|
||||
@@ -190,7 +202,7 @@ class SecurityControllerAdvice {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Fortunately, Thymeleaf provides <<webflux-csrf-include-form-auto,integration>> that works without any additional work.
|
||||
|
||||
@@ -200,14 +212,12 @@ To post an HTML form, the CSRF token must be included in the form as a hidden in
|
||||
The following example shows what the rendered HTML might look like:
|
||||
|
||||
.CSRF Token HTML
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<input type="hidden"
|
||||
name="_csrf"
|
||||
value="4bfd1575-3ad1-4d21-96c7-4ef2d9f86721"/>
|
||||
----
|
||||
====
|
||||
|
||||
Next, we discuss various ways of including the CSRF token in a form as a hidden input.
|
||||
|
||||
@@ -227,7 +237,6 @@ If the <<webflux-csrf-include,other options>> for including the actual CSRF toke
|
||||
The following Thymeleaf sample assumes that you <<webflux-csrf-include-subscribe,expose>> the `CsrfToken` on an attribute named `_csrf`:
|
||||
|
||||
.CSRF Token in Form with Request Attribute
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<form th:action="@{/logout}"
|
||||
@@ -239,7 +248,6 @@ The following Thymeleaf sample assumes that you <<webflux-csrf-include-subscribe
|
||||
th:value="${_csrf.token}"/>
|
||||
</form>
|
||||
----
|
||||
====
|
||||
|
||||
[[webflux-csrf-include-ajax]]
|
||||
==== Ajax and JSON Requests
|
||||
@@ -261,7 +269,6 @@ An alternative pattern to <<webflux-csrf-include-form-auto,exposing the CSRF in
|
||||
The HTML might look something like this:
|
||||
|
||||
.CSRF meta tag HTML
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<html>
|
||||
@@ -272,13 +279,11 @@ The HTML might look something like this:
|
||||
</head>
|
||||
<!-- ... -->
|
||||
----
|
||||
====
|
||||
|
||||
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
|
||||
====
|
||||
[source,javascript]
|
||||
----
|
||||
$(function () {
|
||||
@@ -289,13 +294,11 @@ $(function () {
|
||||
});
|
||||
});
|
||||
----
|
||||
====
|
||||
|
||||
The following sample assumes that you <<webflux-csrf-include-subscribe,expose>> the `CsrfToken` on an attribute named `_csrf`.
|
||||
The following example does this with Thymeleaf:
|
||||
|
||||
.CSRF meta tag JSP
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<html>
|
||||
@@ -307,7 +310,6 @@ The following example does this with Thymeleaf:
|
||||
</head>
|
||||
<!-- ... -->
|
||||
----
|
||||
====
|
||||
|
||||
[[webflux-csrf-considerations]]
|
||||
== CSRF Considerations
|
||||
@@ -339,8 +341,10 @@ For example, the following Java Configuration logs out when the `/logout` URL is
|
||||
// FIXME: This should be a link to log out documentation
|
||||
|
||||
.Log out with HTTP GET
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -352,7 +356,8 @@ public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http)
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -365,7 +370,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-considerations-csrf-timeouts]]
|
||||
@@ -401,8 +406,10 @@ We have xref:features/exploits/csrf.adoc#csrf-considerations-multipart[already d
|
||||
In a WebFlux application, you can do so with the following configuration:
|
||||
|
||||
.Enable obtaining CSRF token from multipart/form-data
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -414,7 +421,8 @@ public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http)
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -427,7 +435,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-csrf-considerations-multipart-url]]
|
||||
==== Include CSRF Token in URL
|
||||
@@ -437,14 +445,12 @@ Since the `CsrfToken` is exposed as an `ServerHttpRequest` <<webflux-csrf-includ
|
||||
An example with Thymeleaf is shown below:
|
||||
|
||||
.CSRF Token in Action
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<form method="post"
|
||||
th:action="@{/upload(${_csrf.parameterName}=${_csrf.token})}"
|
||||
enctype="multipart/form-data">
|
||||
----
|
||||
====
|
||||
|
||||
[[webflux-csrf-considerations-override-method]]
|
||||
=== HiddenHttpMethodFilter
|
||||
|
||||
@@ -16,8 +16,10 @@ For example, assume that you want the defaults but you wish to specify `SAMEORIG
|
||||
You can do so with the following configuration:
|
||||
|
||||
.Customize Default Security Headers
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -33,7 +35,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -48,14 +51,16 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If you do not want the defaults to be added and want explicit control over what should be used, you can disable the defaults:
|
||||
|
||||
|
||||
.Disable HTTP Security Response Headers
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -67,7 +72,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -80,7 +86,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-headers-cache-control]]
|
||||
== Cache Control
|
||||
@@ -96,8 +102,10 @@ You can find details on how to do so in the https://docs.spring.io/spring/docs/5
|
||||
If necessary, you can also disable Spring Security's cache control HTTP response headers.
|
||||
|
||||
.Cache Control Disabled
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -111,7 +119,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -126,7 +135,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-headers-content-type-options]]
|
||||
@@ -135,8 +144,10 @@ By default, Spring Security includes xref:features/exploits/headers.adoc#headers
|
||||
However, you can disable it:
|
||||
|
||||
.Content Type Options Disabled
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -150,7 +161,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -165,7 +177,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-headers-hsts]]
|
||||
== HTTP Strict Transport Security (HSTS)
|
||||
@@ -174,8 +186,10 @@ However, you can customize the results explicitly.
|
||||
For example, the following example explicitly provides HSTS:
|
||||
|
||||
.Strict Transport Security
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -193,7 +207,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -210,7 +225,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-headers-frame-options]]
|
||||
== X-Frame-Options
|
||||
@@ -219,8 +234,10 @@ By default, Spring Security disables rendering within an iframe by using xref:fe
|
||||
You can customize frame options to use the same origin:
|
||||
|
||||
.X-Frame-Options: SAMEORIGIN
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -236,7 +253,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -251,7 +269,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-headers-xss-protection]]
|
||||
== X-XSS-Protection
|
||||
@@ -259,8 +277,10 @@ By default, Spring Security instructs browsers to disable the XSS Auditor by usi
|
||||
You can disable the `X-XSS-Protection` header entirely:
|
||||
|
||||
.X-XSS-Protection Customization
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -274,7 +294,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -289,13 +310,15 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can also change the header value:
|
||||
|
||||
.X-XSS-Protection Explicit header value
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -309,7 +332,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -324,7 +348,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-headers-csp]]
|
||||
== Content Security Policy (CSP)
|
||||
@@ -334,18 +358,18 @@ The web application author must declare the security policies to enforce and/or
|
||||
For example, consider the following security policy:
|
||||
|
||||
.Content Security Policy Example
|
||||
====
|
||||
[source,http]
|
||||
----
|
||||
Content-Security-Policy: script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/
|
||||
----
|
||||
====
|
||||
|
||||
Given the preceding policy, you can enable the CSP header:
|
||||
|
||||
.Content Security Policy
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -361,7 +385,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -376,13 +401,15 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
To enable the CSP `report-only` header, provide the following configuration:
|
||||
|
||||
.Content Security Policy Report Only
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -399,7 +426,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -415,7 +443,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-headers-referrer]]
|
||||
== Referrer Policy
|
||||
@@ -424,8 +452,10 @@ By default, Spring Security does not add xref:features/exploits/headers.adoc#hea
|
||||
You can enable the Referrer Policy header using configuration as shown below:
|
||||
|
||||
.Referrer Policy Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -441,7 +471,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -456,7 +487,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-headers-feature]]
|
||||
@@ -466,18 +497,18 @@ By default, Spring Security does not add xref:features/exploits/headers.adoc#hea
|
||||
Consider the following `Feature-Policy` header:
|
||||
|
||||
.Feature-Policy Example
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Feature-Policy: geolocation 'self'
|
||||
----
|
||||
====
|
||||
|
||||
You can enable the preceding Feature Policy header:
|
||||
|
||||
.Feature-Policy Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -491,7 +522,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -504,7 +536,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-headers-permissions]]
|
||||
@@ -514,18 +546,18 @@ By default, Spring Security does not add xref:features/exploits/headers.adoc#hea
|
||||
Consider the following `Permissions-Policy` header:
|
||||
|
||||
.Permissions-Policy Example
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Permissions-Policy: geolocation=(self)
|
||||
----
|
||||
====
|
||||
|
||||
You can enable the preceding Permissions Policy header:
|
||||
|
||||
.Permissions-Policy Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -541,7 +573,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -556,7 +589,7 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-headers-clear-site-data]]
|
||||
@@ -566,17 +599,17 @@ By default, Spring Security does not add xref:features/exploits/headers.adoc#hea
|
||||
Consider the following `Clear-Site-Data` header:
|
||||
|
||||
.Clear-Site-Data Example
|
||||
====
|
||||
----
|
||||
Clear-Site-Data: "cache", "cookies"
|
||||
----
|
||||
====
|
||||
|
||||
You can send the `Clear-Site-Data` header on logout:
|
||||
|
||||
.Clear-Site-Data Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -594,7 +627,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -612,4 +646,4 @@ fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -13,8 +13,10 @@ If a client makes a request using HTTP rather than HTTPS, you can configure Spri
|
||||
The following Java configuration redirects any HTTP requests to HTTPS:
|
||||
|
||||
.Redirect to HTTPS
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -26,7 +28,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -37,15 +40,17 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -59,7 +64,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -74,7 +80,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-hsts]]
|
||||
== Strict Transport Security
|
||||
|
||||
@@ -14,8 +14,10 @@ For your convenience, you can download a minimal Reactive Spring Boot + Spring S
|
||||
|
||||
You can add Spring Security to your Spring Boot project by adding `spring-boot-starter-security`.
|
||||
|
||||
====
|
||||
.Maven
|
||||
[tabs]
|
||||
======
|
||||
Maven::
|
||||
+
|
||||
[source,xml,role="primary"]
|
||||
----
|
||||
<dependency>
|
||||
@@ -24,12 +26,13 @@ You can add Spring Security to your Spring Boot project by adding `spring-boot-s
|
||||
</dependency>
|
||||
----
|
||||
|
||||
.Gradle
|
||||
Gradle::
|
||||
+
|
||||
[source,groovy,role="secondary"]
|
||||
----
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[servlet-hello-starting]]
|
||||
@@ -38,10 +41,12 @@ You can add Spring Security to your Spring Boot project by adding `spring-boot-s
|
||||
You can now https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-running-with-the-maven-plugin[run the Spring Boot application] by using the Maven Plugin's `run` goal.
|
||||
The following example shows how to do so (and the beginning of the output from doing so):
|
||||
|
||||
.Running Spring Boot Application
|
||||
|
||||
====
|
||||
.Maven
|
||||
.Running Spring Boot Application
|
||||
[tabs]
|
||||
======
|
||||
Maven::
|
||||
+
|
||||
[source,bash,role="primary"]
|
||||
----
|
||||
$ ./mvnw spring-boot:run
|
||||
@@ -53,7 +58,8 @@ Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336
|
||||
...
|
||||
----
|
||||
|
||||
.Gradle
|
||||
Gradle::
|
||||
+
|
||||
[source,bash,role="secondary"]
|
||||
----
|
||||
$ ./gradlew bootRun
|
||||
@@ -64,7 +70,7 @@ Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336
|
||||
|
||||
...
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[authenticating]]
|
||||
== Authenticating
|
||||
|
||||
@@ -10,8 +10,10 @@ The easiest way to ensure that CORS is handled first is to use the `CorsWebFilte
|
||||
Users can integrate the `CorsWebFilter` with Spring Security by providing a `CorsConfigurationSource`.
|
||||
For example, the following will integrate CORS support within Spring Security:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -25,7 +27,8 @@ CorsConfigurationSource corsConfigurationSource() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -38,12 +41,14 @@ fun corsConfigurationSource(): CorsConfigurationSource {
|
||||
return source
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The following will disable the CORS integration within Spring Security:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -55,7 +60,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -68,4 +74,4 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -17,8 +17,10 @@ When an `ObservationRegistry` bean is present, Spring Security creates traces fo
|
||||
|
||||
For example, consider a simple Boot application:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@SpringBootApplication
|
||||
@@ -45,7 +47,8 @@ public class MyApplication {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@SpringBootApplication
|
||||
@@ -72,20 +75,17 @@ class MyApplication {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
And a corresponding request:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
?> http -a user:password :8080
|
||||
----
|
||||
====
|
||||
|
||||
Will produce the following output (indentation added for clarity):
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
START - name='http.server.requests', contextualName='null', error='null', lowCardinalityKeyValues=[], highCardinalityKeyValues=[], map=[class io.micrometer.tracing.handler.TracingObservationHandler$TracingContext='io.micrometer.tracing.handler.TracingObservationHandler$TracingContext@5dfdb78', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=0.00191856, duration(nanos)=1918560.0, startTimeNanos=101177265022745}', class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@121549e0']
|
||||
@@ -101,15 +101,16 @@ START - name='http.server.requests', contextualName='null', error='null', lowCar
|
||||
STOP - name='spring.security.http.chains', contextualName='spring.security.http.chains.after', error='null', lowCardinalityKeyValues=[chain.size='14', filter.section='after'], highCardinalityKeyValues=[request.line='/'], map=[class io.micrometer.tracing.handler.TracingObservationHandler$TracingContext='io.micrometer.tracing.handler.TracingObservationHandler$TracingContext@40b25623', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=0.001693146, duration(nanos)=1693146.0, startTimeNanos=101178044824275}', class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@3b6cec2']
|
||||
STOP - name='http.server.requests', contextualName='null', error='null', lowCardinalityKeyValues=[], highCardinalityKeyValues=[], map=[class io.micrometer.tracing.handler.TracingObservationHandler$TracingContext='io.micrometer.tracing.handler.TracingObservationHandler$TracingContext@5dfdb78', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=0.784320641, duration(nanos)=7.84320641E8, startTimeNanos=101177265022745}', class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@121549e0']
|
||||
----
|
||||
====
|
||||
|
||||
[[webflux-observability-tracing-manual-configuration]]
|
||||
=== Manual Configuration
|
||||
|
||||
For a non-Spring Boot application, or to override the existing Boot configuration, you can publish your own `ObservationRegistry` and Spring Security will still pick it up.
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@SpringBootApplication
|
||||
@@ -138,7 +139,8 @@ public class MyApplication {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@SpringBootApplication
|
||||
@@ -167,7 +169,8 @@ class MyApplication {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
<sec:http auto-config="true" observation-registry-ref="ref">
|
||||
@@ -176,7 +179,7 @@ class MyApplication {
|
||||
|
||||
<!-- define and configure ObservationRegistry bean -->
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-observability-tracing-disable]]
|
||||
=== Disabling Observability
|
||||
@@ -186,8 +189,10 @@ However, this may turn off observations for more than just Spring Security.
|
||||
|
||||
Instead, you can alter the provided `ObservationRegistry` with an `ObservationPredicate` like the following:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -197,7 +202,8 @@ ObservationRegistryCustomizer<ObservationRegistry> noSpringSecurityObservations(
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -206,7 +212,7 @@ fun noSpringSecurityObservations(): ObservationRegistryCustomizer<ObservationReg
|
||||
(registry: ObservationRegistry) -> registry.observationConfig().observationPredicate(predicate)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[TIP]
|
||||
There is no facility for disabling observations with XML support.
|
||||
|
||||
@@ -14,8 +14,10 @@ The following example shows a minimal RSocket Security configuration:
|
||||
|
||||
You can find a minimal RSocket Security configuration below:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -34,7 +36,8 @@ public class HelloRSocketSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -51,7 +54,7 @@ open class HelloRSocketSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
This configuration enables <<rsocket-authentication-simple,simple authentication>> and sets up <<rsocket-authorization,rsocket-authorization>> to require an authenticated user for any request.
|
||||
|
||||
@@ -61,8 +64,10 @@ For Spring Security to work, we need to apply `SecuritySocketAcceptorInterceptor
|
||||
Doing so connects our `PayloadSocketAcceptorInterceptor` with the RSocket infrastructure.
|
||||
In a Spring Boot application, you can do this automatically by using `RSocketSecurityAutoConfiguration` with the following code:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -71,7 +76,8 @@ RSocketServerCustomizer springSecurityRSocketSecurity(SecuritySocketAcceptorInte
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -83,7 +89,7 @@ fun springSecurityRSocketSecurity(interceptor: SecuritySocketAcceptorInterceptor
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[rsocket-authentication]]
|
||||
== RSocket Authentication
|
||||
@@ -123,8 +129,10 @@ See `RSocketSecurity.basicAuthentication(Customizer)` for setting it up.
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -140,7 +148,8 @@ PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -154,30 +163,35 @@ open fun rsocketInterceptor(rsocket: RSocketSecurity): PayloadSocketAcceptorInte
|
||||
return rsocket.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The RSocket sender can send credentials by using `SimpleAuthenticationEncoder`, which you can add to Spring's `RSocketStrategies`.
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
RSocketStrategies.Builder strategies = ...;
|
||||
strategies.encoder(new SimpleAuthenticationEncoder());
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
var strategies: RSocketStrategies.Builder = ...
|
||||
strategies.encoder(SimpleAuthenticationEncoder())
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can then use it to send a username and password to the receiver in the setup:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
MimeType authenticationMimeType =
|
||||
@@ -189,7 +203,8 @@ Mono<RSocketRequester> requester = RSocketRequester.builder()
|
||||
.connectTcp(host, port);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val authenticationMimeType: MimeType =
|
||||
@@ -200,12 +215,14 @@ val requester: Mono<RSocketRequester> = RSocketRequester.builder()
|
||||
.rsocketStrategies(strategies.build())
|
||||
.connectTcp(host, port)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Alternatively or additionally, a username and password can be sent in a request.
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Mono<RSocketRequester> requester;
|
||||
@@ -220,7 +237,8 @@ public Mono<AirportLocation> findRadar(String code) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
import org.springframework.messaging.rsocket.retrieveMono
|
||||
@@ -238,7 +256,7 @@ open fun findRadar(code: String): Mono<AirportLocation> {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[rsocket-authentication-jwt]]
|
||||
=== JWT
|
||||
@@ -249,8 +267,10 @@ The support comes in the form of authenticating a JWT (determining that the JWT
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -266,7 +286,8 @@ PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -280,13 +301,15 @@ fun rsocketInterceptor(rsocket: RSocketSecurity): PayloadSocketAcceptorIntercept
|
||||
return rsocket.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The configuration above relies on the existence of a `ReactiveJwtDecoder` `@Bean` being present.
|
||||
An example of creating one from the issuer can be found below:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -296,7 +319,8 @@ ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -305,13 +329,15 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
.fromIssuerLocation("https://example.com/auth/realms/demo")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
MimeType authenticationMimeType =
|
||||
@@ -322,7 +348,8 @@ Mono<RSocketRequester> requester = RSocketRequester.builder()
|
||||
.connectTcp(host, port);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val authenticationMimeType: MimeType =
|
||||
@@ -333,12 +360,14 @@ val requester = RSocketRequester.builder()
|
||||
.setupMetadata(token, authenticationMimeType)
|
||||
.connectTcp(host, port)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Alternatively or additionally, you can send the token in a request:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
MimeType authenticationMimeType =
|
||||
@@ -355,7 +384,8 @@ public Mono<AirportLocation> findRadar(String code) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val authenticationMimeType: MimeType =
|
||||
@@ -371,7 +401,7 @@ open fun findRadar(code: String): Mono<AirportLocation> {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[rsocket-authorization]]
|
||||
== RSocket Authorization
|
||||
@@ -380,8 +410,10 @@ RSocket authorization is performed with `AuthorizationPayloadInterceptor`, which
|
||||
You can use the DSL to set up authorization rules based upon the `PayloadExchange`.
|
||||
The following listing shows an example configuration:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
rsocket
|
||||
@@ -397,7 +429,9 @@ rsocket
|
||||
.anyExchange().permitAll() // <6>
|
||||
);
|
||||
----
|
||||
.Kotlin
|
||||
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
rsocket
|
||||
@@ -413,6 +447,7 @@ rsocket
|
||||
.anyExchange().permitAll()
|
||||
} // <6>
|
||||
----
|
||||
======
|
||||
<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.
|
||||
@@ -424,7 +459,6 @@ 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 also have no authorization rules.
|
||||
====
|
||||
|
||||
Note that authorization rules are performed in order.
|
||||
Only the first authorization rule that matches is invoked.
|
||||
|
||||
@@ -111,8 +111,10 @@ OPTIONAL. Space delimited, case sensitive list of ASCII string values that speci
|
||||
|
||||
The following example shows how to configure the `DefaultServerOAuth2AuthorizationRequestResolver` with a `Consumer<OAuth2AuthorizationRequest.Builder>` that customizes the Authorization Request for `oauth2Login()`, by including the request parameter `prompt=consent`.
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -155,7 +157,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -196,7 +199,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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.
|
||||
|
||||
@@ -221,8 +224,10 @@ Alternatively, if your requirements are more advanced, you can take full control
|
||||
|
||||
The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example, and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property.
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
|
||||
@@ -232,7 +237,8 @@ private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomi
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
|
||||
@@ -245,7 +251,7 @@ private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationReques
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
=== Storing the Authorization Request
|
||||
@@ -260,8 +266,10 @@ The default implementation of `ServerAuthorizationRequestRepository` is `WebSess
|
||||
If you have a custom implementation of `ServerAuthorizationRequestRepository`, you may configure it as shown in the following example:
|
||||
|
||||
.ServerAuthorizationRequestRepository Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -280,7 +288,8 @@ public class OAuth2ClientSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -299,7 +308,7 @@ class OAuth2ClientSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
=== Requesting an Access Token
|
||||
|
||||
@@ -335,8 +344,10 @@ Alternatively, if your requirements are more advanced, you can take full control
|
||||
Whether you customize `WebClientReactiveAuthorizationCodeTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example:
|
||||
|
||||
.Access Token Response Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -363,7 +374,8 @@ public class OAuth2ClientSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -389,7 +401,7 @@ class OAuth2ClientSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[oauth2Client-refresh-token-grant]]
|
||||
@@ -433,8 +445,10 @@ Alternatively, if your requirements are more advanced, you can take full control
|
||||
Whether you customize `WebClientReactiveRefreshTokenTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example:
|
||||
|
||||
.Access Token Response Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Customize
|
||||
@@ -451,7 +465,8 @@ ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
|
||||
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
// Customize
|
||||
@@ -466,7 +481,7 @@ val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveO
|
||||
|
||||
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
`ReactiveOAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenReactiveOAuth2AuthorizedClientProvider`,
|
||||
@@ -516,8 +531,10 @@ Alternatively, if your requirements are more advanced, you can take full control
|
||||
|
||||
Whether you customize `WebClientReactiveClientCredentialsTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Customize
|
||||
@@ -533,7 +550,8 @@ ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
|
||||
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
// Customize
|
||||
@@ -547,7 +565,7 @@ val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveO
|
||||
|
||||
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
`ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsReactiveOAuth2AuthorizedClientProvider`,
|
||||
@@ -576,8 +594,10 @@ spring:
|
||||
|
||||
...and the `ReactiveOAuth2AuthorizedClientManager` `@Bean`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -599,7 +619,8 @@ public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -615,12 +636,14 @@ fun authorizedClientManager(
|
||||
return authorizedClientManager
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You may obtain the `OAuth2AccessToken` as follows:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -644,7 +667,8 @@ public class OAuth2ClientController {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class OAuth2ClientController {
|
||||
@@ -666,7 +690,7 @@ class OAuth2ClientController {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
`ServerWebExchange` is an OPTIONAL attribute.
|
||||
@@ -713,8 +737,10 @@ Alternatively, if your requirements are more advanced, you can take full control
|
||||
|
||||
Whether you customize `WebClientReactivePasswordTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Customize
|
||||
@@ -731,7 +757,8 @@ ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
|
||||
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val passwordTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...
|
||||
@@ -745,7 +772,7 @@ val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.bui
|
||||
|
||||
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
`ReactiveOAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordReactiveOAuth2AuthorizedClientProvider`,
|
||||
@@ -774,8 +801,10 @@ spring:
|
||||
|
||||
...and the `ReactiveOAuth2AuthorizedClientManager` `@Bean`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -819,7 +848,9 @@ private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttri
|
||||
};
|
||||
}
|
||||
----
|
||||
.Kotlin
|
||||
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -858,12 +889,14 @@ private fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, Mono<Mut
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You may obtain the `OAuth2AccessToken` as follows:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -887,7 +920,8 @@ public class OAuth2ClientController {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -909,7 +943,7 @@ class OAuth2ClientController {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
`ServerWebExchange` is an OPTIONAL attribute.
|
||||
@@ -955,8 +989,10 @@ Alternatively, if your requirements are more advanced, you can take full control
|
||||
|
||||
Whether you customize `WebClientReactiveJwtBearerTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you'll need to configure it as shown in the following example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Customize
|
||||
@@ -975,7 +1011,8 @@ ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
|
||||
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
// Customize
|
||||
@@ -992,7 +1029,7 @@ val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.bui
|
||||
|
||||
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
=== Using the Access Token
|
||||
|
||||
@@ -1017,8 +1054,10 @@ spring:
|
||||
|
||||
...and the `OAuth2AuthorizedClientManager` `@Bean`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -1043,7 +1082,8 @@ public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -1060,12 +1100,14 @@ fun authorizedClientManager(
|
||||
return authorizedClientManager
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You may obtain the `OAuth2AccessToken` as follows:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@RestController
|
||||
@@ -1087,7 +1129,8 @@ public class OAuth2ResourceServerController {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class OAuth2ResourceServerController {
|
||||
@@ -1106,7 +1149,7 @@ class OAuth2ResourceServerController {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
`JwtBearerReactiveOAuth2AuthorizedClientProvider` resolves the `Jwt` assertion via `OAuth2AuthorizationContext.getPrincipal().getPrincipal()` by default, hence the use of `JwtAuthenticationToken` in the preceding example.
|
||||
|
||||
@@ -8,8 +8,10 @@
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -24,7 +26,8 @@ public class OAuth2ClientController {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -37,7 +40,7 @@ class OAuth2ClientController {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The `@RegisteredOAuth2AuthorizedClient` annotation is handled by `OAuth2AuthorizedClientArgumentResolver`, which directly uses a <<oauth2Client-authorized-manager-provider, ReactiveOAuth2AuthorizedClientManager>> and therefore inherits it's capabilities.
|
||||
|
||||
@@ -58,8 +61,10 @@ It directly uses an <<oauth2Client-authorized-manager-provider, ReactiveOAuth2Au
|
||||
|
||||
The following code shows an example of how to configure `WebClient` with OAuth 2.0 Client support:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -72,7 +77,8 @@ WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManage
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -83,7 +89,7 @@ fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): W
|
||||
.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
=== Providing the Authorized Client
|
||||
|
||||
@@ -91,8 +97,10 @@ The `ServerOAuth2AuthorizedClientExchangeFilterFunction` determines the client t
|
||||
|
||||
The following code shows how to set an `OAuth2AuthorizedClient` as a request attribute:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@GetMapping("/")
|
||||
@@ -110,7 +118,8 @@ public Mono<String> index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2Author
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@GetMapping("/")
|
||||
@@ -127,14 +136,16 @@ fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2Auth
|
||||
.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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@GetMapping("/")
|
||||
@@ -152,7 +163,8 @@ public Mono<String> index() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@GetMapping("/")
|
||||
@@ -169,7 +181,7 @@ fun index(): Mono<String> {
|
||||
.thenReturn("index")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
<1> `clientRegistrationId()` is a `static` method in `ServerOAuth2AuthorizedClientExchangeFilterFunction`.
|
||||
|
||||
|
||||
@@ -181,8 +193,10 @@ If `setDefaultOAuth2AuthorizedClient(true)` is configured and the user has authe
|
||||
|
||||
The following code shows the specific configuration:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -196,7 +210,8 @@ WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManage
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -208,7 +223,7 @@ fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): W
|
||||
.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[WARNING]
|
||||
It is recommended to be cautious with this feature since all HTTP requests will receive the access token.
|
||||
@@ -217,8 +232,10 @@ Alternatively, if `setDefaultClientRegistrationId("okta")` is configured with a
|
||||
|
||||
The following code shows the specific configuration:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -232,7 +249,8 @@ WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManage
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -244,7 +262,7 @@ fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): W
|
||||
.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[WARNING]
|
||||
It is recommended to be cautious with this feature since all HTTP requests will receive the access token.
|
||||
|
||||
@@ -36,8 +36,10 @@ spring:
|
||||
|
||||
The following example shows how to configure `WebClientReactiveAuthorizationCodeTokenResponseClient`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Function<ClientRegistration, JWK> jwkResolver = (clientRegistration) -> {
|
||||
@@ -59,7 +61,8 @@ tokenResponseClient.addParametersConverter(
|
||||
new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver));
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val jwkResolver: Function<ClientRegistration, JWK> =
|
||||
@@ -81,7 +84,7 @@ tokenResponseClient.addParametersConverter(
|
||||
NimbusJwtClientAuthenticationParametersConverter(jwkResolver)
|
||||
)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
=== Authenticate using `client_secret_jwt`
|
||||
@@ -105,8 +108,10 @@ spring:
|
||||
|
||||
The following example shows how to configure `WebClientReactiveClientCredentialsTokenResponseClient`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Function<ClientRegistration, JWK> jwkResolver = (clientRegistration) -> {
|
||||
@@ -127,7 +132,8 @@ tokenResponseClient.addParametersConverter(
|
||||
new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver));
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val jwkResolver = Function<ClientRegistration, JWK?> { clientRegistration: ClientRegistration ->
|
||||
@@ -148,14 +154,16 @@ tokenResponseClient.addParametersConverter(
|
||||
NimbusJwtClientAuthenticationParametersConverter(jwkResolver)
|
||||
)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
=== Customizing the JWT assertion
|
||||
|
||||
The JWT produced by `NimbusJwtClientAuthenticationParametersConverter` contains the `iss`, `sub`, `aud`, `jti`, `iat` and `exp` claims by default. You can customize the headers and/or claims by providing a `Consumer<NimbusJwtClientAuthenticationParametersConverter.JwtClientAuthenticationContext<T>>` to `setJwtClientAssertionCustomizer()`. The following example shows how to customize claims of the JWT:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
Function<ClientRegistration, JWK> jwkResolver = ...
|
||||
@@ -168,7 +176,8 @@ converter.setJwtClientAssertionCustomizer((context) -> {
|
||||
});
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val jwkResolver = ...
|
||||
@@ -180,4 +189,4 @@ converter.setJwtClientAssertionCustomizer { context ->
|
||||
context.claims.claim("custom-claim", "claim-value")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -69,20 +69,23 @@ A `ClientRegistration` can be initially configured using discovery of an OpenID
|
||||
|
||||
`ClientRegistrations` provides convenience methods for configuring a `ClientRegistration` in this way, as can be seen in the following example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
ClientRegistration clientRegistration =
|
||||
ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
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.
|
||||
|
||||
@@ -106,8 +109,10 @@ The auto-configuration also registers the `ReactiveClientRegistrationRepository`
|
||||
|
||||
The following listing shows an example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -125,7 +130,8 @@ public class OAuth2ClientController {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -142,7 +148,7 @@ class OAuth2ClientController {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[oauth2Client-authorized-client]]
|
||||
== OAuth2AuthorizedClient
|
||||
@@ -163,8 +169,10 @@ From a developer perspective, the `ServerOAuth2AuthorizedClientRepository` or `R
|
||||
|
||||
The following listing shows an example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -183,7 +191,8 @@ public class OAuth2ClientController {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -201,7 +210,7 @@ class OAuth2ClientController {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
Spring Boot 2.x auto-configuration registers an `ServerOAuth2AuthorizedClientRepository` and/or `ReactiveOAuth2AuthorizedClientService` `@Bean` in the `ApplicationContext`.
|
||||
@@ -235,8 +244,10 @@ The `ReactiveOAuth2AuthorizedClientProviderBuilder` may be used to configure and
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -261,7 +272,8 @@ public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -280,7 +292,7 @@ fun authorizedClientManager(
|
||||
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`.
|
||||
@@ -291,8 +303,10 @@ This can be useful when you need to supply a `ReactiveOAuth2AuthorizedClientProv
|
||||
|
||||
The following code shows an example of the `contextAttributesMapper`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -337,7 +351,8 @@ private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttri
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -376,7 +391,7 @@ private fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, Mono<Mut
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The `DefaultReactiveOAuth2AuthorizedClientManager` is designed to be used *_within_* the context of a `ServerWebExchange`.
|
||||
When operating *_outside_* of a `ServerWebExchange` context, use `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager` instead.
|
||||
@@ -387,8 +402,10 @@ An OAuth 2.0 Client configured with the `client_credentials` grant type can be c
|
||||
|
||||
The following code shows an example of how to configure an `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager` that provides support for the `client_credentials` grant type:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -410,7 +427,8 @@ public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -426,4 +444,4 @@ fun authorizedClientManager(
|
||||
return authorizedClientManager
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -24,8 +24,10 @@ The `ServerHttpSecurity.oauth2Client()` DSL provides a number of configuration o
|
||||
The following code shows the complete configuration options provided by the `ServerHttpSecurity.oauth2Client()` DSL:
|
||||
|
||||
.OAuth2 Client Configuration Options
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -48,7 +50,8 @@ public class OAuth2ClientSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -71,14 +74,16 @@ class OAuth2ClientSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -103,7 +108,8 @@ public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -122,4 +128,4 @@ fun authorizedClientManager(
|
||||
return authorizedClientManager
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -23,8 +23,10 @@ These claims are normally represented by a JSON object that contains a collectio
|
||||
The following code shows the complete configuration options available for the `oauth2Login()` DSL:
|
||||
|
||||
.OAuth2 Login Configuration Options
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -53,7 +55,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -82,7 +85,7 @@ class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The following sections go into more detail on each of the configuration options available:
|
||||
|
||||
@@ -119,8 +122,10 @@ To override the default login page, configure the `exceptionHandling().authentic
|
||||
The following listing shows an example:
|
||||
|
||||
.OAuth2 Login Page Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",subs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -153,7 +158,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",subs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -187,7 +193,7 @@ class OAuth2LoginSecurityConfig {
|
||||
...
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[IMPORTANT]
|
||||
You need to provide a `@Controller` with a `@RequestMapping("/login/oauth2")` that is capable of rendering the custom login page.
|
||||
@@ -220,8 +226,10 @@ The default Authorization Response redirection endpoint is `+/login/oauth2/code/
|
||||
If you would like to customize the Authorization Response redirection endpoint, configure it as shown in the following example:
|
||||
|
||||
.Redirection Endpoint Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",subs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -240,7 +248,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",subs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -259,7 +268,7 @@ class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[IMPORTANT]
|
||||
====
|
||||
@@ -267,7 +276,10 @@ You also need to ensure the `ClientRegistration.redirectUri` matches the custom
|
||||
|
||||
The following listing shows an example:
|
||||
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",subs="-attributes"]
|
||||
----
|
||||
return CommonOAuth2Provider.GOOGLE.getBuilder("google")
|
||||
@@ -277,7 +289,8 @@ return CommonOAuth2Provider.GOOGLE.getBuilder("google")
|
||||
.build();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",subs="-attributes"]
|
||||
----
|
||||
return CommonOAuth2Provider.GOOGLE.getBuilder("google")
|
||||
@@ -286,6 +299,7 @@ return CommonOAuth2Provider.GOOGLE.getBuilder("google")
|
||||
.redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}")
|
||||
.build()
|
||||
----
|
||||
======
|
||||
====
|
||||
|
||||
|
||||
@@ -322,8 +336,10 @@ The `GrantedAuthoritiesMapper` is given a list of granted authorities which cont
|
||||
Register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the configuration, as shown in the following example:
|
||||
|
||||
.Granted Authorities Mapper Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -371,7 +387,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -408,7 +425,7 @@ class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2-login-advanced-map-authorities-reactiveoauth2userservice]]
|
||||
==== Delegation-based strategy with ReactiveOAuth2UserService
|
||||
@@ -420,8 +437,10 @@ The `OAuth2UserRequest` (and `OidcUserRequest`) provides you access to the assoc
|
||||
The following example shows how to implement and configure a delegation-based strategy using an OpenID Connect 1.0 UserService:
|
||||
|
||||
.ReactiveOAuth2UserService Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -462,7 +481,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -501,7 +521,7 @@ class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-oauth2-login-advanced-oauth2-user-service]]
|
||||
@@ -518,8 +538,10 @@ If you need to customize the pre-processing of the UserInfo Request and/or the p
|
||||
|
||||
Whether you customize `DefaultReactiveOAuth2UserService` or provide your own implementation of `ReactiveOAuth2UserService`, you'll need to configure it as shown in the following example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -542,7 +564,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -564,7 +587,7 @@ class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-oauth2-login-advanced-oidc-user-service]]
|
||||
@@ -578,8 +601,10 @@ If you need to customize the pre-processing of the UserInfo Request and/or the p
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -602,7 +627,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -624,7 +650,7 @@ class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-oauth2-login-advanced-idtoken-verify]]
|
||||
@@ -641,8 +667,10 @@ The JWS algorithm resolver is a `Function` that accepts a `ClientRegistration` a
|
||||
|
||||
The following code shows how to configure the `OidcIdTokenDecoderFactory` `@Bean` to default to `MacAlgorithm.HS256` for all `ClientRegistration`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -653,7 +681,8 @@ public ReactiveJwtDecoderFactory<ClientRegistration> idTokenDecoderFactory() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -663,7 +692,7 @@ fun idTokenDecoderFactory(): ReactiveJwtDecoderFactory<ClientRegistration> {
|
||||
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.
|
||||
@@ -699,8 +728,10 @@ spring:
|
||||
|
||||
...and the `OidcClientInitiatedServerLogoutSuccessHandler`, which implements RP-Initiated Logout, may be configured as follows:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",subs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -737,7 +768,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",subs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -772,7 +804,7 @@ class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
NOTE: `OidcClientInitiatedServerLogoutSuccessHandler` supports the `+{baseUrl}+` placeholder.
|
||||
If used, the application's base URL, like `https://app.example.org`, will replace it at request time.
|
||||
|
||||
@@ -252,8 +252,10 @@ If you need to override the auto-configuration based on your specific requiremen
|
||||
|
||||
The following example shows how to register a `ReactiveClientRegistrationRepository` `@Bean`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",attrs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -283,7 +285,8 @@ public class OAuth2LoginConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -312,7 +315,7 @@ class OAuth2LoginConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-oauth2-login-register-securitywebfilterchain-bean]]
|
||||
@@ -321,8 +324,10 @@ class OAuth2LoginConfig {
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -342,7 +347,8 @@ public class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -362,7 +368,7 @@ class OAuth2LoginSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-oauth2-login-completely-override-autoconfiguration]]
|
||||
@@ -371,8 +377,10 @@ class OAuth2LoginSecurityConfig {
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",attrs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -414,7 +422,8 @@ public class OAuth2LoginConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -456,7 +465,7 @@ class OAuth2LoginConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[webflux-oauth2-login-javaconfig-wo-boot]]
|
||||
@@ -465,8 +474,10 @@ class OAuth2LoginConfig {
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -510,7 +521,8 @@ public class OAuth2LoginConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -556,4 +568,4 @@ class OAuth2LoginConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -10,8 +10,10 @@ For example, you may have a need to read the bearer token from a custom header.
|
||||
To do so, you can wire an instance of `ServerBearerTokenAuthenticationConverter` into the DSL:
|
||||
|
||||
.Custom Bearer Token Header
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
ServerBearerTokenAuthenticationConverter converter = new ServerBearerTokenAuthenticationConverter();
|
||||
@@ -22,7 +24,8 @@ http
|
||||
);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val converter = ServerBearerTokenAuthenticationConverter()
|
||||
@@ -33,15 +36,17 @@ return http {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
== Bearer Token Propagation
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -52,7 +57,8 @@ public WebClient rest() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -62,13 +68,15 @@ fun rest(): WebClient {
|
||||
.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
this.rest.get()
|
||||
@@ -77,7 +85,8 @@ this.rest.get()
|
||||
.bodyToMono(String.class)
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
this.rest.get()
|
||||
@@ -85,14 +94,16 @@ this.rest.get()
|
||||
.retrieve()
|
||||
.bodyToMono<String>()
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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, you can supply the header yourself:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
this.rest.get()
|
||||
@@ -102,7 +113,8 @@ this.rest.get()
|
||||
.bodyToMono(String.class)
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
rest.get()
|
||||
@@ -111,7 +123,7 @@ rest.get()
|
||||
.retrieve()
|
||||
.bodyToMono<String>()
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
In this case, the filter falls back and forwards the request onto the rest of the web filter chain.
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ First, include the needed dependencies. Second, indicate the location of the aut
|
||||
|
||||
In a Spring Boot application, you need to specify which authorization server to use:
|
||||
|
||||
====
|
||||
[source,yml]
|
||||
----
|
||||
spring:
|
||||
@@ -26,7 +25,6 @@ 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 issues.
|
||||
This resource server uses this property to further self-configure, discover the authorization server's public keys, and subsequently validate incoming JWTs.
|
||||
@@ -58,13 +56,11 @@ If the authorization server is down when Resource Server queries it (given appro
|
||||
|
||||
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 tries to process the request according to the Bearer Token specification.
|
||||
|
||||
@@ -91,7 +87,6 @@ From here, consider jumping to:
|
||||
|
||||
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:
|
||||
@@ -102,7 +97,6 @@ spring:
|
||||
issuer-uri: https://idp.example.com
|
||||
jwk-set-uri: https://idp.example.com/.well-known/jwks.json
|
||||
----
|
||||
====
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -125,8 +119,10 @@ Spring Boot generates two `@Bean` objects on Resource Server's behalf.
|
||||
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
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -140,7 +136,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -155,15 +152,17 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If the application does not expose a `SecurityWebFilterChain` bean, Spring Boot exposes the default one (shown in the preceding listing).
|
||||
|
||||
To replace it, expose the `@Bean` within the application:
|
||||
|
||||
.Replacing SecurityWebFilterChain
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -180,7 +179,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -196,7 +196,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The preceding configuration requires the scope of `message:read` for any URL that starts with `/messages/`.
|
||||
|
||||
@@ -205,8 +205,10 @@ Methods on the `oauth2ResourceServer` DSL also override or replace auto configur
|
||||
For example, the second `@Bean` Spring Boot creates is a `ReactiveJwtDecoder`, which decodes `String` tokens into validated instances of `Jwt`:
|
||||
|
||||
.ReactiveJwtDecoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -215,7 +217,8 @@ public ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -223,7 +226,7 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
return ReactiveJwtDecoders.fromIssuerLocation(issuerUri)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -238,8 +241,10 @@ Its configuration can be overridden by using `jwkSetUri()` or replaced by using
|
||||
|
||||
You can configure an authorization server's JWK Set URI <<webflux-oauth2resourceserver-jwt-jwkseturi,as a configuration property>> or supply it in the DSL:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -257,7 +262,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -274,7 +280,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Using `jwkSetUri()` takes precedence over any configuration property.
|
||||
|
||||
@@ -283,8 +289,10 @@ Using `jwkSetUri()` takes precedence over any configuration property.
|
||||
|
||||
`decoder()` is more powerful than `jwkSetUri()`, because it completely replaces any Spring Boot auto-configuration of `JwtDecoder`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -302,7 +310,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -319,7 +328,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
This is handy when you need deeper configuration, such as <<webflux-oauth2resourceserver-jwt-validation,validation>>.
|
||||
|
||||
@@ -328,8 +337,10 @@ This is handy when you need deeper configuration, such as <<webflux-oauth2resour
|
||||
|
||||
Alternately, exposing a `ReactiveJwtDecoder` `@Bean` has the same effect as `decoder()`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -338,7 +349,8 @@ public ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -346,7 +358,7 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
return ReactiveJwtDecoders.fromIssuerLocation(issuerUri)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-jwt-decoder-algorithm]]
|
||||
== Configuring Trusted Algorithms
|
||||
@@ -360,7 +372,6 @@ You can customize this behavior with <<webflux-oauth2resourceserver-jwt-boot-alg
|
||||
|
||||
The simplest way to set the algorithm is as a property:
|
||||
|
||||
====
|
||||
[source,yaml]
|
||||
----
|
||||
spring:
|
||||
@@ -371,15 +382,16 @@ spring:
|
||||
jws-algorithm: RS512
|
||||
jwk-set-uri: https://idp.example.org/.well-known/jwks.json
|
||||
----
|
||||
====
|
||||
|
||||
[[webflux-oauth2resourceserver-jwt-decoder-builder]]
|
||||
=== Customizing Trusted Algorithms by Using a Builder
|
||||
|
||||
For greater power, though, we can use a builder that ships with `NimbusReactiveJwtDecoder`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -389,7 +401,8 @@ ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -398,12 +411,14 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
.jwsAlgorithm(RS512).build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Calling `jwsAlgorithm` more than once configures `NimbusReactiveJwtDecoder` to trust more than one algorithm:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -413,7 +428,8 @@ ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -422,12 +438,14 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
.jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Alternately, you can call `jwsAlgorithms`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -440,7 +458,8 @@ ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -453,7 +472,7 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-jwt-decoder-public-key]]
|
||||
=== Trusting a Single Asymmetric Key
|
||||
@@ -466,7 +485,6 @@ The public key can be provided with <<webflux-oauth2resourceserver-jwt-decoder-p
|
||||
|
||||
You can specify a key with Spring Boot:
|
||||
|
||||
====
|
||||
[source,yaml]
|
||||
----
|
||||
spring:
|
||||
@@ -476,13 +494,14 @@ spring:
|
||||
jwt:
|
||||
public-key-location: classpath:my-key.pub
|
||||
----
|
||||
====
|
||||
|
||||
Alternately, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`:
|
||||
|
||||
.BeanFactoryPostProcessor
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -493,7 +512,8 @@ BeanFactoryPostProcessor conversionServiceCustomizer() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -504,42 +524,45 @@ fun conversionServiceCustomizer(): BeanFactoryPostProcessor {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Specify your key's location:
|
||||
|
||||
====
|
||||
[source,yaml]
|
||||
----
|
||||
key.location: hfds://my-key.pub
|
||||
----
|
||||
====
|
||||
|
||||
Then autowire the value:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Value("${key.location}")
|
||||
RSAPublicKey key;
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Value("\${key.location}")
|
||||
val key: RSAPublicKey? = null
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-jwt-decoder-public-key-builder]]
|
||||
==== Using a Builder
|
||||
|
||||
To wire an `RSAPublicKey` directly, use the appropriate `NimbusReactiveJwtDecoder` builder:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -548,7 +571,8 @@ public ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -556,7 +580,7 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
return NimbusReactiveJwtDecoder.withPublicKey(key).build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-jwt-decoder-secret-key]]
|
||||
=== Trusting a Single Symmetric Key
|
||||
@@ -564,8 +588,10 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
You can also use a single symmetric key.
|
||||
You can load in your `SecretKey` and use the appropriate `NimbusReactiveJwtDecoder` builder:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -574,7 +600,8 @@ public ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -582,26 +609,26 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
return NimbusReactiveJwtDecoder.withSecretKey(this.key).build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-jwt-authorization]]
|
||||
=== Configuring Authorization
|
||||
|
||||
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:
|
||||
|
||||
====
|
||||
[source,json]
|
||||
----
|
||||
{ ..., "scope" : "messages contacts"}
|
||||
----
|
||||
====
|
||||
|
||||
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:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -617,7 +644,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -634,25 +662,28 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can do something similar with method security:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@PreAuthorize("hasAuthority('SCOPE_messages')")
|
||||
public Flux<Message> getMessages(...) {}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@PreAuthorize("hasAuthority('SCOPE_messages')")
|
||||
fun getMessages(): Flux<Message> { }
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-jwt-authorization-extraction]]
|
||||
==== Extracting Authorities Manually
|
||||
@@ -663,8 +694,10 @@ At other times, the resource server may need to adapt the attribute or a composi
|
||||
|
||||
To this end, the DSL exposes `jwtAuthenticationConverter()`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -690,7 +723,8 @@ Converter<Jwt, Mono<AbstractAuthenticationToken>> grantedAuthoritiesExtractor()
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -713,15 +747,17 @@ fun grantedAuthoritiesExtractor(): Converter<Jwt, Mono<AbstractAuthenticationTok
|
||||
return ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
`jwtAuthenticationConverter()` is responsible for converting a `Jwt` into an `Authentication`.
|
||||
As part of its configuration, we can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities.
|
||||
|
||||
That final converter might be something like the following `GrantedAuthoritiesExtractor`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
static class GrantedAuthoritiesExtractor
|
||||
@@ -739,7 +775,8 @@ static class GrantedAuthoritiesExtractor
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
internal class GrantedAuthoritiesExtractor : Converter<Jwt, Collection<GrantedAuthority>> {
|
||||
@@ -752,12 +789,14 @@ internal class GrantedAuthoritiesExtractor : Converter<Jwt, Collection<GrantedAu
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter<Jwt, Mono<AbstractAuthenticationToken>>`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
static class CustomAuthenticationConverter implements Converter<Jwt, Mono<AbstractAuthenticationToken>> {
|
||||
@@ -767,7 +806,8 @@ static class CustomAuthenticationConverter implements Converter<Jwt, Mono<Abstra
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
internal class CustomAuthenticationConverter : Converter<Jwt, Mono<AbstractAuthenticationToken>> {
|
||||
@@ -776,7 +816,7 @@ internal class CustomAuthenticationConverter : Converter<Jwt, Mono<AbstractAuthe
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-jwt-validation]]
|
||||
=== Configuring Validation
|
||||
@@ -795,8 +835,10 @@ This can cause some implementation heartburn, as the number of collaborating ser
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -814,7 +856,8 @@ ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -827,7 +870,7 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
return jwtDecoder
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -839,8 +882,10 @@ By default, Resource Server configures a clock skew of 60 seconds.
|
||||
|
||||
You can Add a check for the `aud` claim with the `OAuth2TokenValidator` API:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
|
||||
@@ -856,7 +901,8 @@ public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class AudienceValidator : OAuth2TokenValidator<Jwt> {
|
||||
@@ -870,12 +916,14 @@ class AudienceValidator : OAuth2TokenValidator<Jwt> {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Then, to add into a resource server, you can specifying the `ReactiveJwtDecoder` instance:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -893,7 +941,8 @@ ReactiveJwtDecoder jwtDecoder() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -906,4 +955,4 @@ fun jwtDecoder(): ReactiveJwtDecoder {
|
||||
return jwtDecoder
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -17,8 +17,10 @@ In each case, two things need to be done and trade-offs are associated with how
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver
|
||||
@@ -33,7 +35,8 @@ http
|
||||
);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val customAuthenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo")
|
||||
@@ -47,7 +50,7 @@ return http {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
This is nice because the issuer endpoints are loaded lazily.
|
||||
In fact, the corresponding `JwtReactiveAuthenticationManager` is instantiated only when the first request with the corresponding issuer is sent.
|
||||
@@ -58,8 +61,10 @@ This allows for an application startup that is independent from those authorizat
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
private Mono<ReactiveAuthenticationManager> addManager(
|
||||
@@ -85,7 +90,8 @@ http
|
||||
);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
private fun addManager(
|
||||
@@ -108,7 +114,7 @@ return http {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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.
|
||||
|
||||
@@ -23,7 +23,6 @@ When using https://spring.io/projects/spring-boot[Spring Boot], configuring an a
|
||||
|
||||
You can specify where the introspection endpoint is:
|
||||
|
||||
====
|
||||
[source,yaml]
|
||||
----
|
||||
spring:
|
||||
@@ -35,7 +34,6 @@ spring:
|
||||
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.
|
||||
|
||||
@@ -56,13 +54,11 @@ This startup process is quite a bit simpler than for JWTs, since no endpoints ne
|
||||
|
||||
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 tries to process the request according to the Bearer Token specification.
|
||||
|
||||
@@ -87,8 +83,10 @@ Once a token is authenticated, an instance of `BearerTokenAuthentication` is set
|
||||
|
||||
This means that it is available in `@Controller` methods when you use `@EnableWebFlux` in your configuration:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@GetMapping("/foo")
|
||||
@@ -97,7 +95,8 @@ public Mono<String> foo(BearerTokenAuthentication authentication) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@GetMapping("/foo")
|
||||
@@ -105,12 +104,14 @@ fun foo(authentication: BearerTokenAuthentication): Mono<String> {
|
||||
return Mono.just(authentication.tokenAttributes["sub"].toString() + " is the subject")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Since `BearerTokenAuthentication` holds an `OAuth2AuthenticatedPrincipal`, that also means that it's available to controller methods, too:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@GetMapping("/foo")
|
||||
@@ -119,7 +120,8 @@ public Mono<String> foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal pr
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@GetMapping("/foo")
|
||||
@@ -127,7 +129,7 @@ fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): Mono<
|
||||
return Mono.just(principal.getAttribute<Any>("sub").toString() + " is the subject")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
=== Looking Up Attributes with SpEL
|
||||
|
||||
@@ -135,8 +137,10 @@ You can access attributes with the Spring Expression Language (SpEL).
|
||||
|
||||
For example, if you use `@EnableReactiveMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@PreAuthorize("principal?.attributes['sub'] = 'foo'")
|
||||
@@ -145,7 +149,8 @@ public Mono<String> forFoosEyesOnly() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@PreAuthorize("principal.attributes['sub'] = 'foo'")
|
||||
@@ -153,7 +158,7 @@ fun forFoosEyesOnly(): Mono<String> {
|
||||
return Mono.just("foo")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-opaque-sansboot]]
|
||||
== Overriding or Replacing Boot Auto Configuration
|
||||
@@ -163,8 +168,10 @@ Spring Boot generates two `@Bean` instances for Resource Server.
|
||||
The first is a `SecurityWebFilterChain` that configures the application as a resource server.
|
||||
When you use an Opaque Token, this `SecurityWebFilterChain` looks like:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -178,7 +185,8 @@ SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -193,15 +201,17 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If the application does not expose a `SecurityWebFilterChain` bean, Spring Boot exposes the default bean (shown in the preceding listing).
|
||||
|
||||
You can replace it by exposing the bean within the application:
|
||||
|
||||
.Replacing SecurityWebFilterChain
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -224,7 +234,8 @@ public class MyCustomSecurityConfiguration {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -242,7 +253,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The preceding example requires the scope of `message:read` for any URL that starts with `/messages/`.
|
||||
|
||||
@@ -250,8 +261,10 @@ Methods on the `oauth2ResourceServer` DSL also override or replace auto configur
|
||||
|
||||
For example, the second `@Bean` Spring Boot creates is a `ReactiveOpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -260,7 +273,8 @@ public ReactiveOpaqueTokenIntrospector introspector() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -268,7 +282,7 @@ fun introspector(): ReactiveOpaqueTokenIntrospector {
|
||||
return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If the application does not expose a `ReactiveOpaqueTokenIntrospector` bean, Spring Boot exposes the default one (shown in the preceding listing).
|
||||
|
||||
@@ -279,8 +293,10 @@ You can override its configuration by using `introspectionUri()` and `introspect
|
||||
|
||||
You can configure an authorization server's Introspection URI <<webflux-oauth2resourceserver-opaque-introspectionuri,as a configuration property>>, or you can supply in the DSL:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -303,7 +319,8 @@ public class DirectlyConfiguredIntrospectionUri {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -321,7 +338,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Using `introspectionUri()` takes precedence over any configuration property.
|
||||
|
||||
@@ -330,8 +347,10 @@ Using `introspectionUri()` takes precedence over any configuration property.
|
||||
|
||||
`introspector()` is more powerful than `introspectionUri()`. It completely replaces any Boot auto-configuration of `ReactiveOpaqueTokenIntrospector`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -353,7 +372,8 @@ public class DirectlyConfiguredIntrospector {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -370,7 +390,7 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
This is handy when deeper configuration, such as <<webflux-oauth2resourceserver-opaque-authorization-extraction,authority mapping>>or <<webflux-oauth2resourceserver-opaque-jwt-introspector,JWT revocation>>, is necessary.
|
||||
|
||||
@@ -379,8 +399,10 @@ This is handy when deeper configuration, such as <<webflux-oauth2resourceserver-
|
||||
|
||||
Or, exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` has the same effect as `introspector()`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -389,7 +411,8 @@ public ReactiveOpaqueTokenIntrospector introspector() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -397,26 +420,26 @@ fun introspector(): ReactiveOpaqueTokenIntrospector {
|
||||
return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-opaque-authorization]]
|
||||
== Configuring Authorization
|
||||
|
||||
An OAuth 2.0 Introspection endpoint typically returns a `scope` attribute, indicating the scopes (or authorities) it has been granted -- for example:
|
||||
|
||||
====
|
||||
[source,json]
|
||||
----
|
||||
{ ..., "scope" : "messages contacts"}
|
||||
----
|
||||
====
|
||||
|
||||
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:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -436,7 +459,8 @@ public class MappedAuthorities {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -453,25 +477,28 @@ fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can do something similar with method security:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@PreAuthorize("hasAuthority('SCOPE_messages')")
|
||||
public Flux<Message> getMessages(...) {}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@PreAuthorize("hasAuthority('SCOPE_messages')")
|
||||
fun getMessages(): Flux<Message> { }
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-opaque-authorization-extraction]]
|
||||
=== Extracting Authorities Manually
|
||||
@@ -492,8 +519,10 @@ If the introspection response were as the preceding example shows, Resource Serv
|
||||
|
||||
You can customize behavior by using a custom `ReactiveOpaqueTokenIntrospector` that looks at the attribute set and converts in its own way:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
|
||||
@@ -515,7 +544,8 @@ public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueT
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
|
||||
@@ -535,12 +565,14 @@ class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Thereafter, you can configure this custom introspector by exposing it as a `@Bean`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -549,7 +581,8 @@ public ReactiveOpaqueTokenIntrospector introspector() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -557,7 +590,7 @@ fun introspector(): ReactiveOpaqueTokenIntrospector {
|
||||
return CustomAuthoritiesOpaqueTokenIntrospector()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-opaque-jwt-introspector]]
|
||||
== Using Introspection with JWTs
|
||||
@@ -569,7 +602,6 @@ So, suppose you need to check with the authorization server on each request, in
|
||||
|
||||
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:
|
||||
@@ -581,7 +613,6 @@ 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.
|
||||
@@ -591,8 +622,10 @@ 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:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
|
||||
@@ -618,7 +651,8 @@ public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospect
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
|
||||
@@ -641,12 +675,14 @@ class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Thereafter, you can configure this custom introspector by exposing it as a `@Bean`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -655,7 +691,8 @@ public ReactiveOpaqueTokenIntrospector introspector() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -663,7 +700,7 @@ fun introspector(): ReactiveOpaqueTokenIntrospector {
|
||||
return JwtOpaqueTokenIntrospector()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[webflux-oauth2resourceserver-opaque-userinfo]]
|
||||
== Calling a `/userinfo` Endpoint
|
||||
@@ -679,8 +716,10 @@ The implementation in the next listing does three things:
|
||||
* Looks up the appropriate client registration associated with the `/userinfo` endpoint.
|
||||
* Invokes and returns the response from the `/userinfo` endpoint.
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
|
||||
@@ -709,7 +748,8 @@ public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntro
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
|
||||
@@ -732,13 +772,15 @@ class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If you aren't using `spring-security-oauth2-client`, it's still quite simple.
|
||||
You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
|
||||
@@ -754,7 +796,8 @@ public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntro
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
|
||||
@@ -767,12 +810,14 @@ class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Either way, having created your `ReactiveOpaqueTokenIntrospector`, you should publish it as a `@Bean` to override the defaults:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -781,7 +826,8 @@ ReactiveOpaqueTokenIntrospector introspector() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -789,4 +835,4 @@ fun introspector(): ReactiveOpaqueTokenIntrospector {
|
||||
return UserInfoOpaqueTokenIntrospector()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@@ -39,7 +41,8 @@ public class HelloWorldMessageServiceTests {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@@ -72,4 +75,4 @@ class HelloWorldMessageServiceTests {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockUser;
|
||||
@@ -64,7 +66,8 @@ public void messageWhenMutateWithMockAdminThenOk() throws Exception {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
import org.springframework.test.web.reactive.server.expectBody
|
||||
@@ -111,6 +114,6 @@ fun messageWhenMutateWithMockAdminThenOk() {
|
||||
.expectBody<String>().isEqualTo("Hello World!")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
In addition to `mockUser()`, Spring Security ships with several other convenience mutators for things like xref:reactive/test/web/csrf.adoc[CSRF] and xref:reactive/test/web/oauth2.adoc[OAuth 2.0].
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
Spring Security also provides support for CSRF testing with `WebTestClient` -- for example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf;
|
||||
@@ -16,7 +18,8 @@ this.rest
|
||||
...
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf
|
||||
@@ -28,4 +31,4 @@ this.rest
|
||||
.uri("/login")
|
||||
...
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,8 +2,10 @@
|
||||
|
||||
The basic setup looks like this:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity;
|
||||
@@ -31,7 +33,8 @@ public class HelloWebfluxMethodApplicationTests {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity
|
||||
@@ -58,4 +61,4 @@ class HelloWebfluxMethodApplicationTests {
|
||||
// ...
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -11,7 +11,6 @@ You can use these as a guideline for defining the schema for the database you ar
|
||||
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 can use these as a guideline for defining the schema for the database you use.
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
|
||||
@@ -28,13 +27,11 @@ 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 (
|
||||
@@ -51,14 +48,12 @@ 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 need to adjust the following schema to match the database dialect you use:
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
|
||||
@@ -80,7 +75,6 @@ create table group_members (
|
||||
constraint fk_group_members_group foreign key(group_id) references groups(id)
|
||||
);
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
@@ -91,7 +85,6 @@ This table is used to store the data used by the more secure <<remember-me-persi
|
||||
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]
|
||||
----
|
||||
|
||||
@@ -103,7 +96,6 @@ create table persistent_logins (
|
||||
);
|
||||
|
||||
----
|
||||
====
|
||||
|
||||
[[dbschema-acl]]
|
||||
== ACL Schema
|
||||
@@ -127,7 +119,6 @@ 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(
|
||||
@@ -170,7 +161,6 @@ create table acl_entry(
|
||||
constraint foreign_fk_5 foreign key(sid) references acl_sid(id)
|
||||
);
|
||||
----
|
||||
====
|
||||
|
||||
=== PostgreSQL
|
||||
|
||||
@@ -179,7 +169,6 @@ For PostgreSQL, you have to set the `classIdentityQuery` and `sidIdentityQuery`
|
||||
* `select currval(pg_get_serial_sequence('acl_class', 'id'))`
|
||||
* `select currval(pg_get_serial_sequence('acl_sid', 'id'))`
|
||||
|
||||
====
|
||||
[source,ddl]
|
||||
----
|
||||
create table acl_sid(
|
||||
@@ -222,11 +211,9 @@ create table acl_entry(
|
||||
constraint foreign_fk_5 foreign key(sid) references acl_sid(id)
|
||||
);
|
||||
----
|
||||
====
|
||||
|
||||
=== MySQL and MariaDB
|
||||
|
||||
====
|
||||
[source,ddl]
|
||||
----
|
||||
CREATE TABLE acl_sid (
|
||||
@@ -269,11 +256,9 @@ 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 (
|
||||
@@ -316,11 +301,9 @@ CREATE TABLE acl_entry (
|
||||
CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id)
|
||||
);
|
||||
----
|
||||
====
|
||||
|
||||
=== Oracle Database
|
||||
|
||||
====
|
||||
[source,ddl]
|
||||
----
|
||||
CREATE TABLE ACL_SID (
|
||||
@@ -386,14 +369,12 @@ 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/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 (
|
||||
@@ -410,4 +391,3 @@ CREATE TABLE oauth2_authorized_client (
|
||||
PRIMARY KEY (client_registration_id, principal_name)
|
||||
);
|
||||
----
|
||||
====
|
||||
|
||||
@@ -150,7 +150,6 @@ From Spring Security 2.0.1 onwards, when you use namespace-based configuration,
|
||||
|
||||
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
|
||||
@@ -158,7 +157,6 @@ 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.
|
||||
|
||||
@@ -176,7 +174,6 @@ Note that SSL requests are never cached.
|
||||
|
||||
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
|
||||
@@ -185,7 +182,6 @@ org.springframework.security.AuthenticationCredentialsNotFoundException:
|
||||
at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
|
||||
at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
|
||||
----
|
||||
====
|
||||
|
||||
It is normal and is not something to worry about.
|
||||
|
||||
@@ -202,8 +198,10 @@ 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:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
|
||||
@@ -222,7 +220,8 @@ public void ldapAuthenticationIsSuccessful() throws Exception {
|
||||
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Test
|
||||
@@ -236,7 +235,7 @@ fun ldapAuthenticationIsSuccessful() {
|
||||
val ctx = InitialLdapContext(env, null)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
=== Session Management
|
||||
|
||||
@@ -301,14 +300,12 @@ It is essential to make sure that the Spring Security session registry is notifi
|
||||
Without it, the session information is not removed from the registry.
|
||||
The following example adds a listener in a `web.xml` file:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<listener>
|
||||
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
|
||||
</listener>
|
||||
----
|
||||
====
|
||||
|
||||
[[appendix-faq-unwanted-session-creation]]
|
||||
=== 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?
|
||||
@@ -420,7 +417,6 @@ Any that are marked as "`optional`" in the Spring Security `pom.xml` files have
|
||||
|
||||
If you use Maven, you need to add the following to your `pom.xml` file dependencies:
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
|
||||
@@ -438,7 +434,6 @@ If you use Maven, you need to add the following to your `pom.xml` file dependenc
|
||||
</dependency>
|
||||
|
||||
----
|
||||
====
|
||||
|
||||
The other required jars should be pulled in transitively.
|
||||
|
||||
@@ -531,8 +526,10 @@ To load the data from an alternative source, you must use an explicitly declared
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
|
||||
@@ -561,7 +558,8 @@ You would then implement `FilterInvocationSecurityMetadataSource` to load the da
|
||||
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class MyFilterSecurityMetadataSource : FilterInvocationSecurityMetadataSource {
|
||||
@@ -584,7 +582,7 @@ class MyFilterSecurityMetadataSource : FilterInvocationSecurityMetadataSource {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
For more information, look at the code for `DefaultFilterInvocationSecurityMetadataSource`.
|
||||
|
||||
@@ -597,8 +595,10 @@ The `DefaultLdapAuthoritiesPopulator` loads the user authorities from the LDAP d
|
||||
|
||||
To use JDBC instead, you can implement the interface yourself, by using whatever SQL is appropriate for your schema:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
|
||||
@@ -624,7 +624,8 @@ public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator {
|
||||
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class MyAuthoritiesPopulator : LdapAuthoritiesPopulator {
|
||||
@@ -644,7 +645,7 @@ 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 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.
|
||||
@@ -661,8 +662,10 @@ You can find more information in the https://docs.spring.io/spring/docs/3.0.x/sp
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class CustomBeanPostProcessor implements BeanPostProcessor {
|
||||
@@ -686,7 +689,8 @@ public class CustomBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class CustomBeanPostProcessor : BeanPostProcessor {
|
||||
@@ -704,7 +708,7 @@ class CustomBeanPostProcessor : BeanPostProcessor {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You would then register this bean in your application context.
|
||||
Spring automatically invoke it on the beans defined in the application context.
|
||||
|
||||
@@ -28,8 +28,10 @@ In this case, the `Filter` typically writes the `HttpServletResponse`.
|
||||
The power of the `Filter` comes from the `FilterChain` that is passed into it.
|
||||
|
||||
.`FilterChain` Usage Example
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
|
||||
@@ -39,7 +41,8 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
|
||||
@@ -48,7 +51,7 @@ fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterCh
|
||||
// do something after the rest of the application
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Since a `Filter` impacts only downstream `Filter` instances and the `Servlet`, the order in which each `Filter` is invoked is extremely important.
|
||||
|
||||
@@ -69,8 +72,10 @@ image::{figures}/delegatingfilterproxy.png[]
|
||||
The following listing shows pseudo code of `DelegatingFilterProxy`:
|
||||
|
||||
.`DelegatingFilterProxy` Pseudo Code
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",subs="+quotes,+macros"]
|
||||
----
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
|
||||
@@ -82,7 +87,8 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",subs="+quotes,+macros"]
|
||||
----
|
||||
fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
|
||||
@@ -93,7 +99,7 @@ fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterCh
|
||||
delegate.doFilter(request, response)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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.
|
||||
@@ -232,7 +238,6 @@ If the application does not throw an `AccessDeniedException` or an `Authenticati
|
||||
|
||||
The pseudocode for `ExceptionTranslationFilter` looks something like this:
|
||||
|
||||
====
|
||||
.ExceptionTranslationFilter pseudocode
|
||||
[source,java]
|
||||
----
|
||||
@@ -250,7 +255,6 @@ try {
|
||||
This means that if another part of the application, (<<servlet-authorization-filtersecurityinterceptor,`FilterSecurityInterceptor`>> 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__
|
||||
====
|
||||
|
||||
[[savedrequests]]
|
||||
== Saving Requests Between Authentication
|
||||
@@ -280,8 +284,10 @@ Or you may want to shut off this feature since you always want to redirect the u
|
||||
To do that, you can use {security-api-url}org/springframework/security/web/savedrequest/NullRequestCache.html[the `NullRequestCache` implementation].
|
||||
|
||||
.Prevent the Request From Being Saved
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -296,7 +302,8 @@ SecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -311,7 +318,8 @@ open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http auto-config="true">
|
||||
@@ -321,7 +329,7 @@ open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
|
||||
|
||||
<b:bean id="nullRequestCache" class="org.springframework.security.web.savedrequest.NullRequestCache"/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[requestcacheawarefilter]]
|
||||
|
||||
@@ -32,7 +32,6 @@ There is a corresponding `AnonymousAuthenticationProvider`, which is chained int
|
||||
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]
|
||||
----
|
||||
<bean id="anonymousAuthFilter"
|
||||
@@ -46,7 +45,6 @@ The filter and authentication provider is defined as follows:
|
||||
<property name="key" value="foobar"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
|
||||
@@ -66,7 +64,6 @@ The same syntax is used after the equals sign for the `userMap` property of `InM
|
||||
|
||||
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]
|
||||
----
|
||||
<bean id="filterSecurityInterceptor"
|
||||
@@ -84,7 +81,6 @@ As explained earlier, the benefit of anonymous authentication is that all URI pa
|
||||
</property>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
[[anonymous-auth-trust-resolver]]
|
||||
== AuthenticationTrustResolver
|
||||
@@ -107,8 +103,10 @@ https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc
|
||||
|
||||
This means that a construct like this one:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@GetMapping("/")
|
||||
@@ -121,7 +119,8 @@ public String method(Authentication authentication) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@GetMapping("/")
|
||||
@@ -133,7 +132,7 @@ fun method(authentication: Authentication?): String {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
will always return "not anonymous", even for anonymous requests.
|
||||
The reason is that Spring MVC resolves the parameter using `HttpServletRequest#getPrincipal`, which is `null` when the request is anonymous.
|
||||
@@ -141,8 +140,10 @@ The reason is that Spring MVC resolves the parameter using `HttpServletRequest#g
|
||||
If you'd like to obtain the `Authentication` in anonymous requests, use `@CurrentSecurityContext` instead:
|
||||
|
||||
.Use CurrentSecurityContext for Anonymous requests
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@GetMapping("/")
|
||||
@@ -151,11 +152,12 @@ public String method(@CurrentSecurityContext SecurityContext context) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@GetMapping("/")
|
||||
fun method(@CurrentSecurityContext context : SecurityContext) : String =
|
||||
context!!.authentication!!.name
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -32,7 +32,10 @@ The simplest way to indicate a user is authenticated is to set the `SecurityCont
|
||||
|
||||
.Setting `SecurityContextHolder`
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext(); // <1>
|
||||
@@ -43,7 +46,8 @@ context.setAuthentication(authentication);
|
||||
SecurityContextHolder.setContext(context); // <3>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val context: SecurityContext = SecurityContextHolder.createEmptyContext() // <1>
|
||||
@@ -52,6 +56,7 @@ context.authentication = authentication
|
||||
|
||||
SecurityContextHolder.setContext(context) // <3>
|
||||
----
|
||||
======
|
||||
|
||||
<1> We start by creating an empty `SecurityContext`.
|
||||
You should create a new `SecurityContext` instance instead of using `SecurityContextHolder.getContext().setAuthentication(authentication)` to avoid race conditions across multiple threads.
|
||||
@@ -66,8 +71,10 @@ Spring Security uses this information for xref:servlet/authorization/index.adoc#
|
||||
To obtain information about the authenticated principal, access the `SecurityContextHolder`.
|
||||
|
||||
.Access Currently Authenticated User
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
SecurityContext context = SecurityContextHolder.getContext();
|
||||
@@ -77,7 +84,8 @@ Object principal = authentication.getPrincipal();
|
||||
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val context = SecurityContextHolder.getContext()
|
||||
@@ -86,7 +94,7 @@ val username = authentication.name
|
||||
val principal = authentication.principal
|
||||
val authorities = authentication.authorities
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
// FIXME: Add links to and relevant description of HttpServletRequest.getRemoteUser() and @CurrentSecurityContext @AuthenticationPrincipal
|
||||
|
||||
|
||||
@@ -6,8 +6,10 @@ For each authentication that succeeds or fails, a `AuthenticationSuccessEvent` o
|
||||
To listen for these events, you must first publish an `AuthenticationEventPublisher`.
|
||||
Spring Security's `DefaultAuthenticationEventPublisher` works fine for this purpose:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -17,7 +19,8 @@ public AuthenticationEventPublisher authenticationEventPublisher
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -26,12 +29,14 @@ fun authenticationEventPublisher
|
||||
return DefaultAuthenticationEventPublisher(applicationEventPublisher)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Then you can use Spring's `@EventListener` support:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Component
|
||||
@@ -48,7 +53,8 @@ public class AuthenticationEvents {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Component
|
||||
@@ -64,7 +70,7 @@ class AuthenticationEvents {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
While similar to `AuthenticationSuccessHandler` and `AuthenticationFailureHandler`, these are nice in that they can be used independently from the servlet API.
|
||||
|
||||
@@ -89,8 +95,10 @@ The publisher does an exact `Exception` match, which means that sub-classes of t
|
||||
|
||||
To that end, you may want to supply additional mappings to the publisher through the `setAdditionalExceptionMappings` method:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -106,7 +114,8 @@ public AuthenticationEventPublisher authenticationEventPublisher
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -119,14 +128,16 @@ fun authenticationEventPublisher
|
||||
return authenticationEventPublisher
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
== Default Event
|
||||
|
||||
You can also supply a catch-all event to fire in the case of any `AuthenticationException`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -140,7 +151,8 @@ public AuthenticationEventPublisher authenticationEventPublisher
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -151,4 +163,4 @@ fun authenticationEventPublisher
|
||||
return authenticationEventPublisher
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -68,7 +68,6 @@ While the Spring configuration for `InMemoryConfiguration` can be more verbose t
|
||||
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]
|
||||
----
|
||||
<bean id="jaasAuthProvider"
|
||||
@@ -107,7 +106,6 @@ class="org.springframework.security.authentication.jaas.DefaultJaasAuthenticatio
|
||||
</property>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
[[jaas-jaasauthenticationprovider]]
|
||||
@@ -118,19 +116,16 @@ The `JaasAuthenticationProvider` then uses the default `Configuration` to create
|
||||
|
||||
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 through the application context.
|
||||
The following definitions would correspond to the above JAAS login configuration file:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
|
||||
@@ -153,19 +148,16 @@ class="org.springframework.security.authentication.jaas.JaasAuthenticationProvid
|
||||
</property>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
[[jaas-apiprovision]]
|
||||
== Running as a Subject
|
||||
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());
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
|
||||
@@ -18,8 +18,10 @@ The default is that accessing the URL `/logout` logs the user out by:
|
||||
Similar to configuring login capabilities, however, you also have various options to further customize your logout requirements:
|
||||
|
||||
.Logout Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
@@ -36,7 +38,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
-----
|
||||
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
@@ -53,7 +56,7 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
// ...
|
||||
}
|
||||
-----
|
||||
====
|
||||
======
|
||||
|
||||
<1> Provides logout support.
|
||||
<2> The URL that triggers log out to occur (the default is `/logout`).
|
||||
|
||||
@@ -60,9 +60,11 @@ However, as soon as any servlet based configuration is provided, HTTP Basic must
|
||||
The following example shows a minimal, explicit configuration:
|
||||
|
||||
.Explicit HTTP Basic Configuration
|
||||
====
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
.Java
|
||||
----
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
@@ -73,8 +75,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
.XML
|
||||
----
|
||||
<http>
|
||||
<!-- ... -->
|
||||
@@ -82,8 +85,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
</http>
|
||||
----
|
||||
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
@Bean
|
||||
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
@@ -94,4 +98,4 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
return http.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -25,22 +25,22 @@ This is a value the server generates.
|
||||
Spring Security's nonce adopts the following format:
|
||||
|
||||
.Digest Syntax
|
||||
====
|
||||
[source,txt]
|
||||
----
|
||||
base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
|
||||
expirationTime: The date and time when the nonce expires, expressed in milliseconds
|
||||
key: A private key to prevent modification of the nonce token
|
||||
----
|
||||
====
|
||||
|
||||
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
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Autowired
|
||||
@@ -68,7 +68,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<b:bean id="digestFilter"
|
||||
@@ -88,4 +89,4 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
<custom-filter ref="userFilter" position="DIGEST_AUTH_FILTER"/>
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -67,8 +67,10 @@ However, as soon as any servlet-based configuration is provided, form based logi
|
||||
The following example shows a minimal, explicit Java configuration:
|
||||
|
||||
.Form Login
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
@@ -78,7 +80,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -87,7 +90,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
@@ -97,7 +101,7 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
// ...
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
In the preceding configuration, Spring Security renders a default login page.
|
||||
Most production applications require a custom login form.
|
||||
@@ -106,8 +110,10 @@ Most production applications require a custom login form.
|
||||
The following configuration demonstrates how to provide a custom login form.
|
||||
|
||||
.Custom Login Form Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
@@ -120,7 +126,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -130,7 +137,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
@@ -143,16 +151,14 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
// ...
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[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
|
||||
The following https://www.thymeleaf.org/[Thymeleaf] template produces an HTML login form that complies with a login page of `/login`.:
|
||||
|
||||
.Login Form
|
||||
====
|
||||
.src/main/resources/templates/login.html
|
||||
.Login Form - src/main/resources/templates/login.html
|
||||
[source,xml]
|
||||
----
|
||||
<!DOCTYPE html>
|
||||
@@ -178,7 +184,6 @@ The following https://www.thymeleaf.org/[Thymeleaf] template produces an HTML lo
|
||||
</body>
|
||||
</html>
|
||||
----
|
||||
====
|
||||
|
||||
There are a few key points about the default HTML form:
|
||||
|
||||
@@ -197,8 +202,10 @@ If you use Spring MVC, you need a controller that maps `GET /login` to the login
|
||||
The following example shows a minimal `LoginController`:
|
||||
|
||||
.LoginController
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -210,7 +217,8 @@ class LoginController {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Controller
|
||||
@@ -221,4 +229,4 @@ class LoginController {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -8,8 +8,10 @@ Spring Security's `InMemoryUserDetailsManager` implements xref:servlet/authentic
|
||||
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
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -28,7 +30,8 @@ public UserDetailsService users() {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
<user-service>
|
||||
@@ -41,7 +44,8 @@ public UserDetailsService users() {
|
||||
</user-service>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -59,7 +63,7 @@ fun users(): UserDetailsService {
|
||||
return InMemoryUserDetailsManager(user, admin)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The preceding samples store the passwords in a secure format but leave a lot to be desired in terms of a getting started experience.
|
||||
|
||||
@@ -68,8 +72,10 @@ However, it does not protect against obtaining the password by decompiling the s
|
||||
For this reason, `User.withDefaultPasswordEncoder` should only be used for "`getting started`" and is not intended for production.
|
||||
|
||||
.InMemoryUserDetailsManager with User.withDefaultPasswordEncoder
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -90,7 +96,8 @@ public UserDetailsService users() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -110,13 +117,12 @@ fun users(): UserDetailsService {
|
||||
return InMemoryUserDetailsManager(user, admin)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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]:
|
||||
|
||||
.<user-service> `+{noop}+` XML Configuration
|
||||
====
|
||||
[source,xml,attrs="-attributes"]
|
||||
----
|
||||
<user-service>
|
||||
@@ -128,4 +134,3 @@ For demos or just getting started, you can choose to prefix the password with `+
|
||||
authorities="ROLE_USER,ROLE_ADMIN" />
|
||||
</user-service>
|
||||
----
|
||||
====
|
||||
|
||||
@@ -29,7 +29,6 @@ The default schema is also exposed as a classpath resource named `org/springfram
|
||||
====
|
||||
|
||||
.Default User Schema
|
||||
====
|
||||
[source,sql]
|
||||
----
|
||||
create table users(
|
||||
@@ -45,12 +44,10 @@ create table authorities (
|
||||
);
|
||||
create unique index ix_auth_username on authorities (username,authority);
|
||||
----
|
||||
====
|
||||
|
||||
Oracle is a popular database choice but requires a slightly different schema:
|
||||
|
||||
.Default User Schema for Oracle Databases
|
||||
====
|
||||
[source,sql]
|
||||
----
|
||||
CREATE TABLE USERS (
|
||||
@@ -67,7 +64,6 @@ 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;
|
||||
----
|
||||
====
|
||||
|
||||
[[servlet-authentication-jdbc-schema-group]]
|
||||
=== Group Schema
|
||||
@@ -75,7 +71,6 @@ ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME) RE
|
||||
If your application uses groups, you need to provide the groups schema:
|
||||
|
||||
.Default Group Schema
|
||||
====
|
||||
[source,sql]
|
||||
----
|
||||
create table groups (
|
||||
@@ -96,7 +91,6 @@ create table group_members (
|
||||
constraint fk_group_members_group foreign key(group_id) references groups(id)
|
||||
);
|
||||
----
|
||||
====
|
||||
|
||||
[[servlet-authentication-jdbc-datasource]]
|
||||
== Setting up a DataSource
|
||||
@@ -105,8 +99,10 @@ Before we configure `JdbcUserDetailsManager`, we must create a `DataSource`.
|
||||
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 <<servlet-authentication-jdbc-schema,default user schema>>.
|
||||
|
||||
.Embedded Data Source
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -118,7 +114,8 @@ DataSource dataSource() {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<jdbc:embedded-database>
|
||||
@@ -126,7 +123,8 @@ DataSource dataSource() {
|
||||
</jdbc:embedded-database>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -137,7 +135,7 @@ fun dataSource(): DataSource {
|
||||
.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
In a production environment, you want to ensure that you set up a connection to an external database.
|
||||
|
||||
@@ -148,9 +146,11 @@ In this sample, we use xref:features/authentication/password-storage.adoc#authen
|
||||
See the xref:features/authentication/password-storage.adoc#authentication-password-storage[PasswordEncoder] section for more details about how to store passwords.
|
||||
|
||||
.JdbcUserDetailsManager
|
||||
====
|
||||
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -172,7 +172,8 @@ UserDetailsManager users(DataSource dataSource) {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
<jdbc-user-service>
|
||||
@@ -185,7 +186,8 @@ UserDetailsManager users(DataSource dataSource) {
|
||||
</jdbc-user-service>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -206,4 +208,4 @@ fun users(dataSource: DataSource): UserDetailsManager {
|
||||
return users
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -45,7 +45,6 @@ Spring Security supports using either:
|
||||
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
|
||||
@@ -91,7 +90,6 @@ objectclass: groupOfNames
|
||||
cn: admin
|
||||
uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
|
||||
----
|
||||
====
|
||||
|
||||
[[servlet-authentication-ldap-unboundid]]
|
||||
=== Embedded UnboundID Server
|
||||
@@ -99,8 +97,10 @@ uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
|
||||
If you wish to use https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID], specify the following dependencies:
|
||||
|
||||
.UnboundID Dependencies
|
||||
====
|
||||
.Maven
|
||||
[tabs]
|
||||
======
|
||||
Maven::
|
||||
+
|
||||
[source,xml,role="primary",subs="verbatim,attributes"]
|
||||
----
|
||||
<dependency>
|
||||
@@ -111,21 +111,24 @@ If you wish to use https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID], spe
|
||||
</dependency>
|
||||
----
|
||||
|
||||
.Gradle
|
||||
Gradle::
|
||||
+
|
||||
[source,groovy,role="secondary",subs="verbatim,attributes"]
|
||||
----
|
||||
depenendencies {
|
||||
runtimeOnly "com.unboundid:unboundid-ldapsdk:{unboundid-ldapsdk-version}"
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can then configure the Embedded LDAP Server using an `EmbeddedLdapServerContextSourceFactoryBean`.
|
||||
This will instruct Spring Security to start an in-memory LDAP server:
|
||||
|
||||
.Embedded LDAP Server Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -134,7 +137,8 @@ public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -142,14 +146,16 @@ fun contextSourceFactoryBean(): EmbeddedLdapServerContextSourceFactoryBean {
|
||||
return EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Alternatively, you can manually configure the Embedded LDAP Server.
|
||||
If you choose this approach, you will be responsible for managing the lifecycle of the Embedded LDAP Server.
|
||||
|
||||
.Explicit Embedded LDAP Server Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -159,7 +165,8 @@ UnboundIdContainer ldapContainer() {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<b:bean class="org.springframework.security.ldap.server.UnboundIdContainer"
|
||||
@@ -167,7 +174,8 @@ UnboundIdContainer ldapContainer() {
|
||||
c:ldif="classpath:users.ldif"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -175,7 +183,7 @@ fun ldapContainer(): UnboundIdContainer {
|
||||
return UnboundIdContainer("dc=springframework,dc=org","classpath:users.ldif")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-authentication-ldap-apacheds]]
|
||||
=== Embedded ApacheDS Server
|
||||
@@ -190,8 +198,10 @@ 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], specify the following dependencies:
|
||||
|
||||
.ApacheDS Dependencies
|
||||
====
|
||||
.Maven
|
||||
[tabs]
|
||||
======
|
||||
Maven::
|
||||
+
|
||||
[source,xml,role="primary",subs="+attributes"]
|
||||
----
|
||||
<dependency>
|
||||
@@ -208,7 +218,8 @@ If you wish to use https://directory.apache.org/apacheds/[Apache DS], specify th
|
||||
</dependency>
|
||||
----
|
||||
|
||||
.Gradle
|
||||
Gradle::
|
||||
+
|
||||
[source,groovy,role="secondary",subs="+attributes"]
|
||||
----
|
||||
depenendencies {
|
||||
@@ -216,13 +227,15 @@ depenendencies {
|
||||
runtimeOnly "org.apache.directory.server:apacheds-server-jndi:{apacheds-core-version}"
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can then configure the Embedded LDAP Server:
|
||||
|
||||
.Embedded LDAP Server Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -232,7 +245,8 @@ ApacheDSContainer ldapContainer() {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<b:bean class="org.springframework.security.ldap.server.ApacheDSContainer"
|
||||
@@ -240,7 +254,8 @@ ApacheDSContainer ldapContainer() {
|
||||
c:ldif="classpath:users.ldif"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -248,7 +263,7 @@ fun ldapContainer(): ApacheDSContainer {
|
||||
return ApacheDSContainer("dc=springframework,dc=org", "classpath:users.ldif")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-authentication-ldap-contextsource]]
|
||||
== LDAP ContextSource
|
||||
@@ -258,8 +273,10 @@ To do so, create an LDAP `ContextSource` (which is the equivalent of a JDBC `Dat
|
||||
If you have already configured an `EmbeddedLdapServerContextSourceFactoryBean`, Spring Security will create an LDAP `ContextSource` that points to the embedded LDAP server.
|
||||
|
||||
.LDAP Context Source with Embedded LDAP Server
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -271,7 +288,8 @@ public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -281,13 +299,15 @@ fun contextSourceFactoryBean(): EmbeddedLdapServerContextSourceFactoryBean {
|
||||
return contextSourceFactoryBean
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Alternatively, you can explicitly configure the LDAP `ContextSource` to connect to the supplied LDAP server:
|
||||
|
||||
.LDAP Context Source
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
ContextSource contextSource(UnboundIdContainer container) {
|
||||
@@ -295,21 +315,23 @@ ContextSource contextSource(UnboundIdContainer container) {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<ldap-server
|
||||
url="ldap://localhost:53389/dc=springframework,dc=org" />
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
fun contextSource(container: UnboundIdContainer): ContextSource {
|
||||
return DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-authentication-ldap-authentication]]
|
||||
== Authentication
|
||||
@@ -337,8 +359,10 @@ The advantage to using bind authentication is that the user's secrets (the passw
|
||||
The following example shows bind authentication configuration:
|
||||
|
||||
.Bind Authentication
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -349,14 +373,16 @@ AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSou
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
<ldap-authentication-provider
|
||||
user-dn-pattern="uid={0},ou=people"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -366,15 +392,17 @@ fun authenticationManager(contextSource: BaseLdapPathContextSource): Authenticat
|
||||
return factory.createAuthenticationManager()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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 wish to configure an LDAP search filter to locate the user, you could use the following:
|
||||
|
||||
.Bind Authentication with Search Filter
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -386,7 +414,8 @@ AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSou
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
<ldap-authentication-provider
|
||||
@@ -394,7 +423,8 @@ AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSou
|
||||
user-search-base="ou=people"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -405,7 +435,7 @@ fun authenticationManager(contextSource: BaseLdapPathContextSource): Authenticat
|
||||
return factory.createAuthenticationManager()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If used with the `ContextSource` <<servlet-authentication-ldap-contextsource,definition shown earlier>>, 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 searches for an entry with the `uid` attribute equal to the user name.
|
||||
@@ -419,8 +449,10 @@ This can either be done by retrieving the value of the password attribute and ch
|
||||
An LDAP compare cannot be done when the password is properly hashed with a random salt.
|
||||
|
||||
.Minimal Password Compare Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -432,7 +464,8 @@ AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSou
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
<ldap-authentication-provider
|
||||
@@ -441,7 +474,8 @@ AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSou
|
||||
</ldap-authentication-provider>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -453,13 +487,15 @@ fun authenticationManager(contextSource: BaseLdapPathContextSource?): Authentica
|
||||
return factory.createAuthenticationManager()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The following example shows a more advanced configuration with some customizations:
|
||||
|
||||
.Password Compare Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -472,7 +508,8 @@ AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSou
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
<ldap-authentication-provider
|
||||
@@ -485,7 +522,8 @@ AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSou
|
||||
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -498,7 +536,7 @@ fun authenticationManager(contextSource: BaseLdapPathContextSource): Authenticat
|
||||
return factory.createAuthenticationManager()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
<1> Specify the password attribute as `pwd`.
|
||||
|
||||
@@ -508,8 +546,10 @@ Spring Security's `LdapAuthoritiesPopulator` is used to determine what authoriti
|
||||
The following example shows how configure `LdapAuthoritiesPopulator`:
|
||||
|
||||
.LdapAuthoritiesPopulator Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -530,7 +570,8 @@ AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSou
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
<ldap-authentication-provider
|
||||
@@ -538,7 +579,8 @@ AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSou
|
||||
group-search-filter="member={0}"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
@Bean
|
||||
@@ -559,7 +601,7 @@ fun authenticationManager(
|
||||
return factory.createAuthenticationManager()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
== Active Directory
|
||||
|
||||
@@ -579,8 +621,10 @@ This is not currently supported, but hopefully will be in a future version.
|
||||
The following example configures Active Directory:
|
||||
|
||||
.Example Active Directory Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -589,7 +633,8 @@ ActiveDirectoryLdapAuthenticationProvider authenticationProvider() {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<bean id="authenticationProvider"
|
||||
@@ -599,7 +644,8 @@ ActiveDirectoryLdapAuthenticationProvider authenticationProvider() {
|
||||
</bean>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -607,4 +653,4 @@ fun authenticationProvider(): ActiveDirectoryLdapAuthenticationProvider {
|
||||
return ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/")
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -13,8 +13,10 @@ This is only used if the `AuthenticationManagerBuilder` has not been populated a
|
||||
====
|
||||
|
||||
.Custom UserDetailsService Bean
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -23,18 +25,20 @@ CustomUserDetailsService customUserDetailsService() {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,java,role="secondary"]
|
||||
----
|
||||
<b:bean class="example.CustomUserDetailsService"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
fun customUserDetailsService() = CustomUserDetailsService()
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
// FIXME: Add CustomUserDetails example with links to @AuthenticationPrincipal
|
||||
|
||||
@@ -25,7 +25,6 @@ Location: /login
|
||||
The user submits their username and password.
|
||||
|
||||
.Username and Password Submitted
|
||||
====
|
||||
[source,http]
|
||||
----
|
||||
POST /login HTTP/1.1
|
||||
@@ -34,31 +33,26 @@ Cookie: SESSION=91470ce0-3f3c-455b-b7ad-079b02290f7b
|
||||
|
||||
username=user&password=password&_csrf=35942e65-a172-4cd4-a1d4-d16a51147b3e
|
||||
----
|
||||
====
|
||||
|
||||
Upon authenticating the user, the user is associated to a new session id to prevent xref:servlet/authentication/session-management.adoc#ns-session-fixation[session fixation attacks].
|
||||
|
||||
.Authenticated User is Associated to New Session
|
||||
====
|
||||
[source,http]
|
||||
----
|
||||
HTTP/1.1 302 Found
|
||||
Location: /
|
||||
Set-Cookie: SESSION=4c66e474-3f5a-43ed-8e48-cc1d8cb1d1c8; Path=/; HttpOnly; SameSite=Lax
|
||||
----
|
||||
====
|
||||
|
||||
Subsequent requests include the session cookie which is used to authenticate the user for the remainder of the session.
|
||||
|
||||
.Authenticated Session Provided as Credentials
|
||||
====
|
||||
[source,http]
|
||||
----
|
||||
GET / HTTP/1.1
|
||||
Host: example.com
|
||||
Cookie: SESSION=4c66e474-3f5a-43ed-8e48-cc1d8cb1d1c8
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
[[securitycontextrepository]]
|
||||
@@ -85,7 +79,7 @@ If it is not desirable to associate the `SecurityContext` to an `HttpSession` (i
|
||||
[[requestattributesecuritycontextrepository]]
|
||||
=== RequestAttributeSecurityContextRepository
|
||||
|
||||
The {security-api-url}org/springframework/security/web/context/RequestAttributeSecurityContextRepository.html[`RequestAttributeSecurityContextRepository`] saves the `SecurityContext` as a request attribute to make sure the `SecurityContext` is avaible for a single request that occurs across dispatch types that may clear out the `SecurityContext`.
|
||||
The {security-api-url}org/springframework/security/web/context/RequestAttributeSecurityContextRepository.html[`RequestAttributeSecurityContextRepository`] saves the `SecurityContext` as a request attribute to make sure the `SecurityContext` is available for a single request that occurs across dispatch types that may clear out the `SecurityContext`.
|
||||
|
||||
For example, assume that a client makes a request, is authenticated, and then an error occurs.
|
||||
Depending on the servlet container implementation, the error means that any `SecurityContext` that was established is cleared out and then the error dispatch is made.
|
||||
@@ -93,8 +87,10 @@ When the error dispatch is made, there is no `SecurityContext` established.
|
||||
This means that the error page cannot use the `SecurityContext` for authorization or displaying the current user unless the `SecurityContext` is persisted somehow.
|
||||
|
||||
.Use RequestAttributeSecurityContextRepository
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
@@ -107,7 +103,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http security-context-repository-ref="contextRepository">
|
||||
@@ -116,7 +113,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
<b:bean name="contextRepository"
|
||||
class="org.springframework.security.web.context.RequestAttributeSecurityContextRepository" />
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[delegatingsecuritycontextrepository]]
|
||||
=== DelegatingSecurityContextRepository
|
||||
@@ -126,8 +123,10 @@ The {security-api-url}org/springframework/security/web/context/DelegatingSecurit
|
||||
The most useful arrangement for this is configured with the following example, which allows the use of both xref:requestattributesecuritycontextrepository[`RequestAttributeSecurityContextRepository`] and xref:httpsecuritycontextrepository[`HttpSessionSecurityContextRepository`] simultaneously.
|
||||
|
||||
.Configure DelegatingSecurityContextRepository
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -144,7 +143,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -162,7 +162,8 @@ fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http security-context-repository-ref="contextRepository">
|
||||
@@ -178,7 +179,7 @@ fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
</constructor-arg>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -199,7 +200,7 @@ image:{icondir}/number_2.png[] Next, the application is ran.
|
||||
image:{icondir}/number_3.png[] Finally, if the `SecurityContext` has changed, we save the `SecurityContext` using the `SecurityContextPersistenceRepository`.
|
||||
This means that when using `SecurityContextPersistenceFilter`, just setting the `SecurityContextHolder` will ensure that the `SecurityContext` is persisted using `SecurityContextRepository`.
|
||||
|
||||
In some cases a response is committed and written to the client before the `SecurityContextPersisteneFilter` method completes.
|
||||
In some cases a response is committed and written to the client before the `SecurityContextPersistenceFilter` method completes.
|
||||
For example, if a redirect is sent to the client the response is immediately written back to the client.
|
||||
This means that establishing an `HttpSession` would not be possible in step 3 because the session id could not be included in the already written response.
|
||||
Another situation that can happen is that if a client authenticates successfully, the response is committed before `SecurityContextPersistenceFilter` completes, and the client makes a second request before the `SecurityContextPersistenceFilter` completes the wrong authentication could be present in the second request.
|
||||
|
||||
@@ -26,8 +26,10 @@ This class checks the current contents of the security context and, if it is emp
|
||||
Subclasses override the following methods to obtain this information.
|
||||
|
||||
.Override AbstractPreAuthenticatedProcessingFilter
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
protected abstract Object getPreAuthenticatedPrincipal(HttpServletRequest request);
|
||||
@@ -35,14 +37,15 @@ protected abstract Object getPreAuthenticatedPrincipal(HttpServletRequest reques
|
||||
protected abstract Object getPreAuthenticatedCredentials(HttpServletRequest request);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
protected abstract fun getPreAuthenticatedPrincipal(request: HttpServletRequest): Any?
|
||||
|
||||
protected abstract fun getPreAuthenticatedCredentials(request: HttpServletRequest): Any?
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
After calling these, the filter creates a `PreAuthenticatedAuthenticationToken` that contains the returned data and submits it for authentication.
|
||||
@@ -70,14 +73,12 @@ 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 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.
|
||||
@@ -111,7 +112,6 @@ If an attacker is able to forge the headers in their original request without th
|
||||
==== Siteminder Example Configuration
|
||||
The following example shows a typical configuration that uses this filter:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<security:http>
|
||||
@@ -137,7 +137,6 @@ The following example shows a typical configuration that uses this filter:
|
||||
<security:authentication-provider ref="preauthAuthProvider" />
|
||||
</security:authentication-manager>
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
|
||||
@@ -16,7 +16,6 @@ If you use an authentication provider that does not use a `UserDetailsService` (
|
||||
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:
|
||||
|
||||
====
|
||||
[source,txt]
|
||||
----
|
||||
base64(username + ":" + expirationTime + ":" + algorithmName + ":"
|
||||
@@ -28,7 +27,6 @@ expirationTime: The date and time when the remember-me token expires, express
|
||||
key: A private key to prevent modification of the remember-me token
|
||||
algorithmName: The algorithm used to generate and to verify the remember-me token signature
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
@@ -39,7 +37,6 @@ 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 by adding the `<remember-me>` element:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -47,7 +44,6 @@ If you are familiar with the topics discussed in the chapter on xref:servlet/con
|
||||
<remember-me key="myAppKey"/>
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
@@ -58,7 +54,6 @@ This approach is based on the article titled http://jaspan.com/improved_persiste
|
||||
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]
|
||||
----
|
||||
<http>
|
||||
@@ -66,11 +61,9 @@ To use the this approach with namespace configuration, supply a datasource refer
|
||||
<remember-me data-source-ref="someDataSource"/>
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
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,
|
||||
@@ -78,7 +71,6 @@ 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
|
||||
@@ -87,7 +79,6 @@ It is also used within `BasicAuthenticationFilter`.
|
||||
The hooks invoke a concrete `RememberMeServices` at the appropriate times.
|
||||
The following listing shows the interface:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Authentication autoLogin(HttpServletRequest request, HttpServletResponse response);
|
||||
@@ -97,7 +88,6 @@ void loginFail(HttpServletRequest request, HttpServletResponse response);
|
||||
void loginSuccess(HttpServletRequest request, HttpServletResponse response,
|
||||
Authentication successfulAuthentication);
|
||||
----
|
||||
====
|
||||
|
||||
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`.
|
||||
@@ -120,8 +110,10 @@ If no `algorithmName` is present, the default matching algorithm will be used, w
|
||||
You can specify different algorithms for signature encoding and for signature matching, this allows users to safely upgrade to a different encoding algorithm while still able to verify old ones if there is no `algorithmName` present.
|
||||
To do that you can specify your customized `TokenBasedRememberMeServices` as a Bean and use it in the configuration.
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -144,7 +136,9 @@ RememberMeServices rememberMeServices(UserDetailsService userDetailsService) {
|
||||
return rememberMe;
|
||||
}
|
||||
----
|
||||
.XML
|
||||
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -159,11 +153,10 @@ RememberMeServices rememberMeServices(UserDetailsService userDetailsService) {
|
||||
<property name="encodingAlgorithm" value="SHA256"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The following beans are required in an application context to enable remember-me services:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<bean id="rememberMeFilter" class=
|
||||
@@ -183,7 +176,6 @@ The following beans are required in an application context to enable remember-me
|
||||
<property name="key" value="springRocks"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
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`).
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ Because Spring Security provides a number of helper classes that automatically c
|
||||
== Configuration
|
||||
Spring Security provices a `RunAsManager` interface:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Authentication buildRunAs(Authentication authentication, Object object,
|
||||
@@ -24,7 +23,6 @@ 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.
|
||||
@@ -46,7 +44,6 @@ 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]
|
||||
----
|
||||
<bean id="runAsManager"
|
||||
@@ -59,7 +56,6 @@ The `RunAsManagerImpl` and `RunAsImplAuthenticationProvider` is created in the b
|
||||
<property name="key" value="my_run_as_password"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
|
||||
@@ -87,8 +87,10 @@ First, you need to create an implementation of `SecurityContextRepository` or us
|
||||
|
||||
[[customizing-the-securitycontextrepository]]
|
||||
.Customizing the `SecurityContextRepository`
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -103,7 +105,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -119,7 +122,8 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http security-context-repository-ref="repo">
|
||||
@@ -127,7 +131,7 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
</http>
|
||||
<bean name="repo" class="com.example.MyCustomSecurityContextRepository" />
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -144,8 +148,10 @@ In some cases, for example, you might be authenticating a user manually instead
|
||||
You can use a custom filters or a {spring-framework-reference-url}/web.html#mvc-controller[Spring MVC controller] endpoint to do that.
|
||||
If you want to save the authentication between requests, in the `HttpSession`, for example, you have to do so:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
private SecurityContextRepository securityContextRepository =
|
||||
@@ -170,7 +176,7 @@ class LoginRequest {
|
||||
// getters and setters
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
<1> Add the `SecurityContextRepository` to the controller
|
||||
<2> Inject the `HttpServletRequest` and `HttpServletResponse` to be able to save the `SecurityContext`
|
||||
@@ -194,14 +200,16 @@ The reason is that it doesn't remove it from the `SecurityContextRepository`, wh
|
||||
|
||||
To make sure the authentication is properly cleared and saved, you can invoke {security-api-url}/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html[the `SecurityContextLogoutHandler`] which does that for us, like so:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
SecurityContextLogoutHandler handler = new SecurityContextLogoutHandler(); <1>
|
||||
handler.logout(httpServletRequest, httpServletResponse, null); <2>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
<1> Create a new instance of `SecurityContextLogoutHandler`
|
||||
<2> Call the `logout` method passing in the `HttpServletRequest`, `HttpServletResponse` and a `null` authentication because it is not required for this handler.
|
||||
@@ -216,8 +224,10 @@ Some authentication mechanisms like xref:servlet/authentication/passwords/basic.
|
||||
|
||||
If you do not wish to create sessions, you can use `SessionCreationPolicy.STATELESS`, like so:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -231,7 +241,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -246,19 +257,20 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http create-session="stateless">
|
||||
<!-- ... -->
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The above configuration is <<customizing-where-authentication-is-stored, configuring the `SecurityContextRepository`>> to use a `NullSecurityContextRepository` and is also xref:servlet/architecture.adoc#requestcache-prevent-saved-request[preventing the request from being saved in the session].
|
||||
|
||||
[[never-policy-session-still-created]]
|
||||
|
||||
[[never-policy-session-still-created]]
|
||||
If you are using `SessionCreationPolicy.NEVER`, you might notice that the application is still creating a `HttpSession`.
|
||||
In most cases, this happens because the xref:servlet/architecture.adoc#savedrequests[request is saved in the session] for the authenticated resource to re-request after authentication is successful.
|
||||
To avoid that, please refer to xref:servlet/architecture.adoc#requestcache-prevent-saved-request[how to prevent the request of being saved] section.
|
||||
@@ -272,8 +284,10 @@ If, for some reason, you are using a stateless authentication mechanism, but you
|
||||
For the xref:servlet/authentication/passwords/basic.adoc[HTTP Basic], you can add xref:servlet/configuration/java.adoc#post-processing-configured-objects[a `ObjectPostProcessor`] that changes the `SecurityContextRepository` used by the `BasicAuthenticationFilter`:
|
||||
|
||||
.Store HTTP Basic authentication in the `HttpSession`
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -293,7 +307,7 @@ SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The above also applies to others authentication mechanisms, like xref:servlet/oauth2/resource-server/index.adoc[Bearer Token Authentication].
|
||||
|
||||
@@ -322,8 +336,10 @@ In summary, when `requireExplicitSave` is `true`, Spring Security sets up xref:s
|
||||
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:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -332,7 +348,8 @@ public HttpSessionEventPublisher httpSessionEventPublisher() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -341,7 +358,8 @@ open fun httpSessionEventPublisher(): HttpSessionEventPublisher {
|
||||
}
|
||||
----
|
||||
|
||||
.web.xml
|
||||
web.xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<listener>
|
||||
@@ -350,12 +368,14 @@ open fun httpSessionEventPublisher(): HttpSessionEventPublisher {
|
||||
</listener-class>
|
||||
</listener>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Then add the following lines to your security configuration:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -368,7 +388,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -384,7 +405,8 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -394,15 +416,17 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
</session-management>
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
This will prevent a user from logging in multiple times - a second login will cause the first to be invalidated.
|
||||
|
||||
Using Spring Boot, you can test the above configuration scenario the following way:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@@ -432,14 +456,16 @@ public class MaximumSessionsTests {
|
||||
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can try it using the {gh-samples-url}/servlet/spring-boot/java/session-management/maximum-sessions[Maximum Sessions sample].
|
||||
|
||||
It is also common that you would prefer to prevent a second login, in which case you can use:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -453,7 +479,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -470,7 +497,8 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -479,7 +507,7 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
</session-management>
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
The second login will then be rejected.
|
||||
@@ -489,8 +517,10 @@ If instead you want to use an error page, you can add the attribute `session-aut
|
||||
|
||||
Using Spring Boot, you can test the above configuration the following way:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@@ -521,7 +551,7 @@ public class MaximumSessionsPreventLoginTests {
|
||||
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If you are using a customized authentication filter for form-based login, then you have to configure concurrent session control support explicitly.
|
||||
You can try it using the {gh-samples-url}/servlet/spring-boot/java/session-management/maximum-sessions-prevent-login[Maximum Sessions Prevent Login sample].
|
||||
@@ -533,8 +563,10 @@ That said, Spring Security can detect when a session has expired and take specif
|
||||
For example, you may want to redirect to a specific endpoint when a user makes a request with an already-expired session.
|
||||
This is achieved through the `invalidSessionUrl` in `HttpSecurity`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -547,7 +579,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -561,7 +594,8 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -569,7 +603,7 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
<session-management invalid-session-url="/invalidSession" />
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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.
|
||||
@@ -580,8 +614,10 @@ If that is your case, you might want to <<clearing-session-cookie-on-logout,conf
|
||||
The `invalidSessionUrl` is a convenience method for setting the `InvalidSessionStrategy` using the {security-api-url}/org/springframework/security/web/session/SimpleRedirectInvalidSessionStrategy.html[`SimpleRedirectInvalidSessionStrategy` implementation].
|
||||
If you want to customize the behavior, you can implement the {security-api-url}/org/springframework/security/web/session/InvalidSessionStrategy.html[`InvalidSessionStrategy`] interface and configure it using the `invalidSessionStrategy` method:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -594,7 +630,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -608,7 +645,8 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -617,15 +655,17 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
<bean name="myCustomInvalidSessionStrategy" class="com.example.MyCustomInvalidSessionStrategy" />
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[clearing-session-cookie-on-logout]]
|
||||
== Clearing Session Cookies on Logout
|
||||
|
||||
You can explicitly delete the JSESSIONID cookie on logging out, for example by using the https://w3c.github.io/webappsec-clear-site-data/[`Clear-Site-Data` header] in the logout handler:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -638,7 +678,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -652,7 +693,8 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -670,14 +712,16 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
</b:bean>
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
This has the advantage of being container agnostic and will work with any container that supports the `Clear-Site-Data` header.
|
||||
|
||||
As an alternative, you can also use the following syntax in the logout handler:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -690,7 +734,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -704,14 +749,15 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
<logout delete-cookies="JSESSIONID" />
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Unfortunately, this cannot be guaranteed to work with every servlet container, so you need to test it in your environment.
|
||||
|
||||
@@ -721,14 +767,12 @@ If you run your application behind a proxy, you may also be able to remove the s
|
||||
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]
|
||||
----
|
||||
<LocationMatch "/tutorial/logout">
|
||||
Header always set Set-Cookie "JSESSIONID=;Path=/tutorial;Expires=Thu, 01 Jan 1970 00:00:00 GMT"
|
||||
</LocationMatch>
|
||||
----
|
||||
====
|
||||
|
||||
More details on the xref:servlet/exploits/headers.adoc#servlet-headers-clear-site-data[Clear Site Data] and xref:servlet/authentication/logout.adoc[Logout sections].
|
||||
|
||||
@@ -757,8 +801,10 @@ This is the default in Servlet 3.0 or older containers.
|
||||
|
||||
You can configure the session fixation protection by doing:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -773,7 +819,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -789,14 +836,15 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
<session-management session-fixation-protection="newSession" />
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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 ``jakarta.servlet.http.HttpSessionIdListener``s being notified, so use caution if your code listens for both events.
|
||||
@@ -810,8 +858,10 @@ You can also set the session fixation protection to `none` to disable it, but th
|
||||
|
||||
Consider the following block of code:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
|
||||
@@ -822,7 +872,7 @@ SecurityContext context = SecurityContextHolder.createEmptyContext(); <1>
|
||||
context.setAuthentication(authentication); <2>
|
||||
SecurityContextHolder.setContext(context); <3>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
1. Creates an empty `SecurityContext` instance by accessing the `SecurityContextHolder` statically.
|
||||
2. Sets the `Authentication` object in the `SecurityContext` instance.
|
||||
@@ -837,8 +887,10 @@ By default, they will still look up the strategy from `SecurityContextHolder`.
|
||||
These changes are largely internal, but they present the opportunity for applications to autowire the `SecurityContextHolderStrategy` instead of accessing the `SecurityContext` statically.
|
||||
To do so, you should change the code to the following:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class SomeClass {
|
||||
@@ -857,7 +909,7 @@ public class SomeClass {
|
||||
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
1. Creates an empty `SecurityContext` instance using the configured `SecurityContextHolderStrategy`.
|
||||
2. Sets the `Authentication` object in the `SecurityContext` instance.
|
||||
@@ -870,8 +922,10 @@ public class SomeClass {
|
||||
At times, it can be valuable to eagerly create sessions.
|
||||
This can be done by using the {security-api-url}org/springframework/security/web/session/ForceEagerSessionCreationFilter.html[`ForceEagerSessionCreationFilter`] which can be configured using:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -884,7 +938,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -898,14 +953,15 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http create-session="ALWAYS">
|
||||
|
||||
</http>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ You should get this working before trying it out with Spring Security.
|
||||
Enabling X.509 client authentication is very straightforward.
|
||||
To do so, add the `<x509/>` element to your http security namespace configuration:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -29,7 +28,6 @@ To do so, add the `<x509/>` element to your http security namespace configuratio
|
||||
<x509 subject-principal-regex="CN=(.*?)," user-service-ref="userService"/>;
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
The element has two optional attributes:
|
||||
|
||||
@@ -60,7 +58,6 @@ 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:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" scheme="https" secure="true"
|
||||
@@ -71,7 +68,6 @@ To run tomcat with SSL support, drop the `server.jks` file into the tomcat `conf
|
||||
truststoreType="JKS" truststorePass="password"
|
||||
/>
|
||||
----
|
||||
====
|
||||
|
||||
`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.
|
||||
|
||||
@@ -143,8 +143,10 @@ We do not intend to support non-long identifiers in Spring Security's ACL module
|
||||
|
||||
The following fragment of code shows how to create an `Acl` or modify an existing `Acl`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
// Prepare the information we'd like in our access control entry (ACE)
|
||||
@@ -165,7 +167,8 @@ acl.insertAce(acl.getEntries().length, p, sid, true);
|
||||
aclService.updateAcl(acl);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
val oi: ObjectIdentity = ObjectIdentityImpl(Foo::class.java, 44)
|
||||
@@ -184,7 +187,7 @@ aclService.createAcl(oi)
|
||||
acl!!.insertAce(acl.entries.size, p, sid, true)
|
||||
aclService.updateAcl(acl)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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.
|
||||
|
||||
@@ -14,14 +14,12 @@ The `GrantedAuthority` objects are inserted into the `Authentication` object by
|
||||
|
||||
The `GrantedAuthority` interface has only one method:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
|
||||
String getAuthority();
|
||||
|
||||
----
|
||||
====
|
||||
|
||||
This method lets an
|
||||
`AccessDecisionManager` instance to obtain a precise `String` representation of the `GrantedAuthority`.
|
||||
@@ -49,7 +47,6 @@ Applications that customize an `AccessDecisionManager` or `AccessDecisionVoter`
|
||||
``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> authentication, Object secureObject);
|
||||
@@ -59,7 +56,6 @@ default AuthorizationDecision verify(Supplier<Authentication> authentication, Ob
|
||||
// ...
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
@@ -117,8 +113,10 @@ In some cases, like migrating an older application, it may be desirable to intro
|
||||
To call an existing `AccessDecisionManager`, you can do:
|
||||
|
||||
.Adapting an AccessDecisionManager
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Component
|
||||
@@ -144,15 +142,17 @@ public class AccessDecisionManagerAuthorizationManagerAdapter implements Authori
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
And then wire it into your `SecurityFilterChain`.
|
||||
|
||||
Or to only call an `AccessDecisionVoter`, you can do:
|
||||
|
||||
.Adapting an AccessDecisionVoter
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Component
|
||||
@@ -174,7 +174,7 @@ public class AccessDecisionVoterAuthorizationManagerAdapter implements Authoriza
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
And then wire it into your `SecurityFilterChain`.
|
||||
|
||||
@@ -191,8 +191,10 @@ An extended version of Spring Security's `RoleVoter`, `RoleHierarchyVoter`, is c
|
||||
A typical configuration might look like this:
|
||||
|
||||
.Hierarchical Roles Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -205,7 +207,8 @@ AccessDecisionVoter hierarchyVoter() {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,java,role="secondary"]
|
||||
----
|
||||
|
||||
@@ -223,7 +226,7 @@ AccessDecisionVoter hierarchyVoter() {
|
||||
</property>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
`RoleHierarchy` bean configuration is not yet ported over to `@EnableMethodSecurity`.
|
||||
@@ -285,7 +288,6 @@ The `AccessDecisionManager` then decides whether or not to throw an `AccessDenie
|
||||
|
||||
The `AccessDecisionVoter` interface has three methods:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attrs);
|
||||
@@ -294,7 +296,6 @@ boolean supports(ConfigAttribute attribute);
|
||||
|
||||
boolean supports(Class clazz);
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
|
||||
@@ -16,8 +16,10 @@ 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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -31,7 +33,7 @@ SecurityFilterChain web(HttpSecurity http) throws AuthenticationException {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
This improves on `authorizeRequests` in a number of ways:
|
||||
|
||||
@@ -56,8 +58,10 @@ In this case the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilt
|
||||
We can configure Spring Security to have different rules by adding more rules in order of precedence.
|
||||
|
||||
.Authorize Requests
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -75,7 +79,7 @@ SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
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.
|
||||
@@ -91,8 +95,10 @@ This is a good strategy if you do not want to accidentally forget to update your
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -127,15 +133,17 @@ AuthorizationManager<RequestAuthorizationContext> requestMatcherAuthorizationMan
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -149,13 +157,15 @@ SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Or you can provide it for all requests as seen below:
|
||||
|
||||
.Custom Authorization Manager for All Requests
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -169,14 +179,16 @@ SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
By default, the `AuthorizationFilter` applies to all dispatcher types.
|
||||
We can configure Spring Security to not apply the authorization rules to all dispatcher types by using the `shouldFilterAllDispatcherTypes` method:
|
||||
|
||||
.Set shouldFilterAllDispatcherTypes to false
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -191,7 +203,9 @@ SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
.Kotlin
|
||||
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -205,14 +219,16 @@ open fun web(http: HttpSecurity): SecurityFilterChain {
|
||||
return http.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Instead of setting `shouldFilterAllDispatcherTypes` to `false`, the recommended approach is to customize authorization on the dispatcher types.
|
||||
For example, you may want to grant all access on requests with dispatcher type `ASYNC` or `FORWARD`.
|
||||
|
||||
.Permit ASYNC and FORWARD dispatcher type
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -227,7 +243,9 @@ SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
.Kotlin
|
||||
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -241,13 +259,15 @@ open fun web(http: HttpSecurity): SecurityFilterChain {
|
||||
return http.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can also customize it to require a specific role for a dispatcher type:
|
||||
|
||||
.Require ADMIN for Dispatcher Type ERROR
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -262,7 +282,9 @@ SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
.Kotlin
|
||||
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -276,7 +298,7 @@ open fun web(http: HttpSecurity): SecurityFilterChain {
|
||||
return http.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
== Request Matchers
|
||||
|
||||
@@ -285,8 +307,10 @@ We use `securityMatchers` to determine if a given `HttpSecurity` should be appli
|
||||
The same way, we can use `requestMatchers` to determine the authorization rules that we should apply to a given request.
|
||||
Look at the following example:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -307,7 +331,9 @@ public class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
.Kotlin
|
||||
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -329,7 +355,7 @@ open class SecurityConfig {
|
||||
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
<1> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`
|
||||
<2> Allow access to URLs that start with `/user/` to users with the `USER` role
|
||||
@@ -341,8 +367,10 @@ You can read more about the Spring MVC integration xref:servlet/integrations/mvc
|
||||
|
||||
If you want to use a specific `RequestMatcher`, just pass an implementation to the `securityMatcher` and/or `requestMatcher` methods:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; <1>
|
||||
@@ -375,7 +403,9 @@ public class MyCustomRequestMatcher implements RequestMatcher {
|
||||
}
|
||||
}
|
||||
----
|
||||
.Kotlin
|
||||
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher <1>
|
||||
@@ -401,7 +431,7 @@ open class SecurityConfig {
|
||||
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
<1> Import the static factory methods from `AntPathRequestMatcher` and `RegexRequestMatcher` to create `RequestMatcher` instances.
|
||||
<2> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`, using `AntPathRequestMatcher`
|
||||
@@ -416,37 +446,43 @@ However, `WebExpressionAuthorizationManager` is available to help migrate legacy
|
||||
|
||||
To use `WebExpressionAuthorizationManager`, you can construct one with the expression you are trying to migrate, like so:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
.requestMatchers("/test/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
.requestMatchers("/test/**").access(WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If you are referring to a bean in your expression like so: `@webSecurity.check(authentication, request)`, it's recommended that you instead call the bean directly, which will look something like the following:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
.requestMatchers("/test/**").access((authentication, context) ->
|
||||
new AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
.requestMatchers("/test/**").access((authentication, context): AuthorizationManager<RequestAuthorizationContext> ->
|
||||
AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
For complex instructions that include bean references as well as other expressions, it is recommended that you change those to implement `AuthorizationManager` and refer to them by calling `.access(AuthorizationManager)`.
|
||||
|
||||
|
||||
@@ -33,8 +33,10 @@ The following listing shows the explicit configuration:
|
||||
|
||||
[[servlet-authorize-requests-defaults]]
|
||||
.Every Request Must be Authenticated
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -48,7 +50,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -57,7 +60,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -71,13 +75,15 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
return http.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
We can configure Spring Security to have different rules by adding more rules in order of precedence:
|
||||
|
||||
.Authorize Requests
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -94,7 +100,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http> <!--1-->
|
||||
@@ -110,7 +117,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -129,7 +137,7 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
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.
|
||||
@@ -140,7 +148,6 @@ 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.
|
||||
====
|
||||
|
||||
|
||||
[[filtersecurityinterceptor-every-request]]
|
||||
@@ -151,8 +158,10 @@ This means that if a request is dispatched from a request that was already filte
|
||||
In some scenarios, you may not want to apply authorization on some dispatcher types:
|
||||
|
||||
.Permit ASYNC and ERROR dispatcher types
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -167,7 +176,9 @@ SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
.XML
|
||||
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http auto-config="true">
|
||||
@@ -180,4 +191,4 @@ SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
<b:constructor-arg value="ERROR"/>
|
||||
</b:bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -9,8 +9,10 @@ To listen for these events, you must first publish an `AuthorizationEventPublish
|
||||
Spring Security's `SpringAuthorizationEventPublisher` will probably do fine.
|
||||
It comes publishes authorization events using Spring's `ApplicationEventPublisher`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -20,7 +22,8 @@ public AuthorizationEventPublisher authorizationEventPublisher
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -29,12 +32,14 @@ fun authorizationEventPublisher
|
||||
return SpringAuthorizationEventPublisher(applicationEventPublisher)
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Then, you can use Spring's `@EventListener` support:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Component
|
||||
@@ -47,7 +52,8 @@ public class AuthenticationEvents {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Component
|
||||
@@ -59,7 +65,7 @@ class AuthenticationEvents {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[authorization-granted-events]]
|
||||
== Authorization Granted Events
|
||||
@@ -71,8 +77,10 @@ In fact, publishing these events will likely require some business logic on your
|
||||
You can create your own event publisher that filters success events.
|
||||
For example, the following publisher only publishes authorization grants where `ROLE_ADMIN` was required:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Component
|
||||
@@ -117,7 +125,8 @@ public class MyAuthorizationEventPublisher implements AuthorizationEventPublishe
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Component
|
||||
@@ -157,4 +166,4 @@ class MyAuthorizationEventPublisher(val publisher: ApplicationEventPublisher,
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -88,7 +88,6 @@ Spring Security then expects the `access` attributes of the `<intercept-url>` el
|
||||
Each expression should evaluate to a Boolean, defining whether access should be allowed or not.
|
||||
The following listing shows an example:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -97,7 +96,6 @@ The following listing shows an example:
|
||||
...
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
@@ -113,8 +111,10 @@ So, if you do not use the namespace and want to use expressions, you have to add
|
||||
If you wish to extend the expressions that are available, you can easily refer to any Spring Bean you expose.
|
||||
For example, you could use the following, assuming you have a Bean with the name of `webSecurity` that contains the following method signature:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class WebSecurity {
|
||||
@@ -124,7 +124,8 @@ public class WebSecurity {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class WebSecurity {
|
||||
@@ -133,13 +134,15 @@ class WebSecurity {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You could then refer to the method as follows:
|
||||
|
||||
.Refer to method
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
http
|
||||
@@ -149,7 +152,8 @@ http
|
||||
)
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -159,7 +163,8 @@ http
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
http {
|
||||
@@ -168,7 +173,7 @@ http {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[el-access-web-path-variables]]
|
||||
=== Path Variables in Web Security Expressions
|
||||
@@ -179,8 +184,10 @@ For example, consider a RESTful application that looks up a user by ID from a UR
|
||||
You can easily refer to the path variable by placing it in the pattern.
|
||||
For example, you could use the following if you had a Bean with the name of `webSecurity` that contains the following method signature:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class WebSecurity {
|
||||
@@ -190,7 +197,8 @@ public class WebSecurity {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class WebSecurity {
|
||||
@@ -199,13 +207,15 @@ class WebSecurity {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You could then refer to the method as follows:
|
||||
|
||||
.Path Variables
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary",attrs="-attributes"]
|
||||
----
|
||||
http
|
||||
@@ -215,7 +225,8 @@ http
|
||||
);
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
<http>
|
||||
@@ -225,7 +236,8 @@ http
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary",attrs="-attributes"]
|
||||
----
|
||||
http {
|
||||
@@ -234,7 +246,7 @@ http {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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`.
|
||||
@@ -249,52 +261,56 @@ There are four annotations that support expression attributes to allow pre and p
|
||||
They are `@PreAuthorize`, `@PreFilter`, `@PostAuthorize`, and `@PostFilter`.
|
||||
Their use is enabled through the `global-method-security` namespace element:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<global-method-security pre-post-annotations="enabled"/>
|
||||
----
|
||||
====
|
||||
|
||||
==== Access Control using @PreAuthorize and @PostAuthorize
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
public void create(Contact contact);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
fun create(contact: Contact?)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@PreAuthorize("hasPermission(#contact, 'admin')")
|
||||
public void deletePermission(Contact contact, Sid recipient, Permission permission);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@PreAuthorize("hasPermission(#contact, 'admin')")
|
||||
fun deletePermission(contact: Contact?, recipient: Sid?, permission: Permission?)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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 <<el-permission-evaluator,see later in this section>>.
|
||||
@@ -310,8 +326,10 @@ The following example uses the `@P` annotation:
|
||||
|
||||
+
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
import org.springframework.security.access.method.P;
|
||||
@@ -322,7 +340,8 @@ import org.springframework.security.access.method.P;
|
||||
public void doSomething(@P("c") Contact contact);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
import org.springframework.security.access.method.P
|
||||
@@ -332,7 +351,7 @@ import org.springframework.security.access.method.P
|
||||
@PreAuthorize("#c.name == authentication.name")
|
||||
fun doSomething(@P("c") contact: Contact?)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
+
|
||||
|
||||
@@ -342,8 +361,10 @@ Behind the scenes, this is implemented by using `AnnotationParameterNameDiscover
|
||||
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 `@Param` annotation:
|
||||
+
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
import org.springframework.data.repository.query.Param;
|
||||
@@ -354,7 +375,8 @@ import org.springframework.data.repository.query.Param;
|
||||
Contact findContactByName(@Param("n") String name);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
import org.springframework.data.repository.query.Param
|
||||
@@ -364,7 +386,7 @@ import org.springframework.data.repository.query.Param
|
||||
@PreAuthorize("#n == authentication.name")
|
||||
fun findContactByName(@Param("n") name: String?): Contact?
|
||||
----
|
||||
====
|
||||
======
|
||||
+
|
||||
|
||||
Behind the scenes, this is implemented by using `AnnotationParameterNameDiscoverer`, which you can customize to support the value attribute of any specified annotation.
|
||||
@@ -380,21 +402,24 @@ For interfaces, annotations or the JDK 8 approach must be used.
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@PreAuthorize("#contact.name == authentication.name")
|
||||
public void doSomething(Contact contact);
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@PreAuthorize("#contact.name == authentication.name")
|
||||
fun doSomething(contact: Contact?)
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
.[[el-pre-post-annotations-post]]
|
||||
Here, we access another built-in expression, `authentication`, which is the `Authentication` stored in the security context.
|
||||
@@ -406,8 +431,10 @@ Spring Security supports filtering of collections, arrays, maps, and streams by
|
||||
This is most commonly performed on the return value of a method.
|
||||
The following example uses `@PostFilter`:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
@@ -415,14 +442,15 @@ The following example uses `@PostFilter`:
|
||||
public List<Contact> getAll();
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
@PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')")
|
||||
fun getAll(): List<Contact?>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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 that contains filtered elements is returned.
|
||||
@@ -448,7 +476,6 @@ It is intended to bridge between the expression system and Spring Security's ACL
|
||||
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,
|
||||
@@ -457,7 +484,6 @@ boolean hasPermission(Authentication authentication, Object targetDomainObject,
|
||||
boolean hasPermission(Authentication authentication, Serializable targetId,
|
||||
String targetType, Object permission);
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
@@ -469,7 +495,6 @@ This has traditionally been the Java class of the object but does not have to be
|
||||
To use `hasPermission()` expressions, you have to explicitly configure a `PermissionEvaluator` in your application context.
|
||||
The following example shows how to do so:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<security:global-method-security pre-post-annotations="enabled">
|
||||
@@ -481,7 +506,6 @@ The following example shows how to do so:
|
||||
<property name="permissionEvaluator" ref="myPermissionEvaluator"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
Where `myPermissionEvaluator` is the bean which implements `PermissionEvaluator`.
|
||||
Usually, this is the implementation from the ACL module, which is called `AclPermissionEvaluator`.
|
||||
@@ -493,17 +517,17 @@ You can make use of meta annotations for method security to make your code more
|
||||
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, you can create a meta annotation:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@@ -511,14 +535,15 @@ Instead of repeating this everywhere, you can create a meta annotation:
|
||||
public @interface ContactPermission {}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
@PreAuthorize("#contact.name == authentication.name")
|
||||
annotation class ContactPermission
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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.
|
||||
|
||||
@@ -30,8 +30,10 @@ For earlier versions, please read about similar support with <<jc-enable-global-
|
||||
For example, the following would enable Spring Security's `@PreAuthorize` annotation:
|
||||
|
||||
.Method Security Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -41,7 +43,8 @@ public class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -51,20 +54,23 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:method-security/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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 `DefaultAuthorizationMethodInterceptorChain` for it to make the actual decision:
|
||||
|
||||
.Method Security Annotation Usage
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public interface BankService {
|
||||
@@ -79,7 +85,8 @@ public interface BankService {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
interface BankService {
|
||||
@@ -93,13 +100,15 @@ interface BankService {
|
||||
fun post(account : Account, amount : Double) : Account
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can enable support for Spring Security's `@Secured` annotation using:
|
||||
|
||||
.@Secured Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -109,7 +118,8 @@ public class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -119,18 +129,21 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:method-security secured-enabled="true"/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
or JSR-250 using:
|
||||
|
||||
.JSR-250 Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -140,7 +153,8 @@ public class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -150,12 +164,13 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:method-security jsr250-enabled="true"/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
=== Customizing Authorization
|
||||
|
||||
@@ -165,8 +180,10 @@ Spring Security's `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFil
|
||||
If you need to customize the way that expressions are handled, you can expose a custom `MethodSecurityExpressionHandler`, like so:
|
||||
|
||||
.Custom MethodSecurityExpressionHandler
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -177,7 +194,8 @@ static MethodSecurityExpressionHandler methodSecurityExpressionHandler() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
companion object {
|
||||
@@ -190,7 +208,8 @@ companion object {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:method-security>
|
||||
@@ -202,7 +221,7 @@ companion object {
|
||||
<property name="trustResolver" ref="myCustomTrustResolver"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[TIP]
|
||||
====
|
||||
@@ -215,8 +234,10 @@ Also, for role-based authorization, Spring Security adds a default `ROLE_` prefi
|
||||
You can configure the authorization rules to use a different prefix by exposing a `GrantedAuthorityDefaults` bean, like so:
|
||||
|
||||
.Custom MethodSecurityExpressionHandler
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -225,7 +246,8 @@ static GrantedAuthorityDefaults grantedAuthorityDefaults() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
companion object {
|
||||
@@ -236,7 +258,8 @@ companion object {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:method-security/>
|
||||
@@ -245,7 +268,7 @@ companion object {
|
||||
<constructor-arg value="MYPREFIX_"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[TIP]
|
||||
====
|
||||
@@ -268,8 +291,10 @@ If that authorization denies access, the value is not returned, and an `AccessDe
|
||||
To recreate what adding `@EnableMethodSecurity` does by default, you would publish the following configuration:
|
||||
|
||||
.Full Pre-post Method Security Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -301,7 +326,8 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -333,7 +359,8 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:method-security pre-post-enabled="false"/>
|
||||
@@ -351,15 +378,17 @@ class MethodSecurityConfig {
|
||||
<bean id="postFilterAuthorizationMethodInterceptor"
|
||||
class="org.springframework.security.authorization.method.PostFilterAuthorizationMethodInterceptor"/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Notice that Spring Security's method security is built using Spring AOP.
|
||||
So, interceptors are invoked based on the order specified.
|
||||
This can be customized by calling `setOrder` on the interceptor instances like so:
|
||||
|
||||
.Publish Custom Advisor
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -371,7 +400,8 @@ Advisor postFilterAuthorizationMethodInterceptor() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -383,7 +413,8 @@ fun postFilterAuthorizationMethodInterceptor() : Advisor {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<bean id="postFilterAuthorizationMethodInterceptor"
|
||||
@@ -392,14 +423,16 @@ fun postFilterAuthorizationMethodInterceptor() : Advisor {
|
||||
value="#{T(org.springframework.security.authorization.method.AuthorizationInterceptorsOrder).POST_AUTHORIZE.getOrder() -1}"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You may want to only support `@PreAuthorize` in your application, in which case you can do the following:
|
||||
|
||||
|
||||
.Only @PreAuthorize Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -413,7 +446,8 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -427,7 +461,8 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:method-security pre-post-enabled="false"/>
|
||||
@@ -438,7 +473,7 @@ class MethodSecurityConfig {
|
||||
class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
|
||||
factory-method="preAuthorize"/>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Or, you may have a custom before-method `AuthorizationManager` that you want to add to the list.
|
||||
|
||||
@@ -447,9 +482,11 @@ In this case, you will need to tell Spring Security both the `AuthorizationManag
|
||||
Thus, you can configure Spring Security to invoke your `AuthorizationManager` in between `@PreAuthorize` and `@PostAuthorize` like so:
|
||||
|
||||
.Custom Before Advisor
|
||||
====
|
||||
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -468,7 +505,8 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -487,7 +525,8 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:method-security/>
|
||||
@@ -509,7 +548,7 @@ class MethodSecurityConfig {
|
||||
value="#{T(org.springframework.security.authorization.method.AuthorizationInterceptorsOrder).PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1}"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[TIP]
|
||||
====
|
||||
@@ -522,8 +561,10 @@ After-method authorization is generally concerned with analysing the return valu
|
||||
For example, you might have a method that confirms that the account requested actually belongs to the logged-in user like so:
|
||||
|
||||
.@PostAuthorize example
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public interface BankService {
|
||||
@@ -534,7 +575,8 @@ public interface BankService {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
interface BankService {
|
||||
@@ -544,7 +586,7 @@ interface BankService {
|
||||
fun readAccount(id : Long) : Account
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
You can supply your own `AuthorizationMethodInterceptor` to customize how access to the return value is evaluated.
|
||||
|
||||
@@ -552,8 +594,10 @@ For example, if you have your own custom annotation, you can configure it like s
|
||||
|
||||
|
||||
.Custom After Advisor
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -570,7 +614,8 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -587,7 +632,8 @@ class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Xml
|
||||
Xml::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<sec:method-security/>
|
||||
@@ -609,7 +655,7 @@ class MethodSecurityConfig {
|
||||
value="#{T(org.springframework.security.authorization.method.AuthorizationInterceptorsOrder).PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1}"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
and it will be invoked after the `@PostAuthorize` interceptor.
|
||||
|
||||
@@ -619,8 +665,10 @@ and it will be invoked after the `@PostAuthorize` interceptor.
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -630,7 +678,8 @@ public class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -639,14 +688,16 @@ 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 are passed to the `AccessDecisionManager` for it to make the actual decision:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public interface BankService {
|
||||
@@ -662,7 +713,8 @@ public Account post(Account account, double amount);
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
interface BankService {
|
||||
@@ -676,12 +728,14 @@ interface BankService {
|
||||
fun post(account: Account, amount: Double): Account
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Support for JSR-250 annotations can be enabled by using:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -691,7 +745,8 @@ public class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -700,13 +755,15 @@ open class MethodSecurityConfig {
|
||||
// ...
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -716,7 +773,8 @@ public class MethodSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -725,12 +783,14 @@ open class MethodSecurityConfig {
|
||||
// ...
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The equivalent Java code is:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public interface BankService {
|
||||
@@ -746,7 +806,8 @@ public Account post(Account account, double amount);
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
interface BankService {
|
||||
@@ -760,7 +821,7 @@ interface BankService {
|
||||
fun post(account: Account, amount: Double): Account
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
== GlobalMethodSecurityConfiguration
|
||||
|
||||
@@ -768,8 +829,10 @@ Sometimes, you may need to perform operations that are more complicated than are
|
||||
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:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -783,7 +846,8 @@ public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -795,7 +859,7 @@ open class MethodSecurityConfig : GlobalMethodSecurityConfiguration() {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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.
|
||||
|
||||
@@ -805,20 +869,20 @@ This element is used to enable annotation-based security in your application (by
|
||||
You should only declare one `<global-method-security>` element.
|
||||
The following declaration enables support for Spring Security's `@Secured`:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<global-method-security secured-annotations="enabled" />
|
||||
----
|
||||
====
|
||||
|
||||
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 are passed to the `AccessDecisionManager` for it to make the actual decision.
|
||||
The following example shows the `@Secured` annotation in a typical interface:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public interface BankService {
|
||||
@@ -835,7 +899,8 @@ public Account post(Account account, double amount);
|
||||
----
|
||||
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
interface BankService {
|
||||
@@ -849,31 +914,29 @@ interface BankService {
|
||||
fun post(account: Account, amount: Double): Account
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Support for JSR-250 annotations can be enabled by using:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<global-method-security jsr250-annotations="enabled" />
|
||||
----
|
||||
====
|
||||
|
||||
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]
|
||||
----
|
||||
<global-method-security pre-post-annotations="enabled" />
|
||||
----
|
||||
====
|
||||
|
||||
The equivalent Java code is:
|
||||
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public interface BankService {
|
||||
@@ -889,7 +952,8 @@ public Account post(Account account, double amount);
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
interface BankService {
|
||||
@@ -903,7 +967,7 @@ interface BankService {
|
||||
fun post(account: Account, amount: Double): Account
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Expression-based annotations are a good choice if you need to define simple rules that go beyond checking the role names against the user's list of authorities.
|
||||
|
||||
@@ -925,7 +989,6 @@ If two annotations are found which apply to a particular method, then only one o
|
||||
`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]
|
||||
----
|
||||
<global-method-security>
|
||||
@@ -933,7 +996,6 @@ Consider the following example:
|
||||
access="ROLE_USER"/>
|
||||
</global-method-security>
|
||||
----
|
||||
====
|
||||
|
||||
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`.
|
||||
|
||||
@@ -20,7 +20,6 @@ Other implementations are used to handle annotation-based configuration.
|
||||
=== Explicit MethodSecurityInterceptor Configuration
|
||||
You can configure a `MethodSecurityInterceptor` directly in your application context for use with one of Spring AOP's proxying mechanisms:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<bean id="bankManagerSecurity" class=
|
||||
@@ -36,7 +35,6 @@ You can configure a `MethodSecurityInterceptor` directly in your application con
|
||||
</property>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
[[aspectj]]
|
||||
== AspectJ (JoinPoint) Security Interceptor
|
||||
@@ -49,7 +47,6 @@ It would not be uncommon to use both types of security interceptors in the same
|
||||
|
||||
We first consider how the `AspectJSecurityInterceptor` is configured in the Spring application context:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<bean id="bankManagerSecurity" class=
|
||||
@@ -65,14 +62,12 @@ We first consider how the `AspectJSecurityInterceptor` is configured in the Spri
|
||||
</property>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
|
||||
Next, you need to define an AspectJ `aspect`, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
|
||||
@@ -118,7 +113,6 @@ public aspect DomainObjectInstanceSecurityAspect implements InitializingBean {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
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).
|
||||
@@ -128,7 +122,6 @@ The `AspectJSecurityInterceptor` calls this anonymous `AspectJCallback` class wh
|
||||
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]
|
||||
----
|
||||
|
||||
@@ -138,6 +131,5 @@ The following example shows a bean declaration that achieves this:
|
||||
<property name="securityInterceptor" ref="bankManagerSecurity"/>
|
||||
</bean>
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
|
||||
@@ -19,7 +19,6 @@ 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, and so on) within your application.
|
||||
The following example shows the most basic example of a Spring Security Java Configuration:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -40,7 +39,6 @@ public class WebSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
This configuration is not complex or extensive, but it does a lot:
|
||||
|
||||
@@ -78,7 +76,6 @@ The way in which we use `AbstractSecurityWebApplicationInitializer` differs depe
|
||||
|
||||
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.*;
|
||||
@@ -91,7 +88,6 @@ public class SecurityWebApplicationInitializer
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The `SecurityWebApplicationInitializer`:
|
||||
|
||||
@@ -106,7 +102,6 @@ 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 use Spring MVC, our `SecurityWebApplicationInitializer` could look something like the following:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
import org.springframework.security.web.context.*;
|
||||
@@ -116,14 +111,12 @@ public class SecurityWebApplicationInitializer
|
||||
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
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
|
||||
@@ -137,7 +130,6 @@ public class MvcWebApplicationInitializer extends
|
||||
// ... other overrides ...
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[[jc-httpsecurity]]
|
||||
== HttpSecurity
|
||||
@@ -148,7 +140,6 @@ How does Spring Security know we want to support form-based authentication?
|
||||
Actually, there is a configuration class (called `SecurityFilterChain`) that is being invoked behind the scenes.
|
||||
It is configured with the following default implementation:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Bean
|
||||
@@ -162,7 +153,6 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The default configuration (shown in the preceding example):
|
||||
|
||||
@@ -172,7 +162,6 @@ The default configuration (shown in the preceding example):
|
||||
|
||||
Note that this configuration is parallels the XML Namespace configuration:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -181,7 +170,6 @@ Note that this configuration is parallels the XML Namespace configuration:
|
||||
<http-basic />
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
== Multiple HttpSecurity Instances
|
||||
|
||||
@@ -189,7 +177,6 @@ We can configure multiple `HttpSecurity` instances just as we can have multiple
|
||||
The key is to register multiple `SecurityFilterChain` ``@Bean``s.
|
||||
The following example has a different configuration for URL's that start with `/api/`.
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
@@ -234,14 +221,12 @@ public class MultiHttpSecurityConfig {
|
||||
<4> Create another instance of `SecurityFilterChain`.
|
||||
If the URL does not start with `/api/`, this configuration is used.
|
||||
This configuration is considered after `apiFilterChain`, 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:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {
|
||||
@@ -274,7 +259,6 @@ public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurit
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -283,7 +267,6 @@ This is actually how methods like `HttpSecurity.authorizeRequests()` are impleme
|
||||
|
||||
You can then use the custom DSL:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
@@ -300,7 +283,6 @@ public class Config {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The code is invoked in the following order:
|
||||
|
||||
@@ -312,16 +294,13 @@ If you want, you can have `HttpSecurity` add `MyCustomDsl` by default by using `
|
||||
For example, you can create a resource on the classpath named `META-INF/spring.factories` with the following contents:
|
||||
|
||||
.META-INF/spring.factories
|
||||
====
|
||||
[source]
|
||||
----
|
||||
org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyCustomDsl
|
||||
----
|
||||
====
|
||||
|
||||
You can also explicit disable the default:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
@@ -336,7 +315,6 @@ public class Config {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[[post-processing-configured-objects]]
|
||||
== Post Processing Configured Objects
|
||||
@@ -349,7 +327,6 @@ While there are good reasons to not directly expose every property, users may st
|
||||
To address this issue, Spring Security introduces the concept of an `ObjectPostProcessor`, which can be used to modify or replace many of the `Object` instances created by the Java Configuration.
|
||||
For example, to configure the `filterSecurityPublishAuthorizationSuccess` property on `FilterSecurityInterceptor`, you can use the following:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Bean
|
||||
@@ -368,4 +345,3 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
@@ -17,7 +17,6 @@ How does Spring Security know we want to support form-based authentication?
|
||||
There is a configuration class (called `SecurityFilterChain`) that is being invoked behind the scenes.
|
||||
It is configured with the following default implementation:
|
||||
|
||||
====
|
||||
[source,kotlin]
|
||||
----
|
||||
import org.springframework.security.config.annotation.web.invoke
|
||||
@@ -34,7 +33,6 @@ open fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
return http.build()
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[NOTE]
|
||||
Make sure that import the `invoke` function in your class, sometimes the IDE will not auto-import it causing compilation issues.
|
||||
@@ -47,7 +45,6 @@ The default configuration (shown in the preceding listing):
|
||||
|
||||
Note that this configuration is parallels the XML namespace configuration:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -56,7 +53,6 @@ Note that this configuration is parallels the XML namespace configuration:
|
||||
<http-basic />
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
== Multiple HttpSecurity Instances
|
||||
|
||||
@@ -64,7 +60,6 @@ We can configure multiple `HttpSecurity` instances, just as we can have multiple
|
||||
The key is to register multiple `SecurityFilterChain` ``@Bean``s.
|
||||
The following example has a different configuration for URL's that start with `/api/`:
|
||||
|
||||
====
|
||||
[source,kotlin]
|
||||
----
|
||||
@Configuration
|
||||
@@ -113,4 +108,3 @@ class MultiHttpSecurityConfig {
|
||||
<4> Create another instance of `SecurityFilterChain`.
|
||||
If the URL does not start with `/api/`, this configuration is used.
|
||||
This configuration is considered after `apiFilterChain`, since it has an `@Order` value after `1` (no `@Order` defaults to last).
|
||||
====
|
||||
|
||||
@@ -10,12 +10,10 @@ You can use a namespace element to more concisely configure an individual bean o
|
||||
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]
|
||||
----
|
||||
<security:ldap-server />
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
@@ -26,7 +24,6 @@ We recommend that you try the https://spring.io/tools/sts[Spring Tool Suite], as
|
||||
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]
|
||||
----
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
@@ -39,13 +36,11 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
...
|
||||
</beans>
|
||||
----
|
||||
====
|
||||
|
||||
In many of the examples you can see (and in the sample applications), we often use `security` (rather than `beans`) as the default namespace, which means we can omit the prefix on all the security namespace elements, making the content easier to read.
|
||||
You may also want to do this if you have your application context divided up into separate files and have most of your security configuration in one of them.
|
||||
Your security application context file would then start like this:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<beans:beans xmlns="http://www.springframework.org/schema/security"
|
||||
@@ -58,7 +53,6 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
...
|
||||
</beans:beans>
|
||||
----
|
||||
====
|
||||
|
||||
We assume this syntax is being used from now on in this chapter.
|
||||
|
||||
@@ -95,7 +89,6 @@ In later sections, we introduce more advanced namespace configuration options.
|
||||
=== web.xml Configuration
|
||||
The first thing you need to do is add the following filter declaration to your `web.xml` file:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<filter>
|
||||
@@ -108,7 +101,6 @@ The first thing you need to do is add the following filter declaration to your `
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
----
|
||||
====
|
||||
|
||||
`DelegatingFilterProxy` is a Spring Framework class that delegates to a filter implementation that is defined as a Spring bean in your application context.
|
||||
In this case, the bean is named `springSecurityFilterChain`, which is an internal infrastructure bean created by the namespace to handle web security.
|
||||
@@ -121,7 +113,6 @@ Web security services are configured by the `<http>` element.
|
||||
=== A Minimal <http> Configuration
|
||||
To enable web security, you need the following configuration:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -130,7 +121,6 @@ To enable web security, you need the following configuration:
|
||||
<logout />
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
That listing says that we want:
|
||||
|
||||
@@ -159,7 +149,6 @@ You can also add a `method` attribute to limit the match to a particular HTTP me
|
||||
|
||||
To add users, you can define a set of test data directly in the namespace:
|
||||
|
||||
====
|
||||
[source,xml,attrs="-attributes"]
|
||||
----
|
||||
<authentication-manager>
|
||||
@@ -174,12 +163,10 @@ To add users, you can define a set of test data directly in the namespace:
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
----
|
||||
====
|
||||
|
||||
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"]
|
||||
----
|
||||
<authentication-manager>
|
||||
@@ -195,7 +182,6 @@ The password is prefixed with `+{bcrypt}+` to instruct `DelegatingPasswordEncode
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
[subs="quotes"]
|
||||
@@ -225,7 +211,6 @@ This is the URL to which the user is taken after successfully logging in. it def
|
||||
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]
|
||||
----
|
||||
<http pattern="/login.htm*" security="none"/>
|
||||
@@ -235,7 +220,6 @@ This is useful if your application always requires that the user starts at a "`h
|
||||
always-use-default-target='true' />
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
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`.
|
||||
@@ -357,7 +341,6 @@ The filters, aliases, and namespace elements and attributes that create the filt
|
||||
|
||||
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]
|
||||
----
|
||||
<http>
|
||||
@@ -366,7 +349,6 @@ You can add your own filter to the stack by using the `custom-filter` element an
|
||||
|
||||
<beans:bean id="myFilter" class="com.mycompany.MySpecialAuthenticationFilter"/>
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
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.
|
||||
@@ -407,22 +389,18 @@ If you need to use a more complicated access control strategy, you can set an al
|
||||
|
||||
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]
|
||||
----
|
||||
<global-method-security access-decision-manager-ref="myAccessDecisionManagerBean">
|
||||
...
|
||||
</global-method-security>
|
||||
----
|
||||
====
|
||||
|
||||
The syntax for web security is the same, but the attribute is on the `http` element:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http access-decision-manager-ref="myAccessDecisionManagerBean">
|
||||
...
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
@@ -36,7 +36,6 @@ You can configure `CookieCsrfTokenRepository` in XML byusing the following:
|
||||
|
||||
|
||||
.Store CSRF Token in a Cookie with XML Configuration
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -47,7 +46,6 @@ You can configure `CookieCsrfTokenRepository` in XML byusing the following:
|
||||
class="org.springframework.security.web.csrf.CookieCsrfTokenRepository"
|
||||
p:cookieHttpOnly="false"/>
|
||||
----
|
||||
====
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -60,8 +58,10 @@ If you do not need the ability to read the cookie with JavaScript directly, we r
|
||||
You can configure `CookieCsrfTokenRepository` in Java or Kotlin configuration by using:
|
||||
|
||||
.Store CSRF Token in a Cookie
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -79,7 +79,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -97,7 +98,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -114,7 +115,6 @@ However, you can disable CSRF protection if it xref:features/exploits/csrf.adoc#
|
||||
The following XML configuration disables CSRF protection:
|
||||
|
||||
.Disable CSRF XML Configuration
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -122,13 +122,14 @@ The following XML configuration disables CSRF protection:
|
||||
<csrf disabled="true"/>
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
The following Java or Kotlin configuration disables CSRF protection:
|
||||
|
||||
.Disable CSRF
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -144,7 +145,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -162,7 +164,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-csrf-configure-request-handler]]
|
||||
==== Configure CsrfTokenRequestHandler
|
||||
@@ -175,7 +177,6 @@ As of 6.0, the default implementation is `XorCsrfTokenRequestAttributeHandler`,
|
||||
If you wish to disable BREACH protection of the `CsrfToken` and revert to the 5.8 default, you can configure `CsrfTokenRequestAttributeHandler` in XML using the following:
|
||||
|
||||
.Disable BREACH protection XML Configuration
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -185,13 +186,14 @@ If you wish to disable BREACH protection of the `CsrfToken` and revert to the 5.
|
||||
<b:bean id="requestHandler"
|
||||
class="org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler"/>
|
||||
----
|
||||
====
|
||||
|
||||
You can configure `CsrfTokenRequestAttributeHandler` in Java Configuration using the following:
|
||||
|
||||
.Disable BREACH protection
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@EnableWebSecurity
|
||||
@@ -208,7 +210,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@EnableWebSecurity
|
||||
@@ -225,7 +228,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-csrf-include]]
|
||||
=== Include the CSRF Token
|
||||
@@ -243,14 +246,12 @@ To post an HTML form, the CSRF token must be included in the form as a hidden in
|
||||
For example, the rendered HTML might look like:
|
||||
|
||||
.CSRF Token HTML
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<input type="hidden"
|
||||
name="_csrf"
|
||||
value="4bfd1575-3ad1-4d21-96c7-4ef2d9f86721"/>
|
||||
----
|
||||
====
|
||||
|
||||
Next, we discuss various ways of including the CSRF token in a form as a hidden input.
|
||||
|
||||
@@ -274,7 +275,6 @@ If the <<servlet-csrf-include,other options>> for including the actual CSRF toke
|
||||
The following example does this with a JSP:
|
||||
|
||||
.CSRF Token in Form with Request Attribute
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<c:url var="logoutUrl" value="/logout"/>
|
||||
@@ -287,7 +287,6 @@ The following example does this with a JSP:
|
||||
value="${_csrf.token}"/>
|
||||
</form>
|
||||
----
|
||||
====
|
||||
|
||||
[[servlet-csrf-include-ajax]]
|
||||
==== Ajax and JSON Requests
|
||||
@@ -309,7 +308,6 @@ An alternative pattern to <<servlet-csrf-include-form-auto,exposing the CSRF in
|
||||
The HTML might look something like this:
|
||||
|
||||
.CSRF meta tag HTML
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<html>
|
||||
@@ -320,13 +318,11 @@ The HTML might look something like this:
|
||||
</head>
|
||||
<!-- ... -->
|
||||
----
|
||||
====
|
||||
|
||||
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
|
||||
====
|
||||
[source,javascript]
|
||||
----
|
||||
$(function () {
|
||||
@@ -337,7 +333,6 @@ $(function () {
|
||||
});
|
||||
});
|
||||
----
|
||||
====
|
||||
|
||||
[[servlet-csrf-include-ajax-meta-tag]]
|
||||
====== csrfMeta tag
|
||||
@@ -351,7 +346,6 @@ If the <<servlet-csrf-include,other options>> for including the actual CSRF toke
|
||||
The following example does this with a JSP:
|
||||
|
||||
.CSRF meta tag JSP
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<html>
|
||||
@@ -363,7 +357,6 @@ The following example does this with a JSP:
|
||||
</head>
|
||||
<!-- ... -->
|
||||
----
|
||||
====
|
||||
|
||||
[[servlet-csrf-considerations]]
|
||||
== CSRF Considerations
|
||||
@@ -393,8 +386,10 @@ If you really want to use HTTP GET with logout, you can do so. However, remember
|
||||
For example, the following Java Configuration logs out when the `/logout` URL is requested with any HTTP method:
|
||||
|
||||
.Log out with any HTTP method
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -412,7 +407,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -430,7 +426,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
|
||||
[[servlet-considerations-csrf-timeouts]]
|
||||
@@ -477,8 +473,10 @@ In general, this is the recommended approach because the temporary file upload s
|
||||
To ensure that `MultipartFilter` is specified before the Spring Security filter with XML configuration, you can ensure the `<filter-mapping>` element of the `MultipartFilter` is placed before the `springSecurityFilterChain` within the `web.xml` file:
|
||||
|
||||
.Initializer MultipartFilter
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
|
||||
@@ -490,7 +488,8 @@ public class SecurityApplicationInitializer extends AbstractSecurityWebApplicati
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
class SecurityApplicationInitializer : AbstractSecurityWebApplicationInitializer() {
|
||||
@@ -499,12 +498,11 @@ class SecurityApplicationInitializer : AbstractSecurityWebApplicationInitializer
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
To ensure `MultipartFilter` is specified before the Spring Security filter with XML configuration, users can ensure the <filter-mapping> element of the `MultipartFilter` is placed before the springSecurityFilterChain within the web.xml as shown below:
|
||||
|
||||
.web.xml - MultipartFilter
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<filter>
|
||||
@@ -524,7 +522,6 @@ To ensure `MultipartFilter` is specified before the Spring Security filter with
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
----
|
||||
====
|
||||
|
||||
[[servlet-csrf-considerations-multipart-url]]
|
||||
==== Include a CSRF Token in a URL
|
||||
@@ -534,14 +531,12 @@ Since the `CsrfToken` is exposed as an `HttpServletRequest` <<servlet-csrf-inclu
|
||||
The following example does this with a JSP:
|
||||
|
||||
.CSRF Token in Action
|
||||
====
|
||||
[source,html]
|
||||
----
|
||||
<form method="post"
|
||||
action="./upload?${_csrf.parameterName}=${_csrf.token}"
|
||||
enctype="multipart/form-data">
|
||||
----
|
||||
====
|
||||
|
||||
[[servlet-csrf-considerations-override-method]]
|
||||
=== HiddenHttpMethodFilter
|
||||
|
||||
@@ -46,8 +46,10 @@ However, it is important that you do so knowing that this can open your applicat
|
||||
For example, if you wish to use Spring MVC's matrix variables, you could use the following configuration:
|
||||
|
||||
.Allow Matrix Variables
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -58,7 +60,8 @@ public StrictHttpFirewall httpFirewall() {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<b:bean id="httpFirewall"
|
||||
@@ -68,7 +71,8 @@ public StrictHttpFirewall httpFirewall() {
|
||||
<http-firewall ref="httpFirewall"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -78,7 +82,7 @@ fun httpFirewall(): StrictHttpFirewall {
|
||||
return firewall
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
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`.
|
||||
@@ -87,8 +91,10 @@ The following example allows only HTTP `GET` and `POST` methods:
|
||||
|
||||
|
||||
.Allow Only GET & POST
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -99,7 +105,8 @@ public StrictHttpFirewall httpFirewall() {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<b:bean id="httpFirewall"
|
||||
@@ -109,7 +116,8 @@ public StrictHttpFirewall httpFirewall() {
|
||||
<http-firewall ref="httpFirewall"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -119,7 +127,7 @@ fun httpFirewall(): StrictHttpFirewall {
|
||||
return firewall
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[TIP]
|
||||
====
|
||||
@@ -132,8 +140,8 @@ See https://jira.spring.io/browse/SPR-16851[SPR_16851] for an issue that request
|
||||
If you must allow any HTTP method (not recommended), you can use `StrictHttpFirewall.setUnsafeAllowAnyHttpMethod(true)`.
|
||||
Doing so entirely disables validation of the HTTP method.
|
||||
|
||||
[[servlet-httpfirewall-headers-parameters]]
|
||||
|
||||
[[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.
|
||||
|
||||
@@ -151,8 +159,10 @@ Parameter values can be also controlled with `setAllowedParameterValues(Predicat
|
||||
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
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -165,7 +175,8 @@ public StrictHttpFirewall httpFirewall() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -177,7 +188,7 @@ fun httpFirewall(): StrictHttpFirewall {
|
||||
return firewall
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
Alternatively, there might be a specific value that you need to allow.
|
||||
|
||||
@@ -187,8 +198,10 @@ Due to this fact, some application servers parse this value into two separate ch
|
||||
You can address this with the `setAllowedHeaderValues` method:
|
||||
|
||||
.Allow Certain User Agents
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -201,7 +214,8 @@ public StrictHttpFirewall httpFirewall() {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Bean
|
||||
@@ -213,13 +227,15 @@ fun httpFirewall(): StrictHttpFirewall {
|
||||
return firewall
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
In the case of header values, you may instead consider parsing them as UTF-8 at verification time:
|
||||
|
||||
.Parse Headers As UTF-8
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
firewall.setAllowedHeaderValues((header) -> {
|
||||
@@ -228,7 +244,8 @@ firewall.setAllowedHeaderValues((header) -> {
|
||||
});
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
firewall.setAllowedHeaderValues {
|
||||
@@ -236,4 +253,4 @@ firewall.setAllowedHeaderValues {
|
||||
return allowed.matcher(parsed).matches()
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -16,8 +16,10 @@ For example, assume that you want the defaults but you wish to specify `SAMEORIG
|
||||
You can do so with the following configuration:
|
||||
|
||||
.Customize Default Security Headers
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -38,7 +40,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -50,7 +53,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -70,7 +74,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If you do not want the defaults to be added and want explicit control over what should be used, you can disable the defaults.
|
||||
The next code listing shows how to do so.
|
||||
@@ -78,8 +82,10 @@ The next code listing shows how to do so.
|
||||
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
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -100,7 +106,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -112,7 +119,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -133,13 +141,15 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
If necessary, you can disable all of the HTTP Security response headers with the following configuration:
|
||||
|
||||
.Disable All HTTP Security Headers
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -156,7 +166,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -166,7 +177,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -184,7 +196,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-cache-control]]
|
||||
== Cache Control
|
||||
@@ -200,8 +212,10 @@ You can find details on how to do this in the https://docs.spring.io/spring/docs
|
||||
If necessary, you can also disable Spring Security's cache control HTTP response headers.
|
||||
|
||||
.Cache Control Disabled
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -220,7 +234,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -232,7 +247,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -252,7 +268,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-content-type-options]]
|
||||
== Content Type Options
|
||||
@@ -261,8 +277,10 @@ Spring Security includes xref:features/exploits/headers.adoc#headers-content-typ
|
||||
However, you can disable it:
|
||||
|
||||
.Content Type Options Disabled
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -281,7 +299,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -293,7 +312,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -313,7 +333,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-hsts]]
|
||||
== HTTP Strict Transport Security (HSTS)
|
||||
@@ -323,8 +343,10 @@ However, you can explicitly customize the results.
|
||||
The following example explicitly provides HSTS:
|
||||
|
||||
.Strict Transport Security
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -347,7 +369,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -362,7 +385,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -384,7 +408,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-hpkp]]
|
||||
== HTTP Public Key Pinning (HPKP)
|
||||
@@ -393,8 +417,10 @@ Spring Security provides servlet support for xref:features/exploits/headers.adoc
|
||||
You can enable HPKP headers with the following configuration:
|
||||
|
||||
.HTTP Public Key Pinning
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -416,7 +442,9 @@ public class WebSecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
.XML
|
||||
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -435,7 +463,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -458,7 +487,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-frame-options]]
|
||||
== X-Frame-Options
|
||||
@@ -468,8 +497,10 @@ By default, Spring Security instructs browsers to block reflected XSS attacks by
|
||||
For example, the following configuration specifies that Spring Security should no longer instruct browsers to block the content:
|
||||
|
||||
.X-Frame-Options: SAMEORIGIN
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -490,7 +521,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -504,7 +536,8 @@ public class WebSecurityConfig {
|
||||
----
|
||||
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -524,7 +557,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-xss-protection]]
|
||||
== X-XSS-Protection
|
||||
@@ -535,8 +568,10 @@ For example, the following configuration specifies that Spring Security instruct
|
||||
and block the content:
|
||||
|
||||
.X-XSS-Protection Customization
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -557,7 +592,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -569,7 +605,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -590,7 +627,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-csp]]
|
||||
== Content Security Policy (CSP)
|
||||
@@ -601,18 +638,18 @@ The web application author must declare the security policy (or policies) to enf
|
||||
Consider the following security policy:
|
||||
|
||||
.Content Security Policy Example
|
||||
====
|
||||
[source,http]
|
||||
----
|
||||
Content-Security-Policy: script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/
|
||||
----
|
||||
====
|
||||
|
||||
Given the preceding security policy, you can enable the CSP header:
|
||||
|
||||
.Content Security Policy
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -633,7 +670,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -646,7 +684,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -667,13 +706,15 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
To enable the CSP `report-only` header, provide the following configuration:
|
||||
|
||||
.Content Security Policy Report Only
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -695,7 +736,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -709,7 +751,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -731,7 +774,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-referrer]]
|
||||
== Referrer Policy
|
||||
@@ -740,8 +783,10 @@ Spring Security does not add xref:features/exploits/headers.adoc#headers-referre
|
||||
You can enable the Referrer Policy header by using the configuration:
|
||||
|
||||
.Referrer Policy
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -762,7 +807,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -774,7 +820,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -795,7 +842,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-feature]]
|
||||
== Feature Policy
|
||||
@@ -804,18 +851,18 @@ Spring Security does not add xref:features/exploits/headers.adoc#headers-feature
|
||||
Consider the following `Feature-Policy` header:
|
||||
|
||||
.Feature-Policy Example
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Feature-Policy: geolocation 'self'
|
||||
----
|
||||
====
|
||||
|
||||
You can enable the preceding feature policy header by using the following configuration:
|
||||
|
||||
.Feature-Policy
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -834,7 +881,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -846,7 +894,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -865,7 +914,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-permissions]]
|
||||
== Permissions Policy
|
||||
@@ -874,18 +923,18 @@ Spring Security does not add xref:features/exploits/headers.adoc#headers-permiss
|
||||
Consider the following `Permissions-Policy` header:
|
||||
|
||||
.Permissions-Policy Example
|
||||
====
|
||||
[source]
|
||||
----
|
||||
Permissions-Policy: geolocation=(self)
|
||||
----
|
||||
====
|
||||
|
||||
You can enable the preceding permissions policy header using the following configuration:
|
||||
|
||||
.Permissions-Policy
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -906,7 +955,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -918,7 +968,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -939,7 +990,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-clear-site-data]]
|
||||
== Clear Site Data
|
||||
@@ -948,17 +999,17 @@ Spring Security does not add xref:features/exploits/headers.adoc#headers-clear-s
|
||||
Consider the following Clear-Site-Data header:
|
||||
|
||||
.Clear-Site-Data Example
|
||||
====
|
||||
----
|
||||
Clear-Site-Data: "cache", "cookies"
|
||||
----
|
||||
====
|
||||
|
||||
You can send the preceding header on log out with the following configuration:
|
||||
|
||||
.Clear-Site-Data
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -977,7 +1028,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -996,7 +1048,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-custom]]
|
||||
== Custom Headers
|
||||
@@ -1016,8 +1068,10 @@ X-Custom-Security-Header: header-value
|
||||
Given the preceding header, you could add the headers to the response by using the following configuration:
|
||||
|
||||
.StaticHeadersWriter
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -1036,7 +1090,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -1048,7 +1103,8 @@ public class WebSecurityConfig {
|
||||
</http>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -1067,7 +1123,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[servlet-headers-writer]]
|
||||
=== Headers Writer
|
||||
@@ -1077,8 +1133,10 @@ The next example use a custom instance of `XFrameOptionsHeaderWriter`.
|
||||
If you wanted to explicitly configure <<servlet-headers-frame-options>>, you could do so with the following configuration:
|
||||
|
||||
.Headers Writer
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -1097,7 +1155,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -1115,7 +1174,8 @@ See https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsi
|
||||
c:frameOptionsMode="SAMEORIGIN"/>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -1134,7 +1194,7 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
[[headers-delegatingrequestmatcherheaderwriter]]
|
||||
=== DelegatingRequestMatcherHeaderWriter
|
||||
@@ -1146,8 +1206,10 @@ You could use the `DelegatingRequestMatcherHeaderWriter` to do so.
|
||||
The following configuration example uses `DelegatingRequestMatcherHeaderWriter`:
|
||||
|
||||
.DelegatingRequestMatcherHeaderWriter Java Configuration
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -1170,7 +1232,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.XML
|
||||
XML::
|
||||
+
|
||||
[source,xml,role="secondary"]
|
||||
----
|
||||
<http>
|
||||
@@ -1195,7 +1258,8 @@ public class WebSecurityConfig {
|
||||
</beans:bean>
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -1218,4 +1282,4 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
@@ -13,8 +13,10 @@ If a client makes a request using HTTP rather than HTTPS, you can configure Spri
|
||||
For example, the following Java or Kotlin configuration redirects any HTTP requests to HTTPS:
|
||||
|
||||
.Redirect to HTTPS
|
||||
====
|
||||
.Java
|
||||
[tabs]
|
||||
======
|
||||
Java::
|
||||
+
|
||||
[source,java,role="primary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -33,7 +35,8 @@ public class WebSecurityConfig {
|
||||
}
|
||||
----
|
||||
|
||||
.Kotlin
|
||||
Kotlin::
|
||||
+
|
||||
[source,kotlin,role="secondary"]
|
||||
----
|
||||
@Configuration
|
||||
@@ -52,12 +55,11 @@ class SecurityConfig {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
======
|
||||
|
||||
The following XML configuration redirects all HTTP requests to HTTPS
|
||||
|
||||
.Redirect to HTTPS with XML Configuration
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<http>
|
||||
@@ -65,7 +67,6 @@ The following XML configuration redirects all HTTP requests to HTTPS
|
||||
...
|
||||
</http>
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
[[servlet-hsts]]
|
||||
|
||||
@@ -21,7 +21,6 @@ You can now https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle
|
||||
The following example shows how to do so (and the beginning of the output from doing so):
|
||||
|
||||
.Running Spring Boot Application
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
$ ./mvn spring-boot:run
|
||||
@@ -32,7 +31,6 @@ Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336
|
||||
|
||||
...
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
[[servlet-hello-auto-configuration]]
|
||||
|
||||
@@ -14,7 +14,6 @@ It wraps a delegate `Runnable` to initialize the `SecurityContextHolder` with a
|
||||
It then invokes the delegate `Runnable`, ensuring to clear the `SecurityContextHolder` afterwards.
|
||||
The `DelegatingSecurityContextRunnable` looks something like this:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
public void run() {
|
||||
@@ -26,7 +25,6 @@ try {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
@@ -34,7 +32,6 @@ For example, you might have used Spring Security's xref:servlet/appendix/namespa
|
||||
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() {
|
||||
@@ -49,7 +46,6 @@ DelegatingSecurityContextRunnable wrappedRunnable =
|
||||
|
||||
new Thread(wrappedRunnable).start();
|
||||
----
|
||||
====
|
||||
|
||||
The preceding code:
|
||||
|
||||
@@ -63,7 +59,6 @@ Since it is common to create a `DelegatingSecurityContextRunnable` with the `Sec
|
||||
The following code has the same effect as the preceding code:
|
||||
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Runnable originalRunnable = new Runnable() {
|
||||
@@ -77,7 +72,6 @@ DelegatingSecurityContextRunnable wrappedRunnable =
|
||||
|
||||
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.
|
||||
@@ -90,7 +84,6 @@ Now we look at how `DelegatingSecurityContextExecutor` can shield our code from
|
||||
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();
|
||||
@@ -111,7 +104,6 @@ public void run() {
|
||||
|
||||
executor.execute(originalRunnable);
|
||||
----
|
||||
====
|
||||
|
||||
This code:
|
||||
|
||||
@@ -126,7 +118,6 @@ This is nice if we run background tasks that need to be run by a user with eleva
|
||||
|
||||
Consider the following example:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Autowired
|
||||
@@ -141,21 +132,18 @@ Runnable originalRunnable = new Runnable() {
|
||||
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.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user