├── .gitignore ├── CODE_OF_CONDUCT.adoc ├── CONTRIBUTING.md ├── Jenkinsfile ├── README.adoc ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── license.txt ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── org │ │ └── springframework │ │ └── security │ │ └── dsl │ │ └── config │ │ └── builders │ │ ├── server │ │ ├── AuthorizeExchangeDsl.kt │ │ ├── ServerAnonymousDsl.kt │ │ ├── ServerCorsDsl.kt │ │ ├── ServerCsrfDsl.kt │ │ ├── ServerExceptionHandlingDsl.kt │ │ ├── ServerFormLoginDsl.kt │ │ ├── ServerHeadersDsl.kt │ │ ├── ServerHttpBasicDsl.kt │ │ ├── ServerHttpSecurityDsl.kt │ │ ├── ServerHttpsRedirectDsl.kt │ │ ├── ServerLogoutDsl.kt │ │ ├── ServerOAuth2ClientDsl.kt │ │ ├── ServerOAuth2LoginDsl.kt │ │ ├── ServerOAuth2ResourceServerDsl.kt │ │ ├── ServerRequestCacheDsl.kt │ │ ├── ServerX509Dsl.kt │ │ ├── headers │ │ │ ├── ServerCacheControlDsl.kt │ │ │ ├── ServerContentSecurityPolicyDsl.kt │ │ │ ├── ServerContentTypeOptionsDsl.kt │ │ │ ├── ServerFrameOptionsDsl.kt │ │ │ ├── ServerHttpStrictTransportSecurityDsl.kt │ │ │ ├── ServerReferrerPolicyDsl.kt │ │ │ └── ServerXssProtectionDsl.kt │ │ └── oauth2 │ │ │ └── resourceserver │ │ │ ├── ServerJwtDsl.kt │ │ │ └── ServerOpaqueTokenDsl.kt │ │ └── servlet │ │ ├── AbstractRequestMatcherDsl.kt │ │ ├── AnonymousDsl.kt │ │ ├── AuthorizeRequestsDsl.kt │ │ ├── CorsDsl.kt │ │ ├── CsrfDsl.kt │ │ ├── ExceptionHandlingDsl.kt │ │ ├── FormLoginDsl.kt │ │ ├── HeadersDsl.kt │ │ ├── HttpBasicDsl.kt │ │ ├── HttpSecurityDsl.kt │ │ ├── LogoutDsl.kt │ │ ├── OAuth2ClientDsl.kt │ │ ├── OAuth2LoginDsl.kt │ │ ├── OAuth2ResourceServerDsl.kt │ │ ├── PortMapperDsl.kt │ │ ├── RequestCacheDsl.kt │ │ ├── RequiresChannelDsl.kt │ │ ├── Saml2Dsl.kt │ │ ├── SessionManagementDsl.kt │ │ ├── X509Dsl.kt │ │ ├── headers │ │ ├── CacheControlDsl.kt │ │ ├── ContentSecurityPolicyDsl.kt │ │ ├── ContentTypeOptionsDsl.kt │ │ ├── FrameOptionsDsl.kt │ │ ├── HttpPublicKeyPinningDsl.kt │ │ ├── HttpStrictTransportSecurityDsl.kt │ │ ├── ReferrerPolicyDsl.kt │ │ └── XssProtectionConfigDsl.kt │ │ ├── oauth2 │ │ ├── client │ │ │ └── AuthorizationCodeGrantDsl.kt │ │ ├── login │ │ │ ├── AuthorizationEndpointDsl.kt │ │ │ ├── RedirectionEndpointDsl.kt │ │ │ ├── TokenEndpointDsl.kt │ │ │ └── UserInfoEndpointDsl.kt │ │ └── resourceserver │ │ │ ├── JwtDsl.kt │ │ │ └── OpaqueTokenDsl.kt │ │ └── session │ │ ├── SessionConcurrencyDsl.kt │ │ └── SessionFixationDsl.kt └── resources │ └── application.properties └── test ├── kotlin └── org │ └── springframework │ └── security │ └── dsl │ └── config │ └── builders │ ├── server │ ├── AuthorizeExchangeDslTests.kt │ ├── ServerAnonymousDslTests.kt │ ├── ServerCorsDslTests.kt │ ├── ServerCsrfDslTests.kt │ ├── ServerExceptionHandlingDslTests.kt │ ├── ServerFormLoginDslTests.kt │ ├── ServerHeadersDslTests.kt │ ├── ServerHttpBasicDslTests.kt │ ├── ServerHttpSecurityDslTests.kt │ ├── ServerHttpsRedirectDslTests.kt │ ├── ServerLogoutDslTests.kt │ ├── ServerOAuth2ClientDslTests.kt │ ├── ServerOAuth2LoginDslTests.kt │ ├── ServerOAuth2ResourceServerDslTests.kt │ ├── ServerRequestCacheDslTests.kt │ ├── ServerX509DslTests.kt │ ├── headers │ │ ├── ServerCacheControlDslTests.kt │ │ ├── ServerContentSecurityPolicyDslTests.kt │ │ ├── ServerContentTypeOptionsDslTests.kt │ │ ├── ServerFrameOptionsDslTests.kt │ │ ├── ServerHttpStrictTransportSecurityDslTests.kt │ │ ├── ServerReferrerPolicyDslTests.kt │ │ └── ServerXssProtectionDslTests.kt │ └── oauth2 │ │ └── resourceserver │ │ ├── ServerJwtDslTests.kt │ │ └── ServerOpaqueTokenDslTests.kt │ ├── servlet │ ├── AnonymousDslTests.kt │ ├── AuthorizeRequestsDslTests.kt │ ├── CorsDslTests.kt │ ├── CsrfDslTests.kt │ ├── ExceptionHandlingDslTests.kt │ ├── FormLoginDslTests.kt │ ├── HeadersDslTests.kt │ ├── HttpBasicDslTests.kt │ ├── HttpSecurityDslTests.kt │ ├── LogoutDslTests.kt │ ├── OAuth2ClientDslTests.kt │ ├── OAuth2LoginDslTests.kt │ ├── OAuth2ResourceServerDslTests.kt │ ├── PortMapperDslTests.kt │ ├── RequestCacheDslTests.kt │ ├── RequiresChannelDslTests.kt │ ├── Saml2DslTests.kt │ ├── SessionManagementDslTests.kt │ ├── X509DslTests.kt │ ├── headers │ │ ├── CacheControlDslTests.kt │ │ ├── ContentSecurityPolicyDslTests.kt │ │ ├── ContentTypeOptionsDslTests.kt │ │ ├── FrameOptionsDslTests.kt │ │ ├── HttpPublicKeyPinningDslTests.kt │ │ ├── HttpStrictTransportSecurityDslTests.kt │ │ ├── ReferrerPolicyDslTests.kt │ │ └── XssProtectionConfigDslTests.kt │ ├── oauth2 │ │ ├── client │ │ │ └── AuthorizationCodeGrantDslTests.kt │ │ ├── login │ │ │ ├── AuthorizationEndpointDslTests.kt │ │ │ ├── RedirectionEndpointDslTests.kt │ │ │ ├── TokenEndpointDslTests.kt │ │ │ └── UserInfoEndpointDslTests.kt │ │ └── resourceserver │ │ │ ├── JwtDslTests.kt │ │ │ └── OpaqueTokenDslTests.kt │ └── session │ │ ├── SessionConcurrencyDslTests.kt │ │ └── SessionFixationDslTest.kt │ └── test │ ├── SpringTestContext.kt │ └── SpringTestRule.kt └── resources ├── rod.cer └── rodatexampledotcom.cer /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | .DS_Store 8 | 9 | ### STS ### 10 | .apt_generated 11 | .classpath 12 | .factorypath 13 | .project 14 | .settings 15 | .springBeans 16 | .sts4-cache 17 | 18 | ### IntelliJ IDEA ### 19 | .idea 20 | *.iws 21 | *.iml 22 | *.ipr 23 | out/ 24 | 25 | ### NetBeans ### 26 | /nbproject/private/ 27 | /nbbuild/ 28 | /dist/ 29 | /nbdist/ 30 | /.nb-gradle/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.adoc: -------------------------------------------------------------------------------- 1 | = Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, and in the interest of fostering an open 4 | and welcoming community, we pledge to respect all people who contribute through reporting 5 | issues, posting feature requests, updating documentation, submitting pull requests or 6 | patches, and other activities. 7 | 8 | We are committed to making participation in this project a harassment-free experience for 9 | everyone, regardless of level of experience, gender, gender identity and expression, 10 | sexual orientation, disability, personal appearance, body size, race, ethnicity, age, 11 | religion, or nationality. 12 | 13 | Examples of unacceptable behavior by participants include: 14 | 15 | * The use of sexualized language or imagery 16 | * Personal attacks 17 | * Trolling or insulting/derogatory comments 18 | * Public or private harassment 19 | * Publishing other's private information, such as physical or electronic addresses, 20 | without explicit permission 21 | * Other unethical or unprofessional conduct 22 | 23 | Project maintainers have the right and responsibility to remove, edit, or reject comments, 24 | commits, code, wiki edits, issues, and other contributions that are not aligned to this 25 | Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors 26 | that they deem inappropriate, threatening, offensive, or harmful. 27 | 28 | By adopting this Code of Conduct, project maintainers commit themselves to fairly and 29 | consistently applying these principles to every aspect of managing this project. Project 30 | maintainers who do not follow or enforce the Code of Conduct may be permanently removed 31 | from the project team. 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an 34 | individual is representing the project or its community. 35 | 36 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by 37 | contacting a project maintainer at spring-code-of-conduct@pivotal.io . All complaints will 38 | be reviewed and investigated and will result in a response that is deemed necessary and 39 | appropriate to the circumstances. Maintainers are obligated to maintain confidentiality 40 | with regard to the reporter of an incident. 41 | 42 | This Code of Conduct is adapted from the 43 | https://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at 44 | https://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/] 45 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | def projectProperties = [ 2 | [$class: 'BuildDiscarderProperty', 3 | strategy: [$class: 'LogRotator', numToKeepStr: '5']], 4 | pipelineTriggers([cron('@daily')]) 5 | ] 6 | properties(projectProperties) 7 | 8 | def SUCCESS = hudson.model.Result.SUCCESS.toString() 9 | currentBuild.result = SUCCESS 10 | 11 | try { 12 | parallel check: { 13 | stage('Check') { 14 | node { 15 | checkout scm 16 | sh "git clean -dfx" 17 | try { 18 | withEnv(["JAVA_HOME=${ tool 'jdk8' }"]) { 19 | sh "./gradlew clean check --refresh-dependencies --no-daemon --stacktrace" 20 | } 21 | } catch(Exception e) { 22 | currentBuild.result = 'FAILED: check' 23 | throw e 24 | } finally { 25 | junit '**/build/test-results/*/*.xml' 26 | } 27 | } 28 | } 29 | } 30 | 31 | if(currentBuild.result == 'SUCCESS') { 32 | parallel artifacts: { 33 | stage('Deploy Artifacts') { 34 | node { 35 | checkout scm 36 | sh "git clean -dfx" 37 | withCredentials([file(credentialsId: 'spring-signing-secring.gpg', variable: 'SIGNING_KEYRING_FILE')]) { 38 | withCredentials([string(credentialsId: 'spring-gpg-passphrase', variable: 'SIGNING_PASSWORD')]) { 39 | withCredentials([usernamePassword(credentialsId: 'oss-token', passwordVariable: 'OSSRH_PASSWORD', usernameVariable: 'OSSRH_USERNAME')]) { 40 | withCredentials([usernamePassword(credentialsId: '02bd1690-b54f-4c9f-819d-a77cb7a9822c', usernameVariable: 'ARTIFACTORY_USERNAME', passwordVariable: 'ARTIFACTORY_PASSWORD')]) { 41 | withEnv(["JAVA_HOME=${ tool 'jdk8' }"]) { 42 | sh "./gradlew deployArtifacts finalizeDeployArtifacts -Psigning.secretKeyRingFile=$SIGNING_KEYRING_FILE -Psigning.keyId=$SPRING_SIGNING_KEYID -Psigning.password='$SIGNING_PASSWORD' -PossrhUsername=$OSSRH_USERNAME -PossrhPassword=$OSSRH_PASSWORD -PartifactoryUsername=$ARTIFACTORY_USERNAME -PartifactoryPassword=$ARTIFACTORY_PASSWORD --refresh-dependencies --no-daemon --stacktrace" 43 | } 44 | } 45 | } 46 | } 47 | } 48 | } 49 | } 50 | } 51 | } 52 | } catch(Exception e) { 53 | currentBuild.result = 'FAILED: deploys' 54 | throw e 55 | } finally { 56 | def buildStatus = currentBuild.result 57 | def buildNotSuccess = !SUCCESS.equals(buildStatus) 58 | def lastBuildNotSuccess = !SUCCESS.equals(currentBuild.previousBuild?.result) 59 | } 60 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = Spring Security Kotlin DSL 2 | 3 | == Deprecation Notice 4 | The Spring Security Kotlin DSL Experimental project is deprecated. 5 | The native Kotlin Domain Specific Language (DSL) is fully integrated into https://github.com/spring-projects/spring-security[Spring Security] as of version https://spring.io/blog/2020/09/10/spring-security-5-4-goes-ga[5.4]. 6 | Applications should no longer add this project as an additional dependency, and instead should use Spring Security. 7 | 8 | == Code of Conduct 9 | This project adheres to the Contributor Covenant link:CODE_OF_CONDUCT.adoc[code of conduct]. 10 | By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io. 11 | 12 | == License 13 | Spring Security is Open Source software released under the 14 | https://www.apache.org/licenses/LICENSE-2.0.html[Apache 2.0 license]. 15 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | buildscript { 4 | dependencies { 5 | classpath("io.spring.gradle", "spring-build-conventions", "0.0.23.RELEASE") 6 | classpath("io.spring.nohttp", "nohttp-gradle", "0.0.2.RELEASE") 7 | } 8 | repositories { 9 | maven { setUrl("https://repo.spring.io/plugins-snapshot") } 10 | maven { setUrl("https://repo.spring.io/plugins-release") } 11 | maven { setUrl("https://plugins.gradle.org/m2/") } 12 | } 13 | } 14 | 15 | plugins { 16 | id("io.spring.nohttp") version "0.0.2.RELEASE" 17 | id("io.spring.dependency-management") version "1.0.8.RELEASE" 18 | kotlin("jvm") version "1.3.50" 19 | kotlin("plugin.spring") version "1.3.50" 20 | } 21 | apply() 22 | apply() 23 | 24 | group = "org.springframework.security.dsl" 25 | java.sourceCompatibility = JavaVersion.VERSION_1_8 26 | 27 | dependencyManagement { 28 | imports { 29 | mavenBom("org.springframework:spring-framework-bom:5.2.0.RELEASE") 30 | mavenBom("org.springframework.security:spring-security-bom:5.4.0.BUILD-SNAPSHOT") 31 | } 32 | 33 | dependencies { 34 | dependency("javax.servlet:javax.servlet-api:4.0.1") 35 | dependency("junit:junit:4.12") 36 | dependency("org.assertj:assertj-core:3.12.2") 37 | dependency("org.mockito:mockito-core:3.0.0") 38 | } 39 | } 40 | 41 | dependencies { 42 | compile("org.springframework:spring-aop") 43 | compile("org.springframework:spring-beans") 44 | compile("org.springframework:spring-context") 45 | compile("org.springframework:spring-core") 46 | compile("org.springframework:spring-expression") 47 | compile("org.springframework:spring-web") 48 | compile("org.springframework:spring-webmvc") 49 | compile("org.springframework:spring-webflux") 50 | compile("javax.servlet:javax.servlet-api") 51 | implementation("org.springframework.security:spring-security-config") 52 | implementation("org.springframework.security:spring-security-core") 53 | implementation("org.springframework.security:spring-security-web") 54 | implementation("org.springframework.security:spring-security-oauth2-client") 55 | implementation("org.springframework.security:spring-security-oauth2-jose") 56 | implementation("org.springframework.security:spring-security-oauth2-resource-server") 57 | implementation("org.springframework.security:spring-security-saml2-service-provider") 58 | implementation("org.jetbrains.kotlin:kotlin-reflect") 59 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 60 | 61 | testImplementation("junit:junit") 62 | testImplementation("org.assertj:assertj-core") 63 | testImplementation("org.mockito:mockito-core") 64 | testImplementation("org.springframework.security:spring-security-test") 65 | testImplementation("org.springframework:spring-test") 66 | testImplementation("io.projectreactor.netty:reactor-netty:0.9.4.RELEASE") 67 | testImplementation("com.squareup.okhttp3:mockwebserver:3.14.6") 68 | testImplementation("javax.annotation:jsr250-api:1.0") 69 | } 70 | 71 | tasks.withType { 72 | useJUnitPlatform() 73 | } 74 | 75 | tasks.test { 76 | useJUnit() 77 | 78 | maxHeapSize = "1G" 79 | } 80 | 81 | tasks.withType { 82 | kotlinOptions { 83 | freeCompilerArgs = listOf("-Xjsr305=strict") 84 | jvmTarget = "1.8" 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | springBootVersion=2.2.0.M6 2 | version=0.0.1.BUILD-SNAPSHOT 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-attic/spring-security-kotlin-dsl/2c9fc7b91d5f241e721ad728fdc0652875825de2/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | maven { url = uri("https://repo.spring.io/milestone") } 4 | gradlePluginPortal() 5 | } 6 | resolutionStrategy { 7 | eachPlugin { 8 | if (requested.id.id == "org.springframework.boot") { 9 | useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}") 10 | } 11 | } 12 | } 13 | } 14 | rootProject.name = "spring-security-kotlin-dsl" 15 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerAnonymousDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.core.Authentication 21 | import org.springframework.security.core.GrantedAuthority 22 | import org.springframework.security.web.server.authentication.AnonymousAuthenticationWebFilter 23 | 24 | /** 25 | * A Kotlin DSL to configure [ServerHttpSecurity] anonymous authentication using idiomatic 26 | * Kotlin code. 27 | * 28 | * @author Eleftheria Stein 29 | * @property key the key to identify tokens created for anonymous authentication 30 | * @property principal the principal for [Authentication] objects of anonymous users 31 | * @property authorities the [Authentication.getAuthorities] for anonymous users 32 | * @property authenticationFilter the [AnonymousAuthenticationWebFilter] used to populate 33 | * an anonymous user. 34 | */ 35 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 36 | class ServerAnonymousDsl { 37 | var key: String? = null 38 | var principal: Any? = null 39 | var authorities: List? = null 40 | var authenticationFilter: AnonymousAuthenticationWebFilter? = null 41 | 42 | private var disabled = false 43 | 44 | /** 45 | * Disables anonymous authentication 46 | */ 47 | fun disable() { 48 | disabled = true 49 | } 50 | 51 | internal fun get(): (ServerHttpSecurity.AnonymousSpec) -> Unit { 52 | return { anonymous -> 53 | key?.also { anonymous.key(key) } 54 | principal?.also { anonymous.principal(principal) } 55 | authorities?.also { anonymous.authorities(authorities) } 56 | authenticationFilter?.also { anonymous.authenticationFilter(authenticationFilter) } 57 | if (disabled) { 58 | anonymous.disable() 59 | } 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerCorsDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.web.cors.reactive.CorsConfigurationSource 21 | 22 | /** 23 | * A Kotlin DSL to configure [ServerHttpSecurity] CORS headers using idiomatic 24 | * Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | * @property configurationSource the [CorsConfigurationSource] to use. 28 | */ 29 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 30 | class ServerCorsDsl { 31 | var configurationSource: CorsConfigurationSource? = null 32 | 33 | private var disabled = false 34 | 35 | /** 36 | * Disables CORS support within Spring Security. 37 | */ 38 | fun disable() { 39 | disabled = true 40 | } 41 | 42 | internal fun get(): (ServerHttpSecurity.CorsSpec) -> Unit { 43 | return { cors -> 44 | configurationSource?.also { cors.configurationSource(configurationSource) } 45 | if (disabled) { 46 | cors.disable() 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerCsrfDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler 21 | import org.springframework.security.web.server.csrf.ServerCsrfTokenRepository 22 | import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher 23 | 24 | /** 25 | * A Kotlin DSL to configure [ServerHttpSecurity] CSRF protection using idiomatic 26 | * Kotlin code. 27 | * 28 | * @author Eleftheria Stein 29 | * @property accessDeniedHandler the [ServerAccessDeniedHandler] used when a CSRF token is invalid. 30 | * @property csrfTokenRepository the [ServerCsrfTokenRepository] used to persist the CSRF token. 31 | * @property requireCsrfProtectionMatcher the [ServerWebExchangeMatcher] used to determine when CSRF protection 32 | * is enabled. 33 | */ 34 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 35 | class ServerCsrfDsl { 36 | var accessDeniedHandler: ServerAccessDeniedHandler? = null 37 | var csrfTokenRepository: ServerCsrfTokenRepository? = null 38 | var requireCsrfProtectionMatcher: ServerWebExchangeMatcher? = null 39 | 40 | private var disabled = false 41 | 42 | /** 43 | * Disables CSRF protection 44 | */ 45 | fun disable() { 46 | disabled = true 47 | } 48 | 49 | internal fun get(): (ServerHttpSecurity.CsrfSpec) -> Unit { 50 | return { csrf -> 51 | accessDeniedHandler?.also { csrf.accessDeniedHandler(accessDeniedHandler) } 52 | csrfTokenRepository?.also { csrf.csrfTokenRepository(csrfTokenRepository) } 53 | requireCsrfProtectionMatcher?.also { csrf.requireCsrfProtectionMatcher(requireCsrfProtectionMatcher) } 54 | if (disabled) { 55 | csrf.disable() 56 | } 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerExceptionHandlingDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.web.server.ServerAuthenticationEntryPoint 21 | import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler 22 | 23 | /** 24 | * A Kotlin DSL to configure [ServerHttpSecurity] exception handling using idiomatic Kotlin 25 | * code. 26 | * 27 | * @author Eleftheria Stein 28 | * @property authenticationEntryPoint the [ServerAuthenticationEntryPoint] to use when 29 | * the application request authentication 30 | * @property accessDeniedHandler the [ServerAccessDeniedHandler] to use when an 31 | * authenticated user does not hold a required authority 32 | */ 33 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 34 | class ServerExceptionHandlingDsl { 35 | var authenticationEntryPoint: ServerAuthenticationEntryPoint? = null 36 | var accessDeniedHandler: ServerAccessDeniedHandler? = null 37 | 38 | internal fun get(): (ServerHttpSecurity.ExceptionHandlingSpec) -> Unit { 39 | return { exceptionHandling -> 40 | authenticationEntryPoint?.also { exceptionHandling.authenticationEntryPoint(authenticationEntryPoint) } 41 | accessDeniedHandler?.also { exceptionHandling.accessDeniedHandler(accessDeniedHandler) } 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerFormLoginDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.authentication.ReactiveAuthenticationManager 20 | import org.springframework.security.config.web.server.ServerHttpSecurity 21 | import org.springframework.security.core.Authentication 22 | import org.springframework.security.core.context.SecurityContext 23 | import org.springframework.security.web.server.ServerAuthenticationEntryPoint 24 | import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler 25 | import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler 26 | import org.springframework.security.web.server.context.ReactorContextWebFilter 27 | import org.springframework.security.web.server.context.ServerSecurityContextRepository 28 | import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher 29 | 30 | /** 31 | * A Kotlin DSL to configure [ServerHttpSecurity] form login using idiomatic 32 | * Kotlin code. 33 | * 34 | * @author Eleftheria Stein 35 | * @property authenticationManager the [ReactiveAuthenticationManager] used to authenticate. 36 | * @property loginPage the url to redirect to which provides a form to log in (i.e. "/login"). 37 | * If this is customized: 38 | * - The default log in & log out page are no longer provided 39 | * - The application must render a log in page at the provided URL 40 | * - The application must render an authentication error page at the provided URL + "?error" 41 | * - Authentication will occur for POST to the provided URL 42 | * @property authenticationEntryPoint configures how to request for authentication. 43 | * @property requiresAuthenticationMatcher configures when authentication is performed. 44 | * @property authenticationSuccessHandler the [ServerAuthenticationSuccessHandler] used after 45 | * authentication success. 46 | * @property authenticationFailureHandler the [ServerAuthenticationFailureHandler] used to handle 47 | * a failed authentication. 48 | * @property securityContextRepository the [ServerSecurityContextRepository] used to save 49 | * the [Authentication]. For the [SecurityContext] to be loaded on subsequent requests the 50 | * [ReactorContextWebFilter] must be configured to be able to load the value (they are not 51 | * implicitly linked). 52 | */ 53 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 54 | class ServerFormLoginDsl { 55 | var authenticationManager: ReactiveAuthenticationManager? = null 56 | var loginPage: String? = null 57 | var authenticationEntryPoint: ServerAuthenticationEntryPoint? = null 58 | var requiresAuthenticationMatcher: ServerWebExchangeMatcher? = null 59 | var authenticationSuccessHandler: ServerAuthenticationSuccessHandler? = null 60 | var authenticationFailureHandler: ServerAuthenticationFailureHandler? = null 61 | var securityContextRepository: ServerSecurityContextRepository? = null 62 | 63 | private var disabled = false 64 | 65 | /** 66 | * Disables HTTP basic authentication 67 | */ 68 | fun disable() { 69 | disabled = true 70 | } 71 | 72 | internal fun get(): (ServerHttpSecurity.FormLoginSpec) -> Unit { 73 | return { formLogin -> 74 | authenticationManager?.also { formLogin.authenticationManager(authenticationManager) } 75 | loginPage?.also { formLogin.loginPage(loginPage) } 76 | authenticationEntryPoint?.also { formLogin.authenticationEntryPoint(authenticationEntryPoint) } 77 | requiresAuthenticationMatcher?.also { formLogin.requiresAuthenticationMatcher(requiresAuthenticationMatcher) } 78 | authenticationSuccessHandler?.also { formLogin.authenticationSuccessHandler(authenticationSuccessHandler) } 79 | authenticationFailureHandler?.also { formLogin.authenticationFailureHandler(authenticationFailureHandler) } 80 | securityContextRepository?.also { formLogin.securityContextRepository(securityContextRepository) } 81 | if (disabled) { 82 | formLogin.disable() 83 | } 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerHttpBasicDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.authentication.ReactiveAuthenticationManager 20 | import org.springframework.security.config.web.server.ServerHttpSecurity 21 | import org.springframework.security.core.Authentication 22 | import org.springframework.security.core.context.SecurityContext 23 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter 24 | import org.springframework.security.web.server.ServerAuthenticationEntryPoint 25 | import org.springframework.security.web.server.context.ReactorContextWebFilter 26 | import org.springframework.security.web.server.context.ServerSecurityContextRepository 27 | 28 | /** 29 | * A Kotlin DSL to configure [ServerHttpSecurity] basic authorization using idiomatic 30 | * Kotlin code. 31 | * 32 | * @author Eleftheria Stein 33 | * @property authenticationManager the [ReactiveAuthenticationManager] used to authenticate. 34 | * @property securityContextRepository the [ServerSecurityContextRepository] used to save 35 | * the [Authentication]. For the [SecurityContext] to be loaded on subsequent requests the 36 | * [ReactorContextWebFilter] must be configured to be able to load the value (they are not 37 | * implicitly linked). 38 | * @property authenticationEntryPoint the [ServerAuthenticationEntryPoint] to be 39 | * populated on [BasicAuthenticationFilter] in the event that authentication fails. 40 | */ 41 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 42 | class ServerHttpBasicDsl { 43 | var authenticationManager: ReactiveAuthenticationManager? = null 44 | var securityContextRepository: ServerSecurityContextRepository? = null 45 | var authenticationEntryPoint: ServerAuthenticationEntryPoint? = null 46 | 47 | private var disabled = false 48 | 49 | /** 50 | * Disables HTTP basic authentication 51 | */ 52 | fun disable() { 53 | disabled = true 54 | } 55 | 56 | internal fun get(): (ServerHttpSecurity.HttpBasicSpec) -> Unit { 57 | return { httpBasic -> 58 | authenticationManager?.also { httpBasic.authenticationManager(authenticationManager) } 59 | securityContextRepository?.also { httpBasic.securityContextRepository(securityContextRepository) } 60 | authenticationEntryPoint?.also { httpBasic.authenticationEntryPoint(authenticationEntryPoint) } 61 | if (disabled) { 62 | httpBasic.disable() 63 | } 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerHttpsRedirectDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.web.PortMapper 21 | import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher 22 | import org.springframework.web.server.ServerWebExchange 23 | 24 | /** 25 | * A Kotlin DSL to configure [ServerHttpSecurity] HTTPS redirection rules using idiomatic 26 | * Kotlin code. 27 | * 28 | * @author Eleftheria Stein 29 | * @property portMapper the [PortMapper] that specifies a custom HTTPS port to redirect to. 30 | */ 31 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 32 | class ServerHttpsRedirectDsl { 33 | var portMapper: PortMapper? = null 34 | 35 | private var redirectMatchers: Array? = null 36 | private var redirectMatcherFunction: ((ServerWebExchange) -> Boolean)? = null 37 | 38 | /** 39 | * Configures when this filter should redirect to https. 40 | * If invoked multiple times, whether a matcher or a function is provided, only the 41 | * last redirect rule will apply and all previous rules will be overridden. 42 | * 43 | * @param redirectMatchers the list of conditions that, when any are met, the 44 | * filter should redirect to https. 45 | */ 46 | fun httpsRedirectWhen(vararg redirectMatchers: ServerWebExchangeMatcher) { 47 | this.redirectMatcherFunction = null 48 | this.redirectMatchers = redirectMatchers 49 | } 50 | 51 | /** 52 | * Configures when this filter should redirect to https. 53 | * If invoked multiple times, whether a matcher or a function is provided, only the 54 | * last redirect rule will apply and all previous rules will be overridden. 55 | * 56 | * @param redirectMatcherFunction the condition in which the filter should redirect to 57 | * https. 58 | */ 59 | fun httpsRedirectWhen(redirectMatcherFunction: (ServerWebExchange) -> Boolean) { 60 | this.redirectMatchers = null 61 | this.redirectMatcherFunction = redirectMatcherFunction 62 | } 63 | 64 | internal fun get(): (ServerHttpSecurity.HttpsRedirectSpec) -> Unit { 65 | return { httpsRedirect -> 66 | portMapper?.also { httpsRedirect.portMapper(portMapper) } 67 | redirectMatchers?.also { httpsRedirect.httpsRedirectWhen(*redirectMatchers!!) } 68 | redirectMatcherFunction?.also { httpsRedirect.httpsRedirectWhen(redirectMatcherFunction) } 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerLogoutDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.web.server.authentication.logout.ServerLogoutHandler 21 | import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler 22 | import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher 23 | 24 | /** 25 | * A Kotlin DSL to configure [ServerHttpSecurity] logout support using idiomatic Kotlin 26 | * code. 27 | * 28 | * @author Eleftheria Stein 29 | * @property logoutHandler a [ServerLogoutHandler] that is invoked when logout occurs. 30 | * @property logoutUrl the URL that triggers logout to occur. 31 | * @property requiresLogout the [ServerWebExchangeMatcher] that triggers logout to occur. 32 | * @property logoutSuccessHandler the [ServerLogoutSuccessHandler] to use after logout has 33 | * occurred. 34 | */ 35 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 36 | class ServerLogoutDsl { 37 | var logoutHandler: ServerLogoutHandler? = null 38 | var logoutUrl: String? = null 39 | var requiresLogout: ServerWebExchangeMatcher? = null 40 | var logoutSuccessHandler: ServerLogoutSuccessHandler? = null 41 | 42 | private var disabled = false 43 | 44 | /** 45 | * Disables logout 46 | */ 47 | fun disable() { 48 | disabled = true 49 | } 50 | 51 | internal fun get(): (ServerHttpSecurity.LogoutSpec) -> Unit { 52 | return { logout -> 53 | logoutHandler?.also { logout.logoutHandler(logoutHandler) } 54 | logoutUrl?.also { logout.logoutUrl(logoutUrl) } 55 | requiresLogout?.also { logout.requiresLogout(requiresLogout) } 56 | logoutSuccessHandler?.also { logout.logoutSuccessHandler(logoutSuccessHandler) } 57 | if (disabled) { 58 | logout.disable() 59 | } 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerOAuth2ClientDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.authentication.ReactiveAuthenticationManager 20 | import org.springframework.security.config.web.server.ServerHttpSecurity 21 | import org.springframework.security.core.Authentication 22 | import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository 23 | import org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository 24 | import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository 25 | import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest 26 | import org.springframework.security.web.server.authentication.ServerAuthenticationConverter 27 | import org.springframework.web.server.ServerWebExchange 28 | 29 | /** 30 | * A Kotlin DSL to configure the [ServerHttpSecurity] OAuth 2.0 client using idiomatic Kotlin code. 31 | * 32 | * @author Eleftheria Stein 33 | * @property authenticationManager the [ReactiveAuthenticationManager] used to determine if the provided 34 | * [Authentication] can be authenticated. 35 | * @property authenticationConverter the [ServerAuthenticationConverter] used for converting from a [ServerWebExchange] 36 | * to an [Authentication]. 37 | * @property clientRegistrationRepository the repository of client registrations. 38 | * @property authorizedClientRepository the repository for authorized client(s). 39 | * @property authorizationRequestRepository the repository to use for storing [OAuth2AuthorizationRequest]s. 40 | */ 41 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 42 | class ServerOAuth2ClientDsl { 43 | var authenticationManager: ReactiveAuthenticationManager? = null 44 | var authenticationConverter: ServerAuthenticationConverter? = null 45 | var clientRegistrationRepository: ReactiveClientRegistrationRepository? = null 46 | var authorizedClientRepository: ServerOAuth2AuthorizedClientRepository? = null 47 | var authorizationRequestRepository: ServerAuthorizationRequestRepository? = null 48 | 49 | internal fun get(): (ServerHttpSecurity.OAuth2ClientSpec) -> Unit { 50 | return { oauth2Client -> 51 | authenticationManager?.also { oauth2Client.authenticationManager(authenticationManager) } 52 | authenticationConverter?.also { oauth2Client.authenticationConverter(authenticationConverter) } 53 | clientRegistrationRepository?.also { oauth2Client.clientRegistrationRepository(clientRegistrationRepository) } 54 | authorizedClientRepository?.also { oauth2Client.authorizedClientRepository(authorizedClientRepository) } 55 | authorizationRequestRepository?.also { oauth2Client.authorizationRequestRepository(authorizationRequestRepository) } 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerRequestCacheDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.web.server.savedrequest.ServerRequestCache 21 | 22 | /** 23 | * A Kotlin DSL to configure the request cache using idiomatic Kotlin code. 24 | * 25 | * @author Eleftheria Stein 26 | * @property requestCache allows explicit configuration of the [ServerRequestCache] to be used. 27 | */ 28 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 29 | class ServerRequestCacheDsl { 30 | var requestCache: ServerRequestCache? = null 31 | 32 | private var disabled = false 33 | 34 | /** 35 | * Disables the request cache. 36 | */ 37 | fun disable() { 38 | disabled = true 39 | } 40 | 41 | internal fun get(): (ServerHttpSecurity.RequestCacheSpec) -> Unit { 42 | return { requestCacheConfig -> 43 | requestCache?.also { 44 | requestCacheConfig.requestCache(requestCache) 45 | if (disabled) { 46 | requestCacheConfig.disable() 47 | } 48 | } 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/ServerX509Dsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.springframework.security.authentication.ReactiveAuthenticationManager 20 | import org.springframework.security.config.web.server.ServerHttpSecurity 21 | import org.springframework.security.core.Authentication 22 | import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor 23 | 24 | /** 25 | * A Kotlin DSL to configure [ServerHttpSecurity] X509 based pre authentication using idiomatic Kotlin code. 26 | * 27 | * @author Eleftheria Stein 28 | * @property principalExtractor the [X509PrincipalExtractor] used to obtain the principal for use within the framework. 29 | * @property authenticationManager the [ReactiveAuthenticationManager] used to determine if the provided 30 | * [Authentication] can be authenticated. 31 | */ 32 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 33 | class ServerX509Dsl { 34 | var principalExtractor: X509PrincipalExtractor? = null 35 | var authenticationManager: ReactiveAuthenticationManager? = null 36 | 37 | internal fun get(): (ServerHttpSecurity.X509Spec) -> Unit { 38 | return { x509 -> 39 | authenticationManager?.also { x509.authenticationManager(authenticationManager) } 40 | principalExtractor?.also { x509.principalExtractor(principalExtractor) } 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerCacheControlDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | 21 | /** 22 | * A Kotlin DSL to configure the [ServerHttpSecurity] cache control headers using 23 | * idiomatic Kotlin code. 24 | * 25 | * @author Eleftheria Stein 26 | */ 27 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 28 | class ServerCacheControlDsl { 29 | private var disabled = false 30 | 31 | /** 32 | * Disables cache control response headers 33 | */ 34 | fun disable() { 35 | disabled = true 36 | } 37 | 38 | internal fun get(): (ServerHttpSecurity.HeaderSpec.CacheSpec) -> Unit { 39 | return { cacheControl -> 40 | if (disabled) { 41 | cacheControl.disable() 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerContentSecurityPolicyDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | 21 | /** 22 | * A Kotlin DSL to configure the [ServerHttpSecurity] Content-Security-Policy header using 23 | * idiomatic Kotlin code. 24 | * 25 | * @author Eleftheria Stein 26 | */ 27 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 28 | class ServerContentSecurityPolicyDsl { 29 | var policyDirectives: String? = null 30 | var reportOnly: Boolean? = null 31 | 32 | internal fun get(): (ServerHttpSecurity.HeaderSpec.ContentSecurityPolicySpec) -> Unit { 33 | return { contentSecurityPolicy -> 34 | policyDirectives?.also { 35 | contentSecurityPolicy.policyDirectives(policyDirectives) 36 | } 37 | reportOnly?.also { 38 | contentSecurityPolicy.reportOnly(reportOnly!!) 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerContentTypeOptionsDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | 21 | /** 22 | * A Kotlin DSL to configure the [ServerHttpSecurity] the content type options header 23 | * using idiomatic Kotlin code. 24 | * 25 | * @author Eleftheria Stein 26 | */ 27 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 28 | class ServerContentTypeOptionsDsl { 29 | private var disabled = false 30 | 31 | /** 32 | * Disables content type options response header 33 | */ 34 | fun disable() { 35 | disabled = true 36 | } 37 | 38 | internal fun get(): (ServerHttpSecurity.HeaderSpec.ContentTypeOptionsSpec) -> Unit { 39 | return { contentTypeOptions -> 40 | if (disabled) { 41 | contentTypeOptions.disable() 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerFrameOptionsDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter 21 | 22 | /** 23 | * A Kotlin DSL to configure the [ServerHttpSecurity] X-Frame-Options header using 24 | * idiomatic Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | * @property mode the X-Frame-Options mode to set in the response header. 28 | */ 29 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 30 | class ServerFrameOptionsDsl { 31 | var mode: XFrameOptionsServerHttpHeadersWriter.Mode? = null 32 | 33 | private var disabled = false 34 | 35 | /** 36 | * Disables the X-Frame-Options response header 37 | */ 38 | fun disable() { 39 | disabled = true 40 | } 41 | 42 | internal fun get(): (ServerHttpSecurity.HeaderSpec.FrameOptionsSpec) -> Unit { 43 | return { frameOptions -> 44 | mode?.also { 45 | frameOptions.mode(mode) 46 | } 47 | if (disabled) { 48 | frameOptions.disable() 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerHttpStrictTransportSecurityDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter 21 | import java.time.Duration 22 | 23 | /** 24 | * A Kotlin DSL to configure the [ServerHttpSecurity] HTTP Strict Transport Security 25 | * header using idiomatic Kotlin code. 26 | * 27 | * @author Eleftheria Stein 28 | * @property maxAge he value for the max-age directive of the Strict-Transport-Security 29 | * header. 30 | * @property includeSubdomains if true, subdomains should be considered HSTS Hosts too. 31 | * @property preload if true, preload will be included in HSTS Header. 32 | */ 33 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 34 | class ServerHttpStrictTransportSecurityDsl { 35 | var maxAge: Duration? = null 36 | var includeSubdomains: Boolean? = null 37 | var preload: Boolean? = null 38 | 39 | private var disabled = false 40 | 41 | /** 42 | * Disables the X-Frame-Options response header 43 | */ 44 | fun disable() { 45 | disabled = true 46 | } 47 | 48 | internal fun get(): (ServerHttpSecurity.HeaderSpec.HstsSpec) -> Unit { 49 | return { hsts -> 50 | maxAge?.also { hsts.maxAge(maxAge) } 51 | includeSubdomains?.also { hsts.includeSubdomains(includeSubdomains!!) } 52 | preload?.also { hsts.preload(preload!!) } 53 | if (disabled) { 54 | hsts.disable() 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerReferrerPolicyDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter 21 | import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter 22 | 23 | /** 24 | * A Kotlin DSL to configure the [ServerHttpSecurity] referrer policy header using 25 | * idiomatic Kotlin code. 26 | * 27 | * @author Eleftheria Stein 28 | * @property policy the policy to be used in the response header. 29 | */ 30 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 31 | class ServerReferrerPolicyDsl { 32 | var policy: ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy? = null 33 | 34 | internal fun get(): (ServerHttpSecurity.HeaderSpec.ReferrerPolicySpec) -> Unit { 35 | return { referrerPolicy -> 36 | policy?.also { 37 | referrerPolicy.policy(policy) 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerXssProtectionDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | 21 | /** 22 | * A Kotlin DSL to configure the [ServerHttpSecurity] XSS protection header using 23 | * idiomatic Kotlin code. 24 | * 25 | * @author Eleftheria Stein 26 | */ 27 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 28 | class ServerXssProtectionDsl { 29 | private var disabled = false 30 | 31 | /** 32 | * Disables cache control response headers 33 | */ 34 | fun disable() { 35 | disabled = true 36 | } 37 | 38 | internal fun get(): (ServerHttpSecurity.HeaderSpec.XssProtectionSpec) -> Unit { 39 | return { xss -> 40 | if (disabled) { 41 | xss.disable() 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/oauth2/resourceserver/ServerJwtDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.oauth2.resourceserver 18 | 19 | import org.springframework.core.convert.converter.Converter 20 | import org.springframework.security.authentication.AbstractAuthenticationToken 21 | import org.springframework.security.authentication.ReactiveAuthenticationManager 22 | import org.springframework.security.config.web.server.ServerHttpSecurity 23 | import org.springframework.security.core.Authentication 24 | import org.springframework.security.oauth2.jwt.Jwt 25 | import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder 26 | import reactor.core.publisher.Mono 27 | import java.security.interfaces.RSAPublicKey 28 | 29 | /** 30 | * A Kotlin DSL to configure [ServerHttpSecurity] JWT Resource Server support using idiomatic Kotlin code. 31 | * 32 | * @author Eleftheria Stein 33 | * @property authenticationManager the [ReactiveAuthenticationManager] used to determine if the provided 34 | * [Authentication] can be authenticated. 35 | * @property jwtAuthenticationConverter the [Converter] to use for converting a [Jwt] into an 36 | * [AbstractAuthenticationToken]. 37 | * @property jwtDecoder the [ReactiveJwtDecoder] to use. 38 | * @property publicKey configures a [ReactiveJwtDecoder] that leverages the provided [RSAPublicKey] 39 | * @property jwkSetUri configures a [ReactiveJwtDecoder] using a 40 | * JSON Web Key (JWK) URL 41 | */ 42 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 43 | class ServerJwtDsl { 44 | private var _jwtDecoder: ReactiveJwtDecoder? = null 45 | private var _publicKey: RSAPublicKey? = null 46 | private var _jwkSetUri: String? = null 47 | 48 | var authenticationManager: ReactiveAuthenticationManager? = null 49 | var jwtAuthenticationConverter: Converter>? = null 50 | 51 | var jwtDecoder: ReactiveJwtDecoder? 52 | get() = _jwtDecoder 53 | set(value) { 54 | _jwtDecoder = value 55 | _publicKey = null 56 | _jwkSetUri = null 57 | } 58 | var publicKey: RSAPublicKey? 59 | get() = _publicKey 60 | set(value) { 61 | _publicKey = value 62 | _jwtDecoder = null 63 | _jwkSetUri = null 64 | } 65 | var jwkSetUri: String? 66 | get() = _jwkSetUri 67 | set(value) { 68 | _jwkSetUri = value 69 | _jwtDecoder = null 70 | _publicKey = null 71 | } 72 | 73 | internal fun get(): (ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec) -> Unit { 74 | return { jwt -> 75 | authenticationManager?.also { jwt.authenticationManager(authenticationManager) } 76 | jwtAuthenticationConverter?.also { jwt.jwtAuthenticationConverter(jwtAuthenticationConverter) } 77 | jwtDecoder?.also { jwt.jwtDecoder(jwtDecoder) } 78 | publicKey?.also { jwt.publicKey(publicKey) } 79 | jwkSetUri?.also { jwt.jwkSetUri(jwkSetUri) } 80 | } 81 | } 82 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/server/oauth2/resourceserver/ServerOpaqueTokenDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.oauth2.resourceserver 18 | 19 | import org.springframework.security.config.web.server.ServerHttpSecurity 20 | import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector 21 | 22 | /** 23 | * A Kotlin DSL to configure [ServerHttpSecurity] Opaque Token Resource Server support using idiomatic Kotlin code. 24 | * 25 | * @author Eleftheria Stein 26 | * @property introspectionUri the URI of the Introspection endpoint. 27 | * @property introspector the [ReactiveOpaqueTokenIntrospector] to use. 28 | */ 29 | @Deprecated("Use Spring Security 5.4 or greater for a native Kotlin DSL.") 30 | class ServerOpaqueTokenDsl { 31 | private var _introspectionUri: String? = null 32 | private var _introspector: ReactiveOpaqueTokenIntrospector? = null 33 | private var clientCredentials: Pair? = null 34 | 35 | var introspectionUri: String? 36 | get() = _introspectionUri 37 | set(value) { 38 | _introspectionUri = value 39 | _introspector = null 40 | } 41 | var introspector: ReactiveOpaqueTokenIntrospector? 42 | get() = _introspector 43 | set(value) { 44 | _introspector = value 45 | _introspectionUri = null 46 | clientCredentials = null 47 | } 48 | 49 | /** 50 | * Configures the credentials for Introspection endpoint. 51 | * 52 | * @param clientId the clientId part of the credentials. 53 | * @param clientSecret the clientSecret part of the credentials. 54 | */ 55 | fun introspectionClientCredentials(clientId: String, clientSecret: String) { 56 | clientCredentials = Pair(clientId, clientSecret) 57 | _introspector = null 58 | } 59 | 60 | internal fun get(): (ServerHttpSecurity.OAuth2ResourceServerSpec.OpaqueTokenSpec) -> Unit { 61 | return { opaqueToken -> 62 | introspectionUri?.also { opaqueToken.introspectionUri(introspectionUri) } 63 | clientCredentials?.also { opaqueToken.introspectionClientCredentials(clientCredentials!!.first, clientCredentials!!.second) } 64 | introspector?.also { opaqueToken.introspector(introspector) } 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/AbstractRequestMatcherDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.web.util.matcher.AnyRequestMatcher 20 | import org.springframework.security.web.util.matcher.RequestMatcher 21 | 22 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 23 | abstract class AbstractRequestMatcherDsl { 24 | 25 | /** 26 | * Matches any request. 27 | */ 28 | val anyRequest: RequestMatcher = AnyRequestMatcher.INSTANCE 29 | 30 | protected data class MatcherAuthorizationRule(val matcher: RequestMatcher, 31 | override val rule: String) : AuthorizationRule(rule) 32 | 33 | protected data class PatternAuthorizationRule(val pattern: String, 34 | val patternType: PatternType, 35 | val servletPath: String?, 36 | override val rule: String) : AuthorizationRule(rule) 37 | 38 | protected abstract class AuthorizationRule(open val rule: String) 39 | 40 | protected enum class PatternType { 41 | ANT, MVC 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/AnonymousDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.authentication.AuthenticationProvider 20 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 21 | import org.springframework.security.config.annotation.web.configurers.AnonymousConfigurer 22 | import org.springframework.security.core.Authentication 23 | import org.springframework.security.core.GrantedAuthority 24 | import org.springframework.security.web.authentication.AnonymousAuthenticationFilter 25 | 26 | /** 27 | * A Kotlin DSL to configure [HttpSecurity] anonymous authentication using idiomatic 28 | * Kotlin code. 29 | * 30 | * @author Eleftheria Stein 31 | * @property key the key to identify tokens created for anonymous authentication 32 | * @property principal the principal for [Authentication] objects of anonymous users 33 | * @property authorities the [Authentication.getAuthorities] for anonymous users 34 | * @property authenticationProvider the [AuthenticationProvider] used to validate an 35 | * anonymous user 36 | * @property authenticationFilter the [AnonymousAuthenticationFilter] used to populate 37 | * an anonymous user. 38 | */ 39 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 40 | class AnonymousDsl { 41 | var key: String? = null 42 | var principal: Any? = null 43 | var authorities: List? = null 44 | var authenticationProvider: AuthenticationProvider? = null 45 | var authenticationFilter: AnonymousAuthenticationFilter? = null 46 | 47 | private var disabled = false 48 | 49 | /** 50 | * Disable anonymous authentication 51 | */ 52 | fun disable() { 53 | disabled = true 54 | } 55 | 56 | internal fun get(): (AnonymousConfigurer) -> Unit { 57 | return { anonymous -> 58 | key?.also { anonymous.key(key) } 59 | principal?.also { anonymous.principal(principal) } 60 | authorities?.also { anonymous.authorities(authorities) } 61 | authenticationProvider?.also { anonymous.authenticationProvider(authenticationProvider) } 62 | authenticationFilter?.also { anonymous.authenticationFilter(authenticationFilter) } 63 | if (disabled) { 64 | anonymous.disable() 65 | } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/CorsDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.CorsConfigurer 21 | 22 | /** 23 | * A Kotlin DSL to configure [HttpSecurity] CORS using idiomatic Kotlin code. 24 | * 25 | * @author Eleftheria Stein 26 | */ 27 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 28 | class CorsDsl { 29 | private var disabled = false 30 | 31 | /** 32 | * Disable CORS. 33 | */ 34 | fun disable() { 35 | disabled = true 36 | } 37 | 38 | internal fun get(): (CorsConfigurer) -> Unit { 39 | return { cors -> 40 | if (disabled) { 41 | cors.disable() 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/CsrfDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer 21 | import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy 22 | import org.springframework.security.web.csrf.CsrfTokenRepository 23 | import org.springframework.security.web.util.matcher.RequestMatcher 24 | import javax.servlet.http.HttpServletRequest 25 | 26 | /** 27 | * A Kotlin DSL to configure [HttpSecurity] CSRF protection 28 | * using idiomatic Kotlin code. 29 | * 30 | * @author Eleftheria Stein 31 | * @property csrfTokenRepository the [CsrfTokenRepository] to use. 32 | * @property requireCsrfProtectionMatcher specify the [RequestMatcher] to use for 33 | * determining when CSRF should be applied. 34 | * @property sessionAuthenticationStrategy the [SessionAuthenticationStrategy] to use. 35 | */ 36 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 37 | class CsrfDsl { 38 | var csrfTokenRepository: CsrfTokenRepository? = null 39 | var requireCsrfProtectionMatcher: RequestMatcher? = null 40 | var sessionAuthenticationStrategy: SessionAuthenticationStrategy? = null 41 | 42 | private var ignoringAntMatchers: Array? = null 43 | private var ignoringRequestMatchers: Array? = null 44 | private var disabled = false 45 | 46 | /** 47 | * Allows specifying [HttpServletRequest]s that should not use CSRF Protection 48 | * even if they match the [requireCsrfProtectionMatcher]. 49 | * 50 | * @param antMatchers the ANT pattern matchers that should not use CSRF 51 | * protection 52 | */ 53 | fun ignoringAntMatchers(vararg antMatchers: String) { 54 | ignoringAntMatchers = antMatchers 55 | } 56 | 57 | /** 58 | * Allows specifying [HttpServletRequest]s that should not use CSRF Protection 59 | * even if they match the [requireCsrfProtectionMatcher]. 60 | * 61 | * @param requestMatchers the request matchers that should not use CSRF 62 | * protection 63 | */ 64 | fun ignoringRequestMatchers(vararg requestMatchers: RequestMatcher) { 65 | ignoringRequestMatchers = requestMatchers 66 | } 67 | 68 | /** 69 | * Disable CSRF protection 70 | */ 71 | fun disable() { 72 | disabled = true 73 | } 74 | 75 | internal fun get(): (CsrfConfigurer) -> Unit { 76 | return { csrf -> 77 | csrfTokenRepository?.also { csrf.csrfTokenRepository(csrfTokenRepository) } 78 | requireCsrfProtectionMatcher?.also { csrf.requireCsrfProtectionMatcher(requireCsrfProtectionMatcher) } 79 | sessionAuthenticationStrategy?.also { csrf.sessionAuthenticationStrategy(sessionAuthenticationStrategy) } 80 | ignoringAntMatchers?.also { csrf.ignoringAntMatchers(*ignoringAntMatchers!!) } 81 | ignoringRequestMatchers?.also { csrf.ignoringRequestMatchers(*ignoringRequestMatchers!!) } 82 | if (disabled) { 83 | csrf.disable() 84 | } 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/ExceptionHandlingDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer 21 | import org.springframework.security.web.AuthenticationEntryPoint 22 | import org.springframework.security.web.access.AccessDeniedHandler 23 | import org.springframework.security.web.util.matcher.RequestMatcher 24 | import java.util.* 25 | 26 | /** 27 | * A Kotlin DSL to configure [HttpSecurity] exception handling using idiomatic Kotlin 28 | * code. 29 | * 30 | * @author Eleftheria Stein 31 | * @property accessDeniedPage the URL to the access denied page 32 | * @property accessDeniedHandler the [AccessDeniedHandler] to use 33 | * @property authenticationEntryPoint the [AuthenticationEntryPoint] to use 34 | */ 35 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 36 | class ExceptionHandlingDsl { 37 | var accessDeniedPage: String? = null 38 | var accessDeniedHandler: AccessDeniedHandler? = null 39 | var authenticationEntryPoint: AuthenticationEntryPoint? = null 40 | 41 | private var defaultDeniedHandlerMappings: LinkedHashMap = linkedMapOf() 42 | private var defaultEntryPointMappings: LinkedHashMap = linkedMapOf() 43 | private var disabled = false 44 | 45 | /** 46 | * Sets a default [AccessDeniedHandler] to be used which prefers being 47 | * invoked for the provided [RequestMatcher]. 48 | * 49 | * @param deniedHandler the [AccessDeniedHandler] to use 50 | * @param preferredMatcher the [RequestMatcher] for this default 51 | * [AccessDeniedHandler] 52 | */ 53 | fun defaultAccessDeniedHandlerFor(deniedHandler: AccessDeniedHandler, preferredMatcher: RequestMatcher) { 54 | defaultDeniedHandlerMappings[preferredMatcher] = deniedHandler 55 | } 56 | 57 | /** 58 | * Sets a default [AuthenticationEntryPoint] to be used which prefers being 59 | * invoked for the provided [RequestMatcher]. 60 | * 61 | * @param entryPoint the [AuthenticationEntryPoint] to use 62 | * @param preferredMatcher the [RequestMatcher] for this default 63 | * [AccessDeniedHandler] 64 | */ 65 | fun defaultAuthenticationEntryPointFor(entryPoint: AuthenticationEntryPoint, preferredMatcher: RequestMatcher) { 66 | defaultEntryPointMappings[preferredMatcher] = entryPoint 67 | } 68 | 69 | /** 70 | * Disable exception handling. 71 | */ 72 | fun disable() { 73 | disabled = true 74 | } 75 | 76 | internal fun get(): (ExceptionHandlingConfigurer) -> Unit { 77 | return { exceptionHandling -> 78 | accessDeniedPage?.also { exceptionHandling.accessDeniedPage(accessDeniedPage) } 79 | accessDeniedHandler?.also { exceptionHandling.accessDeniedHandler(accessDeniedHandler) } 80 | authenticationEntryPoint?.also { exceptionHandling.authenticationEntryPoint(authenticationEntryPoint) } 81 | defaultDeniedHandlerMappings.forEach { (matcher, handler) -> 82 | exceptionHandling.defaultAccessDeniedHandlerFor(handler, matcher) 83 | } 84 | defaultEntryPointMappings.forEach { (matcher, entryPoint) -> 85 | exceptionHandling.defaultAuthenticationEntryPointFor(entryPoint, matcher) 86 | } 87 | if (disabled) { 88 | exceptionHandling.disable() 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/FormLoginDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.config.annotation.web.HttpSecurityBuilder 20 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 21 | import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer 22 | import org.springframework.security.web.authentication.AuthenticationFailureHandler 23 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler 24 | 25 | /** 26 | * A Kotlin DSL to configure [HttpSecurity] form login using idiomatic Kotlin code. 27 | * 28 | * @author Eleftheria Stein 29 | * @property loginPage the login page to redirect to if authentication is required (i.e. 30 | * "/login") 31 | * @property authenticationSuccessHandler the [AuthenticationSuccessHandler] used after 32 | * authentication success 33 | * @property authenticationFailureHandler the [AuthenticationFailureHandler] used after 34 | * authentication success 35 | * @property failureUrl the URL to send users if authentication fails 36 | * @property loginProcessingUrl the URL to validate the credentials 37 | * @property permitAll whether to grant access to the urls for [failureUrl] as well as 38 | * for the [HttpSecurityBuilder], the [loginPage] and [loginProcessingUrl] for every user 39 | */ 40 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 41 | class FormLoginDsl { 42 | var loginPage: String? = null 43 | var authenticationSuccessHandler: AuthenticationSuccessHandler? = null 44 | var authenticationFailureHandler: AuthenticationFailureHandler? = null 45 | var failureUrl: String? = null 46 | var loginProcessingUrl: String? = null 47 | var permitAll: Boolean? = null 48 | 49 | private var defaultSuccessUrlOption: Pair? = null 50 | 51 | /** 52 | * Grants access to the urls for [failureUrl] as well as for the [HttpSecurityBuilder], the 53 | * [loginPage] and [loginProcessingUrl] for every user. 54 | */ 55 | fun permitAll() { 56 | permitAll = true 57 | } 58 | 59 | /** 60 | * Specifies where users will be redirected after authenticating successfully if 61 | * they have not visited a secured page prior to authenticating or [alwaysUse] 62 | * is true. 63 | * 64 | * @param defaultSuccessUrl the default success url 65 | * @param alwaysUse true if the [defaultSuccessUrl] should be used after 66 | * authentication despite if a protected page had been previously visited 67 | */ 68 | fun defaultSuccessUrl(defaultSuccessUrl: String, alwaysUse: Boolean) { 69 | defaultSuccessUrlOption = Pair(defaultSuccessUrl, alwaysUse) 70 | } 71 | 72 | internal fun get(): (FormLoginConfigurer) -> Unit { 73 | return { login -> 74 | loginPage?.also { login.loginPage(loginPage) } 75 | failureUrl?.also { login.failureUrl(failureUrl) } 76 | loginProcessingUrl?.also { login.loginProcessingUrl(loginProcessingUrl) } 77 | permitAll?.also { login.permitAll(permitAll!!) } 78 | defaultSuccessUrlOption?.also { 79 | login.defaultSuccessUrl(defaultSuccessUrlOption!!.first, defaultSuccessUrlOption!!.second) 80 | } 81 | authenticationSuccessHandler?.also { login.successHandler(authenticationSuccessHandler) } 82 | authenticationFailureHandler?.also { login.failureHandler(authenticationFailureHandler) } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/HttpBasicDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.authentication.AuthenticationDetailsSource 20 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 21 | import org.springframework.security.config.annotation.web.configurers.HttpBasicConfigurer 22 | import org.springframework.security.web.AuthenticationEntryPoint 23 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter 24 | import javax.servlet.http.HttpServletRequest 25 | 26 | /** 27 | * A Kotlin DSL to configure [HttpSecurity] basic authentication using idiomatic Kotlin code. 28 | * 29 | * @author Eleftheria Stein 30 | * @property realmName the HTTP Basic realm to use. If [authenticationEntryPoint] 31 | * has been invoked, invoking this method will result in an error. 32 | * @property authenticationEntryPoint the [AuthenticationEntryPoint] to be populated on 33 | * [BasicAuthenticationFilter] in the event that authentication fails. 34 | * @property authenticationDetailsSource the custom [AuthenticationDetailsSource] to use for 35 | * basic authentication. 36 | */ 37 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 38 | class HttpBasicDsl { 39 | var realmName: String? = null 40 | var authenticationEntryPoint: AuthenticationEntryPoint? = null 41 | var authenticationDetailsSource: AuthenticationDetailsSource? = null 42 | 43 | private var disabled = false 44 | 45 | /** 46 | * Disables HTTP basic authentication 47 | */ 48 | fun disable() { 49 | disabled = true 50 | } 51 | 52 | internal fun get(): (HttpBasicConfigurer) -> Unit { 53 | return { httpBasic -> 54 | realmName?.also { httpBasic.realmName(realmName) } 55 | authenticationEntryPoint?.also { httpBasic.authenticationEntryPoint(authenticationEntryPoint) } 56 | authenticationDetailsSource?.also { httpBasic.authenticationDetailsSource(authenticationDetailsSource) } 57 | if (disabled) { 58 | httpBasic.disable() 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/OAuth2ClientDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | /* 20 | * Copyright 2002-2020 the original author or authors. 21 | * 22 | * Licensed under the Apache License, Version 2.0 (the "License"); 23 | * you may not use this file except in compliance with the License. 24 | * You may obtain a copy of the License at 25 | * 26 | * https://www.apache.org/licenses/LICENSE-2.0 27 | * 28 | * Unless required by applicable law or agreed to in writing, software 29 | * distributed under the License is distributed on an "AS IS" BASIS, 30 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 31 | * See the License for the specific language governing permissions and 32 | * limitations under the License. 33 | */ 34 | 35 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 36 | import org.springframework.security.dsl.config.builders.servlet.oauth2.client.AuthorizationCodeGrantDsl 37 | import org.springframework.security.dsl.config.builders.servlet.oauth2.login.AuthorizationEndpointDsl 38 | import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2ClientConfigurer 39 | import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService 40 | import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository 41 | import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository 42 | 43 | /** 44 | * A Kotlin DSL to configure [HttpSecurity] OAuth 2.0 client support using idiomatic 45 | * Kotlin code. 46 | * 47 | * @author Eleftheria Stein 48 | * @property clientRegistrationRepository the repository of client registrations. 49 | * @property authorizedClientRepository the repository for authorized client(s). 50 | * @property authorizedClientService the service for authorized client(s). 51 | */ 52 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 53 | class OAuth2ClientDsl { 54 | var clientRegistrationRepository: ClientRegistrationRepository? = null 55 | var authorizedClientRepository: OAuth2AuthorizedClientRepository? = null 56 | var authorizedClientService: OAuth2AuthorizedClientService? = null 57 | 58 | private var authorizationCodeGrant: ((OAuth2ClientConfigurer.AuthorizationCodeGrantConfigurer) -> Unit)? = null 59 | 60 | /** 61 | * Configures the OAuth 2.0 Authorization Code Grant. 62 | * 63 | * Example: 64 | * 65 | * ``` 66 | * @EnableWebSecurity 67 | * class SecurityConfig : WebSecurityConfigurerAdapter() { 68 | * 69 | * override fun configure(http: HttpSecurity) { 70 | * httpSecurity(http) { 71 | * oauth2Client { 72 | * authorizationCodeGrant { 73 | * authorizationRequestResolver = getAuthorizationRequestResolver() 74 | * } 75 | * } 76 | * } 77 | * } 78 | * } 79 | * ``` 80 | * 81 | * @param authorizationCodeGrantConfig custom configurations to configure the authorization 82 | * code grant 83 | * @see [AuthorizationEndpointDsl] 84 | */ 85 | fun authorizationCodeGrant(authorizationCodeGrantConfig: AuthorizationCodeGrantDsl.() -> Unit) { 86 | this.authorizationCodeGrant = AuthorizationCodeGrantDsl().apply(authorizationCodeGrantConfig).get() 87 | } 88 | 89 | internal fun get(): (OAuth2ClientConfigurer) -> Unit { 90 | return { oauth2Client -> 91 | clientRegistrationRepository?.also { oauth2Client.clientRegistrationRepository(clientRegistrationRepository) } 92 | authorizedClientRepository?.also { oauth2Client.authorizedClientRepository(authorizedClientRepository) } 93 | authorizedClientService?.also { oauth2Client.authorizedClientService(authorizedClientService) } 94 | authorizationCodeGrant?.also { oauth2Client.authorizationCodeGrant(authorizationCodeGrant) } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/OAuth2ResourceServerDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.dsl.config.builders.servlet.oauth2.resourceserver.JwtDsl 21 | import org.springframework.security.dsl.config.builders.servlet.oauth2.resourceserver.OpaqueTokenDsl 22 | import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer 23 | import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver 24 | import org.springframework.security.web.AuthenticationEntryPoint 25 | import org.springframework.security.web.access.AccessDeniedHandler 26 | 27 | /** 28 | * A Kotlin DSL to configure [HttpSecurity] OAuth 2.0 resource server support using 29 | * idiomatic Kotlin code. 30 | * 31 | * @author Eleftheria Stein 32 | * @property accessDeniedHandler the [AccessDeniedHandler] to use for requests authenticating 33 | * with Bearer Tokens. 34 | * @property authenticationEntryPoint the [AuthenticationEntryPoint] to use for requests authenticating 35 | * with Bearer Tokens. 36 | * @property bearerTokenResolver the [BearerTokenResolver] to use for requests authenticating 37 | * with Bearer Tokens. 38 | */ 39 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 40 | class OAuth2ResourceServerDsl { 41 | var accessDeniedHandler: AccessDeniedHandler? = null 42 | var authenticationEntryPoint: AuthenticationEntryPoint? = null 43 | var bearerTokenResolver: BearerTokenResolver? = null 44 | 45 | private var jwt: ((OAuth2ResourceServerConfigurer.JwtConfigurer) -> Unit)? = null 46 | private var opaqueToken: ((OAuth2ResourceServerConfigurer.OpaqueTokenConfigurer) -> Unit)? = null 47 | 48 | /** 49 | * Enables JWT-encoded bearer token support. 50 | * 51 | * Example: 52 | * 53 | * ``` 54 | * @EnableWebSecurity 55 | * class SecurityConfig : WebSecurityConfigurerAdapter() { 56 | * 57 | * override fun configure(http: HttpSecurity) { 58 | * httpSecurity(http) { 59 | * oauth2ResourceServer { 60 | * jwt { 61 | * jwkSetUri = "https://example.com/oauth2/jwk" 62 | * } 63 | * } 64 | * } 65 | * } 66 | * } 67 | * ``` 68 | * 69 | * @param jwtConfig custom configurations to configure JWT resource server support 70 | * @see [JwtDsl] 71 | */ 72 | fun jwt(jwtConfig: JwtDsl.() -> Unit) { 73 | this.jwt = JwtDsl().apply(jwtConfig).get() 74 | } 75 | 76 | /** 77 | * Enables opaque token support. 78 | * 79 | * Example: 80 | * 81 | * ``` 82 | * @EnableWebSecurity 83 | * class SecurityConfig : WebSecurityConfigurerAdapter() { 84 | * 85 | * override fun configure(http: HttpSecurity) { 86 | * httpSecurity(http) { 87 | * oauth2ResourceServer { 88 | * opaqueToken { } 89 | * } 90 | * } 91 | * } 92 | * } 93 | * ``` 94 | * 95 | * @param opaqueTokenConfig custom configurations to configure opaque token resource server support 96 | * @see [OpaqueTokenDsl] 97 | */ 98 | fun opaqueToken(opaqueTokenConfig: OpaqueTokenDsl.() -> Unit) { 99 | this.opaqueToken = OpaqueTokenDsl().apply(opaqueTokenConfig).get() 100 | } 101 | 102 | internal fun get(): (OAuth2ResourceServerConfigurer) -> Unit { 103 | return { oauth2ResourceServer -> 104 | accessDeniedHandler?.also { oauth2ResourceServer.accessDeniedHandler(accessDeniedHandler) } 105 | authenticationEntryPoint?.also { oauth2ResourceServer.authenticationEntryPoint(authenticationEntryPoint) } 106 | bearerTokenResolver?.also { oauth2ResourceServer.bearerTokenResolver(bearerTokenResolver) } 107 | jwt?.also { oauth2ResourceServer.jwt(jwt) } 108 | opaqueToken?.also { oauth2ResourceServer.opaqueToken(opaqueToken) } 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/PortMapperDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.PortMapperConfigurer 21 | import org.springframework.security.web.PortMapper 22 | 23 | /** 24 | * A Kotlin DSL to configure a [PortMapper] for [HttpSecurity] using idiomatic 25 | * Kotlin code. 26 | * 27 | * @author Eleftheria Stein 28 | * @property portMapper allows specifying the [PortMapper] instance. 29 | */ 30 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 31 | class PortMapperDsl { 32 | private val mappings = mutableListOf>() 33 | 34 | var portMapper: PortMapper? = null 35 | 36 | /** 37 | * Adds a mapping to the port mapper. 38 | * 39 | * @param fromPort the HTTP port number to map from 40 | * @param toPort the HTTPS port number to map to 41 | */ 42 | fun map(fromPort: Int, toPort: Int) { 43 | mappings.add(Pair(fromPort, toPort)) 44 | } 45 | 46 | internal fun get(): (PortMapperConfigurer) -> Unit { 47 | return { portMapperConfig -> 48 | portMapper?.also { 49 | portMapperConfig.portMapper(portMapper) 50 | } 51 | this.mappings.forEach { 52 | portMapperConfig.http(it.first).mapsTo(it.second) 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/RequestCacheDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.RequestCacheConfigurer 21 | import org.springframework.security.web.savedrequest.RequestCache 22 | 23 | /** 24 | * A Kotlin DSL to enable request caching for [HttpSecurity] using idiomatic 25 | * Kotlin code. 26 | * 27 | * @author Eleftheria Stein 28 | * @property requestCache allows explicit configuration of the [RequestCache] to be used 29 | */ 30 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 31 | class RequestCacheDsl { 32 | var requestCache: RequestCache? = null 33 | 34 | internal fun get(): (RequestCacheConfigurer) -> Unit { 35 | return { requestCacheConfig -> 36 | requestCache?.also { 37 | requestCacheConfig.requestCache(requestCache) 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/Saml2Dsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.config.annotation.web.HttpSecurityBuilder 20 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 21 | import org.springframework.security.config.annotation.web.configurers.saml2.Saml2LoginConfigurer 22 | import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository 23 | import org.springframework.security.web.authentication.AuthenticationFailureHandler 24 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler 25 | 26 | /** 27 | * A Kotlin DSL to configure [HttpSecurity] SAML2 login using idiomatic Kotlin code. 28 | * 29 | * @author Eleftheria Stein 30 | * @property relyingPartyRegistrationRepository the [RelyingPartyRegistrationRepository] of relying parties, 31 | * each party representing a service provider, SP and this host, and identity provider, IDP pair that 32 | * communicate with each other. 33 | * @property loginPage the login page to redirect to if authentication is required (i.e. 34 | * "/login") 35 | * @property authenticationSuccessHandler the [AuthenticationSuccessHandler] used after 36 | * authentication success 37 | * @property authenticationFailureHandler the [AuthenticationFailureHandler] used after 38 | * authentication success 39 | * @property failureUrl the URL to send users if authentication fails 40 | * @property loginProcessingUrl the URL to validate the credentials 41 | * @property permitAll whether to grant access to the urls for [failureUrl] as well as 42 | * for the [HttpSecurityBuilder], the [loginPage] and [loginProcessingUrl] for every user 43 | */ 44 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 45 | class Saml2Dsl { 46 | var relyingPartyRegistrationRepository: RelyingPartyRegistrationRepository? = null 47 | var loginPage: String? = null 48 | var authenticationSuccessHandler: AuthenticationSuccessHandler? = null 49 | var authenticationFailureHandler: AuthenticationFailureHandler? = null 50 | var failureUrl: String? = null 51 | var loginProcessingUrl: String? = null 52 | var permitAll: Boolean? = null 53 | 54 | private var defaultSuccessUrlOption: Pair? = null 55 | 56 | /** 57 | * Grants access to the urls for [failureUrl] as well as for the [HttpSecurityBuilder], the 58 | * [loginPage] and [loginProcessingUrl] for every user. 59 | */ 60 | fun permitAll() { 61 | permitAll = true 62 | } 63 | 64 | /** 65 | * Specifies where users will be redirected after authenticating successfully if 66 | * they have not visited a secured page prior to authenticating or [alwaysUse] 67 | * is true. 68 | * 69 | * @param defaultSuccessUrl the default success url 70 | * @param alwaysUse true if the [defaultSuccessUrl] should be used after 71 | * authentication despite if a protected page had been previously visited 72 | */ 73 | fun defaultSuccessUrl(defaultSuccessUrl: String, alwaysUse: Boolean) { 74 | defaultSuccessUrlOption = Pair(defaultSuccessUrl, alwaysUse) 75 | } 76 | 77 | internal fun get(): (Saml2LoginConfigurer) -> Unit { 78 | return { saml2Login -> 79 | relyingPartyRegistrationRepository?.also { saml2Login.relyingPartyRegistrationRepository(relyingPartyRegistrationRepository) } 80 | loginPage?.also { saml2Login.loginPage(loginPage) } 81 | failureUrl?.also { saml2Login.failureUrl(failureUrl) } 82 | loginProcessingUrl?.also { saml2Login.loginProcessingUrl(loginProcessingUrl) } 83 | permitAll?.also { saml2Login.permitAll(permitAll!!) } 84 | defaultSuccessUrlOption?.also { 85 | saml2Login.defaultSuccessUrl(defaultSuccessUrlOption!!.first, defaultSuccessUrlOption!!.second) 86 | } 87 | authenticationSuccessHandler?.also { saml2Login.successHandler(authenticationSuccessHandler) } 88 | authenticationFailureHandler?.also { saml2Login.failureHandler(authenticationFailureHandler) } 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/X509Dsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.springframework.security.authentication.AuthenticationDetailsSource 20 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 21 | import org.springframework.security.config.annotation.web.configurers.X509Configurer 22 | import org.springframework.security.core.userdetails.AuthenticationUserDetailsService 23 | import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper 24 | import org.springframework.security.core.userdetails.UserDetailsService 25 | import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken 26 | import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails 27 | import org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter 28 | import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor 29 | import javax.servlet.http.HttpServletRequest 30 | 31 | /** 32 | * A Kotlin DSL to configure [HttpSecurity] X509 based pre authentication 33 | * using idiomatic Kotlin code. 34 | * 35 | * @author Eleftheria Stein 36 | * @property x509AuthenticationFilter the entire [X509AuthenticationFilter]. If 37 | * this is specified, the properties on [X509Configurer] will not be populated 38 | * on the {@link X509AuthenticationFilter}. 39 | * @property x509PrincipalExtractor the [X509PrincipalExtractor] 40 | * @property authenticationDetailsSource the [X509PrincipalExtractor] 41 | * @property userDetailsService shortcut for invoking 42 | * [authenticationUserDetailsService] with a [UserDetailsByNameServiceWrapper] 43 | * @property authenticationUserDetailsService the [AuthenticationUserDetailsService] to use 44 | * @property subjectPrincipalRegex the regex to extract the principal from the certificate 45 | */ 46 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 47 | class X509Dsl { 48 | var x509AuthenticationFilter: X509AuthenticationFilter? = null 49 | var x509PrincipalExtractor: X509PrincipalExtractor? = null 50 | var authenticationDetailsSource: AuthenticationDetailsSource? = null 51 | var userDetailsService: UserDetailsService? = null 52 | var authenticationUserDetailsService: AuthenticationUserDetailsService? = null 53 | var subjectPrincipalRegex: String? = null 54 | 55 | internal fun get(): (X509Configurer) -> Unit { 56 | return { x509 -> 57 | x509AuthenticationFilter?.also { x509.x509AuthenticationFilter(x509AuthenticationFilter) } 58 | x509PrincipalExtractor?.also { x509.x509PrincipalExtractor(x509PrincipalExtractor) } 59 | authenticationDetailsSource?.also { x509.authenticationDetailsSource(authenticationDetailsSource) } 60 | userDetailsService?.also { x509.userDetailsService(userDetailsService) } 61 | authenticationUserDetailsService?.also { x509.authenticationUserDetailsService(authenticationUserDetailsService) } 62 | subjectPrincipalRegex?.also { x509.subjectPrincipalRegex(subjectPrincipalRegex) } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/CacheControlDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer 21 | 22 | /** 23 | * A Kotlin DSL to configure the [HttpSecurity] cache control headers using idiomatic 24 | * Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | */ 28 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 29 | class CacheControlDsl { 30 | private var disabled = false 31 | 32 | /** 33 | * Disable cache control headers. 34 | */ 35 | fun disable() { 36 | disabled = true 37 | } 38 | 39 | internal fun get(): (HeadersConfigurer.CacheControlConfig) -> Unit { 40 | return { cacheControl -> 41 | if (disabled) { 42 | cacheControl.disable() 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/ContentSecurityPolicyDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer 21 | 22 | /** 23 | * A Kotlin DSL to configure the [HttpSecurity] Content-Security-Policy header using 24 | * idiomatic Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | * @property policyDirectives the security policy directive(s) to be used in the response header. 28 | * @property reportOnly includes the Content-Security-Policy-Report-Only header in the response. 29 | */ 30 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 31 | class ContentSecurityPolicyDsl { 32 | var policyDirectives: String? = null 33 | var reportOnly: Boolean? = null 34 | 35 | internal fun get(): (HeadersConfigurer.ContentSecurityPolicyConfig) -> Unit { 36 | return { contentSecurityPolicy -> 37 | policyDirectives?.also { 38 | contentSecurityPolicy.policyDirectives(policyDirectives) 39 | } 40 | reportOnly?.also { 41 | if (reportOnly!!) { 42 | contentSecurityPolicy.reportOnly() 43 | } 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/ContentTypeOptionsDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer 21 | 22 | /** 23 | * A Kotlin DSL to configure [HttpSecurity] X-Content-Type-Options header using idiomatic 24 | * Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | */ 28 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 29 | class ContentTypeOptionsDsl { 30 | private var disabled = false 31 | 32 | /** 33 | * Disable the X-Content-Type-Options header. 34 | */ 35 | fun disable() { 36 | disabled = true 37 | } 38 | 39 | internal fun get(): (HeadersConfigurer.ContentTypeOptionsConfig) -> Unit { 40 | return { contentTypeOptions -> 41 | if (disabled) { 42 | contentTypeOptions.disable() 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/FrameOptionsDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer 21 | 22 | /** 23 | * A Kotlin DSL to configure the [HttpSecurity] X-Frame-Options header using 24 | * idiomatic Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | * @property sameOrigin allow any request that comes from the same origin to frame this 28 | * application. 29 | * @property deny deny framing any content from this application. 30 | */ 31 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 32 | class FrameOptionsDsl { 33 | var sameOrigin: Boolean? = null 34 | var deny: Boolean? = null 35 | 36 | private var disabled = false 37 | 38 | /** 39 | * Disable the X-Frame-Options header. 40 | */ 41 | fun disable() { 42 | disabled = true 43 | } 44 | 45 | internal fun get(): (HeadersConfigurer.FrameOptionsConfig) -> Unit { 46 | return { frameOptions -> 47 | sameOrigin?.also { 48 | if (sameOrigin!!) { 49 | frameOptions.sameOrigin() 50 | } 51 | } 52 | deny?.also { 53 | if (deny!!) { 54 | frameOptions.deny() 55 | } 56 | } 57 | if (disabled) { 58 | frameOptions.disable() 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/HttpPublicKeyPinningDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer 21 | 22 | /** 23 | * A Kotlin DSL to configure the [HttpSecurity] HTTP Public Key Pinning header using 24 | * idiomatic Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | * @property pins the value for the pin- directive of the Public-Key-Pins header. 28 | * @property maxAgeInSeconds the value (in seconds) for the max-age directive of the 29 | * Public-Key-Pins header. 30 | * @property includeSubDomains if true, the pinning policy applies to this pinned host 31 | * as well as any subdomains of the host's domain name. 32 | * @property reportOnly if true, the browser should not terminate the connection with 33 | * the server. 34 | * @property reportUri the URI to which the browser should report pin validation failures. 35 | */ 36 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 37 | class HttpPublicKeyPinningDsl { 38 | var pins: Map? = null 39 | var maxAgeInSeconds: Long? = null 40 | var includeSubDomains: Boolean? = null 41 | var reportOnly: Boolean? = null 42 | var reportUri: String? = null 43 | 44 | private var disabled = false 45 | 46 | /** 47 | * Disable the HTTP Public Key Pinning header. 48 | */ 49 | fun disable() { 50 | disabled = true 51 | } 52 | 53 | internal fun get(): (HeadersConfigurer.HpkpConfig) -> Unit { 54 | return { hpkp -> 55 | pins?.also { 56 | hpkp.withPins(pins) 57 | } 58 | maxAgeInSeconds?.also { 59 | hpkp.maxAgeInSeconds(maxAgeInSeconds!!) 60 | } 61 | includeSubDomains?.also { 62 | hpkp.includeSubDomains(includeSubDomains!!) 63 | } 64 | reportOnly?.also { 65 | hpkp.reportOnly(reportOnly!!) 66 | } 67 | reportUri?.also { 68 | hpkp.reportUri(reportUri) 69 | } 70 | if (disabled) { 71 | hpkp.disable() 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/HttpStrictTransportSecurityDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer 21 | import org.springframework.security.web.util.matcher.RequestMatcher 22 | 23 | /** 24 | * A Kotlin DSL to configure the [HttpSecurity] HTTP Strict Transport Security header using 25 | * idiomatic Kotlin code. 26 | * 27 | * @author Eleftheria Stein 28 | * @property maxAgeInSeconds the value (in seconds) for the max-age directive of the 29 | * Strict-Transport-Security header. 30 | * @property requestMatcher the [RequestMatcher] used to determine if the 31 | * "Strict-Transport-Security" header should be added. If true the header is added, 32 | * else the header is not added. 33 | * @property includeSubDomains if true, subdomains should be considered HSTS Hosts too. 34 | * @property preload if true, preload will be included in HSTS Header. 35 | */ 36 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 37 | class HttpStrictTransportSecurityDsl { 38 | var maxAgeInSeconds: Long? = null 39 | var requestMatcher: RequestMatcher? = null 40 | var includeSubDomains: Boolean? = null 41 | var preload: Boolean? = null 42 | 43 | private var disabled = false 44 | 45 | /** 46 | * Disable the HTTP Strict Transport Security header. 47 | */ 48 | fun disable() { 49 | disabled = true 50 | } 51 | 52 | internal fun get(): (HeadersConfigurer.HstsConfig) -> Unit { 53 | return { hsts -> 54 | maxAgeInSeconds?.also { hsts.maxAgeInSeconds(maxAgeInSeconds!!) } 55 | requestMatcher?.also { hsts.requestMatcher(requestMatcher) } 56 | includeSubDomains?.also { hsts.includeSubDomains(includeSubDomains!!) } 57 | preload?.also { hsts.preload(preload!!) } 58 | if (disabled) { 59 | hsts.disable() 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/ReferrerPolicyDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer 21 | import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter 22 | 23 | /** 24 | * A Kotlin DSL to configure the [HttpSecurity] referrer policy header using 25 | * idiomatic Kotlin code. 26 | * 27 | * @author Eleftheria Stein 28 | * @property policy the policy to be used in the response header. 29 | */ 30 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 31 | class ReferrerPolicyDsl { 32 | var policy: ReferrerPolicyHeaderWriter.ReferrerPolicy? = null 33 | 34 | internal fun get(): (HeadersConfigurer.ReferrerPolicyConfig) -> Unit { 35 | return { referrerPolicy -> 36 | policy?.also { 37 | referrerPolicy.policy(policy) 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/XssProtectionConfigDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer 21 | 22 | /** 23 | * A Kotlin DSL to configure the [HttpSecurity] XSS protection header using 24 | * idiomatic Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | * @property block whether to specify the mode as blocked 28 | * @property xssProtectionEnabled if true, the header value will contain a value of 1. 29 | * If false, will explicitly disable specify that X-XSS-Protection is disabled. 30 | */ 31 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 32 | class XssProtectionConfigDsl { 33 | var block: Boolean? = null 34 | var xssProtectionEnabled: Boolean? = null 35 | 36 | private var disabled = false 37 | 38 | /** 39 | * Do not include the X-XSS-Protection header in the response. 40 | */ 41 | fun disable() { 42 | disabled = true 43 | } 44 | 45 | internal fun get(): (HeadersConfigurer.XXssConfig) -> Unit { 46 | return { xssProtection -> 47 | block?.also { xssProtection.block(block!!) } 48 | xssProtectionEnabled?.also { xssProtection.xssProtectionEnabled(xssProtectionEnabled!!) } 49 | 50 | if (disabled) { 51 | xssProtection.disable() 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/oauth2/client/AuthorizationCodeGrantDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.oauth2.client 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2ClientConfigurer 21 | import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient 22 | import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest 23 | import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository 24 | import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver 25 | import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest 26 | 27 | /** 28 | * A Kotlin DSL to configure OAuth 2.0 Authorization Code Grant. 29 | * 30 | * @author Eleftheria Stein 31 | * @property authorizationRequestResolver the resolver used for resolving [OAuth2AuthorizationRequest]'s. 32 | * @property authorizationRequestRepository the repository used for storing [OAuth2AuthorizationRequest]'s. 33 | * @property accessTokenResponseClient the client used for requesting the access token credential 34 | * from the Token Endpoint. 35 | */ 36 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 37 | class AuthorizationCodeGrantDsl { 38 | var authorizationRequestResolver: OAuth2AuthorizationRequestResolver? = null 39 | var authorizationRequestRepository: AuthorizationRequestRepository? = null 40 | var accessTokenResponseClient: OAuth2AccessTokenResponseClient? = null 41 | 42 | internal fun get(): (OAuth2ClientConfigurer.AuthorizationCodeGrantConfigurer) -> Unit { 43 | return { authorizationCodeGrant -> 44 | authorizationRequestResolver?.also { authorizationCodeGrant.authorizationRequestResolver(authorizationRequestResolver) } 45 | authorizationRequestRepository?.also { authorizationCodeGrant.authorizationRequestRepository(authorizationRequestRepository) } 46 | accessTokenResponseClient?.also { authorizationCodeGrant.accessTokenResponseClient(accessTokenResponseClient) } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/oauth2/login/AuthorizationEndpointDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.oauth2.login 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer 21 | import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository 22 | import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver 23 | import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest 24 | 25 | /** 26 | * A Kotlin DSL to configure the Authorization Server's Authorization Endpoint using 27 | * idiomatic Kotlin code. 28 | * 29 | * @author Eleftheria Stein 30 | * @property baseUri the base URI used for authorization requests. 31 | * @property authorizationRequestResolver the resolver used for resolving [OAuth2AuthorizationRequest]'s. 32 | * @property authorizationRequestRepository the repository used for storing [OAuth2AuthorizationRequest]'s. 33 | */ 34 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 35 | class AuthorizationEndpointDsl { 36 | var baseUri: String? = null 37 | var authorizationRequestResolver: OAuth2AuthorizationRequestResolver? = null 38 | var authorizationRequestRepository: AuthorizationRequestRepository? = null 39 | 40 | internal fun get(): (OAuth2LoginConfigurer.AuthorizationEndpointConfig) -> Unit { 41 | return { authorizationEndpoint -> 42 | baseUri?.also { authorizationEndpoint.baseUri(baseUri) } 43 | authorizationRequestResolver?.also { authorizationEndpoint.authorizationRequestResolver(authorizationRequestResolver) } 44 | authorizationRequestRepository?.also { authorizationEndpoint.authorizationRequestRepository(authorizationRequestRepository) } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/oauth2/login/RedirectionEndpointDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.oauth2.login 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer 21 | 22 | /** 23 | * A Kotlin DSL to configure the Authorization Server's Redirection Endpoint using 24 | * idiomatic Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | * @property baseUri the URI where the authorization response will be processed. 28 | */ 29 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 30 | class RedirectionEndpointDsl { 31 | var baseUri: String? = null 32 | 33 | internal fun get(): (OAuth2LoginConfigurer.RedirectionEndpointConfig) -> Unit { 34 | return { redirectionEndpoint -> 35 | baseUri?.also { redirectionEndpoint.baseUri(baseUri) } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/oauth2/login/TokenEndpointDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.oauth2.login 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer 21 | import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient 22 | import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest 23 | 24 | /** 25 | * A Kotlin DSL to configure the Authorization Server's Token Endpoint using 26 | * idiomatic Kotlin code. 27 | * 28 | * @author Eleftheria Stein 29 | * @property accessTokenResponseClient the client used for requesting the access token credential 30 | * from the Token Endpoint. 31 | */ 32 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 33 | class TokenEndpointDsl { 34 | var accessTokenResponseClient: OAuth2AccessTokenResponseClient? = null 35 | 36 | internal fun get(): (OAuth2LoginConfigurer.TokenEndpointConfig) -> Unit { 37 | return { tokenEndpoint -> 38 | accessTokenResponseClient?.also { tokenEndpoint.accessTokenResponseClient(accessTokenResponseClient) } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/oauth2/login/UserInfoEndpointDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.oauth2.login 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer 21 | import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper 22 | import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest 23 | import org.springframework.security.oauth2.client.registration.ClientRegistration 24 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest 25 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserService 26 | import org.springframework.security.oauth2.core.oidc.user.OidcUser 27 | import org.springframework.security.oauth2.core.user.OAuth2User 28 | 29 | /** 30 | * A Kotlin DSL to configure the Authorization Server's UserInfo Endpoint using 31 | * idiomatic Kotlin code. 32 | * 33 | * @author Eleftheria Stein 34 | * @property userService the OAuth 2.0 service used for obtaining the user attributes of the End-User 35 | * from the UserInfo Endpoint. 36 | * @property oidcUserService the OpenID Connect 1.0 service used for obtaining the user attributes of the 37 | * End-User from the UserInfo Endpoint. 38 | * @property userAuthoritiesMapper the [GrantedAuthoritiesMapper] used for mapping [OAuth2User.getAuthorities] 39 | */ 40 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 41 | class UserInfoEndpointDsl { 42 | var userService: OAuth2UserService? = null 43 | var oidcUserService: OAuth2UserService? = null 44 | var userAuthoritiesMapper: GrantedAuthoritiesMapper? = null 45 | 46 | private var customUserTypePair: Pair, String>? = null 47 | 48 | /** 49 | * Sets a custom [OAuth2User] type and associates it to the provided 50 | * client [ClientRegistration.getRegistrationId] registration identifier. 51 | * 52 | * @param customUserType a custom [OAuth2User] type 53 | * @param clientRegistrationId the client registration identifier 54 | */ 55 | fun customUserType(customUserType: Class, clientRegistrationId: String) { 56 | customUserTypePair = Pair(customUserType, clientRegistrationId) 57 | } 58 | 59 | internal fun get(): (OAuth2LoginConfigurer.UserInfoEndpointConfig) -> Unit { 60 | return { userInfoEndpoint -> 61 | userService?.also { userInfoEndpoint.userService(userService) } 62 | oidcUserService?.also { userInfoEndpoint.oidcUserService(oidcUserService) } 63 | userAuthoritiesMapper?.also { userInfoEndpoint.userAuthoritiesMapper(userAuthoritiesMapper) } 64 | customUserTypePair?.also { userInfoEndpoint.customUserType(customUserTypePair!!.first, customUserTypePair!!.second) } 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/oauth2/resourceserver/JwtDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.oauth2.resourceserver 18 | 19 | import org.springframework.core.convert.converter.Converter 20 | import org.springframework.security.authentication.AbstractAuthenticationToken 21 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 22 | import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer 23 | import org.springframework.security.oauth2.jwt.Jwt 24 | import org.springframework.security.oauth2.jwt.JwtDecoder 25 | 26 | /** 27 | * A Kotlin DSL to configure JWT Resource Server Support using idiomatic Kotlin code. 28 | * 29 | * @author Eleftheria Stein 30 | * @property jwtAuthenticationConverter the [Converter] to use for converting a [Jwt] into 31 | * an [AbstractAuthenticationToken]. 32 | * @property jwtDecoder the [JwtDecoder] to use. 33 | * @property jwkSetUri configures a [JwtDecoder] using a 34 | * JSON Web Key (JWK) URL 35 | */ 36 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 37 | class JwtDsl { 38 | var jwtAuthenticationConverter: Converter? = null 39 | var jwtDecoder: JwtDecoder? = null 40 | var jwkSetUri: String? = null 41 | 42 | internal fun get(): (OAuth2ResourceServerConfigurer.JwtConfigurer) -> Unit { 43 | return { jwt -> 44 | jwtAuthenticationConverter?.also { jwt.jwtAuthenticationConverter(jwtAuthenticationConverter) } 45 | jwtDecoder?.also { jwt.decoder(jwtDecoder) } 46 | jwkSetUri?.also { jwt.jwkSetUri(jwkSetUri) } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/oauth2/resourceserver/OpaqueTokenDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.oauth2.resourceserver 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer 21 | import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector 22 | 23 | /** 24 | * A Kotlin DSL to configure JWT Resource Server Support using idiomatic Kotlin code. 25 | * 26 | * @author Eleftheria Stein 27 | * @property introspectionUri the URI of the Introspection endpoint. 28 | * @property introspector the [OpaqueTokenIntrospector] to use. 29 | */ 30 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 31 | class OpaqueTokenDsl { 32 | var introspectionUri: String? = null 33 | var introspector: OpaqueTokenIntrospector? = null 34 | 35 | private var clientCredentials: Pair? = null 36 | 37 | /** 38 | * Configures the credentials for Introspection endpoint. 39 | * 40 | * @param clientId the clientId part of the credentials. 41 | * @param clientSecret the clientSecret part of the credentials. 42 | */ 43 | fun introspectionClientCredentials(clientId: String, clientSecret: String) { 44 | clientCredentials = Pair(clientId, clientSecret) 45 | } 46 | 47 | internal fun get(): (OAuth2ResourceServerConfigurer.OpaqueTokenConfigurer) -> Unit { 48 | return { opaqueToken -> 49 | introspectionUri?.also { opaqueToken.introspectionUri(introspectionUri) } 50 | introspector?.also { opaqueToken.introspector(introspector) } 51 | clientCredentials?.also { opaqueToken.introspectionClientCredentials(clientCredentials!!.first, clientCredentials!!.second) } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/session/SessionConcurrencyDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.session 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer 21 | import org.springframework.security.core.session.SessionRegistry 22 | import org.springframework.security.web.session.SessionInformationExpiredStrategy 23 | 24 | /** 25 | * A Kotlin DSL to configure the behaviour of multiple sessions using idiomatic 26 | * Kotlin code. 27 | * 28 | * @author Eleftheria Stein 29 | * @property maximumSessions controls the maximum number of sessions for a user. 30 | * @property expiredUrl the URL to redirect to if a user tries to access a resource and 31 | * their session has been expired due to too many sessions for the current user. 32 | * @property expiredSessionStrategy determines the behaviour when an expired session 33 | * is detected. 34 | * @property maxSessionsPreventsLogin if true, prevents a user from authenticating when the 35 | * [maximumSessions] has been reached. Otherwise (default), the user who authenticates 36 | * is allowed access and an existing user's session is expired. 37 | * @property sessionRegistry the [SessionRegistry] implementation used. 38 | * 39 | */ 40 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 41 | class SessionConcurrencyDsl { 42 | var maximumSessions: Int? = null 43 | var expiredUrl: String? = null 44 | var expiredSessionStrategy: SessionInformationExpiredStrategy? = null 45 | var maxSessionsPreventsLogin: Boolean? = null 46 | var sessionRegistry: SessionRegistry? = null 47 | 48 | internal fun get(): (SessionManagementConfigurer.ConcurrencyControlConfigurer) -> Unit { 49 | return { sessionConcurrencyControl -> 50 | maximumSessions?.also { 51 | sessionConcurrencyControl.maximumSessions(maximumSessions!!) 52 | } 53 | expiredUrl?.also { 54 | sessionConcurrencyControl.expiredUrl(expiredUrl) 55 | } 56 | expiredSessionStrategy?.also { 57 | sessionConcurrencyControl.expiredSessionStrategy(expiredSessionStrategy) 58 | } 59 | maxSessionsPreventsLogin?.also { 60 | sessionConcurrencyControl.maxSessionsPreventsLogin(maxSessionsPreventsLogin!!) 61 | } 62 | sessionRegistry?.also { 63 | sessionConcurrencyControl.sessionRegistry(sessionRegistry) 64 | } 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/kotlin/org/springframework/security/dsl/config/builders/servlet/session/SessionFixationDsl.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.session 18 | 19 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 20 | import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer 21 | import javax.servlet.http.HttpServletRequest 22 | import javax.servlet.http.HttpSession 23 | 24 | /** 25 | * A Kotlin DSL to configure session fixation protection using idiomatic 26 | * Kotlin code. 27 | * 28 | * @author Eleftheria Stein 29 | */ 30 | @Deprecated("Use Spring Security 5.3 for a native servlet Kotlin DSL.") 31 | class SessionFixationDsl { 32 | private var strategy: SessionFixationStrategy? = null 33 | 34 | /** 35 | * Specifies that a new session should be created, but the session attributes from 36 | * the original [HttpSession] should not be retained. 37 | */ 38 | fun newSession() { 39 | this.strategy = SessionFixationStrategy.NEW 40 | } 41 | 42 | /** 43 | * Specifies that a new session should be created and the session attributes from 44 | * the original [HttpSession] should be retained. 45 | */ 46 | fun migrateSession() { 47 | this.strategy = SessionFixationStrategy.MIGRATE 48 | } 49 | 50 | /** 51 | * Specifies that the Servlet container-provided session fixation protection 52 | * should be used. When a session authenticates, the Servlet method 53 | * [HttpServletRequest.changeSessionId] is called to change the session ID 54 | * and retain all session attributes. 55 | */ 56 | fun changeSessionId() { 57 | this.strategy = SessionFixationStrategy.CHANGE_ID 58 | } 59 | 60 | /** 61 | * Specifies that no session fixation protection should be enabled. 62 | */ 63 | fun none() { 64 | this.strategy = SessionFixationStrategy.NONE 65 | } 66 | 67 | internal fun get(): (SessionManagementConfigurer.SessionFixationConfigurer) -> Unit { 68 | return { sessionFixation -> 69 | strategy?.also { 70 | when (strategy) { 71 | SessionFixationStrategy.NEW -> sessionFixation.newSession() 72 | SessionFixationStrategy.MIGRATE -> sessionFixation.migrateSession() 73 | SessionFixationStrategy.CHANGE_ID -> sessionFixation.changeSessionId() 74 | SessionFixationStrategy.NONE -> sessionFixation.none() 75 | } 76 | } 77 | } 78 | } 79 | } 80 | 81 | private enum class SessionFixationStrategy { 82 | NEW, MIGRATE, CHANGE_ID, NONE 83 | } 84 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/server/ServerRequestCacheDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.mockito.ArgumentMatchers.any 22 | import org.mockito.Mockito 23 | import org.mockito.Mockito.`when` 24 | import org.mockito.Mockito.verify 25 | import org.springframework.beans.factory.annotation.Autowired 26 | import org.springframework.context.ApplicationContext 27 | import org.springframework.context.annotation.Bean 28 | import org.springframework.context.annotation.Configuration 29 | import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity 30 | import org.springframework.security.config.web.server.ServerHttpSecurity 31 | import org.springframework.security.core.userdetails.MapReactiveUserDetailsService 32 | import org.springframework.security.core.userdetails.User 33 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 34 | import org.springframework.security.web.server.SecurityWebFilterChain 35 | import org.springframework.security.web.server.savedrequest.ServerRequestCache 36 | import org.springframework.test.web.reactive.server.WebTestClient 37 | import org.springframework.web.reactive.config.EnableWebFlux 38 | import reactor.core.publisher.Mono 39 | 40 | /** 41 | * Tests for [ServerRequestCacheDsl] 42 | * 43 | * @author Eleftheria Stein 44 | */ 45 | internal class ServerRequestCacheDslTests { 46 | @Rule 47 | @JvmField 48 | val spring = SpringTestRule() 49 | 50 | private lateinit var client: WebTestClient 51 | 52 | @Autowired 53 | fun setup(context: ApplicationContext) { 54 | this.client = WebTestClient 55 | .bindToApplicationContext(context) 56 | .configureClient() 57 | .build() 58 | } 59 | 60 | @Test 61 | fun `GET when request cache enabled then redirected to cached page`() { 62 | this.spring.register(RequestCacheConfig::class.java, UserDetailsConfig::class.java).autowire() 63 | `when`(RequestCacheConfig.REQUEST_CACHE.removeMatchingRequest(any())).thenReturn(Mono.empty()) 64 | 65 | this.client.get() 66 | .uri("/test") 67 | .exchange() 68 | 69 | verify(RequestCacheConfig.REQUEST_CACHE).saveRequest(any()) 70 | } 71 | 72 | @EnableWebFluxSecurity 73 | @EnableWebFlux 74 | class RequestCacheConfig { 75 | companion object { 76 | var REQUEST_CACHE: ServerRequestCache = Mockito.mock(ServerRequestCache::class.java) 77 | } 78 | 79 | @Bean 80 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 81 | return http { 82 | authorizeExchange { 83 | authorize(anyExchange, authenticated) 84 | } 85 | formLogin { } 86 | requestCache { 87 | requestCache = REQUEST_CACHE 88 | } 89 | } 90 | } 91 | } 92 | 93 | @Configuration 94 | class UserDetailsConfig { 95 | @Bean 96 | fun userDetailsService(): MapReactiveUserDetailsService { 97 | val user = User.withDefaultPasswordEncoder() 98 | .username("user") 99 | .password("password") 100 | .roles("USER") 101 | .build() 102 | return MapReactiveUserDetailsService(user) 103 | } 104 | } 105 | } -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerCacheControlDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.context.ApplicationContext 23 | import org.springframework.context.annotation.Bean 24 | import org.springframework.http.HttpHeaders 25 | import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity 26 | import org.springframework.security.config.web.server.ServerHttpSecurity 27 | import org.springframework.security.dsl.config.builders.server.invoke 28 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 29 | import org.springframework.security.web.server.SecurityWebFilterChain 30 | import org.springframework.test.web.reactive.server.WebTestClient 31 | import org.springframework.web.reactive.config.EnableWebFlux 32 | 33 | /** 34 | * Tests for [ServerCacheControlDsl] 35 | * 36 | * @author Eleftheria Stein 37 | */ 38 | internal class ServerCacheControlDslTests { 39 | @Rule 40 | @JvmField 41 | val spring = SpringTestRule() 42 | 43 | private lateinit var client: WebTestClient 44 | 45 | @Autowired 46 | fun setup(context: ApplicationContext) { 47 | this.client = WebTestClient 48 | .bindToApplicationContext(context) 49 | .configureClient() 50 | .build() 51 | } 52 | 53 | @Test 54 | fun `request when cache control configured then cache headers in response`() { 55 | this.spring.register(CacheControlConfig::class.java).autowire() 56 | 57 | this.client.get() 58 | .uri("/") 59 | .exchange() 60 | .expectHeader().valueEquals(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate") 61 | .expectHeader().valueEquals(HttpHeaders.EXPIRES, "0") 62 | .expectHeader().valueEquals(HttpHeaders.PRAGMA, "no-cache") 63 | } 64 | 65 | @EnableWebFluxSecurity 66 | @EnableWebFlux 67 | class CacheControlConfig { 68 | @Bean 69 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 70 | return http { 71 | headers { 72 | cache { } 73 | } 74 | } 75 | } 76 | } 77 | 78 | @Test 79 | fun `request when cache control disabled then no cache headers in response`() { 80 | this.spring.register(CacheControlDisabledConfig::class.java).autowire() 81 | 82 | this.client.get() 83 | .uri("/") 84 | .exchange() 85 | .expectHeader().doesNotExist(HttpHeaders.CACHE_CONTROL) 86 | .expectHeader().doesNotExist(HttpHeaders.EXPIRES) 87 | .expectHeader().doesNotExist(HttpHeaders.PRAGMA) 88 | } 89 | 90 | @EnableWebFluxSecurity 91 | @EnableWebFlux 92 | class CacheControlDisabledConfig { 93 | @Bean 94 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 95 | return http { 96 | headers { 97 | cache { 98 | disable() 99 | } 100 | } 101 | } 102 | } 103 | } 104 | } -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerContentSecurityPolicyDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.context.ApplicationContext 23 | import org.springframework.context.annotation.Bean 24 | import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity 25 | import org.springframework.security.config.web.server.ServerHttpSecurity 26 | import org.springframework.security.dsl.config.builders.server.invoke 27 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 28 | import org.springframework.security.web.server.SecurityWebFilterChain 29 | import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter 30 | import org.springframework.test.web.reactive.server.WebTestClient 31 | import org.springframework.web.reactive.config.EnableWebFlux 32 | 33 | /** 34 | * Tests for [ServerContentSecurityPolicyDsl] 35 | * 36 | * @author Eleftheria Stein 37 | */ 38 | internal class ServerContentSecurityPolicyDslTests { 39 | @Rule 40 | @JvmField 41 | val spring = SpringTestRule() 42 | 43 | private lateinit var client: WebTestClient 44 | 45 | @Autowired 46 | fun setup(context: ApplicationContext) { 47 | this.client = WebTestClient 48 | .bindToApplicationContext(context) 49 | .configureClient() 50 | .build() 51 | } 52 | 53 | @Test 54 | fun `request when content security policy configured then content security policy header in response`() { 55 | this.spring.register(ContentSecurityPolicyConfig::class.java).autowire() 56 | 57 | this.client.get() 58 | .uri("https://example.com") 59 | .exchange() 60 | .expectHeader().valueEquals(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, "default-src 'self'") 61 | } 62 | 63 | @EnableWebFluxSecurity 64 | @EnableWebFlux 65 | class ContentSecurityPolicyConfig { 66 | @Bean 67 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 68 | return http { 69 | headers { 70 | contentSecurityPolicy { } 71 | } 72 | } 73 | } 74 | } 75 | 76 | @Test 77 | fun `request when custom policy directives then custom policy directive in response header`() { 78 | this.spring.register(CustomPolicyDirectivesConfig::class.java).autowire() 79 | 80 | this.client.get() 81 | .uri("https://example.com") 82 | .exchange() 83 | .expectHeader().valueEquals(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, "default-src 'self'; script-src trustedscripts.example.com") 84 | } 85 | 86 | @EnableWebFluxSecurity 87 | @EnableWebFlux 88 | class CustomPolicyDirectivesConfig { 89 | @Bean 90 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 91 | return http { 92 | headers { 93 | contentSecurityPolicy { 94 | policyDirectives = "default-src 'self'; script-src trustedscripts.example.com" 95 | } 96 | } 97 | } 98 | } 99 | } 100 | 101 | @Test 102 | fun `request when report only configured then content security policy report only header in response`() { 103 | this.spring.register(ReportOnlyConfig::class.java).autowire() 104 | 105 | this.client.get() 106 | .uri("https://example.com") 107 | .exchange() 108 | .expectHeader().valueEquals(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY_REPORT_ONLY, "default-src 'self'") 109 | } 110 | 111 | @EnableWebFluxSecurity 112 | @EnableWebFlux 113 | class ReportOnlyConfig { 114 | @Bean 115 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 116 | return http { 117 | headers { 118 | contentSecurityPolicy { 119 | reportOnly = true 120 | } 121 | } 122 | } 123 | } 124 | } 125 | } -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerContentTypeOptionsDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.context.ApplicationContext 23 | import org.springframework.context.annotation.Bean 24 | import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity 25 | import org.springframework.security.config.web.server.ServerHttpSecurity 26 | import org.springframework.security.dsl.config.builders.server.invoke 27 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 28 | import org.springframework.security.web.server.SecurityWebFilterChain 29 | import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter 30 | import org.springframework.test.web.reactive.server.WebTestClient 31 | import org.springframework.web.reactive.config.EnableWebFlux 32 | 33 | /** 34 | * Tests for [ServerContentTypeOptionsDsl] 35 | * 36 | * @author Eleftheria Stein 37 | */ 38 | internal class ServerContentTypeOptionsDslTests { 39 | @Rule 40 | @JvmField 41 | val spring = SpringTestRule() 42 | 43 | private lateinit var client: WebTestClient 44 | 45 | @Autowired 46 | fun setup(context: ApplicationContext) { 47 | this.client = WebTestClient 48 | .bindToApplicationContext(context) 49 | .configureClient() 50 | .build() 51 | } 52 | 53 | @Test 54 | fun `request when content type options configured then header in response`() { 55 | this.spring.register(ContentTypeOptionsConfig::class.java).autowire() 56 | 57 | this.client.get() 58 | .uri("/") 59 | .exchange() 60 | .expectHeader().valueEquals(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, "nosniff") 61 | } 62 | 63 | @EnableWebFluxSecurity 64 | @EnableWebFlux 65 | class ContentTypeOptionsConfig { 66 | @Bean 67 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 68 | return http { 69 | headers { 70 | contentTypeOptions { } 71 | } 72 | } 73 | } 74 | } 75 | 76 | @Test 77 | fun `request when content type options disabled then no content type options header in response`() { 78 | this.spring.register(ContentTypeOptionsDisabledConfig::class.java).autowire() 79 | 80 | this.client.get() 81 | .uri("/") 82 | .exchange() 83 | .expectHeader().doesNotExist(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS) 84 | } 85 | 86 | @EnableWebFluxSecurity 87 | @EnableWebFlux 88 | class ContentTypeOptionsDisabledConfig { 89 | @Bean 90 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 91 | return http { 92 | headers { 93 | contentTypeOptions { 94 | disable() 95 | } 96 | } 97 | } 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerFrameOptionsDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.context.ApplicationContext 23 | import org.springframework.context.annotation.Bean 24 | import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity 25 | import org.springframework.security.config.web.server.ServerHttpSecurity 26 | import org.springframework.security.dsl.config.builders.server.invoke 27 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 28 | import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter 29 | import org.springframework.security.web.server.SecurityWebFilterChain 30 | import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter 31 | import org.springframework.test.web.reactive.server.WebTestClient 32 | import org.springframework.web.reactive.config.EnableWebFlux 33 | 34 | /** 35 | * Tests for [ServerFrameOptionsDsl] 36 | * 37 | * @author Eleftheria Stein 38 | */ 39 | internal class ServerFrameOptionsDslTests { 40 | @Rule 41 | @JvmField 42 | val spring = SpringTestRule() 43 | 44 | private lateinit var client: WebTestClient 45 | 46 | @Autowired 47 | fun setup(context: ApplicationContext) { 48 | this.client = WebTestClient 49 | .bindToApplicationContext(context) 50 | .configureClient() 51 | .build() 52 | } 53 | 54 | @Test 55 | fun `request when frame options configured then header in response`() { 56 | this.spring.register(FrameOptionsConfig::class.java).autowire() 57 | 58 | this.client.get() 59 | .uri("/") 60 | .exchange() 61 | .expectHeader().valueEquals(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, XFrameOptionsHeaderWriter.XFrameOptionsMode.DENY.name) 62 | } 63 | 64 | @EnableWebFluxSecurity 65 | @EnableWebFlux 66 | class FrameOptionsConfig { 67 | @Bean 68 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 69 | return http { 70 | headers { 71 | frameOptions { } 72 | } 73 | } 74 | } 75 | } 76 | 77 | @Test 78 | fun `request when frame options disabled then no frame options header in response`() { 79 | this.spring.register(FrameOptionsDisabledConfig::class.java).autowire() 80 | 81 | this.client.get() 82 | .uri("/") 83 | .exchange() 84 | .expectHeader().doesNotExist(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS) 85 | } 86 | 87 | @EnableWebFluxSecurity 88 | @EnableWebFlux 89 | class FrameOptionsDisabledConfig { 90 | @Bean 91 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 92 | return http { 93 | headers { 94 | frameOptions { 95 | disable() 96 | } 97 | } 98 | } 99 | } 100 | } 101 | 102 | @Test 103 | fun `request when frame options mode set then frame options response header has mode value`() { 104 | this.spring.register(CustomModeConfig::class.java).autowire() 105 | 106 | this.client.get() 107 | .uri("/") 108 | .exchange() 109 | .expectHeader().valueEquals(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN.name) 110 | } 111 | 112 | @EnableWebFluxSecurity 113 | @EnableWebFlux 114 | class CustomModeConfig { 115 | @Bean 116 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 117 | return http { 118 | headers { 119 | frameOptions { 120 | mode = XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN 121 | } 122 | } 123 | } 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerReferrerPolicyDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.context.ApplicationContext 23 | import org.springframework.context.annotation.Bean 24 | import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity 25 | import org.springframework.security.config.web.server.ServerHttpSecurity 26 | import org.springframework.security.dsl.config.builders.server.invoke 27 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 28 | import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter 29 | import org.springframework.security.web.server.SecurityWebFilterChain 30 | import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter 31 | import org.springframework.test.web.reactive.server.WebTestClient 32 | import org.springframework.web.reactive.config.EnableWebFlux 33 | 34 | /** 35 | * Tests for [ServerReferrerPolicyDsl] 36 | * 37 | * @author Eleftheria Stein 38 | */ 39 | internal class ServerReferrerPolicyDslTests { 40 | @Rule 41 | @JvmField 42 | val spring = SpringTestRule() 43 | 44 | private lateinit var client: WebTestClient 45 | 46 | @Autowired 47 | fun setup(context: ApplicationContext) { 48 | this.client = WebTestClient 49 | .bindToApplicationContext(context) 50 | .configureClient() 51 | .build() 52 | } 53 | 54 | @Test 55 | fun `request when referrer policy configured then referrer policy header in response`() { 56 | this.spring.register(ReferrerPolicyConfig::class.java).autowire() 57 | 58 | this.client.get() 59 | .uri("/") 60 | .exchange() 61 | .expectHeader().valueEquals("Referrer-Policy", ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER.policy) 62 | } 63 | 64 | @EnableWebFluxSecurity 65 | @EnableWebFlux 66 | class ReferrerPolicyConfig { 67 | @Bean 68 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 69 | return http { 70 | headers { 71 | referrerPolicy { } 72 | } 73 | } 74 | } 75 | } 76 | 77 | @Test 78 | fun `request when custom policy configured then custom policy in response header`() { 79 | this.spring.register(CustomPolicyConfig::class.java).autowire() 80 | 81 | this.client.get() 82 | .uri("/") 83 | .exchange() 84 | .expectHeader().valueEquals("Referrer-Policy", ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy.SAME_ORIGIN.policy) 85 | } 86 | 87 | @EnableWebFluxSecurity 88 | @EnableWebFlux 89 | class CustomPolicyConfig { 90 | @Bean 91 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 92 | return http { 93 | headers { 94 | referrerPolicy { 95 | policy = ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy.SAME_ORIGIN 96 | } 97 | } 98 | } 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/server/headers/ServerXssProtectionDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.server.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.context.ApplicationContext 23 | import org.springframework.context.annotation.Bean 24 | import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity 25 | import org.springframework.security.config.web.server.ServerHttpSecurity 26 | import org.springframework.security.dsl.config.builders.server.invoke 27 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 28 | import org.springframework.security.web.server.SecurityWebFilterChain 29 | import org.springframework.security.web.server.header.XXssProtectionServerHttpHeadersWriter 30 | import org.springframework.test.web.reactive.server.WebTestClient 31 | import org.springframework.web.reactive.config.EnableWebFlux 32 | 33 | /** 34 | * Tests for [ServerXssProtectionDsl] 35 | * 36 | * @author Eleftheria Stein 37 | */ 38 | internal class ServerXssProtectionDslTests { 39 | @Rule 40 | @JvmField 41 | val spring = SpringTestRule() 42 | 43 | private lateinit var client: WebTestClient 44 | 45 | @Autowired 46 | fun setup(context: ApplicationContext) { 47 | this.client = WebTestClient 48 | .bindToApplicationContext(context) 49 | .configureClient() 50 | .build() 51 | } 52 | 53 | @Test 54 | fun `request when xss protection configured then xss header in response`() { 55 | this.spring.register(XssConfig::class.java).autowire() 56 | 57 | this.client.get() 58 | .uri("/") 59 | .exchange() 60 | .expectHeader().valueEquals(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "1 ; mode=block") 61 | } 62 | 63 | @EnableWebFluxSecurity 64 | @EnableWebFlux 65 | class XssConfig { 66 | @Bean 67 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 68 | return http { 69 | headers { 70 | xssProtection { } 71 | } 72 | } 73 | } 74 | } 75 | 76 | @Test 77 | fun `request when xss protection disabled then no xss header in response`() { 78 | this.spring.register(XssDisabledConfig::class.java).autowire() 79 | 80 | this.client.get() 81 | .uri("/") 82 | .exchange() 83 | .expectHeader().doesNotExist(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION) 84 | } 85 | 86 | @EnableWebFluxSecurity 87 | @EnableWebFlux 88 | class XssDisabledConfig { 89 | @Bean 90 | fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { 91 | return http { 92 | headers { 93 | xssProtection { 94 | disable() 95 | } 96 | } 97 | } 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/servlet/HeadersDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.http.HttpHeaders 23 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 24 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 25 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 26 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 27 | import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter 28 | import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter 29 | import org.springframework.security.web.server.header.StrictTransportSecurityServerHttpHeadersWriter 30 | import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter 31 | import org.springframework.security.web.server.header.XXssProtectionServerHttpHeadersWriter 32 | import org.springframework.test.web.servlet.MockMvc 33 | import org.springframework.test.web.servlet.get 34 | 35 | /** 36 | * Tests for [HeadersDsl] 37 | * 38 | * @author Eleftheria Stein 39 | */ 40 | class HeadersDslTests { 41 | @Rule 42 | @JvmField 43 | var spring = SpringTestRule() 44 | 45 | @Autowired 46 | lateinit var mockMvc: MockMvc 47 | 48 | @Test 49 | fun `headers when defaults enabled then default headers in response`() { 50 | this.spring.register(DefaultHeadersConfig::class.java).autowire() 51 | 52 | this.mockMvc.get("/") { 53 | secure = true 54 | }.andExpect { 55 | header { string(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, "nosniff") } 56 | header { string(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, XFrameOptionsHeaderWriter.XFrameOptionsMode.DENY.name) } 57 | header { string(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains") } 58 | header { string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate") } 59 | header { string(HttpHeaders.EXPIRES, "0") } 60 | header { string(HttpHeaders.PRAGMA, "no-cache") } 61 | header { string(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "1; mode=block") } 62 | } 63 | } 64 | 65 | @EnableWebSecurity 66 | open class DefaultHeadersConfig : WebSecurityConfigurerAdapter() { 67 | override fun configure(http: HttpSecurity) { 68 | http { 69 | headers { } 70 | } 71 | } 72 | } 73 | 74 | @Test 75 | fun `headers when feature policy configured then header in response`() { 76 | this.spring.register(FeaturePolicyConfig::class.java).autowire() 77 | 78 | this.mockMvc.get("/") 79 | .andExpect { 80 | header { string("Feature-Policy", "geolocation 'self'") } 81 | } 82 | } 83 | 84 | @EnableWebSecurity 85 | open class FeaturePolicyConfig : WebSecurityConfigurerAdapter() { 86 | override fun configure(http: HttpSecurity) { 87 | http { 88 | headers { 89 | featurePolicy(policyDirectives = "geolocation 'self'") 90 | } 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/servlet/OAuth2LoginDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.context.annotation.Bean 23 | import org.springframework.context.annotation.Configuration 24 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 25 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 26 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 27 | import org.springframework.security.config.oauth2.client.CommonOAuth2Provider 28 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 29 | import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository 30 | import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository 31 | import org.springframework.test.web.servlet.MockMvc 32 | import org.springframework.test.web.servlet.get 33 | import org.springframework.web.bind.annotation.GetMapping 34 | import org.springframework.web.bind.annotation.RestController 35 | 36 | /** 37 | * Tests for [OAuth2LoginDsl] 38 | * 39 | * @author Eleftheria Stein 40 | */ 41 | class OAuth2LoginDslTests { 42 | @Rule 43 | @JvmField 44 | val spring = SpringTestRule() 45 | 46 | @Autowired 47 | lateinit var mockMvc: MockMvc 48 | 49 | @Test 50 | fun `oauth2Login when custom client registration repository then bean is not required`() { 51 | this.spring.register(ClientRepoConfig::class.java).autowire() 52 | } 53 | 54 | @EnableWebSecurity 55 | open class ClientRepoConfig : WebSecurityConfigurerAdapter() { 56 | override fun configure(http: HttpSecurity) { 57 | http { 58 | oauth2Login { 59 | clientRegistrationRepository = InMemoryClientRegistrationRepository( 60 | CommonOAuth2Provider.GOOGLE 61 | .getBuilder("google").clientId("clientId").clientSecret("clientSecret") 62 | .build() 63 | ) 64 | } 65 | } 66 | } 67 | } 68 | 69 | @Test 70 | fun `login page when oAuth2Login configured then default login page created`() { 71 | this.spring.register(OAuth2LoginConfig::class.java, ClientConfig::class.java).autowire() 72 | 73 | this.mockMvc.get("/login") 74 | .andExpect { 75 | status { isOk } 76 | } 77 | } 78 | 79 | @EnableWebSecurity 80 | open class OAuth2LoginConfig : WebSecurityConfigurerAdapter() { 81 | override fun configure(http: HttpSecurity) { 82 | http { 83 | oauth2Login { } 84 | } 85 | } 86 | } 87 | 88 | @Test 89 | fun `login page when custom login page then redirected to custom page`() { 90 | this.spring.register(LoginPageConfig::class.java, ClientConfig::class.java).autowire() 91 | 92 | this.mockMvc.get("/custom-login") 93 | .andExpect { 94 | status { isOk } 95 | } 96 | } 97 | 98 | @EnableWebSecurity 99 | open class LoginPageConfig : WebSecurityConfigurerAdapter() { 100 | override fun configure(http: HttpSecurity) { 101 | http { 102 | oauth2Login { 103 | loginPage = "/custom-login" 104 | } 105 | } 106 | } 107 | 108 | @RestController 109 | class LoginController { 110 | @GetMapping("/custom-login") 111 | fun loginPage() { } 112 | } 113 | } 114 | 115 | @Configuration 116 | open class ClientConfig { 117 | @Bean 118 | open fun clientRegistrationRepository(): ClientRegistrationRepository { 119 | return InMemoryClientRegistrationRepository( 120 | CommonOAuth2Provider.GOOGLE 121 | .getBuilder("google").clientId("clientId").clientSecret("clientSecret") 122 | .build() 123 | ) 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/servlet/PortMapperDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 23 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 24 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 25 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 26 | import org.springframework.security.web.PortMapperImpl 27 | import org.springframework.test.web.servlet.MockMvc 28 | import org.springframework.test.web.servlet.get 29 | import java.util.* 30 | 31 | /** 32 | * Tests for [PortMapperDsl] 33 | * 34 | * @author Eleftheria Stein 35 | */ 36 | class PortMapperDslTests { 37 | @Rule 38 | @JvmField 39 | val spring = SpringTestRule() 40 | 41 | @Autowired 42 | lateinit var mockMvc: MockMvc 43 | 44 | @Test 45 | fun `port mapper when specifying map then redirects to https port`() { 46 | this.spring.register(PortMapperMapConfig::class.java).autowire() 47 | 48 | this.mockMvc.get("http://localhost:543") 49 | .andExpect { 50 | redirectedUrl("https://localhost:123") 51 | } 52 | } 53 | 54 | @EnableWebSecurity 55 | open class PortMapperMapConfig : WebSecurityConfigurerAdapter() { 56 | override fun configure(http: HttpSecurity) { 57 | http { 58 | requiresChannel { 59 | secure(anyRequest, requiresSecure) 60 | } 61 | portMapper { 62 | map(543, 123) 63 | } 64 | } 65 | } 66 | } 67 | 68 | @Test 69 | fun `port mapper when specifying custom mapper then redirects to https port`() { 70 | this.spring.register(CustomPortMapperConfig::class.java).autowire() 71 | 72 | this.mockMvc.get("http://localhost:543") 73 | .andExpect { 74 | redirectedUrl("https://localhost:123") 75 | } 76 | } 77 | 78 | @EnableWebSecurity 79 | open class CustomPortMapperConfig : WebSecurityConfigurerAdapter() { 80 | override fun configure(http: HttpSecurity) { 81 | val customPortMapper = PortMapperImpl() 82 | customPortMapper.setPortMappings(Collections.singletonMap("543", "123")) 83 | http { 84 | requiresChannel { 85 | secure(anyRequest, requiresSecure) 86 | } 87 | portMapper { 88 | portMapper = customPortMapper 89 | } 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/servlet/RequestCacheDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 23 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 24 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 25 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 26 | import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin 27 | import org.springframework.security.web.savedrequest.NullRequestCache 28 | import org.springframework.test.web.servlet.MockMvc 29 | import org.springframework.test.web.servlet.get 30 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl 31 | 32 | /** 33 | * Tests for [RequestCacheDsl] 34 | * 35 | * @author Eleftheria Stein 36 | */ 37 | class RequestCacheDslTests { 38 | @Rule 39 | @JvmField 40 | val spring = SpringTestRule() 41 | 42 | @Autowired 43 | lateinit var mockMvc: MockMvc 44 | 45 | @Test 46 | fun `GET when request cache enabled then redirected to cached page`() { 47 | this.spring.register(RequestCacheConfig::class.java).autowire() 48 | 49 | this.mockMvc.get("/test") 50 | 51 | this.mockMvc.perform(formLogin()) 52 | .andExpect { 53 | redirectedUrl("http://localhost/test") 54 | } 55 | } 56 | 57 | @EnableWebSecurity 58 | open class RequestCacheConfig : WebSecurityConfigurerAdapter() { 59 | override fun configure(http: HttpSecurity) { 60 | http { 61 | requestCache { } 62 | formLogin { } 63 | } 64 | } 65 | } 66 | 67 | @Test 68 | fun `GET when custom request cache then custom request cache used`() { 69 | this.spring.register(CustomRequestCacheConfig::class.java).autowire() 70 | 71 | this.mockMvc.get("/test") 72 | 73 | this.mockMvc.perform(formLogin()) 74 | .andExpect { 75 | redirectedUrl("/") 76 | } 77 | } 78 | 79 | @EnableWebSecurity 80 | open class CustomRequestCacheConfig : WebSecurityConfigurerAdapter() { 81 | override fun configure(http: HttpSecurity) { 82 | http { 83 | requestCache { 84 | requestCache = NullRequestCache() 85 | } 86 | formLogin { } 87 | } 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/servlet/Saml2DslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet 18 | 19 | import org.assertj.core.api.Assertions 20 | import org.junit.Rule 21 | import org.junit.Test 22 | import org.springframework.beans.factory.BeanCreationException 23 | import org.springframework.beans.factory.annotation.Autowired 24 | import org.springframework.core.io.ClassPathResource 25 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 26 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 27 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 28 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 29 | import org.springframework.security.saml2.credentials.Saml2X509Credential 30 | import org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.VERIFICATION 31 | import org.springframework.security.saml2.provider.service.registration.InMemoryRelyingPartyRegistrationRepository 32 | import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration 33 | import org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter 34 | import org.springframework.test.web.servlet.MockMvc 35 | import org.springframework.test.web.servlet.get 36 | import java.security.cert.Certificate 37 | import java.security.cert.CertificateFactory 38 | 39 | /** 40 | * Tests for [Saml2Dsl] 41 | * 42 | * @author Eleftheria Stein 43 | */ 44 | class Saml2DslTests { 45 | @Rule 46 | @JvmField 47 | val spring = SpringTestRule() 48 | 49 | @Autowired 50 | lateinit var mockMvc: MockMvc 51 | 52 | @Test 53 | fun `saml2Login when no relying party registration repository then exception`() { 54 | Assertions.assertThatThrownBy { this.spring.register(Saml2LoginNoRelyingPArtyRegistrationRepoConfig::class.java).autowire() } 55 | .isInstanceOf(BeanCreationException::class.java) 56 | .hasMessageContaining("relyingPartyRegistrationRepository cannot be null") 57 | 58 | } 59 | 60 | @EnableWebSecurity 61 | open class Saml2LoginNoRelyingPArtyRegistrationRepoConfig : WebSecurityConfigurerAdapter() { 62 | override fun configure(http: HttpSecurity) { 63 | http { 64 | saml2Login { } 65 | } 66 | } 67 | } 68 | 69 | @Test 70 | fun `login page when saml2Configured then default login page created`() { 71 | this.spring.register(Saml2LoginConfig::class.java).autowire() 72 | 73 | this.mockMvc.get("/login") 74 | .andExpect { 75 | status { isOk } 76 | } 77 | } 78 | 79 | @EnableWebSecurity 80 | open class Saml2LoginConfig : WebSecurityConfigurerAdapter() { 81 | 82 | override fun configure(http: HttpSecurity) { 83 | http { 84 | saml2Login { 85 | relyingPartyRegistrationRepository = 86 | InMemoryRelyingPartyRegistrationRepository( 87 | RelyingPartyRegistration.withRegistrationId("samlId") 88 | .remoteIdpEntityId("entityId") 89 | .assertionConsumerServiceUrlTemplate("{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI) 90 | .credentials { c -> c.add(Saml2X509Credential(loadCert("rod.cer"), VERIFICATION)) } 91 | .idpWebSsoUrl("ssoUrl") 92 | .build() 93 | ) 94 | } 95 | } 96 | } 97 | 98 | private fun loadCert(location: String): T { 99 | ClassPathResource(location).inputStream.use { inputStream -> 100 | val certFactory = CertificateFactory.getInstance("X.509") 101 | return certFactory.generateCertificate(inputStream) as T 102 | } 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/CacheControlDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.http.HttpHeaders 23 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 24 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 25 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 26 | import org.springframework.security.dsl.config.builders.servlet.invoke 27 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 28 | import org.springframework.test.web.servlet.MockMvc 29 | import org.springframework.test.web.servlet.get 30 | 31 | /** 32 | * Tests for [CacheControlDsl] 33 | * 34 | * @author Eleftheria Stein 35 | */ 36 | class CacheControlDslTests { 37 | @Rule 38 | @JvmField 39 | var spring = SpringTestRule() 40 | 41 | @Autowired 42 | lateinit var mockMvc: MockMvc 43 | 44 | @Test 45 | fun `headers when cache control configured then cache control headers in response`() { 46 | this.spring.register(CacheControlConfig::class.java).autowire() 47 | 48 | this.mockMvc.get("/") 49 | .andExpect { 50 | header { string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate") } 51 | header { string(HttpHeaders.EXPIRES, "0") } 52 | header { string(HttpHeaders.PRAGMA, "no-cache") } 53 | } 54 | } 55 | 56 | @EnableWebSecurity 57 | open class CacheControlConfig : WebSecurityConfigurerAdapter() { 58 | override fun configure(http: HttpSecurity) { 59 | http { 60 | headers { 61 | defaultsDisabled = true 62 | cacheControl { } 63 | } 64 | } 65 | } 66 | } 67 | 68 | @Test 69 | fun `headers when cache control disabled then no cache control headers in response`() { 70 | this.spring.register(CacheControlDisabledConfig::class.java).autowire() 71 | 72 | this.mockMvc.get("/") 73 | .andExpect { 74 | header { doesNotExist(HttpHeaders.CACHE_CONTROL) } 75 | header { doesNotExist(HttpHeaders.EXPIRES) } 76 | header { doesNotExist(HttpHeaders.PRAGMA) } 77 | } 78 | } 79 | 80 | @EnableWebSecurity 81 | open class CacheControlDisabledConfig : WebSecurityConfigurerAdapter() { 82 | override fun configure(http: HttpSecurity) { 83 | http { 84 | headers { 85 | cacheControl { 86 | disable() 87 | } 88 | } 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/ContentSecurityPolicyDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 23 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 24 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 25 | import org.springframework.security.dsl.config.builders.servlet.invoke 26 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 27 | import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter 28 | import org.springframework.test.web.servlet.MockMvc 29 | import org.springframework.test.web.servlet.get 30 | 31 | /** 32 | * Tests for [ContentSecurityPolicyDsl] 33 | * 34 | * @author Eleftheria Stein 35 | */ 36 | class ContentSecurityPolicyDslTests { 37 | @Rule 38 | @JvmField 39 | var spring = SpringTestRule() 40 | 41 | @Autowired 42 | lateinit var mockMvc: MockMvc 43 | 44 | @Test 45 | fun `headers when content security policy configured then header in response`() { 46 | this.spring.register(ContentSecurityPolicyConfig::class.java).autowire() 47 | 48 | this.mockMvc.get("/") { 49 | secure = true 50 | }.andExpect { 51 | header { string(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, "default-src 'self'") } 52 | } 53 | } 54 | 55 | @EnableWebSecurity 56 | open class ContentSecurityPolicyConfig : WebSecurityConfigurerAdapter() { 57 | override fun configure(http: HttpSecurity) { 58 | http { 59 | headers { 60 | defaultsDisabled = true 61 | contentSecurityPolicy { } 62 | } 63 | } 64 | } 65 | } 66 | 67 | @Test 68 | fun `headers when content security policy configured with custom policy directives then custom directives in header`() { 69 | this.spring.register(CustomPolicyDirectivesConfig::class.java).autowire() 70 | 71 | this.mockMvc.get("/") { 72 | secure = true 73 | }.andExpect { 74 | header { string(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, "default-src 'self'; script-src trustedscripts.example.com") } 75 | } 76 | } 77 | 78 | @EnableWebSecurity 79 | open class CustomPolicyDirectivesConfig : WebSecurityConfigurerAdapter() { 80 | override fun configure(http: HttpSecurity) { 81 | http { 82 | headers { 83 | defaultsDisabled = true 84 | contentSecurityPolicy { 85 | policyDirectives = "default-src 'self'; script-src trustedscripts.example.com" 86 | } 87 | } 88 | } 89 | } 90 | } 91 | 92 | @Test 93 | fun `headers when report only content security policy report only header in response`() { 94 | this.spring.register(ReportOnlyConfig::class.java).autowire() 95 | 96 | this.mockMvc.get("/") { 97 | secure = true 98 | }.andExpect { 99 | header { string(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY_REPORT_ONLY, "default-src 'self'") } 100 | } 101 | } 102 | 103 | @EnableWebSecurity 104 | open class ReportOnlyConfig : WebSecurityConfigurerAdapter() { 105 | override fun configure(http: HttpSecurity) { 106 | http { 107 | headers { 108 | defaultsDisabled = true 109 | contentSecurityPolicy { 110 | reportOnly = true 111 | } 112 | } 113 | } 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/ContentTypeOptionsDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 23 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 24 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 25 | import org.springframework.security.dsl.config.builders.servlet.invoke 26 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 27 | import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter 28 | import org.springframework.test.web.servlet.MockMvc 29 | import org.springframework.test.web.servlet.get 30 | 31 | /** 32 | * Tests for [ContentTypeOptionsDsl] 33 | * 34 | * @author Eleftheria Stein 35 | */ 36 | class ContentTypeOptionsDslTests { 37 | @Rule 38 | @JvmField 39 | var spring = SpringTestRule() 40 | 41 | @Autowired 42 | lateinit var mockMvc: MockMvc 43 | 44 | @Test 45 | fun `headers when content type options configured then X-Content-Type-Options header in response`() { 46 | this.spring.register(ContentTypeOptionsConfig::class.java).autowire() 47 | 48 | this.mockMvc.get("/") 49 | .andExpect { 50 | header { string(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, "nosniff") } 51 | } 52 | } 53 | 54 | @EnableWebSecurity 55 | open class ContentTypeOptionsConfig : WebSecurityConfigurerAdapter() { 56 | override fun configure(http: HttpSecurity) { 57 | http { 58 | headers { 59 | defaultsDisabled = true 60 | contentTypeOptions { } 61 | } 62 | } 63 | } 64 | } 65 | 66 | @Test 67 | fun `headers when content type options disabled then X-Content-Type-Options header not in response`() { 68 | this.spring.register(ContentTypeOptionsDisabledConfig::class.java).autowire() 69 | 70 | this.mockMvc.get("/") 71 | .andExpect { 72 | header { doesNotExist(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS) } 73 | } 74 | } 75 | 76 | @EnableWebSecurity 77 | open class ContentTypeOptionsDisabledConfig : WebSecurityConfigurerAdapter() { 78 | override fun configure(http: HttpSecurity) { 79 | http { 80 | headers { 81 | contentTypeOptions { 82 | disable() 83 | } 84 | } 85 | } 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/servlet/headers/ReferrerPolicyDslTests.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.servlet.headers 18 | 19 | import org.junit.Rule 20 | import org.junit.Test 21 | import org.springframework.beans.factory.annotation.Autowired 22 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 23 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 24 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 25 | import org.springframework.security.dsl.config.builders.servlet.invoke 26 | import org.springframework.security.dsl.config.builders.test.SpringTestRule 27 | import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter 28 | import org.springframework.test.web.servlet.MockMvc 29 | import org.springframework.test.web.servlet.get 30 | 31 | /** 32 | * Tests for [ReferrerPolicyDsl] 33 | * 34 | * @author Eleftheria Stein 35 | */ 36 | class ReferrerPolicyDslTests { 37 | @Rule 38 | @JvmField 39 | var spring = SpringTestRule() 40 | 41 | @Autowired 42 | lateinit var mockMvc: MockMvc 43 | 44 | @Test 45 | fun `headers when referrer policy configured then header in response`() { 46 | this.spring.register(ReferrerPolicyConfig::class.java).autowire() 47 | 48 | this.mockMvc.get("/") 49 | .andExpect { 50 | header { string("Referrer-Policy", ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER.policy) } 51 | } 52 | } 53 | 54 | @EnableWebSecurity 55 | open class ReferrerPolicyConfig : WebSecurityConfigurerAdapter() { 56 | override fun configure(http: HttpSecurity) { 57 | http { 58 | headers { 59 | defaultsDisabled = true 60 | referrerPolicy { } 61 | } 62 | } 63 | } 64 | } 65 | 66 | @Test 67 | fun `headers when referrer policy configured with custom policy then custom policy in header`() { 68 | this.spring.register(ReferrerPolicyCustomPolicyConfig::class.java).autowire() 69 | 70 | this.mockMvc.get("/") 71 | .andExpect { 72 | header { string("Referrer-Policy", ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN.policy) } 73 | } 74 | } 75 | 76 | @EnableWebSecurity 77 | open class ReferrerPolicyCustomPolicyConfig : WebSecurityConfigurerAdapter() { 78 | override fun configure(http: HttpSecurity) { 79 | http { 80 | headers { 81 | defaultsDisabled = true 82 | referrerPolicy { 83 | policy = ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN 84 | } 85 | } 86 | } 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/test/SpringTestContext.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.test 18 | 19 | import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor 20 | import org.springframework.mock.web.MockServletConfig 21 | import org.springframework.mock.web.MockServletContext 22 | import org.springframework.security.config.BeanIds.SPRING_SECURITY_FILTER_CHAIN 23 | import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity 24 | import org.springframework.test.web.servlet.MockMvc 25 | import org.springframework.test.web.servlet.request.RequestPostProcessor 26 | import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder 27 | import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder 28 | import org.springframework.test.web.servlet.setup.MockMvcBuilders 29 | import org.springframework.test.web.servlet.setup.MockMvcConfigurer 30 | import org.springframework.web.context.ConfigurableWebApplicationContext 31 | import org.springframework.web.context.WebApplicationContext 32 | import org.springframework.web.context.support.AnnotationConfigWebApplicationContext 33 | import java.io.Closeable 34 | import java.util.* 35 | import javax.servlet.Filter 36 | 37 | /** 38 | * @author Rob Winch 39 | * @since 5.0 40 | */ 41 | open class SpringTestContext : Closeable { 42 | private var test: Any? = null 43 | 44 | private var context: ConfigurableWebApplicationContext? = null 45 | 46 | private val filters = ArrayList() 47 | 48 | fun setTest(test: Any) { 49 | this.test = test 50 | } 51 | 52 | override fun close() { 53 | try { 54 | this.context!!.close() 55 | } catch (e: Exception) { 56 | } 57 | 58 | } 59 | 60 | fun register(vararg classes: Class<*>): SpringTestContext { 61 | val applicationContext = AnnotationConfigWebApplicationContext() 62 | applicationContext.register(*classes) 63 | this.context = applicationContext 64 | return this 65 | } 66 | 67 | fun autowire() { 68 | this.context!!.servletContext = MockServletContext() 69 | this.context!!.servletConfig = MockServletConfig() 70 | this.context!!.refresh() 71 | 72 | if (this.context!!.containsBean(SPRING_SECURITY_FILTER_CHAIN)) { 73 | val mockMvc = MockMvcBuilders.webAppContextSetup(this.context!!) 74 | .apply(springSecurity()) 75 | .apply(AddFilter()).build() 76 | this.context!!.beanFactory 77 | .registerResolvableDependency(MockMvc::class.java, mockMvc) 78 | } 79 | 80 | val bpp = AutowiredAnnotationBeanPostProcessor() 81 | bpp.setBeanFactory(this.context!!.beanFactory) 82 | bpp.processInjection(this.test!!) 83 | } 84 | 85 | fun getContext(): ConfigurableWebApplicationContext { 86 | if (!this.context!!.isRunning()) { 87 | this.context!!.refresh() 88 | } 89 | return this.context!! 90 | } 91 | 92 | private inner class AddFilter : MockMvcConfigurer { 93 | override fun beforeMockMvcCreated(builder: ConfigurableMockMvcBuilder<*>, context: WebApplicationContext): RequestPostProcessor? { 94 | (builder as ConfigurableMockMvcBuilder).addFilters(*this@SpringTestContext.filters.toTypedArray()) 95 | return null 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/test/kotlin/org/springframework/security/dsl/config/builders/test/SpringTestRule.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.security.dsl.config.builders.test 18 | 19 | import org.junit.rules.MethodRule 20 | import org.junit.runners.model.FrameworkMethod 21 | import org.junit.runners.model.Statement 22 | import org.springframework.security.test.context.TestSecurityContextHolder 23 | 24 | /** 25 | * @author Rob Winch 26 | */ 27 | class SpringTestRule : SpringTestContext(), MethodRule { 28 | override fun apply(base: Statement, method: FrameworkMethod, 29 | target: Any): Statement { 30 | return object : Statement() { 31 | override fun evaluate() { 32 | setTest(target) 33 | try { 34 | base.evaluate() 35 | } finally { 36 | TestSecurityContextHolder.clearContext() 37 | close() 38 | } 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/resources/rod.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-attic/spring-security-kotlin-dsl/2c9fc7b91d5f241e721ad728fdc0652875825de2/src/test/resources/rod.cer -------------------------------------------------------------------------------- /src/test/resources/rodatexampledotcom.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-attic/spring-security-kotlin-dsl/2c9fc7b91d5f241e721ad728fdc0652875825de2/src/test/resources/rodatexampledotcom.cer --------------------------------------------------------------------------------