1
0
mirror of synced 2026-08-31 22:46:02 +00:00

Compare commits

..

145 Commits

Author SHA1 Message Date
Rob Winch c33fc00507 Release 5.0.9.RELEASE
Fixes: gh-5973
2018-10-15 14:56:03 -05:00
Rob Winch 1150dafd55 Update to Thymeleaf 3.0.10.RELEASE
Fixes: gh-5972
2018-10-15 14:54:02 -05:00
Rob Winch 4f80b9d737 Update to htmlunit driver 2.33.0
Fixes: gh-5971
2018-10-15 14:53:47 -05:00
Rob Winch e6f5d4f13b Update to Unboundid 4.0.8
Fixes: gh-5970
2018-10-15 14:53:36 -05:00
Rob Winch 23dfe33877 Update JAXB 2.3.0.1
Fixes: gh-5969
2018-10-15 14:53:24 -05:00
Rob Winch 0e2b75e994 Update to Jackson 2.9.7
Fixes: gh-5968
2018-10-15 14:53:12 -05:00
Rob Winch e9e57b7509 Update to Spring Data Kay SR11
Fixes: gh-5967
2018-10-15 14:52:57 -05:00
Rob Winch c60a3e165e Update to Spring 5.0.10.RELEASE
Fixes: gh-5966
2018-10-15 14:52:42 -05:00
Rob Winch 3a756bfa57 Update to Reactor Bismuth SR12
Fixes: gh-5965
2018-10-15 14:52:34 -05:00
Josh Cummings 800157fe42 Password Modify Extended Operation Support
LdapUserDetailsManager can be configured to either use direct
attribute modification or the LDAP Password Modify Extended Operation
to change a user's password.

Fixes: gh-3392
2018-10-15 11:43:15 -06:00
Josh Cummings ba32758b92 UnboundIdContainer Random Port Support
Setting a port of 0 will now induce the container to select a random
port.

Fixes: gh-5920
2018-10-15 11:43:14 -06:00
Josh Cummings 05e940692a Polish UnboundIdContainerTests
Basic startup test now confirms successful startup instead of
asserting on startup failure.

Issue: gh-5920
2018-10-15 11:43:14 -06:00
Johnny Lim 5e74da9b4f Add a missing space in Secured.value() signature 2018-10-03 14:49:45 -04:00
Joe Grandja 9a49795abc Ensure consistent matching of redirect_uri
Fixes gh-5756
2018-09-20 12:15:43 -04:00
Rob Winch 566fb939ca Fix SwitchUserFilter matchers
Fixes: gh-4249
2018-09-14 10:04:46 -05:00
Rob Winch 5b26158f4d AntPathRequestMatcher supports UrlPathHelper
Fixes: gh-5846
2018-09-14 10:04:46 -05:00
Joe Grandja a7eaaec431 Next Development Version 2018-09-10 17:14:07 -04:00
Joe Grandja 5fde56d84a Release 5.0.8.RELEASE 2018-09-10 10:01:43 -04:00
Joe Grandja 10d53be70b Update to Spring Data Kay-SR10
Fixes gh-5808
2018-09-10 09:30:11 -04:00
Joe Grandja 93e0ce5236 Update to Reactor Bismuth-SR11
Fixes gh-5807
2018-09-07 14:57:36 -04:00
Joe Grandja 677a9634b8 Update to Spring 5.0.9
Fixes gh-5806
2018-09-07 14:57:36 -04:00
Joe Grandja 6d72c3f3aa Update to javax.servlet.jsp-api:2.3.3
Fixes gh-5805
2018-09-07 14:57:36 -04:00
Joe Grandja 67fcd51d59 Update to hibernate-validator:6.0.12.Final
Fixes gh-5804
2018-09-07 14:57:36 -04:00
Joe Grandja 15a777d534 Update to oauth2-oidc-sdk:5.64.4
Fixes gh-5803
2018-09-07 14:57:36 -04:00
Joe Grandja 7e0622c7be Update to unboundid-ldapsdk:4.0.7
Fixes gh-5802
2018-09-07 14:57:36 -04:00
Joe Grandja 07dd883d6d Update to javax.persistence:2.2.1
Fixes gh-5801
2018-09-07 14:57:36 -04:00
Rob Winch 8170e47ff2 Fix OptimizeAntPathRequestMatcher
Previously the logic for determining if the pathInfo should be appended
was inverted.

This correctly concatenates url + pathInfo if url is a non empty String.

Fixes: gh-5473
2018-09-07 11:51:50 -06:00
Christoph Dreis c408fb7edf Optimize AntPathRequestMatcher.getRequestPath() 2018-09-07 11:51:29 -06:00
Josh Cummings 4ff0fdfff9 Polish Commit on Reactive Http Basic Test 2018-09-07 11:39:54 -06:00
Tim Koopman 47b82ccd83 Reactive HttpBasic Support For Coloned Passwords
This makes so that reactive httpBasic supports passwords containing
one or more colons.
2018-09-07 11:39:41 -06:00
Rob Winch 54cc2e4509 Fix settings.gradle on Windows
Fixes: gh-5724
2018-09-07 11:37:19 -06:00
Rob Winch 31650d7eaa Ensure NamingException.resolvedObj is Serializable
Fixes: gh-5378
2018-09-04 11:06:37 -05:00
Johnny Lim 5888a3f6b7 Fix typo
Closes #5579
2018-08-03 09:58:40 -05:00
Rob Winch 87a5c16b53 Add @Configuration to ServerHttpSecurityConfiguration
Fixes: gh-5635
2018-08-03 09:39:17 -05:00
Rob Winch 4b407189c2 ServerHttpBasicAuthenticationConverter Validates Scheme Name
Fixes: gh-5615
2018-07-31 09:12:39 -05:00
Rob Winch 96c944c4fc BasicAuthenticationFilter case insenstive
Fixes: gh-5616
2018-07-31 09:11:54 -05:00
Joe Grandja 1bbae835a4 ClaimAccessor.getClaimAsString() checks null claim value
Fixes gh-5608
2018-07-30 15:41:46 -04:00
Josh Cummings de640a10d6 Next Development Version 2018-07-26 16:02:51 -06:00
Josh Cummings 85c8d53b36 Release 5.0.7.RELEASE 2018-07-26 14:46:31 -06:00
Josh Cummings 2d6bcf2cc3 Update to Spring Data Kay SR8
Fixes: gh-5591
2018-07-26 14:43:54 -06:00
Josh Cummings 18b98fc607 Update to Spring Framework 5.0.8
Fixes: gh-5590
2018-07-26 14:42:39 -06:00
Joe Grandja 7bf8091e22 Update to hibernate-validator:6.0.11.Final
Fixes gh-5576
2018-07-24 17:26:17 -04:00
Joe Grandja d19d03dea8 Update to bcpkix-jdk15on:1.60
Fixes gh-5574
2018-07-24 17:26:16 -04:00
Joe Grandja 35df3ff89b Update to org.apache.httpcomponents:httpclient:4.5.6
Fixes gh-5573
2018-07-24 17:26:16 -04:00
Joe Grandja 5f75e137d8 Update to ehcache:2.10.5
Fixes gh-5572
2018-07-24 17:26:16 -04:00
Joe Grandja b988f656c6 Update to javax.servlet.jsp.jstl-api:1.2.2
Fixes gh-5571
2018-07-24 17:26:16 -04:00
Joe Grandja 06fff9441e Update to oauth2-oidc-sdk:5.64.2
Fixes gh-5569
2018-07-24 17:26:16 -04:00
Joe Grandja edb354a2a9 Update to nimbus-jose-jwt:5.14
Fixes gh-5568
2018-07-24 17:26:16 -04:00
Joe Grandja 1ce0cf44a8 Update to cglib-nodep:3.2.7
Fixes gh-5567
2018-07-24 17:26:16 -04:00
Josh Cummings ffd8f7c8e4 Close Nimbus Information Leak
This commit captures and remaps the exception that Nimbus throws
when a PlainJWT is presented to it.

While the surrounding classes are likely only used today by the
oauth2Login flow, since they are public, we'll patch them at this
point for anyone who may be using them directly.

Fixes: gh-5457
2018-07-24 13:24:34 -06:00
Rob Winch ecaa2c5b1c Cache Control disabled for 304
Fixes: gh-5534
2018-07-17 22:13:52 -05:00
Rob Winch a1c381c276 Add JdbcUserDetailsManager(DataSource) constructor
Fixes: gh-5512
2018-07-13 15:58:36 -05:00
mhyeon.lee 1b213d65d2 Enhance OAuth2AccessToken to be serializable
Change the TokenType to Serializable
so that the OAuth2AccessToken can be serialized.
(org.springframework.security.oauth2.core.OAuth2AccessToken.TokenType)

Fixes gh-5492
2018-07-13 12:10:55 -04:00
mhyeon.lee eb897ac69c Fix oauth2login loginProcessingUrl NPE for java config
Java Config http.oauth2Login().loginProcessingUrl("url"); throws NPE.
Override loginProcessingUrl method and cached config url.
Then when the config is initialized,
it calls the super method to complete the configuration.

Fixes gh-5488
2018-07-13 11:42:43 -04:00
Rob Winch bd8180da12 Update to Spring Boot 2.0.3.RELEASE
Issue: gh-5454
2018-06-20 15:53:56 -05:00
Rob Winch 5dabff25c3 Next Development Version 2018-06-12 21:24:07 -05:00
Rob Winch 09429479fe Release 5.0.6.RELEASE 2018-06-12 21:23:02 -05:00
Rob Winch dc602c0840 Update to Spring Framework 5.0.7
Fixes: gh-5425
2018-06-12 16:51:01 -05:00
Rob Winch fedc183b5b Fix htmlunit
Fixes: gh-5426
2018-06-12 16:50:52 -05:00
Rob Winch d3f12f0ee7 Update to Selenium 3.12.0
Fixes: gh-5427
2018-06-12 16:50:48 -05:00
Rob Winch 2a723cf5c7 Update to htmlunit-driver:2.31.0
Fixes: gh-5428
2018-06-12 16:50:42 -05:00
Rob Winch 6f32303866 Update to hibernate-validator:6.0.10.Final
Fixes: gh-5429
2018-06-12 16:50:34 -05:00
Rob Winch 400adaef1c Update to Hibernate 5.2.17
Fixes: gh-5430
2018-06-12 16:50:29 -05:00
Rob Winch 9924d6e920 Update to hsqldb:2.4.1
Fixes: gh-5431
2018-06-12 16:50:23 -05:00
Rob Winch 6cfd30aee8 Update to assertj-core:3.10.0
Fixes: gh-5432
2018-06-12 16:50:15 -05:00
Rob Winch 1abdb69615 Update to htmlunit:2.31
Fixes: gh-5433
2018-06-12 16:49:23 -05:00
Rob Winch b07f6b0178 Update to unboundid-ldapsdk:4.0.6
Fixes: gh-54234
2018-06-12 16:49:10 -05:00
Rob Winch f0eec1b03b Update to oauth2-oidc-sdk:5.62
Fixes: gh-5435
2018-06-12 16:48:57 -05:00
Rob Winch 6ca6d80184 Update to nimbus-jose-jwt:5.11
Fixes: gh-5436
2018-06-12 16:47:35 -05:00
Rob Winch ce5eec8761 Update to Jackson 2.9.6
Fixes: gh-5424
2018-06-12 16:47:30 -05:00
Rob Winch 86e03b3fb4 Update to Spring Boot 2.0.2.RELEASE
Fixes: gh-5423
2018-06-12 16:47:26 -05:00
Rob Winch c909264b31 Update GAE to 1.9.64
Fixes: gh-5422
2018-06-12 16:47:21 -05:00
Rob Winch f52ab9a146 Update to Reactor Bismuth SR10
Fixes: gh-5421
2018-06-12 16:47:06 -05:00
Rob Winch ad2cb501b8 Add cross references to ReactorContextTestExecutionListener
Fixes: gh-5418
2018-06-11 17:16:15 -05:00
Rob Winch 8659a4b555 Add UserDetailsRepositoryReactiveAuthenticationManager.setScheduler
Fixes: gh-5417
2018-06-11 14:30:11 -05:00
Joe Grandja e04b29426b DefaultLoginPageGeneratingFilter escapes OAuth2 ClientRegistrations
Fixes gh-5394
2018-05-29 09:53:31 -04:00
Josh Cummings 350d434e28 Next Development Version 2018-05-08 09:25:49 -06:00
Josh Cummings bbfc3d2b4b Release 5.0.5.RELEASE 2018-05-08 09:22:58 -06:00
Rob Winch a7e4f36dbe Update to Spring Data Kay SR7
Fixes: gh-5318
2018-05-08 09:04:23 -05:00
Rob Winch e61aafe115 Update to Reactor Bismuth SR9
Fixes: gh-5319
2018-05-08 09:04:05 -05:00
Rob Winch ff95388ce1 Update to Spring 5.0.6
Fixes: gh-5290
2018-05-08 08:34:35 -05:00
Rob Winch 545228cf8d Documentation typo fixes
Fixes: gh-5317
2018-05-07 16:48:03 -05:00
Denys Ivano 7b8fa90d96 Add accessDeniedHandler method to ExceptionHandlingSpec
This allows to configure accessDeniedHandler in ExceptionTranslationWebFilter through ServerHttpSecurity.

Issue: gh-5257
2018-05-07 16:23:32 -05:00
Alexander Münch c30e218f1f Avoid unnecessary grow of ArrayList
Adapted ArrayList size in CacheControlHeadersWriter::createHeaders()

Fixes: gh-5310
2018-05-04 14:43:17 -05:00
XYUU 70d284865f DefaultLoginPageGeneratingFilter should calculate ContentLength using UTF-8
Fixes: gh-5309
2018-05-04 14:43:17 -05:00
Johnny Lim a4b5523063 Fix 'attributes' deprecation warning in spring-security-docs-guides
Fixes: gh-5308
2018-05-04 14:13:44 -05:00
Kazuki Shimizu 8883ec17e5 Fix JdbcDaoImpl Javadoc
Fix incorrect explanation for customizing query on JdbcDaoImpl

Issue: gh-5306
2018-05-04 10:48:55 -05:00
Joe Grandja f524da3edc Add test NimbusUserInfoResponseClient sets Accept header to JSON
Issue gh-5294
2018-05-03 20:23:03 -04:00
Joe Grandja e1e464387e NimbusUserInfoResponseClient sets Accept header to JSON
Fixes gh-5294
2018-05-03 20:22:47 -04:00
Rob Winch a5dc48f9d9 Improve PasswordEncoder deprecated notices
Fixes: gh-5296
2018-05-03 15:13:20 -05:00
Rob Winch 9b722a9c85 Update to Spring Framework 5.0.6.BUILD-SNAPSHOT
Issue: gh-5290
2018-05-03 11:01:37 -05:00
Rob Winch 884a4e46df Update to selenium 3.11.0
Fixes: gh-5289
2018-05-03 11:01:37 -05:00
Rob Winch 01c2d57d46 Update to mockito-core:2.18.3
Fixes: gh-5284
2018-05-03 11:01:37 -05:00
Rob Winch c9e42ce756 Update to htmlunit:2.30
Fixes: gh-5283
2018-05-03 11:01:37 -05:00
Rob Winch 9b0b933736 Update to aspectj 1.9.1
Fixes: gh-5282
2018-05-03 11:01:37 -05:00
Rob Winch 0169b8746b Update to javax.servlet-api:4.0.1
Fixes: gh-5281
2018-05-03 11:01:37 -05:00
Rob Winch 25a87051a6 Update to oauth2-oidc-sdk:5.61
Fixes: gh-5280
2018-05-03 11:01:37 -05:00
Rob Winch 7edf9fc6c8 Update to nimbus-jose-jwt:5.10
Fixes: gh-5279
2018-05-03 11:01:37 -05:00
Rob Winch a06f1e3936 Update Spring Boot 2.0.1.RELEASE
Fixes: gh-5278
2018-05-03 11:01:37 -05:00
Rob Winch b296d2eaa5 Update GAE 1.9.63
Fixes: gh-5277
2018-05-03 11:01:37 -05:00
Rob Winch 11a8c76991 Add update-dependencies.sh
Fixes: gh-5276
2018-05-03 11:01:37 -05:00
Rob Winch 2f441f18e6 Make MIN_SPRING_VERSION Dynamic
Fixes: gh-5065

# Conflicts:
#	core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java
2018-05-03 11:01:27 -05:00
Joe Grandja a7de1e363f OAuth2LoginAuthenticationFilter should handle null ClientRegistration
Fixes gh-5251
2018-05-02 20:31:59 -04:00
Rob Winch 32f5fb5eb2 ExceptionTranslationFilter does not handle committed responses
Fixes: gh-5273
2018-04-30 16:50:02 -05:00
Rob Winch f7f6798f71 DefaultWebSecurityExpressionHandler uses PermissionEvaluator Bean
The default instance of DefaultWebSecurityExpressionHandler uses the
PermissionEvaluator Bean by default.

Fixes: gh-5272
2018-04-30 12:16:34 -05:00
Joe Grandja 0b72f93027 WebSecurityConfigurationTests groovy->java
Issue: gh-4939
2018-04-30 11:43:30 -05:00
Rob Winch 5b751baf61 Fixes: gh-5190 2018-04-16 17:52:55 -05:00
Joe Grandja ec9ab1965a Next Development Version 2018-04-04 13:36:28 -04:00
Joe Grandja 30aede82da Release 5.0.4.RELEASE 2018-04-04 13:03:55 -04:00
Joe Grandja 2686452b99 Update to aspectjtools:1.9.0
Fixes gh-5211
2018-04-04 13:00:46 -04:00
Joe Grandja 7e470ff5bd Update to aspectjrt:1.9.0
Fixes gh-5210
2018-04-04 12:59:09 -04:00
Joe Grandja df6a6e5991 Update to Reactor Bismuth SR8
Fixes gh-5209
2018-04-04 12:53:54 -04:00
Joe Grandja 1500a22439 Update to Spring Data Kay SR6
Fixes gh-5167
2018-04-04 10:31:04 -04:00
Joe Grandja 64cb256bb9 Update to Spring Framework 5.0.5
Fixes gh-5166
2018-04-04 10:27:43 -04:00
Joe Grandja e6d68acfd6 Fix NPE with exp claim in NimbusJwtDecoderJwkSupport
Fixes gh-5168
2018-04-04 09:02:05 -04:00
Joe Grandja bc2a7ac394 ClaimAccessor.getClaimAsInstant() converts Long or Date
Fixes gh-5191, Fixes gh-5192
2018-04-04 04:57:36 -04:00
Joe Grandja 55019b2f0b Fix SecuredAnnotationSecurityMetadataSourceTests -> Related SPR-16677 2018-04-03 11:16:50 -04:00
Rob Winch 151b545ed0 Polish Javadoc
Fixes: gh-5186
2018-03-29 15:33:31 -05:00
Rob Winch c67ce144b9 Polish HeadersSpec
Fixes: gh-5187
2018-03-29 15:33:31 -05:00
Rob Winch 6729c39905 Fix JDK 9
Issue: gh-5160
2018-03-28 15:00:41 -05:00
Rob Winch 197439f9e1 Update to mockito 2.17.0
Fixes: gh-5181
2018-03-28 14:42:43 -05:00
Rob Winch 70a11267fa Update to hibernate-validator:6.0.9.Final
Fixes: gh-5180
2018-03-28 14:42:35 -05:00
Rob Winch 4e0c165d47 Update to hibernate-entitymanager:5.2.16.Final
Fixes: gh-5178
2018-03-28 14:42:09 -05:00
Rob Winch 93844b1823 Update to assertj 2.9.1
Fixes: gh-5177
2018-03-28 14:32:49 -05:00
Rob Winch a30b3321c4 Update to thymeleaf-layout-dialect:2.3.0
Fixes: gh-5176
2018-03-28 14:32:30 -05:00
Rob Winch ffb8c1978a Update to unbounded 4.0.5
Fixes: gh-5175
2018-03-28 14:32:13 -05:00
Rob Winch 4722ab21bf Update to oauth2-oidc-sdk:5.57
Fixes: gh-5179
2018-03-28 14:32:07 -05:00
Rob Winch 335735e227 Update to nimbus-jose-jwt:5.9
Fixes: gh-5174
2018-03-28 14:31:47 -05:00
Rob Winch 501269a51f Update to appengine 1.9.63
Fixes: gh-5173
2018-03-28 14:30:57 -05:00
Rob Winch 6b58218256 Update to Jackson 2.9.5
Fixes: gh-5172
2018-03-28 14:30:48 -05:00
Rob Winch de1137fc5e Update mockwebserver 3.10.0
Fixes: gh-5171
2018-03-28 14:30:36 -05:00
Rob Winch e68657216c Fixes for SPR-16624
Fixes: gh-5165
2018-03-27 22:36:03 -05:00
Rob Winch bfada59a1e CookieClearingLogoutHandler adds uses contextPath + "/"
Fixes: gh-5140
2018-03-19 16:50:48 -05:00
Rob Winch bc17860cb6 Fix ReactorContextTestExecutionListener with custom SecurityContext
Fixes: gh-5139
2018-03-19 09:33:34 -05:00
Oleh Dokuka 5e351a4f75 ReactorContextTestExecutionListener with multiple Threads
Fixes: gh-5138
2018-03-19 09:32:36 -05:00
Rob Winch 0458ca88e6 Relax assertions in HeaderSpecTests
Fixes: gh-5117
2018-03-15 08:31:21 -05:00
Rob Winch a7a71d6cef Fix @since on GlobalAuthenticationConfigurerAdapter
Fixes: gh-5109
2018-03-13 14:25:40 -05:00
Josh Cummings a7f180b2c7 Authorities authenticate TestingAuthenticationToken
In other extensions of `AbstractAuthenticationToken`, the constructors
that include `authorities` call `setAuthenticated(true)`. This includes
`PreAuthenticated`-, `UsernamePassword`-, and
`RememberMeAuthenticationToken`.

This change brings `TestingAuthenticationToken` in line with that
convention.

Note that this was done once already to one of the constructors
(ee13be4) in `TestingAuthenticationToken` that takes an arity of
`authorities`. It was not propagated to the constructor that takes a
collection, which is what this commit remedies.

Fixes: gh-5098
2018-03-09 13:26:36 -06:00
Josh Cummings 87f266133b Update to Spring Boot 2.0.0.RELEASE
Fixes: gh-5091
2018-03-09 09:45:20 -06:00
Rob Winch 8f8deac0f4 Fix StrictHttpFirewall rules
Fixes: gh-5092
2018-03-08 21:29:31 -06:00
Vedran Pavic 9830d01acc Upgrade Nimbus JOSE + JWT to 5.6
Fixes: gh-5089
2018-03-08 16:43:05 -06:00
Vedran Pavic d8fea5c6f1 Upgrade Nimbus OAuth + OIDC SDK to 5.56
Fixes: gh-5088
2018-03-08 16:42:54 -06:00
Rob Winch 4d410b0b61 Polish Javadoc HttpStatusServerAccessDeniedHandler 2018-03-07 12:34:15 -06:00
Rob Winch 24a4fbfe56 HttpStatusServerAccessDeniedHandler use injected HttpStatus
Fixes: gh-5078
2018-03-07 12:28:45 -06:00
Josh Cummings d5d1c30d1d Update to Gradle 4.6
Only thing of interest really is that the Jacoco Gradle plugin was bumped
to 0.8.0, which requires org.ow2.asm:asm:6.0.

Fixes: gh-5077
2018-03-06 20:27:31 -06:00
763 changed files with 20810 additions and 56621 deletions
+6 -11
View File
@@ -1,22 +1,17 @@
# EditorConfig for Spring Security
# see https://github.com/spring-projects/spring-security/blob/master/CONTRIBUTING.md#mind-the-whitespace
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 120
[*.java]
indent_style = tab
indent_size = 4
charset = latin1
continuation_indent_size = 8
[*.xml]
# 4 tabs indentation
indent_style = tab
indent_size = 4
charset = latin1
continuation_indent_size = 8
tab_width = 4
trim_trailing_whitespace = true
-4
View File
@@ -1,7 +1,3 @@
<!--
For Security Vulnerabilities, please use https://pivotal.io/security#reporting
-->
### Summary
<!--
-4
View File
@@ -1,7 +1,3 @@
<!--
For Security Vulnerabilities, please use https://pivotal.io/security#reporting
-->
<!--
Thanks for contributing to Spring Security. Please provide a brief description of your pull-request and reference any related issue numbers (prefix references with #).
-->
+1 -2
View File
@@ -8,7 +8,7 @@ By participating, you are expected to uphold this code. Please report unaccepta
# Similar but different
Each Spring module is slightly different than another in terms of team size, number of issues, etc. Therefore each project is managed slightly different. You will notice that this document is very similar to the [Spring Framework Contributor guidelines](https://github.com/spring-projects/spring-framework/wiki/Contributor-guidelines). However, there are some subtle differences between the two documents, so please be sure to read this document thoroughly.
Each Spring module is slightly different than another in terms of team size, number of issues, etc. Therefore each project is managed slightly different. You will notice that this document is very similar to the [Spring Framework Contributor guidelines](https://github.com/SpringSource/spring-framework/wiki/Contributor-guidelines). However, there are some subtle differences between the two documents, so please be sure to read this document thoroughly.
# Importing into IDE
@@ -180,7 +180,6 @@ Fixes gh-123
2. Do not end the subject line with a period
3. In the body of the commit message, explain how things worked before this commit, what has changed, and how things work now
3. Include Fixes gh-<issue-number> at the end if this fixes a GitHub issue
5. Avoid markdown, including back-ticks identifying code
# Run all tests prior to submission
Vendored
+6 -49
View File
@@ -39,63 +39,20 @@ try {
}
}
},
snapshots: {
stage('Snapshot Tests') {
springio: {
stage('Spring IO') {
node {
checkout scm
try {
sh "./gradlew clean test -PspringVersion='5.+' -PreactorVersion=Californium-BUILD-SNAPSHOT -PspringDataVersion=Lovelace-BUILD-SNAPSHOT --refresh-dependencies --no-daemon --stacktrace"
sh "./gradlew clean springIoCheck -PplatformVersion=Cairo-BUILD-SNAPSHOT -PexcludeProjects='**/samples/**' --refresh-dependencies --no-daemon --stacktrace"
} catch(Exception e) {
currentBuild.result = 'FAILED: snapshots'
currentBuild.result = 'FAILED: springio'
throw e
} finally {
junit '**/build/spring-io*-results/*.xml'
}
}
}
},
jdk9: {
stage('JDK 9') {
node {
checkout scm
try {
withEnv(["JAVA_HOME=${ tool 'jdk9' }"]) {
sh "./gradlew clean test --refresh-dependencies --no-daemon --stacktrace"
}
} catch(Exception e) {
currentBuild.result = 'FAILED: jdk9'
throw e
}
}
}
},
jdk10: {
stage('JDK 10') {
node {
checkout scm
try {
withEnv(["JAVA_HOME=${ tool 'jdk10' }"]) {
sh "./gradlew clean test --refresh-dependencies --no-daemon --stacktrace"
}
} catch(Exception e) {
currentBuild.result = 'FAILED: jdk10'
throw e
}
}
}
},
jdk11: {
stage('JDK 11') {
node {
checkout scm
try {
withEnv(["JAVA_HOME=${ tool 'jdk11' }"]) {
sh "./gradlew clean test --refresh-dependencies --no-daemon --stacktrace"
}
} catch(Exception e) {
currentBuild.result = 'FAILED: jdk11'
throw e
}
}
}
}
if(currentBuild.result == 'SUCCESS') {
@@ -92,11 +92,11 @@ public abstract class AclFormattingUtils {
*/
public static String printBinary(int mask, char code) {
Assert.doesNotContain(Character.toString(code),
Character.toString(Permission.RESERVED_ON),
() -> Permission.RESERVED_ON + " is a reserved character code");
Character.toString(Permission.RESERVED_ON), Permission.RESERVED_ON
+ " is a reserved character code");
Assert.doesNotContain(Character.toString(code),
Character.toString(Permission.RESERVED_OFF),
() -> Permission.RESERVED_OFF + " is a reserved character code");
Character.toString(Permission.RESERVED_OFF), Permission.RESERVED_OFF
+ " is a reserved character code");
return printBinary(mask, Permission.RESERVED_ON, Permission.RESERVED_OFF)
.replace(Permission.RESERVED_ON, code);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -104,9 +104,9 @@ public class DefaultPermissionFactory implements PermissionFactory {
// Ensure no existing Permission uses this integer or code
Assert.isTrue(!registeredPermissionsByInteger.containsKey(mask),
() -> "An existing Permission already provides mask " + mask);
"An existing Permission already provides mask " + mask);
Assert.isTrue(!registeredPermissionsByName.containsKey(permissionName),
() -> "An existing Permission already provides name '" + permissionName + "'");
"An existing Permission already provides name '" + permissionName + "'");
// Register the new Permission
registeredPermissionsByInteger.put(mask, perm);
@@ -111,7 +111,7 @@ public class JdbcAclService implements AclService {
throws NotFoundException {
Map<ObjectIdentity, Acl> map = readAclsById(Arrays.asList(object), sids);
Assert.isTrue(map.containsKey(object),
() -> "There should have been an Acl entry for ObjectIdentity " + object);
"There should have been an Acl entry for ObjectIdentity " + object);
return (Acl) map.get(object);
}
+1 -1
View File
@@ -1,6 +1,6 @@
buildscript {
dependencies {
classpath 'io.spring.gradle:spring-build-conventions:0.0.16.RELEASE'
classpath 'io.spring.gradle:spring-build-conventions:0.0.15.RELEASE'
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
}
repositories {
-3
View File
@@ -13,7 +13,6 @@ dependencies {
optional project(':spring-security-messaging')
optional project(':spring-security-oauth2-client')
optional project(':spring-security-oauth2-jose')
optional project(':spring-security-oauth2-resource-server')
optional project(':spring-security-openid')
optional project(':spring-security-web')
optional 'io.projectreactor:reactor-core'
@@ -35,9 +34,7 @@ dependencies {
testCompile apachedsDependencies
testCompile powerMock2Dependencies
testCompile spockDependencies
testCompile 'com.squareup.okhttp3:mockwebserver'
testCompile 'ch.qos.logback:logback-classic'
testCompile 'io.projectreactor.netty:reactor-netty'
testCompile 'javax.annotation:jsr250-api:1.0'
testCompile 'javax.xml.bind:jaxb-api'
testCompile 'ldapsdk:ldapsdk:4.1'
@@ -122,7 +122,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
* invokes {@link SecurityConfigurerAdapter#setBuilder(SecurityBuilder)}.
*
* @param configurer
* @return the {@link SecurityConfigurerAdapter} for further customizations
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
@@ -140,7 +140,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
* are not considered.
*
* @param configurer
* @return the {@link SecurityConfigurerAdapter} for further customizations
* @return
* @throws Exception
*/
public <C extends SecurityConfigurer<O, B>> C apply(C configurer) throws Exception {
@@ -172,7 +172,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
/**
* Gets the shared objects
* @return the shared Objects
* @return
*/
public Map<Class<? extends Object>, Object> getSharedObjects() {
return Collections.unmodifiableMap(this.sharedObjects);
@@ -214,7 +214,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
* List if not found. Note that object hierarchies are not considered.
*
* @param clazz the {@link SecurityConfigurer} class to look for
* @return a list of {@link SecurityConfigurer}s for further customization
* @return
*/
@SuppressWarnings("unchecked")
public <C extends SecurityConfigurer<O, B>> List<C> getConfigurers(Class<C> clazz) {
@@ -230,7 +230,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
* List if not found. Note that object hierarchies are not considered.
*
* @param clazz the {@link SecurityConfigurer} class to look for
* @return a list of {@link SecurityConfigurer}s for further customization
* @return
*/
@SuppressWarnings("unchecked")
public <C extends SecurityConfigurer<O, B>> List<C> removeConfigurers(Class<C> clazz) {
@@ -246,7 +246,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
* found. Note that object hierarchies are not considered.
*
* @param clazz
* @return the {@link SecurityConfigurer} for further customizations
* @return
*/
@SuppressWarnings("unchecked")
public <C extends SecurityConfigurer<O, B>> C getConfigurer(Class<C> clazz) {
@@ -359,7 +359,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
/**
* Subclasses must implement this method to build the object that is being returned.
*
* @return the Object to be buit or null if the implementation allows it
* @return
*/
protected abstract O performBuild() throws Exception;
@@ -51,7 +51,7 @@ public abstract class SecurityConfigurerAdapter<O, B extends SecurityBuilder<O>>
* Return the {@link SecurityBuilder} when done using the {@link SecurityConfigurer}.
* This is useful for method chaining.
*
* @return the {@link SecurityBuilder} for further customizations
* @return
*/
public B and() {
return getBuilder();
@@ -258,7 +258,7 @@ public class AuthenticationManagerBuilder
* default configuration in the {@link SecurityConfigurer#configure(SecurityBuilder)}
* method.
*
* @return true, if {@link AuthenticationManagerBuilder} is configured, otherwise false
* @return
*/
public boolean isConfigured() {
return !authenticationProviders.isEmpty() || parentAuthenticationManager != null;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -152,7 +152,7 @@ public class AuthenticationConfiguration {
return null;
}
Assert.isTrue(beanNamesForType.length == 1,
() -> "Expecting to only find a single bean for type " + interfaceName
"Expecting to only find a single bean for type " + interfaceName
+ ", but found " + Arrays.asList(beanNamesForType));
lazyTargetSource.setTargetBeanName(beanNamesForType[0]);
lazyTargetSource.setBeanFactory(applicationContext);
@@ -289,11 +289,6 @@ public class AuthenticationConfiguration {
return getPasswordEncoder().matches(rawPassword, encodedPassword);
}
@Override
public boolean upgradeEncoding(String encodedPassword) {
return getPasswordEncoder().upgradeEncoding(encodedPassword);
}
private PasswordEncoder getPasswordEncoder() {
if (this.passwordEncoder != null) {
return this.passwordEncoder;
@@ -22,7 +22,6 @@ import org.springframework.security.authentication.dao.DaoAuthenticationProvider
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
/**
* Lazily initializes the global authentication with a {@link UserDetailsService} if it is
@@ -66,16 +65,12 @@ class InitializeUserDetailsBeanManagerConfigurer
}
PasswordEncoder passwordEncoder = getBeanOrNull(PasswordEncoder.class);
UserDetailsPasswordService passwordManager = getBeanOrNull(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
if (passwordEncoder != null) {
provider.setPasswordEncoder(passwordEncoder);
}
if (passwordManager != null) {
provider.setUserDetailsPasswordService(passwordManager);
}
provider.afterPropertiesSet();
auth.authenticationProvider(provider);
@@ -95,4 +90,4 @@ class InitializeUserDetailsBeanManagerConfigurer
.getBean(userDetailsBeanNames[0], type);
}
}
}
}
@@ -302,7 +302,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
/**
* Specifies the attribute name which contains the role name. Default is "cn".
* @param groupRoleAttribute the attribute name that maps a group to a role.
* @return the {@link LdapAuthenticationProviderConfigurer} for further customizations
* @return
*/
public LdapAuthenticationProviderConfigurer<B> groupRoleAttribute(
String groupRoleAttribute) {
@@ -384,11 +384,11 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
*/
public final class PasswordCompareConfigurer {
/**Us
/**
* Allows specifying the {@link PasswordEncoder} to use. The default is
* {@link org.springframework.security.crypto.password.NoOpPasswordEncoder}.
* @param passwordEncoder the {@link PasswordEncoder} to use
* @return the {@link PasswordCompareConfigurer} for further customizations
* @return the {@link PasswordEncoder} to use
*/
public PasswordCompareConfigurer passwordEncoder(PasswordEncoder passwordEncoder) {
LdapAuthenticationProviderConfigurer.this.passwordEncoder = passwordEncoder;
@@ -602,7 +602,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
}
/**
* @return the {@link PasswordCompareConfigurer} for further customizations
* @return
*/
public PasswordCompareConfigurer passwordCompare() {
return new PasswordCompareConfigurer().passwordAttribute("password")
@@ -63,7 +63,7 @@ public class JdbcUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B
* Populates the {@link DataSource} to be used. This is the only required attribute.
*
* @param dataSource the {@link DataSource} to be used. Cannot be null.
* @return The {@link JdbcUserDetailsManagerConfigurer} used for additional customizations
* @return
* @throws Exception
*/
public JdbcUserDetailsManagerConfigurer<B> dataSource(DataSource dataSource)
@@ -142,7 +142,7 @@ public class JdbcUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B
* storage (default is "").
*
* @param rolePrefix
* @return The {@link JdbcUserDetailsManagerConfigurer} used for additional customizations
* @return
* @throws Exception
*/
public JdbcUserDetailsManagerConfigurer<B> rolePrefix(String rolePrefix)
@@ -69,7 +69,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* method can be invoked multiple times to add multiple users.
*
* @param userDetails the user to add. Cannot be null.
* @return the {@link UserDetailsBuilder} for further customizations
* @return
*/
@SuppressWarnings("unchecked")
public final C withUser(UserDetails userDetails) {
@@ -82,7 +82,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* method can be invoked multiple times to add multiple users.
*
* @param userBuilder the user to add. Cannot be null.
* @return the {@link UserDetailsBuilder} for further customizations
* @return
*/
@SuppressWarnings("unchecked")
public final C withUser(User.UserBuilder userBuilder) {
@@ -95,7 +95,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* method can be invoked multiple times to add multiple users.
*
* @param username the username for the user being added. Cannot be null.
* @return the {@link UserDetailsBuilder} for further customizations
* @return
*/
@SuppressWarnings("unchecked")
public final UserDetailsBuilder withUser(String username) {
@@ -21,7 +21,6 @@ import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.authentication.ProviderManagerBuilder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
/**
* Allows configuring a {@link DaoAuthenticationProvider}
@@ -47,9 +46,6 @@ abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuil
protected AbstractDaoAuthenticationConfigurer(U userDetailsService) {
this.userDetailsService = userDetailsService;
provider.setUserDetailsService(userDetailsService);
if (userDetailsService instanceof UserDetailsPasswordService) {
this.provider.setUserDetailsPasswordService((UserDetailsPasswordService) userDetailsService);
}
}
/**
@@ -69,7 +65,7 @@ abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuil
* {@link DaoAuthenticationProvider}. The default is to use plain text.
*
* @param passwordEncoder The {@link PasswordEncoder} to use.
* @return the {@link AbstractDaoAuthenticationConfigurer} for further customizations
* @return
*/
@SuppressWarnings("unchecked")
public C passwordEncoder(PasswordEncoder passwordEncoder) {
@@ -77,11 +73,6 @@ abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuil
return (C) this;
}
public C userDetailsPasswordManager(UserDetailsPasswordService passwordManager) {
provider.setUserDetailsPasswordService(passwordManager);
return (C) this;
}
@Override
public void configure(B builder) throws Exception {
provider = postProcess(provider);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -118,7 +118,7 @@ public class GlobalMethodSecurityConfiguration
* {@link MethodInterceptor}.
* </p>
*
* @return the {@link MethodInterceptor}.
* @return
* @throws Exception
*/
@Bean
@@ -204,7 +204,7 @@ public class GlobalMethodSecurityConfiguration
* {@link AfterInvocationManager}
* </p>
*
* @return the {@link AfterInvocationManager} to use
* @return
*/
protected AfterInvocationManager afterInvocationManager() {
if (prePostEnabled()) {
@@ -225,7 +225,7 @@ public class GlobalMethodSecurityConfiguration
* Provide a custom {@link RunAsManager} for the default implementation of
* {@link #methodSecurityInterceptor()}. The default is null.
*
* @return the {@link RunAsManager} to use
* @return
*/
protected RunAsManager runAsManager() {
return null;
@@ -241,7 +241,7 @@ public class GlobalMethodSecurityConfiguration
* <li>{@link AuthenticatedVoter}</li>
* </ul>
*
* @return the {@link AccessDecisionManager} to use
* @return
*/
protected AccessDecisionManager accessDecisionManager() {
List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList<AccessDecisionVoter<? extends Object>>();
@@ -270,7 +270,7 @@ public class GlobalMethodSecurityConfiguration
* {@link MethodSecurityExpressionHandler}
* </p>
*
* @return the {@link MethodSecurityExpressionHandler} to use
* @return
*/
protected MethodSecurityExpressionHandler createExpressionHandler() {
return defaultMethodExpressionHandler;
@@ -307,7 +307,7 @@ public class GlobalMethodSecurityConfiguration
* {@link #configure(AuthenticationManagerBuilder)} was not overridden, then an
* {@link AuthenticationManager} is attempted to be autowired by type.
*
* @return the {@link AuthenticationManager} to use
* @return
*/
protected AuthenticationManager authenticationManager() throws Exception {
if (authenticationManager == null) {
@@ -346,7 +346,7 @@ public class GlobalMethodSecurityConfiguration
* {@link #customMethodSecurityMetadataSource()} and the attributes on
* {@link EnableGlobalMethodSecurity}.
*
* @return the {@link MethodSecurityMetadataSource}
* @return
*/
@Bean
public MethodSecurityMetadataSource methodSecurityMetadataSource() {
@@ -379,7 +379,7 @@ public class GlobalMethodSecurityConfiguration
* Creates the {@link PreInvocationAuthorizationAdvice} to be used. The default is
* {@link ExpressionBasedPreInvocationAdvice}.
*
* @return the {@link PreInvocationAuthorizationAdvice}
* @return
*/
@Bean
public PreInvocationAuthorizationAdvice preInvocationAuthorizationAdvice() {
@@ -457,7 +457,7 @@ public class GlobalMethodSecurityConfiguration
EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils
.findAnnotation(getClass(), EnableGlobalMethodSecurity.class);
Assert.notNull(methodSecurityAnnotation,
() -> EnableGlobalMethodSecurity.class.getName() + " is required");
EnableGlobalMethodSecurity.class.getName() + " is required");
Map<String, Object> methodSecurityAttrs = AnnotationUtils
.getAnnotationAttributes(methodSecurityAnnotation);
this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,7 +42,7 @@ final class GlobalMethodSecuritySelector implements ImportSelector {
.getAnnotationAttributes(annoType.getName(), false);
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(annotationAttributes);
Assert.notNull(attributes, () -> String.format(
Assert.notNull(attributes, String.format(
"@%s is not present on importing class '%s' as expected",
annoType.getSimpleName(), importingClassMetadata.getClassName()));
@@ -146,10 +146,8 @@ public interface HttpSecurityBuilder<H extends HttpSecurityBuilder<H>> extends
* <li>{@link ConcurrentSessionFilter}</li>
* <li>{@link OpenIDAuthenticationFilter}</li>
* <li>{@link org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter}</li>
* <li>{@link org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter}</li>
* <li>{@link ConcurrentSessionFilter}</li>
* <li>{@link DigestAuthenticationFilter}</li>
* <li>{@link org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter}</li>
* <li>{@link BasicAuthenticationFilter}</li>
* <li>{@link RequestCacheAwareFilter}</li>
* <li>{@link SecurityContextHolderAwareRequestFilter}</li>
@@ -19,6 +19,7 @@ import java.io.Serializable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import org.springframework.security.web.access.ExceptionTranslationFilter;
@@ -32,7 +33,6 @@ import org.springframework.security.web.authentication.preauth.x509.X509Authenti
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter;
import org.springframework.security.web.authentication.switchuser.SwitchUserFilter;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.authentication.www.DigestAuthenticationFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
@@ -101,15 +101,10 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
order += STEP;
put(DefaultLoginPageGeneratingFilter.class, order);
order += STEP;
put(DefaultLogoutPageGeneratingFilter.class, order);
order += STEP;
put(ConcurrentSessionFilter.class, order);
order += STEP;
put(DigestAuthenticationFilter.class, order);
order += STEP;
filterToOrder.put(
"org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter", order);
order += STEP;
put(BasicAuthenticationFilter.class, order);
order += STEP;
put(RequestCacheAwareFilter.class, order);
@@ -122,10 +117,6 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
order += STEP;
put(AnonymousAuthenticationFilter.class, order);
order += STEP;
filterToOrder.put(
"org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter",
order);
order += STEP;
put(SessionManagementFilter.class, order);
order += STEP;
put(ExceptionTranslationFilter.class, order);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,14 @@
*/
package org.springframework.security.config.annotation.web.builders;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
@@ -48,13 +56,12 @@ import org.springframework.security.config.annotation.web.configurers.SecurityCo
import org.springframework.security.config.annotation.web.configurers.ServletApiConfigurer;
import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer;
import org.springframework.security.config.annotation.web.configurers.X509Configurer;
import org.springframework.security.config.annotation.web.configurers.oauth2.OAuth2Configurer;
import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer;
import org.springframework.security.config.annotation.web.configurers.openid.OpenIDLoginConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.PortMapper;
import org.springframework.security.web.PortMapperImpl;
@@ -72,13 +79,6 @@ import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* A {@link HttpSecurity} is similar to Spring Security's XML &lt;http&gt; element in the
* namespace configuration. It allows configuring web based security for specific http
@@ -327,7 +327,7 @@ public final class HttpSecurity extends
* }
* </pre>
*
* @return the {@link HeadersConfigurer} for further customizations
* @return
* @throws Exception
* @see HeadersConfigurer
*/
@@ -643,7 +643,7 @@ public final class HttpSecurity extends
*
* @see #requestMatcher(RequestMatcher)
*
* @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations
* @return
* @throws Exception
*/
public ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests()
@@ -763,7 +763,7 @@ public final class HttpSecurity extends
* }
* </pre>
*
* @return the {@link LogoutConfigurer} for further customizations
* @return
* @throws Exception
*/
public LogoutConfigurer<HttpSecurity> logout() throws Exception {
@@ -826,7 +826,7 @@ public final class HttpSecurity extends
* }
* </pre>
*
* @return the {@link AnonymousConfigurer} for further customizations
* @return
* @throws Exception
*/
public AnonymousConfigurer<HttpSecurity> anonymous() throws Exception {
@@ -890,7 +890,7 @@ public final class HttpSecurity extends
*
* @see FormLoginConfigurer#loginPage(String)
*
* @return the {@link FormLoginConfigurer} for further customizations
* @return
* @throws Exception
*/
public FormLoginConfigurer<HttpSecurity> formLogin() throws Exception {
@@ -991,20 +991,6 @@ public final class HttpSecurity extends
return getOrApply(new OAuth2LoginConfigurer<>());
}
/**
* Configures support for the <a target="_blank" href="https://tools.ietf.org/html/rfc6749">OAuth 2.0 Authorization Framework</a>.
*
* @author Joe Grandja
* @since 5.1
* @return the {@link OAuth2Configurer} for further customizations
* @throws Exception
*/
public OAuth2Configurer<HttpSecurity> oauth2() throws Exception {
OAuth2Configurer<HttpSecurity> configurer = getOrApply(new OAuth2Configurer<>());
this.postProcess(configurer);
return configurer;
}
/**
* Configures channel security. In order for this configuration to be useful at least
* one mapping to a required channel must be provided.
@@ -1177,11 +1163,6 @@ public final class HttpSecurity extends
* addFilterAt(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
* </pre>
*
* Registration of multiple Filters in the same location means their ordering is not
* deterministic. More concretely, registering multiple Filters in the same location
* does not override existing Filters. Instead, do not register Filters you do not
* want to use.
*
* @param filter the Filter to register
* @param atFilter the location of another {@link Filter} that is already registered
* (i.e. known) with Spring Security.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -235,7 +235,7 @@ public final class WebSecurity extends
/**
* Gets the {@link SecurityExpressionHandler} to be used.
* @return the {@link SecurityExpressionHandler} for further customizations
* @return
*/
public SecurityExpressionHandler<FilterInvocation> getExpressionHandler() {
return expressionHandler;
@@ -243,7 +243,7 @@ public final class WebSecurity extends
/**
* Gets the {@link WebInvocationPrivilegeEvaluator} to be used.
* @return the {@link WebInvocationPrivilegeEvaluator} for further customizations
* @return
*/
public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() {
if (privilegeEvaluator != null) {
@@ -279,9 +279,7 @@ public final class WebSecurity extends
protected Filter performBuild() throws Exception {
Assert.state(
!securityFilterChainBuilders.isEmpty(),
() -> "At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. "
+ "Typically this done by adding a @Configuration that extends WebSecurityConfigurerAdapter. "
+ "More advanced users can invoke "
"At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. Typically this done by adding a @Configuration that extends WebSecurityConfigurerAdapter. More advanced users can invoke "
+ WebSecurity.class.getSimpleName()
+ ".addSecurityFilterChainBuilder directly");
int chainSize = ignoredRequests.size() + securityFilterChainBuilders.size();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -52,7 +52,7 @@ import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
* }
*
* &#064;Override
* protected void configure(AuthenticationManagerBuilder auth) throws Exception {
* protected void configure(AuthenticationManagerBuilder auth) {
* auth
* // enable in memory based authentication with a user named &quot;user&quot; and &quot;admin&quot;
* .inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;)
@@ -73,8 +73,7 @@ import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ WebSecurityConfiguration.class,
SpringWebMvcImportSelector.class,
OAuth2ImportSelector.class })
SpringWebMvcImportSelector.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
@@ -84,4 +83,4 @@ public @interface EnableWebSecurity {
* @return if true, enables debug support with Spring Security
*/
boolean debug() default false;
}
}
@@ -1,78 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.method.annotation.OAuth2AuthorizedClientArgumentResolver;
import org.springframework.util.ClassUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* {@link Configuration} for OAuth 2.0 Client support.
*
* <p>
* This {@code Configuration} is conditionally imported by {@link OAuth2ImportSelector}
* when the {@code spring-security-oauth2-client} module is present on the classpath.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2ImportSelector
*/
@Import(OAuth2ClientConfiguration.OAuth2ClientWebMvcImportSelector.class)
final class OAuth2ClientConfiguration {
static class OAuth2ClientWebMvcImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
boolean webmvcPresent = ClassUtils.isPresent(
"org.springframework.web.servlet.DispatcherServlet", getClass().getClassLoader());
return webmvcPresent ?
new String[] { "org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration.OAuth2ClientWebMvcSecurityConfiguration" } :
new String[] {};
}
}
@Configuration
static class OAuth2ClientWebMvcSecurityConfiguration implements WebMvcConfigurer {
private OAuth2AuthorizedClientRepository authorizedClientRepository;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
if (this.authorizedClientRepository != null) {
OAuth2AuthorizedClientArgumentResolver authorizedClientArgumentResolver =
new OAuth2AuthorizedClientArgumentResolver(this.authorizedClientRepository);
argumentResolvers.add(authorizedClientArgumentResolver);
}
}
@Autowired(required = false)
public void setAuthorizedClientRepository(List<OAuth2AuthorizedClientRepository> authorizedClientRepositories) {
if (authorizedClientRepositories.size() == 1) {
this.authorizedClientRepository = authorizedClientRepositories.get(0);
}
}
}
}
@@ -1,41 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
/**
* Used by {@link EnableWebSecurity} to conditionally import {@link OAuth2ClientConfiguration}
* when the {@code spring-security-oauth2-client} module is present on the classpath.
* @author Joe Grandja
* @since 5.1
* @see OAuth2ClientConfiguration
*/
final class OAuth2ImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
boolean oauth2ClientPresent = ClassUtils.isPresent(
"org.springframework.security.oauth2.client.registration.ClientRegistration", getClass().getClassLoader());
return oauth2ClientPresent ?
new String[] { "org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration" } :
new String[] {};
}
}
@@ -88,7 +88,7 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
/**
* Creates the Spring Security Filter Chain
* @return the {@link Filter} that represents the security filter chain
* @return
* @throws Exception
*/
@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
@@ -257,7 +257,7 @@ public abstract class WebSecurityConfigurerAdapter implements
* {@link AuthenticationManagerBuilder} that was passed in. Otherwise, autowire the
* {@link AuthenticationManager} by type.
*
* @return the {@link AuthenticationManager} to use
* @return
* @throws Exception
*/
protected AuthenticationManager authenticationManager() throws Exception {
@@ -291,7 +291,7 @@ public abstract class WebSecurityConfigurerAdapter implements
*
* To change the instance returned, developers should change
* {@link #userDetailsService()} instead
* @return the {@link UserDetailsService}
* @return
* @throws Exception
* @see #userDetailsService()
*/
@@ -308,7 +308,7 @@ public abstract class WebSecurityConfigurerAdapter implements
* {@link ApplicationContext}. Developers should override this method when changing
* the instance of {@link #userDetailsServiceBean()}.
*
* @return the {@link UserDetailsService} to use
* @return
*/
protected UserDetailsService userDetailsService() {
AuthenticationManagerBuilder globalAuthBuilder = context
@@ -593,11 +593,6 @@ public abstract class WebSecurityConfigurerAdapter implements
return getPasswordEncoder().matches(rawPassword, encodedPassword);
}
@Override
public boolean upgradeEncoding(String encodedPassword) {
return getPasswordEncoder().upgradeEncoding(encodedPassword);
}
private PasswordEncoder getPasswordEncoder() {
if (this.passwordEncoder != null) {
return this.passwordEncoder;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,7 +32,6 @@ import org.springframework.security.web.authentication.SavedRequestAwareAuthenti
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;
@@ -66,8 +65,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
private SavedRequestAwareAuthenticationSuccessHandler defaultSuccessHandler = new SavedRequestAwareAuthenticationSuccessHandler();
private AuthenticationSuccessHandler successHandler = this.defaultSuccessHandler;
private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
private LoginUrlAuthenticationEntryPoint authenticationEntryPoint;
@@ -130,7 +128,6 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
handler.setDefaultTargetUrl(defaultSuccessUrl);
handler.setAlwaysUseDefaultTargetUrl(alwaysUse);
this.defaultSuccessHandler = handler;
return successHandler(handler);
}
@@ -184,7 +181,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
/**
* Equivalent of invoking permitAll(true)
* @return the {@link FormLoginConfigurer} for additional customization
* @return
*/
public final T permitAll() {
return permitAll(true);
@@ -237,27 +234,20 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
@Override
public void init(B http) throws Exception {
updateAuthenticationDefaults();
updateAccessDefaults(http);
if (permitAll) {
PermitAllSupport.permitAll(http, loginPage, loginProcessingUrl, failureUrl);
}
registerDefaultAuthenticationEntryPoint(http);
}
@SuppressWarnings("unchecked")
protected final void registerDefaultAuthenticationEntryPoint(B http) {
registerAuthenticationEntryPoint(http, this.authenticationEntryPoint);
}
@SuppressWarnings("unchecked")
protected final void registerAuthenticationEntryPoint(B http, AuthenticationEntryPoint authenticationEntryPoint) {
private void registerDefaultAuthenticationEntryPoint(B http) {
ExceptionHandlingConfigurer<B> exceptionHandling = http
.getConfigurer(ExceptionHandlingConfigurer.class);
if (exceptionHandling == null) {
return;
}
exceptionHandling.defaultAuthenticationEntryPointFor(
postProcess(authenticationEntryPoint), getAuthenticationEntryPointMatcher(http));
}
protected final RequestMatcher getAuthenticationEntryPointMatcher(B http) {
ContentNegotiationStrategy contentNegotiationStrategy = http
.getSharedObject(ContentNegotiationStrategy.class);
if (contentNegotiationStrategy == null) {
@@ -272,7 +262,10 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
RequestMatcher notXRequestedWith = new NegatedRequestMatcher(
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"));
return new AndRequestMatcher(Arrays.asList(notXRequestedWith, mediaMatcher));
RequestMatcher preferredMatcher = new AndRequestMatcher(Arrays.asList(notXRequestedWith, mediaMatcher));
exceptionHandling.defaultAuthenticationEntryPointFor(
postProcess(authenticationEntryPoint), preferredMatcher);
}
@Override
@@ -282,11 +275,6 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
authenticationEntryPoint.setPortMapper(portMapper);
}
RequestCache requestCache = http.getSharedObject(RequestCache.class);
if (requestCache != null) {
this.defaultSuccessHandler.setRequestCache(requestCache);
}
authFilter.setAuthenticationManager(http
.getSharedObject(AuthenticationManager.class));
authFilter.setAuthenticationSuccessHandler(successHandler);
@@ -363,15 +351,6 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
return loginPage;
}
/**
* Gets the Authentication Entry Point
*
* @return the Authentication Entry Point
*/
protected final AuthenticationEntryPoint getAuthenticationEntryPoint() {
return authenticationEntryPoint;
}
/**
* Gets the URL to submit an authentication request to (i.e. where username/password
* must be submitted)
@@ -385,7 +364,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
/**
* Gets the URL to send users to if authentication fails
*
* @return the URL to send users if authentication fails (e.g. "/login?error").
* @return
*/
protected final String getFailureUrl() {
return failureUrl;
@@ -396,7 +375,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
*
* @throws Exception
*/
protected final void updateAuthenticationDefaults() {
private void updateAuthenticationDefaults() {
if (loginProcessingUrl == null) {
loginProcessingUrl(loginPage);
}
@@ -411,15 +390,6 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
}
}
/**
* Updates the default values for access.
*/
protected final void updateAccessDefaults(B http) {
if (permitAll) {
PermitAllSupport.permitAll(http, loginPage, loginProcessingUrl, failureUrl);
}
}
/**
* Sets the loginPage and updates the {@link AuthenticationEntryPoint}.
* @param loginPage
@@ -188,7 +188,7 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>> e
* Sets the {@link ChannelProcessor} instances to use in
* {@link ChannelDecisionManagerImpl}
* @param channelProcessors
* @return the {@link ChannelSecurityConfigurer} for further customizations
* @return
*/
public ChannelRequestMatcherRegistry channelProcessors(
List<ChannelProcessor> channelProcessors) {
@@ -200,7 +200,7 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>> e
* Return the {@link SecurityBuilder} when done using the
* {@link SecurityConfigurer}. This is useful for method chaining.
*
* @return the type of {@link HttpSecurityBuilder} that is being configured
* @return
*/
public H and() {
return ChannelSecurityConfigurer.this.and();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -128,7 +128,7 @@ public final class CsrfConfigurer<H extends HttpSecurityBuilder<H>>
* </p>
*
* <p>
* For example, the following configuration will ensure CSRF protection ignores:
* The following will ensure CSRF protection ignores:
* </p>
* <ul>
* <li>Any GET, HEAD, TRACE, OPTIONS (this is the default)</li>
@@ -150,35 +150,6 @@ public final class CsrfConfigurer<H extends HttpSecurityBuilder<H>>
.and();
}
/**
* <p>
* Allows specifying {@link HttpServletRequest}s that should not use CSRF Protection
* even if they match the {@link #requireCsrfProtectionMatcher(RequestMatcher)}.
* </p>
*
* <p>
* For example, the following configuration will ensure CSRF protection ignores:
* </p>
* <ul>
* <li>Any GET, HEAD, TRACE, OPTIONS (this is the default)</li>
* <li>We also explicitly state to ignore any request that has a "X-Requested-With: XMLHttpRequest" header</li>
* </ul>
*
* <pre>
* http
* .csrf()
* .ignoringRequestMatchers(request -> "XMLHttpRequest".equals(request.getHeader("X-Requested-With")))
* .and()
* ...
* </pre>
*
* @since 5.1
*/
public CsrfConfigurer<H> ignoringRequestMatchers(RequestMatcher... requestMatchers) {
return new IgnoreCsrfProtectionRegistry(this.context).requestMatchers(requestMatchers)
.and();
}
@SuppressWarnings("unchecked")
@Override
public void configure(H http) throws Exception {
@@ -19,13 +19,9 @@ import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter;
import org.springframework.security.web.csrf.CsrfToken;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
/**
* Adds a Filter that will generate a login page if one is not specified otherwise when
@@ -70,19 +66,15 @@ public final class DefaultLoginPageConfigurer<H extends HttpSecurityBuilder<H>>
private DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = new DefaultLoginPageGeneratingFilter();
private DefaultLogoutPageGeneratingFilter logoutPageGeneratingFilter = new DefaultLogoutPageGeneratingFilter();
@Override
public void init(H http) throws Exception {
Function<HttpServletRequest, Map<String, String>> hiddenInputs = request -> {
this.loginPageGeneratingFilter.setResolveHiddenInputs( request -> {
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (token == null) {
if(token == null) {
return Collections.emptyMap();
}
return Collections.singletonMap(token.getParameterName(), token.getToken());
};
this.loginPageGeneratingFilter.setResolveHiddenInputs(hiddenInputs);
this.logoutPageGeneratingFilter.setResolveHiddenInputs(hiddenInputs);
});
http.setSharedObject(DefaultLoginPageGeneratingFilter.class,
loginPageGeneratingFilter);
}
@@ -100,8 +92,7 @@ public final class DefaultLoginPageConfigurer<H extends HttpSecurityBuilder<H>>
if (loginPageGeneratingFilter.isEnabled() && authenticationEntryPoint == null) {
loginPageGeneratingFilter = postProcess(loginPageGeneratingFilter);
http.addFilter(loginPageGeneratingFilter);
http.addFilter(this.logoutPageGeneratingFilter);
}
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.access.RequestMatcherDelegatingAccessDeniedHandler;
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
@@ -71,8 +70,6 @@ public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
private LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> defaultEntryPointMappings = new LinkedHashMap<>();
private LinkedHashMap<RequestMatcher, AccessDeniedHandler> defaultDeniedHandlerMappings = new LinkedHashMap<>();
/**
* Creates a new instance
* @see HttpSecurity#exceptionHandling()
@@ -107,26 +104,6 @@ public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
return this;
}
/**
* Sets a default {@link AccessDeniedHandler} to be used which prefers being
* invoked for the provided {@link RequestMatcher}. If only a single default
* {@link AccessDeniedHandler} is specified, it will be what is used for the
* default {@link AccessDeniedHandler}. If multiple default
* {@link AccessDeniedHandler} instances are configured, then a
* {@link RequestMatcherDelegatingAccessDeniedHandler} will be used.
*
* @param deniedHandler the {@link AccessDeniedHandler} to use
* @param preferredMatcher the {@link RequestMatcher} for this default
* {@link AccessDeniedHandler}
* @return the {@link ExceptionHandlingConfigurer} for further customizations
* @since 5.1
*/
public ExceptionHandlingConfigurer<H> defaultAccessDeniedHandlerFor(
AccessDeniedHandler deniedHandler, RequestMatcher preferredMatcher) {
this.defaultDeniedHandlerMappings.put(preferredMatcher, deniedHandler);
return this;
}
/**
* Sets the {@link AuthenticationEntryPoint} to be used.
*
@@ -192,27 +169,13 @@ public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
AuthenticationEntryPoint entryPoint = getAuthenticationEntryPoint(http);
ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(
entryPoint, getRequestCache(http));
AccessDeniedHandler deniedHandler = getAccessDeniedHandler(http);
exceptionTranslationFilter.setAccessDeniedHandler(deniedHandler);
if (accessDeniedHandler != null) {
exceptionTranslationFilter.setAccessDeniedHandler(accessDeniedHandler);
}
exceptionTranslationFilter = postProcess(exceptionTranslationFilter);
http.addFilter(exceptionTranslationFilter);
}
/**
* Gets the {@link AccessDeniedHandler} according to the rules specified by
* {@link #accessDeniedHandler(AccessDeniedHandler)}
* @param http the {@link HttpSecurity} used to look up shared
* {@link AccessDeniedHandler}
* @return the {@link AccessDeniedHandler} to use
*/
AccessDeniedHandler getAccessDeniedHandler(H http) {
AccessDeniedHandler deniedHandler = this.accessDeniedHandler;
if (deniedHandler == null) {
deniedHandler = createDefaultDeniedHandler(http);
}
return deniedHandler;
}
/**
* Gets the {@link AuthenticationEntryPoint} according to the rules specified by
* {@link #authenticationEntryPoint(AuthenticationEntryPoint)}
@@ -228,28 +191,16 @@ public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
return entryPoint;
}
private AccessDeniedHandler createDefaultDeniedHandler(H http) {
if (this.defaultDeniedHandlerMappings.isEmpty()) {
return new AccessDeniedHandlerImpl();
}
if (this.defaultDeniedHandlerMappings.size() == 1) {
return this.defaultDeniedHandlerMappings.values().iterator().next();
}
return new RequestMatcherDelegatingAccessDeniedHandler(
this.defaultDeniedHandlerMappings,
new AccessDeniedHandlerImpl());
}
private AuthenticationEntryPoint createDefaultEntryPoint(H http) {
if (this.defaultEntryPointMappings.isEmpty()) {
if (defaultEntryPointMappings.isEmpty()) {
return new Http403ForbiddenEntryPoint();
}
if (this.defaultEntryPointMappings.size() == 1) {
return this.defaultEntryPointMappings.values().iterator().next();
if (defaultEntryPointMappings.size() == 1) {
return defaultEntryPointMappings.values().iterator().next();
}
DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(
this.defaultEntryPointMappings);
entryPoint.setDefaultEntryPoint(this.defaultEntryPointMappings.values().iterator()
defaultEntryPointMappings);
entryPoint.setDefaultEntryPoint(defaultEntryPointMappings.values().iterator()
.next());
return entryPoint;
}
@@ -442,7 +442,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>> extends
* application.
* </p>
*
* @return the {@link HeadersConfigurer} for additional customization.
* @return
*/
public HeadersConfigurer<H> sameOrigin() {
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
@@ -45,7 +45,7 @@ public final class PortMapperConfigurer<H extends HttpSecurityBuilder<H>> extend
/**
* Allows specifying the {@link PortMapper} instance.
* @param portMapper
* @return the {@link PortMapperConfigurer} for further customizations
* @return
*/
public PortMapperConfigurer<H> portMapper(PortMapper portMapper) {
this.portMapper = portMapper;
@@ -19,8 +19,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -115,26 +113,11 @@ public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>> exte
if (result != null) {
return result;
}
result = getBeanOrNull(RequestCache.class);
if (result != null) {
return result;
}
HttpSessionRequestCache defaultCache = new HttpSessionRequestCache();
defaultCache.setRequestMatcher(createDefaultSavedRequestMatcher(http));
return defaultCache;
}
private <T> T getBeanOrNull(Class<T> type) {
ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class);
if (context == null) {
return null;
}
try {
return context.getBean(type);
} catch (NoSuchBeanDefinitionException e) {
return null;
}
}
@SuppressWarnings("unchecked")
private RequestMatcher createDefaultSavedRequestMatcher(H http) {
ContentNegotiationStrategy contentNegotiationStrategy = http
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.security.config.annotation.web.configurers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@@ -104,7 +105,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
private Integer maximumSessions;
private String expiredUrl;
private boolean maxSessionsPreventsLogin;
private SessionCreationPolicy sessionPolicy;
private SessionCreationPolicy sessionPolicy = SessionCreationPolicy.IF_REQUIRED;
private boolean enableSessionUrlRewriting;
private String invalidSessionUrl;
private String sessionAuthenticationErrorUrl;
@@ -548,14 +549,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link SessionCreationPolicy}
*/
SessionCreationPolicy getSessionCreationPolicy() {
if (this.sessionPolicy != null) {
return this.sessionPolicy;
}
SessionCreationPolicy sessionPolicy =
getBuilder().getSharedObject(SessionCreationPolicy.class);
return sessionPolicy == null ?
SessionCreationPolicy.IF_REQUIRED : sessionPolicy;
return this.sessionPolicy;
}
/**
@@ -564,9 +558,8 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return true if the {@link SessionCreationPolicy} allows session creation
*/
private boolean isAllowSessionCreation() {
SessionCreationPolicy sessionPolicy = getSessionCreationPolicy();
return SessionCreationPolicy.ALWAYS == sessionPolicy
|| SessionCreationPolicy.IF_REQUIRED == sessionPolicy;
return SessionCreationPolicy.ALWAYS == this.sessionPolicy
|| SessionCreationPolicy.IF_REQUIRED == this.sessionPolicy;
}
/**
@@ -574,8 +567,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
* @return
*/
private boolean isStateless() {
SessionCreationPolicy sessionPolicy = getSessionCreationPolicy();
return SessionCreationPolicy.STATELESS == sessionPolicy;
return SessionCreationPolicy.STATELESS == this.sessionPolicy;
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -99,7 +99,7 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
* The StandardInterceptUrlRegistry is what users will interact with after applying
* the {@link UrlAuthorizationConfigurer}.
*
* @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations
* @return
*/
public StandardInterceptUrlRegistry getRegistry() {
return REGISTRY;
@@ -198,7 +198,7 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
* provided {@link ConfigAttribute} instances
* @param configAttributes the {@link ConfigAttribute} instances that should be mapped
* by the {@link RequestMatcher} instances
* @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations
* @return the {@link UrlAuthorizationConfigurer} for further customizations
*/
private StandardInterceptUrlRegistry addMapping(
Iterable<? extends RequestMatcher> requestMatchers,
@@ -220,7 +220,7 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
private static String hasRole(String role) {
Assert.isTrue(
!role.startsWith("ROLE_"),
() -> role
role
+ " should not start with ROLE_ since ROLE_ is automatically prepended when using hasRole. Consider using hasAuthority or access instead.");
return "ROLE_" + role;
}
@@ -1,105 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2ClientConfigurer;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
/**
* An {@link AbstractHttpConfigurer} that provides support for the
* <a target="_blank" href="https://tools.ietf.org/html/rfc6749">OAuth 2.0 Authorization Framework</a>.
*
* @author Joe Grandja
* @since 5.1
* @see HttpSecurity#oauth2()
* @see OAuth2ClientConfigurer
* @see AbstractHttpConfigurer
*/
public final class OAuth2Configurer<B extends HttpSecurityBuilder<B>>
extends AbstractHttpConfigurer<OAuth2Configurer<B>, B> {
@Autowired
private ObjectPostProcessor<Object> objectPostProcessor;
private OAuth2ClientConfigurer<B> clientConfigurer;
private OAuth2ResourceServerConfigurer<B> resourceServerConfigurer;
/**
* Returns the {@link OAuth2ClientConfigurer} for configuring OAuth 2.0 Client support.
*
* @return the {@link OAuth2ClientConfigurer}
*/
public OAuth2ClientConfigurer<B> client() {
if (this.clientConfigurer == null) {
this.initClientConfigurer();
}
return this.clientConfigurer;
}
/**
* Returns the {@link OAuth2ResourceServerConfigurer} for configuring OAuth 2.0 Resource Server support.
*
* @return the {@link OAuth2ResourceServerConfigurer}
*/
public OAuth2ResourceServerConfigurer<B> resourceServer() {
if (this.resourceServerConfigurer == null) {
this.initResourceServerConfigurer();
}
return this.resourceServerConfigurer;
}
@Override
public void init(B builder) throws Exception {
if (this.clientConfigurer != null) {
this.clientConfigurer.init(builder);
}
if (this.resourceServerConfigurer != null) {
this.resourceServerConfigurer.init(builder);
}
}
@Override
public void configure(B builder) throws Exception {
if (this.clientConfigurer != null) {
this.clientConfigurer.configure(builder);
}
if (this.resourceServerConfigurer != null) {
this.resourceServerConfigurer.configure(builder);
}
}
private void initClientConfigurer() {
this.clientConfigurer = new OAuth2ClientConfigurer<>();
this.clientConfigurer.setBuilder(this.getBuilder());
this.clientConfigurer.addObjectPostProcessor(this.objectPostProcessor);
}
private void initResourceServerConfigurer() {
ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class);
this.resourceServerConfigurer = new OAuth2ResourceServerConfigurer<>(context);
this.resourceServerConfigurer.setBuilder(this.getBuilder());
this.resourceServerConfigurer.addObjectPostProcessor(this.objectPostProcessor);
}
}
@@ -15,6 +15,7 @@
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
@@ -85,7 +86,7 @@ public final class ImplicitGrantConfigurer<B extends HttpSecurityBuilder<B>> ext
@Override
public void configure(B http) throws Exception {
OAuth2AuthorizationRequestRedirectFilter authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder()), this.getAuthorizationRequestBaseUri());
this.getClientRegistrationRepository(), this.getAuthorizationRequestBaseUri());
http.addFilter(this.postProcess(authorizationRequestFilter));
}
@@ -94,4 +95,17 @@ public final class ImplicitGrantConfigurer<B extends HttpSecurityBuilder<B>> ext
this.authorizationRequestBaseUri :
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
}
private ClientRegistrationRepository getClientRegistrationRepository() {
ClientRegistrationRepository clientRegistrationRepository = this.getBuilder().getSharedObject(ClientRegistrationRepository.class);
if (clientRegistrationRepository == null) {
clientRegistrationRepository = this.getClientRegistrationRepositoryBean();
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
}
return clientRegistrationRepository;
}
private ClientRegistrationRepository getClientRegistrationRepositoryBean() {
return this.getBuilder().getSharedObject(ApplicationContext.class).getBean(ClientRegistrationRepository.class);
}
}
@@ -1,334 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationProvider;
import org.springframework.security.oauth2.client.endpoint.NimbusAuthorizationCodeTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.util.Assert;
/**
* An {@link AbstractHttpConfigurer} for OAuth 2.0 Client support.
*
* <p>
* The following configuration options are available:
*
* <ul>
* <li>{@link #authorizationCodeGrant()} - enables the OAuth 2.0 Authorization Code Grant</li>
* </ul>
*
* <p>
* Defaults are provided for all configuration options with the only required configuration
* being {@link #clientRegistrationRepository(ClientRegistrationRepository)}.
* Alternatively, a {@link ClientRegistrationRepository} {@code @Bean} may be registered instead.
*
* <h2>Security Filters</h2>
*
* The following {@code Filter}'s are populated when {@link #authorizationCodeGrant()} is configured:
*
* <ul>
* <li>{@link OAuth2AuthorizationRequestRedirectFilter}</li>
* <li>{@link OAuth2AuthorizationCodeGrantFilter}</li>
* </ul>
*
* <h2>Shared Objects Created</h2>
*
* The following shared objects are populated:
*
* <ul>
* <li>{@link ClientRegistrationRepository} (required)</li>
* <li>{@link OAuth2AuthorizedClientRepository} (optional)</li>
* </ul>
*
* <h2>Shared Objects Used</h2>
*
* The following shared objects are used:
*
* <ul>
* <li>{@link ClientRegistrationRepository}</li>
* <li>{@link OAuth2AuthorizedClientRepository}</li>
* </ul>
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizationRequestRedirectFilter
* @see OAuth2AuthorizationCodeGrantFilter
* @see ClientRegistrationRepository
* @see OAuth2AuthorizedClientRepository
* @see AbstractHttpConfigurer
*/
public final class OAuth2ClientConfigurer<B extends HttpSecurityBuilder<B>> extends
AbstractHttpConfigurer<OAuth2ClientConfigurer<B>, B> {
private AuthorizationCodeGrantConfigurer authorizationCodeGrantConfigurer;
/**
* Sets the repository of client registrations.
*
* @param clientRegistrationRepository the repository of client registrations
* @return the {@link OAuth2ClientConfigurer} for further configuration
*/
public OAuth2ClientConfigurer<B> clientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
return this;
}
/**
* Sets the repository for authorized client(s).
*
* @param authorizedClientRepository the authorized client repository
* @return the {@link OAuth2ClientConfigurer} for further configuration
*/
public OAuth2ClientConfigurer<B> authorizedClientRepository(OAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.getBuilder().setSharedObject(OAuth2AuthorizedClientRepository.class, authorizedClientRepository);
return this;
}
/**
* Sets the service for authorized client(s).
*
* @param authorizedClientService the authorized client service
* @return the {@link OAuth2ClientConfigurer} for further configuration
*/
public OAuth2ClientConfigurer<B> authorizedClientService(OAuth2AuthorizedClientService authorizedClientService) {
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
this.authorizedClientRepository(new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService));
return this;
}
/**
* Returns the {@link AuthorizationCodeGrantConfigurer} for configuring the OAuth 2.0 Authorization Code Grant.
*
* @return the {@link AuthorizationCodeGrantConfigurer}
*/
public AuthorizationCodeGrantConfigurer authorizationCodeGrant() {
if (this.authorizationCodeGrantConfigurer == null) {
this.authorizationCodeGrantConfigurer = new AuthorizationCodeGrantConfigurer();
}
return this.authorizationCodeGrantConfigurer;
}
/**
* Configuration options for the OAuth 2.0 Authorization Code Grant.
*/
public class AuthorizationCodeGrantConfigurer {
private final AuthorizationEndpointConfig authorizationEndpointConfig = new AuthorizationEndpointConfig();
private final TokenEndpointConfig tokenEndpointConfig = new TokenEndpointConfig();
private AuthorizationCodeGrantConfigurer() {
}
/**
* Returns the {@link AuthorizationEndpointConfig} for configuring the Authorization Server's Authorization Endpoint.
*
* @return the {@link AuthorizationEndpointConfig}
*/
public AuthorizationEndpointConfig authorizationEndpoint() {
return this.authorizationEndpointConfig;
}
/**
* Configuration options for the Authorization Server's Authorization Endpoint.
*/
public class AuthorizationEndpointConfig {
private String authorizationRequestBaseUri;
private OAuth2AuthorizationRequestResolver authorizationRequestResolver;
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
private AuthorizationEndpointConfig() {
}
/**
* Sets the base {@code URI} used for authorization requests.
*
* @param authorizationRequestBaseUri the base {@code URI} used for authorization requests
* @return the {@link AuthorizationEndpointConfig} for further configuration
*/
public AuthorizationEndpointConfig baseUri(String authorizationRequestBaseUri) {
Assert.hasText(authorizationRequestBaseUri, "authorizationRequestBaseUri cannot be empty");
this.authorizationRequestBaseUri = authorizationRequestBaseUri;
return this;
}
/**
* Sets the resolver used for resolving {@link OAuth2AuthorizationRequest}'s.
*
* @param authorizationRequestResolver the resolver used for resolving {@link OAuth2AuthorizationRequest}'s
* @return the {@link AuthorizationEndpointConfig} for further configuration
*/
public AuthorizationEndpointConfig authorizationRequestResolver(OAuth2AuthorizationRequestResolver authorizationRequestResolver) {
Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null");
this.authorizationRequestResolver = authorizationRequestResolver;
return this;
}
/**
* Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s.
*
* @param authorizationRequestRepository the repository used for storing {@link OAuth2AuthorizationRequest}'s
* @return the {@link AuthorizationEndpointConfig} for further configuration
*/
public AuthorizationEndpointConfig authorizationRequestRepository(
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
this.authorizationRequestRepository = authorizationRequestRepository;
return this;
}
/**
* Returns the {@link AuthorizationCodeGrantConfigurer} for further configuration.
*
* @return the {@link AuthorizationCodeGrantConfigurer}
*/
public AuthorizationCodeGrantConfigurer and() {
return AuthorizationCodeGrantConfigurer.this;
}
}
/**
* Returns the {@link TokenEndpointConfig} for configuring the Authorization Server's Token Endpoint.
*
* @return the {@link TokenEndpointConfig}
*/
public TokenEndpointConfig tokenEndpoint() {
return this.tokenEndpointConfig;
}
/**
* Configuration options for the Authorization Server's Token Endpoint.
*/
public class TokenEndpointConfig {
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
private TokenEndpointConfig() {
}
/**
* Sets the client used for requesting the access token credential from the Token Endpoint.
*
* @param accessTokenResponseClient the client used for requesting the access token credential from the Token Endpoint
* @return the {@link TokenEndpointConfig} for further configuration
*/
public TokenEndpointConfig accessTokenResponseClient(
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
return this;
}
/**
* Returns the {@link AuthorizationCodeGrantConfigurer} for further configuration.
*
* @return the {@link AuthorizationCodeGrantConfigurer}
*/
public AuthorizationCodeGrantConfigurer and() {
return AuthorizationCodeGrantConfigurer.this;
}
}
/**
* Returns the {@link OAuth2ClientConfigurer} for further configuration.
*
* @return the {@link OAuth2ClientConfigurer}
*/
public OAuth2ClientConfigurer<B> and() {
return OAuth2ClientConfigurer.this;
}
}
@Override
public void init(B builder) throws Exception {
if (this.authorizationCodeGrantConfigurer != null) {
this.init(builder, this.authorizationCodeGrantConfigurer);
}
}
@Override
public void configure(B builder) throws Exception {
if (this.authorizationCodeGrantConfigurer != null) {
this.configure(builder, this.authorizationCodeGrantConfigurer);
}
}
private void init(B builder, AuthorizationCodeGrantConfigurer authorizationCodeGrantConfigurer) throws Exception {
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient =
authorizationCodeGrantConfigurer.tokenEndpointConfig.accessTokenResponseClient;
if (accessTokenResponseClient == null) {
accessTokenResponseClient = new NimbusAuthorizationCodeTokenResponseClient();
}
OAuth2AuthorizationCodeAuthenticationProvider authorizationCodeAuthenticationProvider =
new OAuth2AuthorizationCodeAuthenticationProvider(accessTokenResponseClient);
builder.authenticationProvider(this.postProcess(authorizationCodeAuthenticationProvider));
}
private void configure(B builder, AuthorizationCodeGrantConfigurer authorizationCodeGrantConfigurer) throws Exception {
OAuth2AuthorizationRequestRedirectFilter authorizationRequestFilter;
if (authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestResolver != null) {
authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestResolver);
} else {
String authorizationRequestBaseUri = authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestBaseUri;
if (authorizationRequestBaseUri == null) {
authorizationRequestBaseUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
}
authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(builder), authorizationRequestBaseUri);
}
if (authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestRepository != null) {
authorizationRequestFilter.setAuthorizationRequestRepository(
authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestRepository);
}
RequestCache requestCache = builder.getSharedObject(RequestCache.class);
if (requestCache != null) {
authorizationRequestFilter.setRequestCache(requestCache);
}
builder.addFilter(this.postProcess(authorizationRequestFilter));
AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class);
OAuth2AuthorizationCodeGrantFilter authorizationCodeGrantFilter = new OAuth2AuthorizationCodeGrantFilter(
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(builder),
OAuth2ClientConfigurerUtils.getAuthorizedClientRepository(builder),
authenticationManager);
if (authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestRepository != null) {
authorizationCodeGrantFilter.setAuthorizationRequestRepository(
authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestRepository);
}
builder.addFilter(this.postProcess(authorizationCodeGrantFilter));
}
}
@@ -1,99 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.client;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* Utility methods for the OAuth 2.0 Client {@link AbstractHttpConfigurer}'s.
*
* @author Joe Grandja
* @since 5.1
*/
final class OAuth2ClientConfigurerUtils {
private OAuth2ClientConfigurerUtils() {
}
static <B extends HttpSecurityBuilder<B>> ClientRegistrationRepository getClientRegistrationRepository(B builder) {
ClientRegistrationRepository clientRegistrationRepository = builder.getSharedObject(ClientRegistrationRepository.class);
if (clientRegistrationRepository == null) {
clientRegistrationRepository = getClientRegistrationRepositoryBean(builder);
builder.setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
}
return clientRegistrationRepository;
}
private static <B extends HttpSecurityBuilder<B>> ClientRegistrationRepository getClientRegistrationRepositoryBean(B builder) {
return builder.getSharedObject(ApplicationContext.class).getBean(ClientRegistrationRepository.class);
}
static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientRepository getAuthorizedClientRepository(B builder) {
OAuth2AuthorizedClientRepository authorizedClientRepository = builder.getSharedObject(OAuth2AuthorizedClientRepository.class);
if (authorizedClientRepository == null) {
authorizedClientRepository = getAuthorizedClientRepositoryBean(builder);
if (authorizedClientRepository == null) {
authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(
getAuthorizedClientService((builder)));
}
builder.setSharedObject(OAuth2AuthorizedClientRepository.class, authorizedClientRepository);
}
return authorizedClientRepository;
}
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientRepository getAuthorizedClientRepositoryBean(B builder) {
Map<String, OAuth2AuthorizedClientRepository> authorizedClientRepositoryMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
builder.getSharedObject(ApplicationContext.class), OAuth2AuthorizedClientRepository.class);
if (authorizedClientRepositoryMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientRepository.class, authorizedClientRepositoryMap.size(),
"Expected single matching bean of type '" + OAuth2AuthorizedClientRepository.class.getName() + "' but found " +
authorizedClientRepositoryMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(authorizedClientRepositoryMap.keySet()));
}
return (!authorizedClientRepositoryMap.isEmpty() ? authorizedClientRepositoryMap.values().iterator().next() : null);
}
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientService(B builder) {
OAuth2AuthorizedClientService authorizedClientService = getAuthorizedClientServiceBean(builder);
if (authorizedClientService == null) {
authorizedClientService = new InMemoryOAuth2AuthorizedClientService(getClientRegistrationRepository(builder));
}
return authorizedClientService;
}
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientServiceBean(B builder) {
Map<String, OAuth2AuthorizedClientService> authorizedClientServiceMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
builder.getSharedObject(ApplicationContext.class), OAuth2AuthorizedClientService.class);
if (authorizedClientServiceMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientService.class, authorizedClientServiceMap.size(),
"Expected single matching bean of type '" + OAuth2AuthorizedClientService.class.getName() + "' but found " +
authorizedClientServiceMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(authorizedClientServiceMap.keySet()));
}
return (!authorizedClientServiceMap.isEmpty() ? authorizedClientServiceMap.values().iterator().next() : null);
}
}
@@ -26,6 +26,7 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHt
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
@@ -42,11 +43,8 @@ import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserServ
import org.springframework.security.oauth2.client.userinfo.DelegatingOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
@@ -54,23 +52,14 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequ
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -102,7 +91,7 @@ import java.util.Map;
*
* <ul>
* <li>{@link ClientRegistrationRepository} (required)</li>
* <li>{@link OAuth2AuthorizedClientRepository} (optional)</li>
* <li>{@link OAuth2AuthorizedClientService} (optional)</li>
* <li>{@link GrantedAuthoritiesMapper} (optional)</li>
* </ul>
*
@@ -112,7 +101,7 @@ import java.util.Map;
*
* <ul>
* <li>{@link ClientRegistrationRepository}</li>
* <li>{@link OAuth2AuthorizedClientRepository}</li>
* <li>{@link OAuth2AuthorizedClientService}</li>
* <li>{@link GrantedAuthoritiesMapper}</li>
* <li>{@link DefaultLoginPageGeneratingFilter} - if {@link #loginPage(String)} is not configured
* and {@code DefaultLoginPageGeneratingFilter} is available, than a default login page will be made available</li>
@@ -125,7 +114,6 @@ import java.util.Map;
* @see OAuth2AuthorizationRequestRedirectFilter
* @see OAuth2LoginAuthenticationFilter
* @see ClientRegistrationRepository
* @see OAuth2AuthorizedClientRepository
* @see AbstractAuthenticationFilterConfigurer
*/
public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> extends
@@ -150,19 +138,6 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
return this;
}
/**
* Sets the repository for authorized client(s).
*
* @since 5.1
* @param authorizedClientRepository the authorized client repository
* @return the {@link OAuth2LoginConfigurer} for further configuration
*/
public OAuth2LoginConfigurer<B> authorizedClientRepository(OAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.getBuilder().setSharedObject(OAuth2AuthorizedClientRepository.class, authorizedClientRepository);
return this;
}
/**
* Sets the service for authorized client(s).
*
@@ -171,7 +146,7 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
*/
public OAuth2LoginConfigurer<B> authorizedClientService(OAuth2AuthorizedClientService authorizedClientService) {
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
this.authorizedClientRepository(new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService));
this.getBuilder().setSharedObject(OAuth2AuthorizedClientService.class, authorizedClientService);
return this;
}
@@ -203,7 +178,6 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
*/
public class AuthorizationEndpointConfig {
private String authorizationRequestBaseUri;
private OAuth2AuthorizationRequestResolver authorizationRequestResolver;
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
private AuthorizationEndpointConfig() {
@@ -221,19 +195,6 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
return this;
}
/**
* Sets the resolver used for resolving {@link OAuth2AuthorizationRequest}'s.
*
* @since 5.1
* @param authorizationRequestResolver the resolver used for resolving {@link OAuth2AuthorizationRequest}'s
* @return the {@link AuthorizationEndpointConfig} for further configuration
*/
public AuthorizationEndpointConfig authorizationRequestResolver(OAuth2AuthorizationRequestResolver authorizationRequestResolver) {
Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null");
this.authorizationRequestResolver = authorizationRequestResolver;
return this;
}
/**
* Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s.
*
@@ -423,29 +384,15 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
public void init(B http) throws Exception {
OAuth2LoginAuthenticationFilter authenticationFilter =
new OAuth2LoginAuthenticationFilter(
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder()),
OAuth2ClientConfigurerUtils.getAuthorizedClientRepository(this.getBuilder()),
this.getClientRegistrationRepository(),
this.getAuthorizedClientService(),
this.loginProcessingUrl);
this.setAuthenticationFilter(authenticationFilter);
super.loginProcessingUrl(this.loginProcessingUrl);
if (this.loginPage != null) {
// Set custom login page
super.loginPage(this.loginPage);
super.init(http);
} else {
Map<String, String> loginUrlToClientName = this.getLoginLinks();
if (loginUrlToClientName.size() == 1) {
// Setup auto-redirect to provider login page
// when only 1 client is configured
this.updateAuthenticationDefaults();
this.updateAccessDefaults(http);
String providerLoginPage = loginUrlToClientName.keySet().iterator().next();
this.registerAuthenticationEntryPoint(http, this.getLoginEntryPoint(http, providerLoginPage));
} else {
super.init(http);
}
}
super.init(http);
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient =
this.tokenEndpointConfig.accessTokenResponseClient;
@@ -497,28 +444,18 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
@Override
public void configure(B http) throws Exception {
OAuth2AuthorizationRequestRedirectFilter authorizationRequestFilter;
if (this.authorizationEndpointConfig.authorizationRequestResolver != null) {
authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
this.authorizationEndpointConfig.authorizationRequestResolver);
} else {
String authorizationRequestBaseUri = this.authorizationEndpointConfig.authorizationRequestBaseUri;
if (authorizationRequestBaseUri == null) {
authorizationRequestBaseUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
}
authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder()), authorizationRequestBaseUri);
String authorizationRequestBaseUri = this.authorizationEndpointConfig.authorizationRequestBaseUri;
if (authorizationRequestBaseUri == null) {
authorizationRequestBaseUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
}
OAuth2AuthorizationRequestRedirectFilter authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(
this.getClientRegistrationRepository(), authorizationRequestBaseUri);
if (this.authorizationEndpointConfig.authorizationRequestRepository != null) {
authorizationRequestFilter.setAuthorizationRequestRepository(
this.authorizationEndpointConfig.authorizationRequestRepository);
}
RequestCache requestCache = http.getSharedObject(RequestCache.class);
if (requestCache != null) {
authorizationRequestFilter.setRequestCache(requestCache);
}
http.addFilter(this.postProcess(authorizationRequestFilter));
OAuth2LoginAuthenticationFilter authenticationFilter = this.getAuthenticationFilter();
@@ -537,6 +474,41 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
return new AntPathRequestMatcher(loginProcessingUrl);
}
private ClientRegistrationRepository getClientRegistrationRepository() {
ClientRegistrationRepository clientRegistrationRepository =
this.getBuilder().getSharedObject(ClientRegistrationRepository.class);
if (clientRegistrationRepository == null) {
clientRegistrationRepository = this.getClientRegistrationRepositoryBean();
this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
}
return clientRegistrationRepository;
}
private ClientRegistrationRepository getClientRegistrationRepositoryBean() {
return this.getBuilder().getSharedObject(ApplicationContext.class).getBean(ClientRegistrationRepository.class);
}
private OAuth2AuthorizedClientService getAuthorizedClientService() {
OAuth2AuthorizedClientService authorizedClientService =
this.getBuilder().getSharedObject(OAuth2AuthorizedClientService.class);
if (authorizedClientService == null) {
authorizedClientService = this.getAuthorizedClientServiceBean();
if (authorizedClientService == null) {
authorizedClientService = new InMemoryOAuth2AuthorizedClientService(this.getClientRegistrationRepository());
}
this.getBuilder().setSharedObject(OAuth2AuthorizedClientService.class, authorizedClientService);
}
return authorizedClientService;
}
private OAuth2AuthorizedClientService getAuthorizedClientServiceBean() {
Map<String, OAuth2AuthorizedClientService> authorizedClientServiceMap =
BeanFactoryUtils.beansOfTypeIncludingAncestors(
this.getBuilder().getSharedObject(ApplicationContext.class),
OAuth2AuthorizedClientService.class);
return (!authorizedClientServiceMap.isEmpty() ? authorizedClientServiceMap.values().iterator().next() : null);
}
private GrantedAuthoritiesMapper getGrantedAuthoritiesMapper() {
GrantedAuthoritiesMapper grantedAuthoritiesMapper =
this.getBuilder().getSharedObject(GrantedAuthoritiesMapper.class);
@@ -551,9 +523,9 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
private GrantedAuthoritiesMapper getGrantedAuthoritiesMapperBean() {
Map<String, GrantedAuthoritiesMapper> grantedAuthoritiesMapperMap =
BeanFactoryUtils.beansOfTypeIncludingAncestors(
this.getBuilder().getSharedObject(ApplicationContext.class),
GrantedAuthoritiesMapper.class);
BeanFactoryUtils.beansOfTypeIncludingAncestors(
this.getBuilder().getSharedObject(ApplicationContext.class),
GrantedAuthoritiesMapper.class);
return (!grantedAuthoritiesMapperMap.isEmpty() ? grantedAuthoritiesMapperMap.values().iterator().next() : null);
}
@@ -563,51 +535,28 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
return;
}
loginPageGeneratingFilter.setOauth2LoginEnabled(true);
loginPageGeneratingFilter.setOauth2AuthenticationUrlToClientName(this.getLoginLinks());
loginPageGeneratingFilter.setLoginPageUrl(this.getLoginPage());
loginPageGeneratingFilter.setFailureUrl(this.getFailureUrl());
}
@SuppressWarnings("unchecked")
private Map<String, String> getLoginLinks() {
Iterable<ClientRegistration> clientRegistrations = null;
ClientRegistrationRepository clientRegistrationRepository =
OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder());
ClientRegistrationRepository clientRegistrationRepository = this.getClientRegistrationRepository();
ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class);
if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
}
if (clientRegistrations == null) {
return Collections.emptyMap();
return;
}
String authorizationRequestBaseUri = this.authorizationEndpointConfig.authorizationRequestBaseUri != null ?
this.authorizationEndpointConfig.authorizationRequestBaseUri :
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
Map<String, String> loginUrlToClientName = new HashMap<>();
clientRegistrations.forEach(registration -> loginUrlToClientName.put(
authorizationRequestBaseUri + "/" + registration.getRegistrationId(),
registration.getClientName()));
this.authorizationEndpointConfig.authorizationRequestBaseUri :
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
Map<String, String> authenticationUrlToClientName = new HashMap<>();
return loginUrlToClientName;
}
private AuthenticationEntryPoint getLoginEntryPoint(B http, String providerLoginPage) {
RequestMatcher loginPageMatcher = new AntPathRequestMatcher(this.getLoginPage());
RequestMatcher faviconMatcher = new AntPathRequestMatcher("/favicon.ico");
RequestMatcher defaultEntryPointMatcher = this.getAuthenticationEntryPointMatcher(http);
RequestMatcher defaultLoginPageMatcher = new AndRequestMatcher(
new OrRequestMatcher(loginPageMatcher, faviconMatcher), defaultEntryPointMatcher);
LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>();
entryPoints.put(new NegatedRequestMatcher(defaultLoginPageMatcher),
new LoginUrlAuthenticationEntryPoint(providerLoginPage));
DelegatingAuthenticationEntryPoint loginEntryPoint = new DelegatingAuthenticationEntryPoint(entryPoints);
loginEntryPoint.setDefaultEntryPoint(this.getAuthenticationEntryPoint());
return loginEntryPoint;
clientRegistrations.forEach(registration -> authenticationUrlToClientName.put(
authorizationRequestBaseUri + "/" + registration.getRegistrationId(),
registration.getClientName()));
loginPageGeneratingFilter.setOauth2LoginEnabled(true);
loginPageGeneratingFilter.setOauth2AuthenticationUrlToClientName(authenticationUrlToClientName);
loginPageGeneratingFilter.setLoginPageUrl(this.getLoginPage());
loginPageGeneratingFilter.setFailureUrl(this.getFailureUrl());
}
private static class OidcAuthenticationRequestChecker implements AuthenticationProvider {
@@ -639,4 +588,5 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
return OAuth2LoginAuthenticationToken.class.isAssignableFrom(authentication);
}
}
}
@@ -1,290 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.server.resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoderJwkSupport;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
/**
*
* An {@link AbstractHttpConfigurer} for OAuth 2.0 Resource Server Support.
*
* By default, this wires a {@link BearerTokenAuthenticationFilter}, which can be used to parse the request
* for bearer tokens and make an authentication attempt.
*
* <p>
* The following configuration options are available:
*
* <ul>
* <li>{@link #accessDeniedHandler(AccessDeniedHandler)}</li> - customizes how access denied errors are handled
* <li>{@link #authenticationEntryPoint(AuthenticationEntryPoint)}</li> - customizes how authentication failures are handled
* <li>{@link #bearerTokenResolver(BearerTokenResolver)} - customizes how to resolve a bearer token from the request</li>
* <li>{@link #jwt()} - enables Jwt-encoded bearer token support</li>
* </ul>
*
* <p>
* When using {@link #jwt()}, either
*
* <ul>
* <li>
* supply a Jwk Set Uri via {@link JwtConfigurer#jwkSetUri}, or
* </li>
* <li>
* supply a {@link JwtDecoder} instance via {@link JwtConfigurer#decoder}, or
* </li>
* <li>
* expose a {@link JwtDecoder} bean
* </li>
* </ul>
*
* <h2>Security Filters</h2>
*
* The following {@code Filter}s are populated when {@link #jwt()} is configured:
*
* <ul>
* <li>{@link BearerTokenAuthenticationFilter}</li>
* </ul>
*
* <h2>Shared Objects Created</h2>
*
* The following shared objects are populated:
*
* <ul>
* <li>{@link SessionCreationPolicy} (optional)</li>
* </ul>
*
* <h2>Shared Objects Used</h2>
*
* The following shared objects are used:
*
* <ul>
* <li>{@link AuthenticationManager}</li>
* </ul>
*
* @author Josh Cummings
* @since 5.1
* @see BearerTokenAuthenticationFilter
* @see JwtAuthenticationProvider
* @see NimbusJwtDecoderJwkSupport
* @see AbstractHttpConfigurer
*/
public final class OAuth2ResourceServerConfigurer<H extends HttpSecurityBuilder<H>> extends
AbstractHttpConfigurer<OAuth2ResourceServerConfigurer<H>, H> {
private final ApplicationContext context;
private BearerTokenResolver bearerTokenResolver;
private JwtConfigurer jwtConfigurer;
private AccessDeniedHandler accessDeniedHandler = new BearerTokenAccessDeniedHandler();
private AuthenticationEntryPoint authenticationEntryPoint = new BearerTokenAuthenticationEntryPoint();
private BearerTokenRequestMatcher requestMatcher = new BearerTokenRequestMatcher();
public OAuth2ResourceServerConfigurer(ApplicationContext context) {
Assert.notNull(context, "context cannot be null");
this.context = context;
}
public OAuth2ResourceServerConfigurer<H> accessDeniedHandler(AccessDeniedHandler accessDeniedHandler) {
Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null");
this.accessDeniedHandler = accessDeniedHandler;
return this;
}
public OAuth2ResourceServerConfigurer<H> authenticationEntryPoint(AuthenticationEntryPoint entryPoint) {
Assert.notNull(entryPoint, "entryPoint cannot be null");
this.authenticationEntryPoint = entryPoint;
return this;
}
public OAuth2ResourceServerConfigurer<H> bearerTokenResolver(BearerTokenResolver bearerTokenResolver) {
Assert.notNull(bearerTokenResolver, "bearerTokenResolver cannot be null");
this.bearerTokenResolver = bearerTokenResolver;
return this;
}
public JwtConfigurer jwt() {
if ( this.jwtConfigurer == null ) {
this.jwtConfigurer = new JwtConfigurer(this.context);
}
return this.jwtConfigurer;
}
@Override
public void setBuilder(H http) {
super.setBuilder(http);
initSessionCreationPolicy(http);
}
@Override
public void init(H http) throws Exception {
registerDefaultAccessDeniedHandler(http);
registerDefaultEntryPoint(http);
registerDefaultCsrfOverride(http);
}
@Override
public void configure(H http) throws Exception {
BearerTokenResolver bearerTokenResolver = getBearerTokenResolver();
this.requestMatcher.setBearerTokenResolver(bearerTokenResolver);
AuthenticationManager manager = http.getSharedObject(AuthenticationManager.class);
BearerTokenAuthenticationFilter filter =
new BearerTokenAuthenticationFilter(manager);
filter.setBearerTokenResolver(bearerTokenResolver);
filter.setAuthenticationEntryPoint(this.authenticationEntryPoint);
filter = postProcess(filter);
http.addFilter(filter);
if ( this.jwtConfigurer == null ) {
throw new IllegalStateException("Jwt is the only supported format for bearer tokens " +
"in Spring Security and no Jwt configuration was found. Make sure to specify " +
"a jwk set uri by doing http.oauth2().resourceServer().jwt().jwkSetUri(uri), or wire a " +
"JwtDecoder instance by doing http.oauth2().resourceServer().jwt().decoder(decoder), or " +
"expose a JwtDecoder instance as a bean and do http.oauth2().resourceServer().jwt().");
}
JwtDecoder decoder = this.jwtConfigurer.getJwtDecoder();
JwtAuthenticationProvider provider =
new JwtAuthenticationProvider(decoder);
provider = postProcess(provider);
http.authenticationProvider(provider);
}
public class JwtConfigurer {
private final ApplicationContext context;
private JwtDecoder decoder;
JwtConfigurer(ApplicationContext context) {
this.context = context;
}
public OAuth2ResourceServerConfigurer<H> decoder(JwtDecoder decoder) {
this.decoder = decoder;
return OAuth2ResourceServerConfigurer.this;
}
public OAuth2ResourceServerConfigurer<H> jwkSetUri(String uri) {
this.decoder = new NimbusJwtDecoderJwkSupport(uri);
return OAuth2ResourceServerConfigurer.this;
}
JwtDecoder getJwtDecoder() {
if ( this.decoder == null ) {
return this.context.getBean(JwtDecoder.class);
}
return this.decoder;
}
}
private void initSessionCreationPolicy(H http) {
if (http.getSharedObject(SessionCreationPolicy.class) == null) {
http.setSharedObject(SessionCreationPolicy.class, SessionCreationPolicy.STATELESS);
}
}
private void registerDefaultAccessDeniedHandler(H http) {
ExceptionHandlingConfigurer<H> exceptionHandling = http
.getConfigurer(ExceptionHandlingConfigurer.class);
if (exceptionHandling == null) {
return;
}
exceptionHandling.defaultAccessDeniedHandlerFor(
this.accessDeniedHandler,
this.requestMatcher);
}
private void registerDefaultEntryPoint(H http) {
ExceptionHandlingConfigurer<H> exceptionHandling = http
.getConfigurer(ExceptionHandlingConfigurer.class);
if (exceptionHandling == null) {
return;
}
exceptionHandling.defaultAuthenticationEntryPointFor(
this.authenticationEntryPoint,
this.requestMatcher);
}
private void registerDefaultCsrfOverride(H http) {
CsrfConfigurer<H> csrf = http
.getConfigurer(CsrfConfigurer.class);
if (csrf == null) {
return;
}
csrf.ignoringRequestMatchers(this.requestMatcher);
}
BearerTokenResolver getBearerTokenResolver() {
if ( this.bearerTokenResolver == null ) {
if ( this.context.getBeanNamesForType(BearerTokenResolver.class).length > 0 ) {
this.bearerTokenResolver = this.context.getBean(BearerTokenResolver.class);
} else {
this.bearerTokenResolver = new DefaultBearerTokenResolver();
}
}
return this.bearerTokenResolver;
}
private static final class BearerTokenRequestMatcher implements RequestMatcher {
private BearerTokenResolver bearerTokenResolver;
@Override
public boolean matches(HttpServletRequest request) {
try {
return this.bearerTokenResolver.resolve(request) != null;
} catch ( OAuth2AuthenticationException e ) {
return false;
}
}
public void setBearerTokenResolver(BearerTokenResolver tokenResolver) {
Assert.notNull(tokenResolver, "resolver cannot be null");
this.bearerTokenResolver = tokenResolver;
}
}
}
@@ -479,7 +479,7 @@ public final class OpenIDLoginConfigurer<H extends HttpSecurityBuilder<H>> exten
/**
* The OpenID attribute type.
* @param type
* @return the {@link AttributeConfigurer} for further customizations
* @return
*/
public AttributeConfigurer type(String type) {
this.type = type;
@@ -82,8 +82,7 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import({ServerHttpSecurityConfiguration.class, WebFluxSecurityConfiguration.class,
ReactiveOAuth2ClientImportSelector.class})
@Import({ServerHttpSecurityConfiguration.class, WebFluxSecurityConfiguration.class})
@Configuration
public @interface EnableWebFluxSecurity {
}
@@ -1,70 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.reactive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.web.reactive.result.method.annotation.OAuth2AuthorizedClientArgumentResolver;
import org.springframework.util.ClassUtils;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer;
import java.util.List;
/**
* {@link Configuration} for OAuth 2.0 Client support.
*
* <p>
* This {@code Configuration} is imported by {@link EnableWebFluxSecurity}
*
* @author Rob Winch
* @since 5.1
*/
final class ReactiveOAuth2ClientImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
boolean oauth2ClientPresent = ClassUtils.isPresent(
"org.springframework.security.oauth2.client.registration.ClientRegistration", getClass().getClassLoader());
return oauth2ClientPresent ?
new String[] { "org.springframework.security.config.annotation.web.reactive.ReactiveOAuth2ClientImportSelector$OAuth2ClientWebFluxSecurityConfiguration" } :
new String[] {};
}
@Configuration
static class OAuth2ClientWebFluxSecurityConfiguration implements WebFluxConfigurer {
private ReactiveOAuth2AuthorizedClientService authorizedClientService;
@Override
public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
if (this.authorizedClientService != null) {
configurer.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver(this.authorizedClientService));
}
}
@Autowired(required = false)
public void setAuthorizedClientService(List<ReactiveOAuth2AuthorizedClientService> authorizedClientService) {
if (authorizedClientService.size() == 1) {
this.authorizedClientService = authorizedClientService.get(0);
}
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,29 +16,27 @@
package org.springframework.security.config.annotation.web.reactive;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.ReactiveUserDetailsPasswordService;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.reactive.result.method.annotation.AuthenticationPrincipalArgumentResolver;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer;
import static org.springframework.security.config.web.server.ServerHttpSecurity.http;
/**
* @author Rob Winch
* @since 5.0
*/
@Configuration
class ServerHttpSecurityConfiguration implements WebFluxConfigurer {
private static final String BEAN_NAME_PREFIX = "org.springframework.security.config.annotation.web.reactive.HttpSecurityConfiguration.";
private static final String HTTPSECURITY_BEAN_NAME = BEAN_NAME_PREFIX + "httpSecurity";
@@ -55,12 +53,6 @@ class ServerHttpSecurityConfiguration implements WebFluxConfigurer {
@Autowired(required = false)
private PasswordEncoder passwordEncoder;
@Autowired(required = false)
private ReactiveUserDetailsPasswordService userDetailsPasswordService;
@Autowired(required = false)
private BeanFactory beanFactory;
@Override
public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
configurer.addCustomResolver(authenticationPrincipalArgumentResolver());
@@ -68,19 +60,13 @@ class ServerHttpSecurityConfiguration implements WebFluxConfigurer {
@Bean
public AuthenticationPrincipalArgumentResolver authenticationPrincipalArgumentResolver() {
AuthenticationPrincipalArgumentResolver resolver = new AuthenticationPrincipalArgumentResolver(
this.adapterRegistry);
if(this.beanFactory != null) {
resolver.setBeanResolver(new BeanFactoryResolver(this.beanFactory));
}
return resolver;
return new AuthenticationPrincipalArgumentResolver(this.adapterRegistry);
}
@Bean(HTTPSECURITY_BEAN_NAME)
@Scope("prototype")
public ServerHttpSecurity httpSecurity() {
ContextAwareServerHttpSecurity http = new ContextAwareServerHttpSecurity();
return http
return http()
.authenticationManager(authenticationManager())
.headers().and()
.logout().and();
@@ -96,18 +82,8 @@ class ServerHttpSecurityConfiguration implements WebFluxConfigurer {
if(this.passwordEncoder != null) {
manager.setPasswordEncoder(this.passwordEncoder);
}
manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
return manager;
}
return null;
}
private static class ContextAwareServerHttpSecurity extends ServerHttpSecurity implements
ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
super.setApplicationContext(applicationContext);
}
}
}
@@ -16,9 +16,6 @@
package org.springframework.security.config.annotation.web.reactive;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -28,10 +25,12 @@ import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.reactive.result.view.CsrfRequestDataValueProcessor;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.WebFilterChainProxy;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.reactive.result.view.AbstractView;
import java.util.Arrays;
import java.util.List;
/**
* @author Rob Winch
* @since 5.0
@@ -44,11 +43,6 @@ class WebFluxSecurityConfiguration {
private static final String SPRING_SECURITY_WEBFILTERCHAINFILTER_BEAN_NAME = BEAN_NAME_PREFIX + "WebFilterChainFilter";
public static final String REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME = "org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository";
private static final boolean isOAuth2Present = ClassUtils.isPresent(
REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, WebFluxSecurityConfiguration.class.getClassLoader());
@Autowired(required = false)
private List<SecurityWebFilterChain> securityWebFilterChains;
@@ -87,29 +81,10 @@ class WebFluxSecurityConfiguration {
private SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange()
.anyExchange().authenticated();
if (isOAuth2Present && OAuth2ClasspathGuard.shouldConfigure(this.context)) {
OAuth2ClasspathGuard.configure(this.context, http);
} else {
http
.httpBasic().and()
.formLogin();
}
SecurityWebFilterChain result = http.build();
return result;
}
private static class OAuth2ClasspathGuard {
static void configure(ApplicationContext context, ServerHttpSecurity http) {
http.oauth2Login();
}
static boolean shouldConfigure(ApplicationContext context) {
ClassLoader loader = context.getClassLoader();
Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils.resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader);
return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1;
}
.anyExchange().authenticated()
.and()
.httpBasic().and()
.formLogin();
return http.build();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -103,7 +103,7 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition
else {
BeanDefinition provider = resolver.resolve(
providerElt.getNamespaceURI()).parse(providerElt, pc);
Assert.notNull(provider, () -> "Parser for " + providerElt.getNodeName()
Assert.notNull(provider, "Parser for " + providerElt.getNodeName()
+ " returned a null bean definition");
String providerId = pc.getReaderContext().generateBeanName(provider);
pc.registerBeanComponent(new BeanComponentDefinition(provider,
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,7 +49,7 @@ public class CachingUserDetailsService implements UserDetailsService {
user = delegate.loadUserByUsername(username);
}
Assert.notNull(user, () -> "UserDetailsService " + delegate
Assert.notNull(user, "UserDetailsService " + delegate
+ " returned null for username " + username + ". "
+ "This is an interface contract violation");
@@ -57,6 +57,7 @@ public class ReactiveUserDetailsServiceResourceFactoryBean
* Sets the location of a Resource that is a Properties file in the format defined in {@link UserDetailsResourceFactoryBean}.
*
* @param resourceLocation the location of the properties file that contains the users (i.e. "classpath:users.properties")
* @return the UserDetailsResourceFactoryBean
*/
public void setResourceLocation(String resourceLocation) {
this.userDetails.setResourceLocation(resourceLocation);
@@ -48,7 +48,6 @@ import org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthe
import org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor;
import org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CsrfToken;
@@ -124,7 +123,6 @@ final class AuthenticationConfigBuilder {
@SuppressWarnings("rawtypes")
private ManagedList logoutHandlers;
private BeanDefinition loginPageGenerationFilter;
private BeanDefinition logoutPageGenerationFilter;
private BeanDefinition etf;
private final BeanReference requestCache;
private final BeanReference portMapper;
@@ -546,10 +544,6 @@ final class AuthenticationConfigBuilder {
.rootBeanDefinition(DefaultLoginPageGeneratingFilter.class);
loginPageFilter.addPropertyValue("resolveHiddenInputs", new CsrfTokenHiddenInputFunction());
BeanDefinitionBuilder logoutPageFilter = BeanDefinitionBuilder
.rootBeanDefinition(DefaultLogoutPageGeneratingFilter.class);
logoutPageFilter.addPropertyValue("resolveHiddenInputs", new CsrfTokenHiddenInputFunction());
if (formFilterId != null) {
loginPageFilter.addConstructorArgReference(formFilterId);
loginPageFilter.addPropertyValue("authenticationUrl", loginProcessingUrl);
@@ -562,7 +556,6 @@ final class AuthenticationConfigBuilder {
}
loginPageGenerationFilter = loginPageFilter.getBeanDefinition();
this.logoutPageGenerationFilter = logoutPageFilter.getBeanDefinition();
}
}
@@ -805,7 +798,6 @@ final class AuthenticationConfigBuilder {
if (loginPageGenerationFilter != null) {
filters.add(new OrderDecorator(loginPageGenerationFilter, LOGIN_PAGE_FILTER));
filters.add(new OrderDecorator(this.logoutPageGenerationFilter, LOGOUT_PAGE_FILTER));
}
if (basicFilter != null) {
@@ -40,9 +40,7 @@ enum SecurityFilters {
FORM_LOGIN_FILTER,
OPENID_FILTER,
LOGIN_PAGE_FILTER,
LOGOUT_PAGE_FILTER,
DIGEST_AUTH_FILTER,
BEARER_TOKEN_AUTH_FILTER,
BASIC_AUTH_FILTER,
REQUEST_CACHE_FILTER,
SERVLET_API_SUPPORT_FILTER,
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -512,7 +512,7 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
synchronized (delegateMonitor) {
if (delegate == null) {
Assert.state(beanFactory != null,
() -> "BeanFactory must be set to resolve " + authMgrBean);
"BeanFactory must be set to resolve " + authMgrBean);
try {
delegate = beanFactory.getBean(authMgrBean,
AuthenticationManager.class);
@@ -36,7 +36,7 @@ public enum CommonOAuth2Provider {
@Override
public Builder getBuilder(String registrationId) {
ClientRegistration.Builder builder = getBuilder(registrationId,
ClientAuthenticationMethod.BASIC, DEFAULT_REDIRECT_URL);
ClientAuthenticationMethod.BASIC, DEFAULT_LOGIN_REDIRECT_URL);
builder.scope("openid", "profile", "email");
builder.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
builder.tokenUri("https://www.googleapis.com/oauth2/v4/token");
@@ -53,7 +53,7 @@ public enum CommonOAuth2Provider {
@Override
public Builder getBuilder(String registrationId) {
ClientRegistration.Builder builder = getBuilder(registrationId,
ClientAuthenticationMethod.BASIC, DEFAULT_REDIRECT_URL);
ClientAuthenticationMethod.BASIC, DEFAULT_LOGIN_REDIRECT_URL);
builder.scope("read:user");
builder.authorizationUri("https://github.com/login/oauth/authorize");
builder.tokenUri("https://github.com/login/oauth/access_token");
@@ -69,11 +69,11 @@ public enum CommonOAuth2Provider {
@Override
public Builder getBuilder(String registrationId) {
ClientRegistration.Builder builder = getBuilder(registrationId,
ClientAuthenticationMethod.POST, DEFAULT_REDIRECT_URL);
ClientAuthenticationMethod.POST, DEFAULT_LOGIN_REDIRECT_URL);
builder.scope("public_profile", "email");
builder.authorizationUri("https://www.facebook.com/v2.8/dialog/oauth");
builder.tokenUri("https://graph.facebook.com/v2.8/oauth/access_token");
builder.userInfoUri("https://graph.facebook.com/me?fields=id,name,email");
builder.userInfoUri("https://graph.facebook.com/me");
builder.userNameAttributeName("id");
builder.clientName("Facebook");
return builder;
@@ -85,7 +85,7 @@ public enum CommonOAuth2Provider {
@Override
public Builder getBuilder(String registrationId) {
ClientRegistration.Builder builder = getBuilder(registrationId,
ClientAuthenticationMethod.BASIC, DEFAULT_REDIRECT_URL);
ClientAuthenticationMethod.BASIC, DEFAULT_LOGIN_REDIRECT_URL);
builder.scope("openid", "profile", "email", "address", "phone");
builder.userNameAttributeName(IdTokenClaimNames.SUB);
builder.clientName("Okta");
@@ -93,7 +93,7 @@ public enum CommonOAuth2Provider {
}
};
private static final String DEFAULT_REDIRECT_URL = "{baseUrl}/{action}/oauth2/code/{registrationId}";
private static final String DEFAULT_LOGIN_REDIRECT_URL = "{baseUrl}/login/oauth2/code/{registrationId}";
protected final ClientRegistration.Builder getBuilder(String registrationId,
ClientAuthenticationMethod method, String redirectUri) {
@@ -1,139 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.oauth2.client.oidc;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.web.client.RestTemplate;
import com.nimbusds.oauth2.sdk.GrantType;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.Scope;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
/**
* Allows creating a {@link ClientRegistration.Builder} from an
* <a href="https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig">OpenID Provider Configuration</a>.
*
* @author Rob Winch
* @since 5.1
*/
public final class OidcConfigurationProvider {
/**
* Creates a {@link ClientRegistration.Builder} using the provided
* <a href="http://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a> by making an
* <a href="https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">OpenID Provider
* Configuration Request</a> and using the values in the
* <a href="https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID
* Provider Configuration Response</a> to initialize the {@link ClientRegistration.Builder}.
*
* <p>
* For example, if the issuer provided is "https://example.com", then an "OpenID Provider Configuration Request" will
* be made to "https://example.com/.well-known/openid-configuration". The result is expected to be an "OpenID
* Provider Configuration Response".
* </p>
*
* <p>
* Example usage:
* </p>
* <pre>
* ClientRegistration registration = OidcConfigurationProvider.issuer("https://example.com")
* .clientId("client-id")
* .clientSecret("client-secret")
* .build();
* </pre>
* @param issuer the <a href="http://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return a {@link ClientRegistration.Builder} that was initialized by the OpenID Provider Configuration.
*/
public static ClientRegistration.Builder issuer(String issuer) {
String openidConfiguration = getOpenidConfiguration(issuer);
OIDCProviderMetadata metadata = parse(openidConfiguration);
String metadataIssuer = metadata.getIssuer().getValue();
if (!issuer.equals(metadataIssuer)) {
throw new IllegalStateException("The Issuer \"" + metadataIssuer + "\" provided in the OpenID Configuration did not match the requested issuer \"" + issuer + "\"");
}
String name = URI.create(issuer).getHost();
ClientAuthenticationMethod method = getClientAuthenticationMethod(issuer, metadata.getTokenEndpointAuthMethods());
List<GrantType> grantTypes = metadata.getGrantTypes();
// If null, the default includes authorization_code
if (grantTypes != null && !grantTypes.contains(GrantType.AUTHORIZATION_CODE)) {
throw new IllegalArgumentException("Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \"" + issuer + "\" returned a configuration of " + grantTypes);
}
List<String> scopes = getScopes(metadata);
return ClientRegistration.withRegistrationId(name)
.userNameAttributeName(IdTokenClaimNames.SUB)
.scope(scopes)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.clientAuthenticationMethod(method)
.redirectUriTemplate("{baseUrl}/{action}/oauth2/code/{registrationId}")
.authorizationUri(metadata.getAuthorizationEndpointURI().toASCIIString())
.jwkSetUri(metadata.getJWKSetURI().toASCIIString())
.userInfoUri(metadata.getUserInfoEndpointURI().toASCIIString())
.tokenUri(metadata.getTokenEndpointURI().toASCIIString())
.clientName(issuer);
}
private static String getOpenidConfiguration(String issuer) {
RestTemplate rest = new RestTemplate();
try {
return rest.getForObject(issuer + "/.well-known/openid-configuration", String.class);
} catch(RuntimeException e) {
throw new IllegalArgumentException("Unable to resolve the OpenID Configuration with the provided Issuer of \"" + issuer + "\"", e);
}
}
private static ClientAuthenticationMethod getClientAuthenticationMethod(String issuer, List<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> metadataAuthMethods) {
if (metadataAuthMethods == null || metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
// If null, the default includes client_secret_basic
return ClientAuthenticationMethod.BASIC;
}
if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_POST)) {
return ClientAuthenticationMethod.POST;
}
throw new IllegalArgumentException("Only ClientAuthenticationMethod.BASIC and ClientAuthenticationMethod.POST are supported. The issuer \"" + issuer + "\" returned a configuration of " + metadataAuthMethods);
}
private static List<String> getScopes(OIDCProviderMetadata metadata) {
Scope scope = metadata.getScopes();
if (scope == null) {
// If null, default to "openid" which must be supported
return Collections.singletonList(OidcScopes.OPENID);
} else {
return scope.toStringList();
}
}
private static OIDCProviderMetadata parse(String body) {
try {
return OIDCProviderMetadata.parse(body);
}
catch (ParseException e) {
throw new RuntimeException(e);
}
}
private OidcConfigurationProvider() {}
}
@@ -24,43 +24,23 @@ import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.DelegatingReactiveAuthenticationManager;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager;
import org.springframework.security.authorization.AuthorityReactiveAuthorizationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.InMemoryReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginReactiveAuthenticationManager;
import org.springframework.security.oauth2.client.endpoint.WebClientReactiveAuthorizationCodeTokenResponseClient;
import org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeReactiveAuthenticationManager;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcReactiveOAuth2UserService;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.userinfo.DefaultReactiveOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectWebFilter;
import org.springframework.security.oauth2.client.web.ServerOAuth2LoginAuthenticationTokenConverter;
import org.springframework.security.web.server.DelegatingServerAuthenticationEntryPoint;
import org.springframework.security.web.server.MatcherSecurityWebFilterChain;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.ServerFormLoginAuthenticationConverter;
import org.springframework.security.web.server.ServerHttpBasicAuthenticationConverter;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationEntryPoint;
@@ -99,12 +79,10 @@ import org.springframework.security.web.server.savedrequest.WebSessionServerRequ
import org.springframework.security.web.server.ui.LoginPageGeneratingWebFilter;
import org.springframework.security.web.server.ui.LogoutPageGeneratingWebFilter;
import org.springframework.security.web.server.util.matcher.MediaTypeServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.PathPatternParserServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcherEntry;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
@@ -183,12 +161,8 @@ public class ServerHttpSecurity {
private FormLoginSpec formLogin;
private OAuth2LoginSpec oauth2Login;
private LogoutSpec logout = new LogoutSpec();
private LoginPageSpec loginPage = new LoginPageSpec();
private ReactiveAuthenticationManager authenticationManager;
private ServerSecurityContextRepository securityContextRepository = new WebSessionServerSecurityContextRepository();
@@ -201,8 +175,6 @@ public class ServerHttpSecurity {
private List<WebFilter> webFilters = new ArrayList<>();
private ApplicationContext context;
private Throwable built;
/**
@@ -210,7 +182,6 @@ public class ServerHttpSecurity {
*
* @param matcher the ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
* Default is all requests.
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity securityMatcher(ServerWebExchangeMatcher matcher) {
Assert.notNull(matcher, "matcher cannot be null");
@@ -347,107 +318,6 @@ public class ServerHttpSecurity {
return this.formLogin;
}
public OAuth2LoginSpec oauth2Login() {
if (this.oauth2Login == null) {
this.oauth2Login = new OAuth2LoginSpec();
}
return this.oauth2Login;
}
public class OAuth2LoginSpec {
private ReactiveClientRegistrationRepository clientRegistrationRepository;
private ReactiveOAuth2AuthorizedClientService authorizedClientService;
public OAuth2LoginSpec clientRegistrationRepository(ReactiveClientRegistrationRepository clientRegistrationRepository) {
this.clientRegistrationRepository = clientRegistrationRepository;
return this;
}
public OAuth2LoginSpec authorizedClientService(ReactiveOAuth2AuthorizedClientService authorizedClientService) {
this.authorizedClientService = authorizedClientService;
return this;
}
protected void configure(ServerHttpSecurity http) {
ReactiveClientRegistrationRepository clientRegistrationRepository = getClientRegistrationRepository();
ReactiveOAuth2AuthorizedClientService authorizedClientService = getAuthorizedClientService();
OAuth2AuthorizationRequestRedirectWebFilter oauthRedirectFilter = new OAuth2AuthorizationRequestRedirectWebFilter(clientRegistrationRepository);
WebClientReactiveAuthorizationCodeTokenResponseClient client = new WebClientReactiveAuthorizationCodeTokenResponseClient();
ReactiveOAuth2UserService userService = new DefaultReactiveOAuth2UserService();
ReactiveAuthenticationManager manager = new OAuth2LoginReactiveAuthenticationManager(client, userService,
authorizedClientService);
boolean oidcAuthenticationProviderEnabled = ClassUtils.isPresent(
"org.springframework.security.oauth2.jwt.JwtDecoder", this.getClass().getClassLoader());
if (oidcAuthenticationProviderEnabled) {
OidcAuthorizationCodeReactiveAuthenticationManager oidc = new OidcAuthorizationCodeReactiveAuthenticationManager(client, new OidcReactiveOAuth2UserService(), authorizedClientService);
manager = new DelegatingReactiveAuthenticationManager(oidc, manager);
}
AuthenticationWebFilter authenticationFilter = new AuthenticationWebFilter(manager);
authenticationFilter.setRequiresAuthenticationMatcher(new PathPatternParserServerWebExchangeMatcher("/login/oauth2/code/{registrationId}"));
authenticationFilter.setAuthenticationConverter(new ServerOAuth2LoginAuthenticationTokenConverter(clientRegistrationRepository));
RedirectServerAuthenticationSuccessHandler redirectHandler = new RedirectServerAuthenticationSuccessHandler();
authenticationFilter.setAuthenticationSuccessHandler(redirectHandler);
authenticationFilter.setAuthenticationFailureHandler(new ServerAuthenticationFailureHandler() {
@Override
public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange,
AuthenticationException exception) {
return Mono.error(exception);
}
});
authenticationFilter.setSecurityContextRepository(new WebSessionServerSecurityContextRepository());
MediaTypeServerWebExchangeMatcher htmlMatcher = new MediaTypeServerWebExchangeMatcher(
MediaType.TEXT_HTML);
htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
Map<String, String> urlToText = http.oauth2Login.getLinks();
if (urlToText.size() == 1) {
http.defaultEntryPoints.add(new DelegateEntry(htmlMatcher, new RedirectServerAuthenticationEntryPoint(urlToText.keySet().iterator().next())));
} else {
http.defaultEntryPoints.add(new DelegateEntry(htmlMatcher, new RedirectServerAuthenticationEntryPoint("/login")));
}
http.addFilterAt(oauthRedirectFilter, SecurityWebFiltersOrder.HTTP_BASIC);
http.addFilterAt(authenticationFilter, SecurityWebFiltersOrder.AUTHENTICATION);
}
private Map<String, String> getLinks() {
Iterable<ClientRegistration> registrations = getBeanOrNull(ResolvableType.forClassWithGenerics(Iterable.class, ClientRegistration.class));
if (registrations == null) {
return Collections.emptyMap();
}
Map<String, String> result = new HashMap<>();
registrations.iterator().forEachRemaining(r -> {
result.put("/oauth2/authorization/" + r.getRegistrationId(), r.getClientName());
});
return result;
}
private ReactiveClientRegistrationRepository getClientRegistrationRepository() {
if (this.clientRegistrationRepository == null) {
this.clientRegistrationRepository = getBeanOrNull(ReactiveClientRegistrationRepository.class);
}
return this.clientRegistrationRepository;
}
private ReactiveOAuth2AuthorizedClientService getAuthorizedClientService() {
if (this.authorizedClientService == null) {
this.authorizedClientService = getBeanOrNull(ReactiveOAuth2AuthorizedClientService.class);
}
if (this.authorizedClientService == null) {
this.authorizedClientService = new InMemoryReactiveOAuth2AuthorizedClientService(getClientRegistrationRepository());
}
return this.authorizedClientService;
}
private OAuth2LoginSpec() {}
}
/**
* Configures HTTP Response Headers. The default headers are:
*
@@ -640,12 +510,12 @@ public class ServerHttpSecurity {
if(this.securityContextRepository != null) {
this.formLogin.securityContextRepository(this.securityContextRepository);
}
if(this.formLogin.authenticationEntryPoint == null) {
this.webFilters.add(new OrderedWebFilter(new LoginPageGeneratingWebFilter(), SecurityWebFiltersOrder.LOGIN_PAGE_GENERATING.getOrder()));
this.webFilters.add(new OrderedWebFilter(new LogoutPageGeneratingWebFilter(), SecurityWebFiltersOrder.LOGOUT_PAGE_GENERATING.getOrder()));
}
this.formLogin.configure(this);
}
if (this.oauth2Login != null) {
this.oauth2Login.configure(this);
}
this.loginPage.configure(this);
if(this.logout != null) {
this.logout.configure(this);
}
@@ -658,8 +528,8 @@ public class ServerHttpSecurity {
exceptionTranslationWebFilter.setAuthenticationEntryPoint(
authenticationEntryPoint);
}
if(this.accessDeniedHandler != null) {
exceptionTranslationWebFilter.setAccessDeniedHandler(this.accessDeniedHandler);
if(accessDeniedHandler != null) {
exceptionTranslationWebFilter.setAccessDeniedHandler(accessDeniedHandler);
}
this.addFilterAt(exceptionTranslationWebFilter, SecurityWebFiltersOrder.EXCEPTION_TRANSLATION);
this.authorizeExchange.configure(this);
@@ -719,7 +589,7 @@ public class ServerHttpSecurity {
return new OrderedWebFilter(result, SecurityWebFiltersOrder.REACTOR_CONTEXT.getOrder());
}
protected ServerHttpSecurity() {}
private ServerHttpSecurity() {}
/**
* Configures authorization
@@ -744,7 +614,7 @@ public class ServerHttpSecurity {
/**
* Disables authorization.
* @return the {@link Access} to continue configuring
* @return the {@link ServerHttpSecurity} to continue configuring
*/
@Override
public Access anyExchange() {
@@ -1095,8 +965,6 @@ public class ServerHttpSecurity {
private ServerAuthenticationEntryPoint authenticationEntryPoint;
private boolean isEntryPointExplicit;
private ServerWebExchangeMatcher requiresAuthenticationMatcher;
private ServerAuthenticationFailureHandler authenticationFailureHandler;
@@ -1219,10 +1087,7 @@ public class ServerHttpSecurity {
protected void configure(ServerHttpSecurity http) {
if(this.authenticationEntryPoint == null) {
this.isEntryPointExplicit = false;
loginPage("/login");
} else {
this.isEntryPointExplicit = true;
}
if(http.requestCache != null) {
ServerRequestCache requestCache = http.requestCache.requestCache;
@@ -1249,35 +1114,6 @@ public class ServerHttpSecurity {
}
}
private class LoginPageSpec {
protected void configure(ServerHttpSecurity http) {
if (http.authenticationEntryPoint != null) {
return;
}
if (http.formLogin != null && http.formLogin.isEntryPointExplicit) {
return;
}
LoginPageGeneratingWebFilter loginPage = null;
if (http.formLogin != null && !http.formLogin.isEntryPointExplicit) {
loginPage = new LoginPageGeneratingWebFilter();
loginPage.setFormLoginEnabled(true);
}
if (http.oauth2Login != null) {
Map<String, String> urlToText = http.oauth2Login.getLinks();
if (loginPage == null) {
loginPage = new LoginPageGeneratingWebFilter();
}
loginPage.setOauth2AuthenticationUrlToClientName(urlToText);
}
if (loginPage != null) {
http.addFilterAt(loginPage, SecurityWebFiltersOrder.LOGIN_PAGE_GENERATING);
http.addFilterAt(new LogoutPageGeneratingWebFilter(), SecurityWebFiltersOrder.LOGOUT_PAGE_GENERATING);
}
}
private LoginPageSpec() {}
}
/**
* Configures HTTP Response Headers.
*
@@ -1421,7 +1257,7 @@ public class ServerHttpSecurity {
/**
* Disables frame options response header
* @return the {@link HeaderSpec} to continue configuring
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public HeaderSpec disable() {
HeaderSpec.this.writers.remove(HeaderSpec.this.frameOptions);
@@ -1439,21 +1275,17 @@ public class ServerHttpSecurity {
/**
* Configures the max age. Default is one year.
* @param maxAge the max age
* @return the {@link HstsSpec} to continue configuring
*/
public HstsSpec maxAge(Duration maxAge) {
public void maxAge(Duration maxAge) {
HeaderSpec.this.hsts.setMaxAge(maxAge);
return this;
}
/**
* Configures if subdomains should be included. Default is true
* @param includeSubDomains if subdomains should be included
* @return the {@link HstsSpec} to continue configuring
*/
public HstsSpec includeSubdomains(boolean includeSubDomains) {
public void includeSubdomains(boolean includeSubDomains) {
HeaderSpec.this.hsts.setIncludeSubDomains(includeSubDomains);
return this;
}
/**
@@ -1466,7 +1298,7 @@ public class ServerHttpSecurity {
/**
* Disables strict transport security response header
* @return the {@link HeaderSpec} to continue configuring
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public HeaderSpec disable() {
HeaderSpec.this.writers.remove(HeaderSpec.this.hsts);
@@ -1483,7 +1315,7 @@ public class ServerHttpSecurity {
public class XssProtectionSpec {
/**
* Disables the x-xss-protection response header
* @return the {@link HeaderSpec} to continue configuring
* @return
*/
public HeaderSpec disable() {
HeaderSpec.this.writers.remove(HeaderSpec.this.xss);
@@ -1512,7 +1344,7 @@ public class ServerHttpSecurity {
/**
* Configures the logout handler. Default is {@code SecurityContextServerLogoutHandler}
* @param logoutHandler
* @return the {@link LogoutSpec} to configure
* @return
*/
public LogoutSpec logoutHandler(ServerLogoutHandler logoutHandler) {
this.logoutWebFilter.setLogoutHandler(logoutHandler);
@@ -1570,27 +1402,6 @@ public class ServerHttpSecurity {
private LogoutSpec() {}
}
private <T> T getBeanOrNull(Class<T> beanClass) {
return getBeanOrNull(ResolvableType.forClass(beanClass));
}
private <T> T getBeanOrNull(ResolvableType type) {
if (this.context == null) {
return null;
}
String[] names = this.context.getBeanNamesForType(type);
if (names.length == 1) {
return (T) this.context.getBean(names[0]);
}
return null;
}
protected void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
private static class OrderedWebFilter implements WebFilter, Ordered {
private final WebFilter webFilter;
private final int order;
@@ -110,7 +110,7 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
/**
* @param element
* @param parserContext
* @return the {@link BeanDefinition}
* @return
*/
public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();
@@ -1,5 +1,4 @@
http\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-5.1.xsd
http\://www.springframework.org/schema/security/spring-security-5.1.xsd=org/springframework/security/config/spring-security-5.1.xsd
http\://www.springframework.org/schema/security/spring-security.xsd=org/springframework/security/config/spring-security-5.0.xsd
http\://www.springframework.org/schema/security/spring-security-5.0.xsd=org/springframework/security/config/spring-security-5.0.xsd
http\://www.springframework.org/schema/security/spring-security-4.2.xsd=org/springframework/security/config/spring-security-4.2.xsd
http\://www.springframework.org/schema/security/spring-security-4.1.xsd=org/springframework/security/config/spring-security-4.1.xsd
@@ -1,909 +0,0 @@
namespace a = "http://relaxng.org/ns/compatibility/annotations/1.0"
datatypes xsd = "http://www.w3.org/2001/XMLSchema-datatypes"
default namespace = "http://www.springframework.org/schema/security"
start = http | ldap-server | authentication-provider | ldap-authentication-provider | any-user-service | ldap-server | ldap-authentication-provider
hash =
## Defines the hashing algorithm used on user passwords. Bcrypt is recommended.
attribute hash {"bcrypt"}
base64 =
## Whether a string should be base64 encoded
attribute base64 {xsd:boolean}
request-matcher =
## Defines the strategy use for matching incoming requests. Currently the options are 'mvc' (for Spring MVC matcher), 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions.
attribute request-matcher {"mvc" | "ant" | "regex" | "ciRegex"}
port =
## Specifies an IP port number. Used to configure an embedded LDAP server, for example.
attribute port { xsd:positiveInteger }
url =
## Specifies a URL.
attribute url { xsd:token }
id =
## A bean identifier, used for referring to the bean elsewhere in the context.
attribute id {xsd:token}
name =
## A bean identifier, used for referring to the bean elsewhere in the context.
attribute name {xsd:token}
ref =
## Defines a reference to a Spring bean Id.
attribute ref {xsd:token}
cache-ref =
## Defines a reference to a cache for use with a UserDetailsService.
attribute cache-ref {xsd:token}
user-service-ref =
## A reference to a user-service (or UserDetailsService bean) Id
attribute user-service-ref {xsd:token}
authentication-manager-ref =
## A reference to an AuthenticationManager bean
attribute authentication-manager-ref {xsd:token}
data-source-ref =
## A reference to a DataSource bean
attribute data-source-ref {xsd:token}
debug =
## Enables Spring Security debugging infrastructure. This will provide human-readable (multi-line) debugging information to monitor requests coming into the security filters. This may include sensitive information, such as request parameters or headers, and should only be used in a development environment.
element debug {empty}
password-encoder =
## element which defines a password encoding strategy. Used by an authentication provider to convert submitted passwords to hashed versions, for example.
element password-encoder {password-encoder.attlist}
password-encoder.attlist &=
ref | (hash)
role-prefix =
## A non-empty string prefix that will be added to role strings loaded from persistent storage (e.g. "ROLE_"). Use the value "none" for no prefix in cases where the default is non-empty.
attribute role-prefix {xsd:token}
use-expressions =
## Enables the use of expressions in the 'access' attributes in <intercept-url> elements rather than the traditional list of configuration attributes. Defaults to 'true'. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to 'true', access will be granted.
attribute use-expressions {xsd:boolean}
ldap-server =
## Defines an LDAP server location or starts an embedded server. The url indicates the location of a remote server. If no url is given, an embedded server will be started, listening on the supplied port number. The port is optional and defaults to 33389. A Spring LDAP ContextSource bean will be registered for the server with the id supplied.
element ldap-server {ldap-server.attlist}
ldap-server.attlist &= id?
ldap-server.attlist &= (url | port)?
ldap-server.attlist &=
## Username (DN) of the "manager" user identity which will be used to authenticate to a (non-embedded) LDAP server. If omitted, anonymous access will be used.
attribute manager-dn {xsd:string}?
ldap-server.attlist &=
## The password for the manager DN. This is required if the manager-dn is specified.
attribute manager-password {xsd:string}?
ldap-server.attlist &=
## Explicitly specifies an ldif file resource to load into an embedded LDAP server. The default is classpath*:*.ldiff
attribute ldif { xsd:string }?
ldap-server.attlist &=
## Optional root suffix for the embedded LDAP server. Default is "dc=springframework,dc=org"
attribute root { xsd:string }?
ldap-server-ref-attribute =
## The optional server to use. If omitted, and a default LDAP server is registered (using <ldap-server> with no Id), that server will be used.
attribute server-ref {xsd:token}
group-search-filter-attribute =
## Group search filter. Defaults to (uniqueMember={0}). The substituted parameter is the DN of the user.
attribute group-search-filter {xsd:token}
group-search-base-attribute =
## Search base for group membership searches. Defaults to "" (searching from the root).
attribute group-search-base {xsd:token}
user-search-filter-attribute =
## The LDAP filter used to search for users (optional). For example "(uid={0})". The substituted parameter is the user's login name.
attribute user-search-filter {xsd:token}
user-search-base-attribute =
## Search base for user searches. Defaults to "". Only used with a 'user-search-filter'.
attribute user-search-base {xsd:token}
group-role-attribute-attribute =
## The LDAP attribute name which contains the role name which will be used within Spring Security. Defaults to "cn".
attribute group-role-attribute {xsd:token}
user-details-class-attribute =
## Allows the objectClass of the user entry to be specified. If set, the framework will attempt to load standard attributes for the defined class into the returned UserDetails object
attribute user-details-class {"person" | "inetOrgPerson"}
user-context-mapper-attribute =
## Allows explicit customization of the loaded user object by specifying a UserDetailsContextMapper bean which will be called with the context information from the user's directory entry
attribute user-context-mapper-ref {xsd:token}
ldap-user-service =
## This element configures a LdapUserDetailsService which is a combination of a FilterBasedLdapUserSearch and a DefaultLdapAuthoritiesPopulator.
element ldap-user-service {ldap-us.attlist}
ldap-us.attlist &= id?
ldap-us.attlist &=
ldap-server-ref-attribute?
ldap-us.attlist &=
user-search-filter-attribute?
ldap-us.attlist &=
user-search-base-attribute?
ldap-us.attlist &=
group-search-filter-attribute?
ldap-us.attlist &=
group-search-base-attribute?
ldap-us.attlist &=
group-role-attribute-attribute?
ldap-us.attlist &=
cache-ref?
ldap-us.attlist &=
role-prefix?
ldap-us.attlist &=
(user-details-class-attribute | user-context-mapper-attribute)?
ldap-authentication-provider =
## Sets up an ldap authentication provider
element ldap-authentication-provider {ldap-ap.attlist, password-compare-element?}
ldap-ap.attlist &=
ldap-server-ref-attribute?
ldap-ap.attlist &=
user-search-base-attribute?
ldap-ap.attlist &=
user-search-filter-attribute?
ldap-ap.attlist &=
group-search-base-attribute?
ldap-ap.attlist &=
group-search-filter-attribute?
ldap-ap.attlist &=
group-role-attribute-attribute?
ldap-ap.attlist &=
## A specific pattern used to build the user's DN, for example "uid={0},ou=people". The key "{0}" must be present and will be substituted with the username.
attribute user-dn-pattern {xsd:token}?
ldap-ap.attlist &=
role-prefix?
ldap-ap.attlist &=
(user-details-class-attribute | user-context-mapper-attribute)?
password-compare-element =
## Specifies that an LDAP provider should use an LDAP compare operation of the user's password to authenticate the user
element password-compare {password-compare.attlist, password-encoder?}
password-compare.attlist &=
## The attribute in the directory which contains the user password. Defaults to "userPassword".
attribute password-attribute {xsd:token}?
password-compare.attlist &=
hash?
intercept-methods =
## Can be used inside a bean definition to add a security interceptor to the bean and set up access configuration attributes for the bean's methods
element intercept-methods {intercept-methods.attlist, protect+}
intercept-methods.attlist &=
## Optional AccessDecisionManager bean ID to be used by the created method security interceptor.
attribute access-decision-manager-ref {xsd:token}?
protect =
## Defines a protected method and the access control configuration attributes that apply to it. We strongly advise you NOT to mix "protect" declarations with any services provided "global-method-security".
element protect {protect.attlist, empty}
protect.attlist &=
## A method name
attribute method {xsd:token}
protect.attlist &=
## Access configuration attributes list that applies to the method, e.g. "ROLE_A,ROLE_B".
attribute access {xsd:token}
method-security-metadata-source =
## Creates a MethodSecurityMetadataSource instance
element method-security-metadata-source {msmds.attlist, protect+}
msmds.attlist &= id?
msmds.attlist &= use-expressions?
global-method-security =
## Provides method security for all beans registered in the Spring application context. Specifically, beans will be scanned for matches with the ordered list of "protect-pointcut" sub-elements, Spring Security annotations and/or. Where there is a match, the beans will automatically be proxied and security authorization applied to the methods accordingly. If you use and enable all four sources of method security metadata (ie "protect-pointcut" declarations, expression annotations, @Secured and also JSR250 security annotations), the metadata sources will be queried in that order. In practical terms, this enables you to use XML to override method security metadata expressed in annotations. If using annotations, the order of precedence is EL-based (@PreAuthorize etc.), @Secured and finally JSR-250.
element global-method-security {global-method-security.attlist, (pre-post-annotation-handling | expression-handler)?, protect-pointcut*, after-invocation-provider*}
global-method-security.attlist &=
## Specifies whether the use of Spring Security's pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) should be enabled for this application context. Defaults to "disabled".
attribute pre-post-annotations {"disabled" | "enabled" }?
global-method-security.attlist &=
## Specifies whether the use of Spring Security's @Secured annotations should be enabled for this application context. Defaults to "disabled".
attribute secured-annotations {"disabled" | "enabled" }?
global-method-security.attlist &=
## Specifies whether JSR-250 style attributes are to be used (for example "RolesAllowed"). This will require the javax.annotation.security classes on the classpath. Defaults to "disabled".
attribute jsr250-annotations {"disabled" | "enabled" }?
global-method-security.attlist &=
## Optional AccessDecisionManager bean ID to override the default used for method security.
attribute access-decision-manager-ref {xsd:token}?
global-method-security.attlist &=
## Optional RunAsmanager implementation which will be used by the configured MethodSecurityInterceptor
attribute run-as-manager-ref {xsd:token}?
global-method-security.attlist &=
## Allows the advice "order" to be set for the method security interceptor.
attribute order {xsd:token}?
global-method-security.attlist &=
## If true, class based proxying will be used instead of interface based proxying.
attribute proxy-target-class {xsd:boolean}?
global-method-security.attlist &=
## Can be used to specify that AspectJ should be used instead of the default Spring AOP. If set, secured classes must be woven with the AnnotationSecurityAspect from the spring-security-aspects module.
attribute mode {"aspectj"}?
global-method-security.attlist &=
## An external MethodSecurityMetadataSource instance can be supplied which will take priority over other sources (such as the default annotations).
attribute metadata-source-ref {xsd:token}?
global-method-security.attlist &=
authentication-manager-ref?
after-invocation-provider =
## Allows addition of extra AfterInvocationProvider beans which should be called by the MethodSecurityInterceptor created by global-method-security.
element after-invocation-provider {ref}
pre-post-annotation-handling =
## Allows the default expression-based mechanism for handling Spring Security's pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) to be replace entirely. Only applies if these annotations are enabled.
element pre-post-annotation-handling {invocation-attribute-factory, pre-invocation-advice, post-invocation-advice}
invocation-attribute-factory =
## Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods.
element invocation-attribute-factory {ref}
pre-invocation-advice =
## Customizes the PreInvocationAuthorizationAdviceVoter with the ref as the PreInvocationAuthorizationAdviceVoter for the <pre-post-annotation-handling> element.
element pre-invocation-advice {ref}
post-invocation-advice =
## Customizes the PostInvocationAdviceProvider with the ref as the PostInvocationAuthorizationAdvice for the <pre-post-annotation-handling> element.
element post-invocation-advice {ref}
expression-handler =
## Defines the SecurityExpressionHandler instance which will be used if expression-based access-control is enabled. A default implementation (with no ACL support) will be used if not supplied.
element expression-handler {ref}
protect-pointcut =
## Defines a protected pointcut and the access control configuration attributes that apply to it. Every bean registered in the Spring application context that provides a method that matches the pointcut will receive security authorization.
element protect-pointcut {protect-pointcut.attlist, empty}
protect-pointcut.attlist &=
## An AspectJ expression, including the 'execution' keyword. For example, 'execution(int com.foo.TargetObject.countLength(String))' (without the quotes).
attribute expression {xsd:string}
protect-pointcut.attlist &=
## Access configuration attributes list that applies to all methods matching the pointcut, e.g. "ROLE_A,ROLE_B"
attribute access {xsd:token}
websocket-message-broker =
## Allows securing a Message Broker. There are two modes. If no id is specified: ensures that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver; ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel; and that a ChannelSecurityInterceptor is registered with the clientInboundChannel. If the id is specified, creates a ChannelSecurityInterceptor that can be manually registered with the clientInboundChannel.
element websocket-message-broker { websocket-message-broker.attrlist, (intercept-message* & expression-handler?) }
websocket-message-broker.attrlist &=
## A bean identifier, used for referring to the bean elsewhere in the context. If specified, explicit configuration within clientInboundChannel is required. If not specified, ensures that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver; ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel; and that a ChannelSecurityInterceptor is registered with the clientInboundChannel.
attribute id {xsd:token}?
websocket-message-broker.attrlist &=
## Disables the requirement for CSRF token to be present in the Stomp headers (default false). Changing the default is useful if it is necessary to allow other origins to make SockJS connections.
attribute same-origin-disabled {xsd:boolean}?
intercept-message =
## Creates an authorization rule for a websocket message.
element intercept-message {intercept-message.attrlist}
intercept-message.attrlist &=
## The destination ant pattern which will be mapped to the access attribute. For example, /** matches any message with a destination, /admin/** matches any message that has a destination that starts with admin.
attribute pattern {xsd:token}?
intercept-message.attrlist &=
## The access configuration attributes that apply for the configured message. For example, permitAll grants access to anyone, hasRole('ROLE_ADMIN') requires the user have the role 'ROLE_ADMIN'.
attribute access {xsd:token}?
intercept-message.attrlist &=
## The type of message to match on. Valid values are defined in SimpMessageType (i.e. CONNECT, CONNECT_ACK, HEARTBEAT, MESSAGE, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, DISCONNECT_ACK, OTHER).
attribute type {"CONNECT" | "CONNECT_ACK" | "HEARTBEAT" | "MESSAGE" | "SUBSCRIBE"| "UNSUBSCRIBE" | "DISCONNECT" | "DISCONNECT_ACK" | "OTHER"}?
http-firewall =
## Allows a custom instance of HttpFirewall to be injected into the FilterChainProxy created by the namespace.
element http-firewall {ref}
http =
## Container element for HTTP security configuration. Multiple elements can now be defined, each with a specific pattern to which the enclosed security configuration applies. A pattern can also be configured to bypass Spring Security's filters completely by setting the "security" attribute to "none".
element http {http.attlist, (intercept-url* & access-denied-handler? & form-login? & openid-login? & x509? & jee? & http-basic? & logout? & session-management & remember-me? & anonymous? & port-mappings & custom-filter* & request-cache? & expression-handler? & headers? & csrf? & cors?) }
http.attlist &=
## The request URL pattern which will be mapped to the filter chain created by this <http> element. If omitted, the filter chain will match all requests.
attribute pattern {xsd:token}?
http.attlist &=
## When set to 'none', requests matching the pattern attribute will be ignored by Spring Security. No security filters will be applied and no SecurityContext will be available. If set, the <http> element must be empty, with no children.
attribute security {"none"}?
http.attlist &=
## Allows a RequestMatcher instance to be used, as an alternative to pattern-matching.
attribute request-matcher-ref { xsd:token }?
http.attlist &=
## A legacy attribute which automatically registers a login form, BASIC authentication and a logout URL and logout services. If unspecified, defaults to "false". We'd recommend you avoid using this and instead explicitly configure the services you require.
attribute auto-config {xsd:boolean}?
http.attlist &=
use-expressions?
http.attlist &=
## Controls the eagerness with which an HTTP session is created by Spring Security classes. If not set, defaults to "ifRequired". If "stateless" is used, this implies that the application guarantees that it will not create a session. This differs from the use of "never" which means that Spring Security will not create a session, but will make use of one if the application does.
attribute create-session {"ifRequired" | "always" | "never" | "stateless"}?
http.attlist &=
## A reference to a SecurityContextRepository bean. This can be used to customize how the SecurityContext is stored between requests.
attribute security-context-repository-ref {xsd:token}?
http.attlist &=
request-matcher?
http.attlist &=
## Provides versions of HttpServletRequest security methods such as isUserInRole() and getPrincipal() which are implemented by accessing the Spring SecurityContext. Defaults to "true".
attribute servlet-api-provision {xsd:boolean}?
http.attlist &=
## If available, runs the request as the Subject acquired from the JaasAuthenticationToken. Defaults to "false".
attribute jaas-api-provision {xsd:boolean}?
http.attlist &=
## Optional attribute specifying the ID of the AccessDecisionManager implementation which should be used for authorizing HTTP requests.
attribute access-decision-manager-ref {xsd:token}?
http.attlist &=
## Optional attribute specifying the realm name that will be used for all authentication features that require a realm name (eg BASIC and Digest authentication). If unspecified, defaults to "Spring Security Application".
attribute realm {xsd:token}?
http.attlist &=
## Allows a customized AuthenticationEntryPoint to be set on the ExceptionTranslationFilter.
attribute entry-point-ref {xsd:token}?
http.attlist &=
## Corresponds to the observeOncePerRequest property of FilterSecurityInterceptor. Defaults to "true"
attribute once-per-request {xsd:boolean}?
http.attlist &=
## Prevents the jsessionid parameter from being added to rendered URLs. Defaults to "true" (rewriting is disabled).
attribute disable-url-rewriting {xsd:boolean}?
http.attlist &=
## Exposes the list of filters defined by this configuration under this bean name in the application context.
name?
http.attlist &=
authentication-manager-ref?
access-denied-handler =
## Defines the access-denied strategy that should be used. An access denied page can be defined or a reference to an AccessDeniedHandler instance.
element access-denied-handler {access-denied-handler.attlist, empty}
access-denied-handler.attlist &= (ref | access-denied-handler-page)
access-denied-handler-page =
## The access denied page that an authenticated user will be redirected to if they request a page which they don't have the authority to access.
attribute error-page {xsd:token}
intercept-url =
## Specifies the access attributes and/or filter list for a particular set of URLs.
element intercept-url {intercept-url.attlist, empty}
intercept-url.attlist &=
(pattern | request-matcher-ref)
intercept-url.attlist &=
## The access configuration attributes that apply for the configured path.
attribute access {xsd:token}?
intercept-url.attlist &=
## The HTTP Method for which the access configuration attributes should apply. If not specified, the attributes will apply to any method.
attribute method {"GET" | "DELETE" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "PATCH" | "TRACE"}?
intercept-url.attlist &=
## The filter list for the path. Currently can be set to "none" to remove a path from having any filters applied. The full filter stack (consisting of all filters created by the namespace configuration, and any added using 'custom-filter'), will be applied to any other paths.
attribute filters {"none"}?
intercept-url.attlist &=
## Used to specify that a URL must be accessed over http or https, or that there is no preference. The value should be "http", "https" or "any", respectively.
attribute requires-channel {xsd:token}?
intercept-url.attlist &=
## The path to the servlet. This attribute is only applicable when 'request-matcher' is 'mvc'. In addition, the value is only required in the following 2 use cases: 1) There are 2 or more HttpServlet's registered in the ServletContext that have mappings starting with '/' and are different; 2) The pattern starts with the same value of a registered HttpServlet path, excluding the default (root) HttpServlet '/'.
attribute servlet-path {xsd:token}?
logout =
## Incorporates a logout processing filter. Most web applications require a logout filter, although you may not require one if you write a controller to provider similar logic.
element logout {logout.attlist, empty}
logout.attlist &=
## Specifies the URL that will cause a logout. Spring Security will initialize a filter that responds to this particular URL. Defaults to /logout if unspecified.
attribute logout-url {xsd:token}?
logout.attlist &=
## Specifies the URL to display once the user has logged out. If not specified, defaults to <form-login-login-page>/?logout (i.e. /login?logout).
attribute logout-success-url {xsd:token}?
logout.attlist &=
## Specifies whether a logout also causes HttpSession invalidation, which is generally desirable. If unspecified, defaults to true.
attribute invalidate-session {xsd:boolean}?
logout.attlist &=
## A reference to a LogoutSuccessHandler implementation which will be used to determine the destination to which the user is taken after logging out.
attribute success-handler-ref {xsd:token}?
logout.attlist &=
## A comma-separated list of the names of cookies which should be deleted when the user logs out
attribute delete-cookies {xsd:token}?
request-cache =
## Allow the RequestCache used for saving requests during the login process to be set
element request-cache {ref}
form-login =
## Sets up a form login configuration for authentication with a username and password
element form-login {form-login.attlist, empty}
form-login.attlist &=
## The URL that the login form is posted to. If unspecified, it defaults to /login.
attribute login-processing-url {xsd:token}?
form-login.attlist &=
## The name of the request parameter which contains the username. Defaults to 'username'.
attribute username-parameter {xsd:token}?
form-login.attlist &=
## The name of the request parameter which contains the password. Defaults to 'password'.
attribute password-parameter {xsd:token}?
form-login.attlist &=
## The URL that will be redirected to after successful authentication, if the user's previous action could not be resumed. This generally happens if the user visits a login page without having first requested a secured operation that triggers authentication. If unspecified, defaults to the root of the application.
attribute default-target-url {xsd:token}?
form-login.attlist &=
## Whether the user should always be redirected to the default-target-url after login.
attribute always-use-default-target {xsd:boolean}?
form-login.attlist &=
## The URL for the login page. If no login URL is specified, Spring Security will automatically create a login URL at GET /login and a corresponding filter to render that login URL when requested.
attribute login-page {xsd:token}?
form-login.attlist &=
## The URL for the login failure page. If no login failure URL is specified, Spring Security will automatically create a failure login URL at /login?error and a corresponding filter to render that login failure URL when requested.
attribute authentication-failure-url {xsd:token}?
form-login.attlist &=
## Reference to an AuthenticationSuccessHandler bean which should be used to handle a successful authentication request. Should not be used in combination with default-target-url (or always-use-default-target-url) as the implementation should always deal with navigation to the subsequent destination
attribute authentication-success-handler-ref {xsd:token}?
form-login.attlist &=
## Reference to an AuthenticationFailureHandler bean which should be used to handle a failed authentication request. Should not be used in combination with authentication-failure-url as the implementation should always deal with navigation to the subsequent destination
attribute authentication-failure-handler-ref {xsd:token}?
form-login.attlist &=
## Reference to an AuthenticationDetailsSource which will be used by the authentication filter
attribute authentication-details-source-ref {xsd:token}?
form-login.attlist &=
## The URL for the ForwardAuthenticationFailureHandler
attribute authentication-failure-forward-url {xsd:token}?
form-login.attlist &=
## The URL for the ForwardAuthenticationSuccessHandler
attribute authentication-success-forward-url {xsd:token}?
openid-login =
## Sets up form login for authentication with an Open ID identity
element openid-login {form-login.attlist, user-service-ref?, attribute-exchange*}
attribute-exchange =
## Sets up an attribute exchange configuration to request specified attributes from the OpenID identity provider. When multiple elements are used, each must have an identifier-attribute attribute. Each configuration will be matched in turn against the supplied login identifier until a match is found.
element attribute-exchange {attribute-exchange.attlist, openid-attribute+}
attribute-exchange.attlist &=
## A regular expression which will be compared against the claimed identity, when deciding which attribute-exchange configuration to use during authentication.
attribute identifier-match {xsd:token}?
openid-attribute =
## Attributes used when making an OpenID AX Fetch Request
element openid-attribute {openid-attribute.attlist}
openid-attribute.attlist &=
## Specifies the name of the attribute that you wish to get back. For example, email.
attribute name {xsd:token}
openid-attribute.attlist &=
## Specifies the attribute type. For example, http://axschema.org/contact/email. See your OP's documentation for valid attribute types.
attribute type {xsd:token}
openid-attribute.attlist &=
## Specifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. Default is false.
attribute required {xsd:boolean}?
openid-attribute.attlist &=
## Specifies the number of attributes that you wish to get back. For example, return 3 emails. The default value is 1.
attribute count {xsd:int}?
filter-chain-map =
## Used to explicitly configure a FilterChainProxy instance with a FilterChainMap
element filter-chain-map {filter-chain-map.attlist, filter-chain+}
filter-chain-map.attlist &=
request-matcher?
filter-chain =
## Used within to define a specific URL pattern and the list of filters which apply to the URLs matching that pattern. When multiple filter-chain elements are assembled in a list in order to configure a FilterChainProxy, the most specific patterns must be placed at the top of the list, with most general ones at the bottom.
element filter-chain {filter-chain.attlist, empty}
filter-chain.attlist &=
(pattern | request-matcher-ref)
filter-chain.attlist &=
## A comma separated list of bean names that implement Filter that should be processed for this FilterChain. If the value is none, then no Filters will be used for this FilterChain.
attribute filters {xsd:token}
pattern =
## The request URL pattern which will be mapped to the FilterChain.
attribute pattern {xsd:token}
request-matcher-ref =
## Allows a RequestMatcher instance to be used, as an alternative to pattern-matching.
attribute request-matcher-ref {xsd:token}
filter-security-metadata-source =
## Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the <http> element. The intercept-url elements used should only contain pattern, method and access attributes. Any others will result in a configuration error.
element filter-security-metadata-source {fsmds.attlist, intercept-url+}
fsmds.attlist &=
use-expressions?
fsmds.attlist &=
id?
fsmds.attlist &=
request-matcher?
http-basic =
## Adds support for basic authentication
element http-basic {http-basic.attlist, empty}
http-basic.attlist &=
## Sets the AuthenticationEntryPoint which is used by the BasicAuthenticationFilter.
attribute entry-point-ref {xsd:token}?
http-basic.attlist &=
## Reference to an AuthenticationDetailsSource which will be used by the authentication filter
attribute authentication-details-source-ref {xsd:token}?
session-management =
## Session-management related functionality is implemented by the addition of a SessionManagementFilter to the filter stack.
element session-management {session-management.attlist, concurrency-control?}
session-management.attlist &=
## Indicates how session fixation protection will be applied when a user authenticates. If set to "none", no protection will be applied. "newSession" will create a new empty session, with only Spring Security-related attributes migrated. "migrateSession" will create a new session and copy all session attributes to the new session. In Servlet 3.1 (Java EE 7) and newer containers, specifying "changeSessionId" will keep the existing session and use the container-supplied session fixation protection (HttpServletRequest#changeSessionId()). Defaults to "changeSessionId" in Servlet 3.1 and newer containers, "migrateSession" in older containers. Throws an exception if "changeSessionId" is used in older containers.
attribute session-fixation-protection {"none" | "newSession" | "migrateSession" | "changeSessionId" }?
session-management.attlist &=
## The URL to which a user will be redirected if they submit an invalid session indentifier. Typically used to detect session timeouts.
attribute invalid-session-url {xsd:token}?
session-management.attlist &=
## Allows injection of the InvalidSessionStrategy instance used by the SessionManagementFilter
attribute invalid-session-strategy-ref {xsd:token}?
session-management.attlist &=
## Allows injection of the SessionAuthenticationStrategy instance used by the SessionManagementFilter
attribute session-authentication-strategy-ref {xsd:token}?
session-management.attlist &=
## Defines the URL of the error page which should be shown when the SessionAuthenticationStrategy raises an exception. If not set, an unauthorized (401) error code will be returned to the client. Note that this attribute doesn't apply if the error occurs during a form-based login, where the URL for authentication failure will take precedence.
attribute session-authentication-error-url {xsd:token}?
concurrency-control =
## Enables concurrent session control, limiting the number of authenticated sessions a user may have at the same time.
element concurrency-control {concurrency-control.attlist, empty}
concurrency-control.attlist &=
## The maximum number of sessions a single authenticated user can have open at the same time. Defaults to "1". A negative value denotes unlimited sessions.
attribute max-sessions {xsd:integer}?
concurrency-control.attlist &=
## The URL a user will be redirected to if they attempt to use a session which has been "expired" because they have logged in again.
attribute expired-url {xsd:token}?
concurrency-control.attlist &=
## Allows injection of the SessionInformationExpiredStrategy instance used by the ConcurrentSessionFilter
attribute expired-session-strategy-ref {xsd:token}?
concurrency-control.attlist &=
## Specifies that an unauthorized error should be reported when a user attempts to login when they already have the maximum configured sessions open. The default behaviour is to expire the original session. If the session-authentication-error-url attribute is set on the session-management URL, the user will be redirected to this URL.
attribute error-if-maximum-exceeded {xsd:boolean}?
concurrency-control.attlist &=
## Allows you to define an alias for the SessionRegistry bean in order to access it in your own configuration.
attribute session-registry-alias {xsd:token}?
concurrency-control.attlist &=
## Allows you to define an external SessionRegistry bean to be used by the concurrency control setup.
attribute session-registry-ref {xsd:token}?
remember-me =
## Sets up remember-me authentication. If used with the "key" attribute (or no attributes) the cookie-only implementation will be used. Specifying "token-repository-ref" or "remember-me-data-source-ref" will use the more secure, persisten token approach.
element remember-me {remember-me.attlist}
remember-me.attlist &=
## The "key" used to identify cookies from a specific token-based remember-me application. You should set this to a unique value for your application. If unset, it will default to a random value generated by SecureRandom.
attribute key {xsd:token}?
remember-me.attlist &=
(token-repository-ref | remember-me-data-source-ref | remember-me-services-ref)
remember-me.attlist &=
user-service-ref?
remember-me.attlist &=
## Exports the internally defined RememberMeServices as a bean alias, allowing it to be used by other beans in the application context.
attribute services-alias {xsd:token}?
remember-me.attlist &=
## Determines whether the "secure" flag will be set on the remember-me cookie. If set to true, the cookie will only be submitted over HTTPS (recommended). By default, secure cookies will be used if the request is made on a secure connection.
attribute use-secure-cookie {xsd:boolean}?
remember-me.attlist &=
## The period (in seconds) for which the remember-me cookie should be valid.
attribute token-validity-seconds {xsd:string}?
remember-me.attlist &=
## Reference to an AuthenticationSuccessHandler bean which should be used to handle a successful remember-me authentication.
attribute authentication-success-handler-ref {xsd:token}?
remember-me.attlist &=
## The name of the request parameter which toggles remember-me authentication. Defaults to 'remember-me'.
attribute remember-me-parameter {xsd:token}?
remember-me.attlist &=
## The name of cookie which store the token for remember-me authentication. Defaults to 'remember-me'.
attribute remember-me-cookie {xsd:token}?
token-repository-ref =
## Reference to a PersistentTokenRepository bean for use with the persistent token remember-me implementation.
attribute token-repository-ref {xsd:token}
remember-me-services-ref =
## Allows a custom implementation of RememberMeServices to be used. Note that this implementation should return RememberMeAuthenticationToken instances with the same "key" value as specified in the remember-me element. Alternatively it should register its own AuthenticationProvider. It should also implement the LogoutHandler interface, which will be invoked when a user logs out. Typically the remember-me cookie would be removed on logout.
attribute services-ref {xsd:token}?
remember-me-data-source-ref =
## DataSource bean for the database that contains the token repository schema.
data-source-ref
anonymous =
## Adds support for automatically granting all anonymous web requests a particular principal identity and a corresponding granted authority.
element anonymous {anonymous.attlist}
anonymous.attlist &=
## The key shared between the provider and filter. This generally does not need to be set. If unset, it will default to a random value generated by SecureRandom.
attribute key {xsd:token}?
anonymous.attlist &=
## The username that should be assigned to the anonymous request. This allows the principal to be identified, which may be important for logging and auditing. if unset, defaults to "anonymousUser".
attribute username {xsd:token}?
anonymous.attlist &=
## The granted authority that should be assigned to the anonymous request. Commonly this is used to assign the anonymous request particular roles, which can subsequently be used in authorization decisions. If unset, defaults to "ROLE_ANONYMOUS".
attribute granted-authority {xsd:token}?
anonymous.attlist &=
## With the default namespace setup, the anonymous "authentication" facility is automatically enabled. You can disable it using this property.
attribute enabled {xsd:boolean}?
port-mappings =
## Defines the list of mappings between http and https ports for use in redirects
element port-mappings {port-mappings.attlist, port-mapping+}
port-mappings.attlist &= empty
port-mapping =
## Provides a method to map http ports to https ports when forcing a redirect.
element port-mapping {http-port, https-port}
http-port =
## The http port to use.
attribute http {xsd:token}
https-port =
## The https port to use.
attribute https {xsd:token}
x509 =
## Adds support for X.509 client authentication.
element x509 {x509.attlist}
x509.attlist &=
## The regular expression used to obtain the username from the certificate's subject. Defaults to matching on the common name using the pattern "CN=(.*?),".
attribute subject-principal-regex {xsd:token}?
x509.attlist &=
## Explicitly specifies which user-service should be used to load user data for X.509 authenticated clients. If ommitted, the default user-service will be used.
user-service-ref?
x509.attlist &=
## Reference to an AuthenticationDetailsSource which will be used by the authentication filter
attribute authentication-details-source-ref {xsd:token}?
jee =
## Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication.
element jee {jee.attlist}
jee.attlist &=
## A comma-separate list of roles to look for in the incoming HttpServletRequest.
attribute mappable-roles {xsd:token}
jee.attlist &=
## Explicitly specifies which user-service should be used to load user data for container authenticated clients. If ommitted, the set of mappable-roles will be used to construct the authorities for the user.
user-service-ref?
authentication-manager =
## Registers the AuthenticationManager instance and allows its list of AuthenticationProviders to be defined. Also allows you to define an alias to allow you to reference the AuthenticationManager in your own beans.
element authentication-manager {authman.attlist & authentication-provider* & ldap-authentication-provider*}
authman.attlist &=
id?
authman.attlist &=
## An alias you wish to use for the AuthenticationManager bean (not required it you are using a specific id)
attribute alias {xsd:token}?
authman.attlist &=
## If set to true, the AuthenticationManger will attempt to clear any credentials data in the returned Authentication object, once the user has been authenticated.
attribute erase-credentials {xsd:boolean}?
authentication-provider =
## Indicates that the contained user-service should be used as an authentication source.
element authentication-provider {ap.attlist & any-user-service & password-encoder?}
ap.attlist &=
## Specifies a reference to a separately configured AuthenticationProvider instance which should be registered within the AuthenticationManager.
ref?
ap.attlist &=
## Specifies a reference to a separately configured UserDetailsService from which to obtain authentication data.
user-service-ref?
user-service =
## Creates an in-memory UserDetailsService from a properties file or a list of "user" child elements. Usernames are converted to lower-case internally to allow for case-insensitive lookups, so this should not be used if case-sensitivity is required.
element user-service {id? & (properties-file | (user*))}
properties-file =
## The location of a Properties file where each line is in the format of username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]
attribute properties {xsd:token}?
user =
## Represents a user in the application.
element user {user.attlist, empty}
user.attlist &=
## The username assigned to the user.
attribute name {xsd:token}
user.attlist &=
## The password assigned to the user. This may be hashed if the corresponding authentication provider supports hashing (remember to set the "hash" attribute of the "user-service" element). This attribute be omitted in the case where the data will not be used for authentication, but only for accessing authorities. If omitted, the namespace will generate a random value, preventing its accidental use for authentication. Cannot be empty.
attribute password {xsd:string}?
user.attlist &=
## One of more authorities granted to the user. Separate authorities with a comma (but no space). For example, "ROLE_USER,ROLE_ADMINISTRATOR"
attribute authorities {xsd:token}
user.attlist &=
## Can be set to "true" to mark an account as locked and unusable.
attribute locked {xsd:boolean}?
user.attlist &=
## Can be set to "true" to mark an account as disabled and unusable.
attribute disabled {xsd:boolean}?
jdbc-user-service =
## Causes creation of a JDBC-based UserDetailsService.
element jdbc-user-service {id? & jdbc-user-service.attlist}
jdbc-user-service.attlist &=
## The bean ID of the DataSource which provides the required tables.
attribute data-source-ref {xsd:token}
jdbc-user-service.attlist &=
cache-ref?
jdbc-user-service.attlist &=
## An SQL statement to query a username, password, and enabled status given a username. Default is "select username,password,enabled from users where username = ?"
attribute users-by-username-query {xsd:token}?
jdbc-user-service.attlist &=
## An SQL statement to query for a user's granted authorities given a username. The default is "select username, authority from authorities where username = ?"
attribute authorities-by-username-query {xsd:token}?
jdbc-user-service.attlist &=
## An SQL statement to query user's group authorities given a username. The default is "select g.id, g.group_name, ga.authority from groups g, group_members gm, group_authorities ga where gm.username = ? and g.id = ga.group_id and g.id = gm.group_id"
attribute group-authorities-by-username-query {xsd:token}?
jdbc-user-service.attlist &=
role-prefix?
csrf =
## Element for configuration of the CsrfFilter for protection against CSRF. It also updates the default RequestCache to only replay "GET" requests.
element csrf {csrf-options.attlist}
csrf-options.attlist &=
## Specifies if csrf protection should be disabled. Default false (i.e. CSRF protection is enabled).
attribute disabled {xsd:boolean}?
csrf-options.attlist &=
## The RequestMatcher instance to be used to determine if CSRF should be applied. Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS"
attribute request-matcher-ref { xsd:token }?
csrf-options.attlist &=
## The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository
attribute token-repository-ref { xsd:token }?
headers =
## Element for configuration of the HeaderWritersFilter. Enables easy setting for the X-Frame-Options, X-XSS-Protection and X-Content-Type-Options headers.
element headers { headers-options.attlist, (cache-control? & xss-protection? & hsts? & frame-options? & content-type-options? & hpkp? & content-security-policy? & referrer-policy? & header*)}
headers-options.attlist &=
## Specifies if the default headers should be disabled. Default false.
attribute defaults-disabled {xsd:boolean}?
headers-options.attlist &=
## Specifies if headers should be disabled. Default false.
attribute disabled {xsd:boolean}?
hsts =
## Adds support for HTTP Strict Transport Security (HSTS)
element hsts {hsts-options.attlist}
hsts-options.attlist &=
## Specifies if HTTP Strict Transport Security (HSTS) should be disabled. Default false.
attribute disabled {xsd:boolean}?
hsts-options.attlist &=
## Specifies if subdomains should be included. Default true.
attribute include-subdomains {xsd:boolean}?
hsts-options.attlist &=
## Specifies the maximum ammount of time the host should be considered a Known HSTS Host. Default one year.
attribute max-age-seconds {xsd:integer}?
hsts-options.attlist &=
## The RequestMatcher instance to be used to determine if the header should be set. Default is if HttpServletRequest.isSecure() is true.
attribute request-matcher-ref { xsd:token }?
cors =
## Element for configuration of CorsFilter. If no CorsFilter or CorsConfigurationSource is specified a HandlerMappingIntrospector is used as the CorsConfigurationSource
element cors { cors-options.attlist }
cors-options.attlist &=
ref?
cors-options.attlist &=
## Specifies a bean id that is a CorsConfigurationSource used to construct the CorsFilter to use
attribute configuration-source-ref {xsd:token}?
hpkp =
## Adds support for HTTP Public Key Pinning (HPKP).
element hpkp {hpkp.pins,hpkp.attlist}
hpkp.pins =
## The list with pins
element pins {hpkp.pin+}
hpkp.pin =
## A pin is specified using the base64-encoded SPKI fingerprint as value and the cryptographic hash algorithm as attribute
element pin {
## The cryptographic hash algorithm
attribute algorithm { xsd:string }?,
text
}
hpkp.attlist &=
## Specifies if HTTP Public Key Pinning (HPKP) should be disabled. Default false.
attribute disabled {xsd:boolean}?
hpkp.attlist &=
## Specifies if subdomains should be included. Default false.
attribute include-subdomains {xsd:boolean}?
hpkp.attlist &=
## Sets the value for the max-age directive of the Public-Key-Pins header. Default 60 days.
attribute max-age-seconds {xsd:integer}?
hpkp.attlist &=
## Specifies if the browser should only report pin validation failures. Default true.
attribute report-only {xsd:boolean}?
hpkp.attlist &=
## Specifies the URI to which the browser should report pin validation failures.
attribute report-uri {xsd:string}?
content-security-policy =
## Adds support for Content Security Policy (CSP)
element content-security-policy {csp-options.attlist}
csp-options.attlist &=
## The security policy directive(s) for the Content-Security-Policy header or if report-only is set to true, then the Content-Security-Policy-Report-Only header is used.
attribute policy-directives {xsd:token}?
csp-options.attlist &=
## Set to true, to enable the Content-Security-Policy-Report-Only header for reporting policy violations only. Defaults to false.
attribute report-only {xsd:boolean}?
referrer-policy =
## Adds support for Referrer Policy
element referrer-policy {referrer-options.attlist}
referrer-options.attlist &=
## The policies for the Referrer-Policy header.
attribute policy {"no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"}?
cache-control =
## Adds Cache-Control no-cache, no-store, must-revalidate, Pragma no-cache, and Expires 0 for every request
element cache-control {cache-control.attlist}
cache-control.attlist &=
## Specifies if Cache Control should be disabled. Default false.
attribute disabled {xsd:boolean}?
frame-options =
## Enable basic clickjacking support for newer browsers (IE8+), will set the X-Frame-Options header.
element frame-options {frame-options.attlist,empty}
frame-options.attlist &=
## If disabled, the X-Frame-Options header will not be included. Default false.
attribute disabled {xsd:boolean}?
frame-options.attlist &=
## Specify the policy to use for the X-Frame-Options-Header.
attribute policy {"DENY","SAMEORIGIN","ALLOW-FROM"}?
frame-options.attlist &=
## Specify the strategy to use when ALLOW-FROM is chosen.
attribute strategy {"static","whitelist","regexp"}?
frame-options.attlist &=
## Specify a reference to the custom AllowFromStrategy to use when ALLOW-FROM is chosen.
ref?
frame-options.attlist &=
## Specify a value to use for the chosen strategy.
attribute value {xsd:string}?
frame-options.attlist &=
## Specify the request parameter to use for the origin when using a 'whitelist' or 'regexp' based strategy. Default is 'from'.
attribute from-parameter {xsd:string}?
xss-protection =
## Enable basic XSS browser protection, supported by newer browsers (IE8+), will set the X-XSS-Protection header.
element xss-protection {xss-protection.attlist,empty}
xss-protection.attlist &=
## disable the X-XSS-Protection header. Default is 'false' meaning it is enabled.
attribute disabled {xsd:boolean}?
xss-protection.attlist &=
## specify that XSS Protection should be explicitly enabled or disabled. Default is 'true' meaning it is enabled.
attribute enabled {xsd:boolean}?
xss-protection.attlist &=
## Add mode=block to the header or not, default is on.
attribute block {xsd:boolean}?
content-type-options =
## Add a X-Content-Type-Options header to the resopnse. Value is always 'nosniff'.
element content-type-options {content-type-options.attlist, empty}
content-type-options.attlist &=
## If disabled, the X-Content-Type-Options header will not be included. Default false.
attribute disabled {xsd:boolean}?
header=
## Add additional headers to the response.
element header {header.attlist}
header.attlist &=
## The name of the header to add.
attribute name {xsd:token}?
header.attlist &=
## The value for the header.
attribute value {xsd:token}?
header.attlist &=
## Reference to a custom HeaderWriter implementation.
ref?
any-user-service = user-service | jdbc-user-service | ldap-user-service
custom-filter =
## Used to indicate that a filter bean declaration should be incorporated into the security filter chain.
element custom-filter {custom-filter.attlist}
custom-filter.attlist &=
ref
custom-filter.attlist &=
(after | before | position)
after =
## The filter immediately after which the custom-filter should be placed in the chain. This feature will only be needed by advanced users who wish to mix their own filters into the security filter chain and have some knowledge of the standard Spring Security filters. The filter names map to specific Spring Security implementation filters.
attribute after {named-security-filter}
before =
## The filter immediately before which the custom-filter should be placed in the chain
attribute before {named-security-filter}
position =
## The explicit position at which the custom-filter should be placed in the chain. Use if you are replacing a standard filter.
attribute position {named-security-filter}
named-security-filter = "FIRST" | "CHANNEL_FILTER" | "SECURITY_CONTEXT_FILTER" | "CONCURRENT_SESSION_FILTER" | "WEB_ASYNC_MANAGER_FILTER" | "HEADERS_FILTER" | "CORS_FILTER" | "CSRF_FILTER" | "LOGOUT_FILTER" | "X509_FILTER" | "PRE_AUTH_FILTER" | "CAS_FILTER" | "FORM_LOGIN_FILTER" | "OPENID_FILTER" | "LOGIN_PAGE_FILTER" |"LOGOUT_PAGE_FILTER" | "DIGEST_AUTH_FILTER" | "BEARER_TOKEN_AUTH_FILTER" | "BASIC_AUTH_FILTER" | "REQUEST_CACHE_FILTER" | "SERVLET_API_SUPPORT_FILTER" | "JAAS_API_SUPPORT_FILTER" | "REMEMBER_ME_FILTER" | "ANONYMOUS_FILTER" | "SESSION_MANAGEMENT_FILTER" | "EXCEPTION_TRANSLATION_FILTER" | "FILTER_SECURITY_INTERCEPTOR" | "SWITCH_USER_FILTER" | "LAST"
@@ -0,0 +1,92 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.method.configuration
import static org.assertj.core.api.Assertions.assertThat
import static org.junit.Assert.fail
import java.io.Serializable;
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Configuration
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.method.configuration.NamespaceGlobalMethodSecurityTests.BaseMethodConfig;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder
/**
*
* @author Rob Winch
*/
public class NamespaceGlobalMethodSecurityExpressionHandlerTests extends BaseSpringSpec {
def setup() {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("user", "password","ROLE_USER"))
}
def "global-method-security/expression-handler @PreAuthorize"() {
setup:
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomAccessDecisionManagerConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
when:
service.hasPermission("granted")
then:
noExceptionThrown()
when:
service.hasPermission("denied")
then:
thrown(AccessDeniedException)
}
def "global-method-security/expression-handler @PostAuthorize"() {
setup:
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomAccessDecisionManagerConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
when:
service.postHasPermission("granted")
then:
noExceptionThrown()
when:
service.postHasPermission("denied")
then:
thrown(AccessDeniedException)
}
@EnableGlobalMethodSecurity(prePostEnabled = true)
public static class CustomAccessDecisionManagerConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler()
expressionHandler.permissionEvaluator = new PermissionEvaluator() {
boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
"granted" == targetDomainObject
}
boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
throw new UnsupportedOperationException()
}
}
return expressionHandler
}
}
}
@@ -0,0 +1,444 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.method.configuration
import org.springframework.security.access.annotation.Jsr250MethodSecurityMetadataSource
import org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor
import static org.assertj.core.api.Assertions.assertThat
import static org.junit.Assert.fail
import java.lang.reflect.Method
import org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
import org.springframework.beans.factory.BeanCreationException
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.context.annotation.AdviceMode
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.core.Ordered
import org.springframework.security.access.AccessDecisionManager
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.access.ConfigAttribute
import org.springframework.security.access.SecurityConfig
import org.springframework.security.access.intercept.AfterInvocationManager
import org.springframework.security.access.intercept.RunAsManager
import org.springframework.security.access.intercept.RunAsManagerImpl
import org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor
import org.springframework.security.access.intercept.aopalliance.MethodSecurityMetadataSourceAdvisor
import org.springframework.security.access.method.AbstractMethodSecurityMetadataSource
import org.springframework.security.access.method.MethodSecurityMetadataSource
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.authentication.BaseAuthenticationConfig;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
/**
*
* @author Rob Winch
*/
public class NamespaceGlobalMethodSecurityTests extends BaseSpringSpec {
def setup() {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("user", "password","ROLE_USER"))
}
// --- access-decision-manager-ref ---
def "custom AccessDecisionManager can be used"() {
setup: "Create an instance with an AccessDecisionManager that always denies access"
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomAccessDecisionManagerConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
when:
service.preAuthorize()
then:
thrown(AccessDeniedException)
when:
service.secured()
then:
thrown(AccessDeniedException)
}
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public static class CustomAccessDecisionManagerConfig extends GlobalMethodSecurityConfiguration {
@Override
protected AccessDecisionManager accessDecisionManager() {
return new DenyAllAccessDecisionManager()
}
public static class DenyAllAccessDecisionManager implements AccessDecisionManager {
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {
throw new AccessDeniedException("Always Denied")
}
public boolean supports(ConfigAttribute attribute) {
return true
}
public boolean supports(Class<?> clazz) {
return true
}
}
}
// --- authentication-manager-ref ---
def "custom AuthenticationManager can be used"() {
when:
context = new AnnotationConfigApplicationContext(CustomAuthenticationConfig)
MethodSecurityInterceptor interceptor = context.getBean(MethodSecurityInterceptor)
interceptor.authenticationManager.authenticate(SecurityContextHolder.context.authentication)
then:
thrown(UnsupportedOperationException)
}
@EnableGlobalMethodSecurity
public static class CustomAuthenticationConfig extends GlobalMethodSecurityConfiguration {
@Override
protected AuthenticationManager authenticationManager() {
return new AuthenticationManager() {
Authentication authenticate(Authentication authentication) {
throw new UnsupportedOperationException()
}
}
}
}
// --- jsr250-annotations ---
def "enable jsr250"() {
when:
context = new AnnotationConfigApplicationContext(Jsr250Config)
MethodSecurityService service = context.getBean(MethodSecurityService)
then: "@Secured and @PreAuthorize are ignored"
service.secured() == null
service.preAuthorize() == null
when: "@DenyAll method invoked"
service.jsr250()
then: "access is denied"
thrown(AccessDeniedException)
when: "@PermitAll method invoked"
String jsr250PermitAll = service.jsr250PermitAll()
then: "access is allowed"
jsr250PermitAll == null
}
@EnableGlobalMethodSecurity(jsr250Enabled = true)
@Configuration
public static class Jsr250Config extends BaseMethodConfig {
}
// --- metadata-source-ref ---
def "custom MethodSecurityMetadataSource can be used with higher priority than other sources"() {
setup:
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomMethodSecurityMetadataSourceConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
when:
service.preAuthorize()
then:
thrown(AccessDeniedException)
when:
service.secured()
then:
thrown(AccessDeniedException)
when:
service.jsr250()
then:
thrown(AccessDeniedException)
}
@EnableGlobalMethodSecurity
public static class CustomMethodSecurityMetadataSourceConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
return new AbstractMethodSecurityMetadataSource() {
public Collection<ConfigAttribute> getAttributes(Method method, Class<?> targetClass) {
// require ROLE_NOBODY for any method on MethodSecurityService class
return MethodSecurityService.isAssignableFrom(targetClass) ? [new SecurityConfig("ROLE_NOBODY")] : []
}
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null
}
}
}
}
// --- mode ---
def "aspectj mode works"() {
when:
context = new AnnotationConfigApplicationContext(AspectJModeConfig)
then:
context.getBean(AnnotationSecurityAspect)
context.getBean(AspectJMethodSecurityInterceptor)
}
@EnableGlobalMethodSecurity(mode = AdviceMode.ASPECTJ, proxyTargetClass = true)
public static class AspectJModeConfig extends BaseMethodConfig {
}
def "aspectj mode works extending GlobalMethodSecurityConfiguration"() {
when:
context = new AnnotationConfigApplicationContext(BaseMethodConfig,AspectJModeExtendsGMSCConfig)
then:
context.getBean(AnnotationSecurityAspect)
context.getBean(AspectJMethodSecurityInterceptor)
}
@EnableGlobalMethodSecurity(mode = AdviceMode.ASPECTJ)
public static class AspectJModeExtendsGMSCConfig extends GlobalMethodSecurityConfiguration {
}
// --- order ---
def order() {
when:
context = new AnnotationConfigApplicationContext(CustomOrderConfig)
MethodSecurityMetadataSourceAdvisor advisor = context.getBean(MethodSecurityMetadataSourceAdvisor)
then:
advisor.order == 135
}
@EnableGlobalMethodSecurity(order = 135)
public static class CustomOrderConfig extends BaseMethodConfig {
}
def "order is defaulted to Ordered.LOWEST_PRECEDENCE when using @EnableGlobalMethodSecurity"() {
when:
context = new AnnotationConfigApplicationContext(DefaultOrderConfig)
MethodSecurityMetadataSourceAdvisor advisor = context.getBean(MethodSecurityMetadataSourceAdvisor)
then:
advisor.order == Ordered.LOWEST_PRECEDENCE
}
@EnableGlobalMethodSecurity
public static class DefaultOrderConfig extends BaseMethodConfig {
}
def "order is defaulted to Ordered.LOWEST_PRECEDENCE when extending GlobalMethodSecurityConfiguration"() {
when:
context = new AnnotationConfigApplicationContext(BaseMethodConfig,DefaultOrderExtendsMethodSecurityConfig)
MethodSecurityMetadataSourceAdvisor advisor = context.getBean(MethodSecurityMetadataSourceAdvisor)
then:
advisor.order == Ordered.LOWEST_PRECEDENCE
}
@EnableGlobalMethodSecurity
public static class DefaultOrderExtendsMethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}
// --- pre-post-annotations ---
def preAuthorize() {
when:
context = new AnnotationConfigApplicationContext(PreAuthorizeConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
then:
service.secured() == null
service.jsr250() == null
when:
service.preAuthorize()
then:
thrown(AccessDeniedException)
}
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public static class PreAuthorizeConfig extends BaseMethodConfig {
}
def "prePostEnabled extends GlobalMethodSecurityConfiguration"() {
when:
context = new AnnotationConfigApplicationContext(BaseMethodConfig,PreAuthorizeExtendsGMSCConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
then:
service.secured() == null
service.jsr250() == null
when:
service.preAuthorize()
then:
thrown(AccessDeniedException)
}
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public static class PreAuthorizeExtendsGMSCConfig extends GlobalMethodSecurityConfiguration {
}
// --- proxy-target-class ---
def "proxying classes works"() {
when:
context = new AnnotationConfigApplicationContext(ProxyTargetClass)
MethodSecurityServiceImpl service = context.getBean(MethodSecurityServiceImpl)
then:
noExceptionThrown()
}
@EnableGlobalMethodSecurity(proxyTargetClass = true)
@Configuration
public static class ProxyTargetClass extends BaseMethodConfig {
}
def "proxying interfaces works"() {
when:
context = new AnnotationConfigApplicationContext(PreAuthorizeConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
then: "we get an instance of the interface"
noExceptionThrown()
when: "try to cast to the class"
MethodSecurityServiceImpl serviceImpl = service
then: "we get a class cast exception"
thrown(ClassCastException)
}
// --- run-as-manager-ref ---
def "custom RunAsManager"() {
when:
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomRunAsManagerConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
then:
service.runAs().authorities.find { it.authority == "ROLE_RUN_AS_SUPER"}
}
@EnableGlobalMethodSecurity(securedEnabled = true)
public static class CustomRunAsManagerConfig extends GlobalMethodSecurityConfiguration {
@Override
protected RunAsManager runAsManager() {
RunAsManagerImpl runAsManager = new RunAsManagerImpl()
runAsManager.setKey("some key")
return runAsManager
}
}
// --- secured-annotation ---
def "secured enabled"() {
setup:
context = new AnnotationConfigApplicationContext(SecuredConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
when:
service.secured()
then:
thrown(AccessDeniedException)
and: "service with ROLE_USER allowed"
service.securedUser() == null
and:
service.preAuthorize() == null
service.jsr250() == null
}
@EnableGlobalMethodSecurity(securedEnabled = true)
@Configuration
public static class SecuredConfig extends BaseMethodConfig {
}
// --- after-invocation-provider
def "custom AfterInvocationManager"() {
setup:
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomAfterInvocationManagerConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
when:
service.preAuthorizePermitAll()
then:
AccessDeniedException e = thrown()
e.message == "custom AfterInvocationManager"
}
@EnableGlobalMethodSecurity(prePostEnabled = true)
public static class CustomAfterInvocationManagerConfig extends GlobalMethodSecurityConfiguration {
@Override
protected AfterInvocationManager afterInvocationManager() {
return new AfterInvocationManagerStub()
}
public static class AfterInvocationManagerStub implements AfterInvocationManager {
Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> attributes,
Object returnedObject) throws AccessDeniedException {
throw new AccessDeniedException("custom AfterInvocationManager")
}
boolean supports(ConfigAttribute attribute) {
return true
}
boolean supports(Class<?> clazz) {
return true
}
}
}
// --- misc ---
def "good error message when no Enable annotation"() {
when:
context = new AnnotationConfigApplicationContext(ExtendsNoEnableAnntotationConfig)
MethodSecurityInterceptor interceptor = context.getBean(MethodSecurityInterceptor)
interceptor.authenticationManager.authenticate(SecurityContextHolder.context.authentication)
then:
BeanCreationException e = thrown()
e.message.contains(EnableGlobalMethodSecurity.class.getName() + " is required")
}
@Configuration
public static class ExtendsNoEnableAnntotationConfig extends GlobalMethodSecurityConfiguration {
@Override
protected AuthenticationManager authenticationManager() {
return new AuthenticationManager() {
Authentication authenticate(Authentication authentication) {
throw new UnsupportedOperationException()
}
}
}
}
def "import subclass of GlobalMethodSecurityConfiguration"() {
when:
context = new AnnotationConfigApplicationContext(ImportSubclassGMSCConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
then:
service.secured() == null
service.jsr250() == null
when:
service.preAuthorize()
then:
thrown(AccessDeniedException)
}
@Configuration
@Import(PreAuthorizeExtendsGMSCConfig)
public static class ImportSubclassGMSCConfig extends BaseMethodConfig {
}
@Configuration
public static class BaseMethodConfig extends BaseAuthenticationConfig {
@Bean
public MethodSecurityService methodSecurityService() {
return new MethodSecurityServiceImpl()
}
}
}
@@ -0,0 +1,143 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.sec2758;
import javax.annotation.security.RolesAllowed;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.core.PriorityOrdered;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.access.annotation.Jsr250MethodSecurityMetadataSource;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.sec2377.a.*
import org.springframework.security.config.annotation.web.configuration.sec2377.b.*
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext
public class Sec2758Tests extends BaseSpringSpec {
def cleanup() {
SecurityContextHolder.clearContext()
}
def "SEC-2758: Verify Passivity Restored with Advice from JIRA"() {
setup:
SecurityContextHolder.context.authentication = new TestingAuthenticationToken("user", "pass", "USER")
loadConfig(SecurityConfig)
Service service = context.getBean(Service)
when:
findFilter(FilterSecurityInterceptor).doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain())
then:
noExceptionThrown()
when:
service.doPreAuthorize()
then:
noExceptionThrown()
when:
service.doJsr250()
then:
noExceptionThrown()
}
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().hasAnyAuthority("USER");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth
.inMemoryAuthentication()
.withUser("user").password("password").authorities("USER")
}
@Bean
Service service() {
return new ServiceImpl()
}
@Bean
static DefaultRolesPrefixPostProcessor defaultRolesPrefixPostProcessor() {
new DefaultRolesPrefixPostProcessor()
}
}
interface Service {
void doPreAuthorize()
void doJsr250()
}
static class ServiceImpl implements Service {
@PreAuthorize("hasRole('USER')")
void doPreAuthorize() {}
@RolesAllowed("USER")
void doJsr250() {}
}
static class DefaultRolesPrefixPostProcessor implements BeanPostProcessor, PriorityOrdered {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if(bean instanceof Jsr250MethodSecurityMetadataSource) {
((Jsr250MethodSecurityMetadataSource) bean).setDefaultRolePrefix(null);
}
if(bean instanceof DefaultMethodSecurityExpressionHandler) {
((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
}
if(bean instanceof DefaultWebSecurityExpressionHandler) {
((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
}
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
@Override
public int getOrder() {
return PriorityOrdered.HIGHEST_PRECEDENCE;
}
}
}
@@ -0,0 +1,144 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration
import org.springframework.mock.web.MockServletContext
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.core.context.SecurityContextImpl
import org.springframework.security.core.userdetails.PasswordEncodedUser
import org.springframework.security.core.userdetails.User
import org.springframework.security.web.context.HttpSessionSecurityContextRepository
import org.springframework.test.context.web.WebAppConfiguration
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.security.authentication.AnonymousAuthenticationToken
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter
import org.springframework.security.web.debug.DebugFilter
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
class EnableWebSecurityTests extends BaseSpringSpec {
def "@Bean(BeanIds.AUTHENTICATION_MANAGER) includes HttpSecurity's AuthenticationManagerBuilder"() {
when:
loadConfig(SecurityConfig)
AuthenticationManager authenticationManager = context.getBean(AuthenticationManager)
AnonymousAuthenticationToken anonymousAuthToken = findFilter(AnonymousAuthenticationFilter).createAuthentication(new MockHttpServletRequest())
then:
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"))
authenticationManager.authenticate(anonymousAuthToken)
}
@EnableWebSecurity
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean()
throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/*").hasRole("USER")
.and()
.formLogin();
}
}
def "@EnableWebSecurity on superclass"() {
when:
loadConfig(ChildSecurityConfig)
then:
context.getBean("springSecurityFilterChain", DebugFilter)
}
@Configuration
static class ChildSecurityConfig extends DebugSecurityConfig {
}
@EnableWebSecurity(debug=true)
static class DebugSecurityConfig extends WebSecurityConfigurerAdapter {
}
def "SEC-2942: EnableWebSecurity adds AuthenticationPrincipalArgumentResolver"() {
setup:
def username = "test"
context = new AnnotationConfigWebApplicationContext()
context.servletContext = new MockServletContext()
context.register(AuthenticationPrincipalConfig)
context.refresh()
SecurityContext securityContext = new SecurityContextImpl(authentication: new TestingAuthenticationToken(username, "pass", "ROLE_USER"))
MockMvc mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.addFilters(springSecurityFilterChain)
.build()
when:
String body = mockMvc
.perform(get("/").sessionAttr(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext))
.andReturn().response.contentAsString
then:
body == username
}
@EnableWebSecurity
@EnableWebMvc
@Configuration
static class AuthenticationPrincipalConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.inMemoryAuthentication()
}
@RestController
static class AuthController {
@RequestMapping("/")
String principal(@AuthenticationPrincipal String principal) {
principal
}
}
}
}
@@ -0,0 +1,113 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.FatalBeanException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
public class Sec2515Tests extends BaseSpringSpec {
def "SEC-2515: Prevent StackOverflow with bean graph cycle"() {
when:
loadConfig(StackOverflowSecurityConfig)
then:
thrown(FatalBeanException)
}
@EnableWebSecurity
static class StackOverflowSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean
public AuthenticationManager authenticationManagerBean()
throws Exception {
return super.authenticationManagerBean();
}
}
def "Custom Name Prevent StackOverflow with bean graph cycle"() {
when:
loadConfig(StackOverflowSecurityConfig)
then:
thrown(FatalBeanException)
}
@EnableWebSecurity
static class CustomBeanNameStackOverflowSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean(name="custom")
public AuthenticationManager authenticationManagerBean()
throws Exception {
return super.authenticationManagerBean();
}
}
def "SEC-2549: Can load with child classloader"() {
setup:
CanLoadWithChildConfig.AM = Mock(AuthenticationManager)
context = new AnnotationConfigApplicationContext()
context.classLoader = new URLClassLoader(new URL[0], context.classLoader)
context.register(CanLoadWithChildConfig)
context.refresh()
when:
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"))
then:
noExceptionThrown()
1 * CanLoadWithChildConfig.AM.authenticate(_) >> new TestingAuthenticationToken("user","password","ROLE_USER")
}
@EnableWebSecurity
static class CanLoadWithChildConfig extends WebSecurityConfigurerAdapter {
static AuthenticationManager AM
@Bean
public AuthenticationManager am() {
AM
}
}
def "SEC-2515: @Bean still works when configure(AuthenticationManagerBuilder) used"() {
when:
loadConfig(SecurityConfig)
then:
noExceptionThrown();
}
@EnableWebSecurity
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean
public AuthenticationManager authenticationManagerBean()
throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
}
}
}
@@ -15,10 +15,7 @@
*/
package org.springframework.security.config.annotation.web.configurers
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.core.userdetails.PasswordEncodedUser
import org.springframework.security.web.firewall.StrictHttpFirewall
import javax.servlet.http.HttpServletResponse
@@ -47,7 +44,7 @@ class CsrfConfigurerTests extends BaseSpringSpec {
@Unroll
def "csrf applied by default"() {
setup:
loadConfig(CsrfAppliedDefaultConfig, AllowHttpMethodsFirewallConfig)
loadConfig(CsrfAppliedDefaultConfig)
request.method = httpMethod
clearCsrfToken()
when:
@@ -69,21 +66,11 @@ class CsrfConfigurerTests extends BaseSpringSpec {
def "csrf default creates CsrfRequestDataValueProcessor"() {
when:
loadConfig(CsrfAppliedDefaultConfig, AllowHttpMethodsFirewallConfig)
loadConfig(CsrfAppliedDefaultConfig)
then:
context.getBean(RequestDataValueProcessor)
}
@Configuration
static class AllowHttpMethodsFirewallConfig {
@Bean
StrictHttpFirewall strictHttpFirewall() {
StrictHttpFirewall result = new StrictHttpFirewall();
result.setAllowedHttpMethods(StrictHttpFirewall.ALLOW_ANY_HTTP_METHOD);
return result;
}
}
@EnableWebSecurity
static class CsrfAppliedDefaultConfig extends WebSecurityConfigurerAdapter {
@@ -53,33 +53,15 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
request.requestURI = "/login"
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
</head>
<body>
<div class="container">
<form class="form-signin" method="post" action="/login">
<h2 class="form-signin-heading">Please sign in</h2>
<p>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
</p>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</body></html>"""
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
</table>
</form></body></html>"""
when: "fail to log in"
super.setup()
request.servletPath = "/login"
@@ -95,33 +77,15 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
request.queryString = "error"
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
</head>
<body>
<div class="container">
<form class="form-signin" method="post" action="/login">
<h2 class="form-signin-heading">Please sign in</h2>
<div class="alert alert-danger" role="alert">Bad credentials</div> <p>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
</p>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</body></html>"""
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<p style='color:red;'>Your login attempt was not successful, try again.<br/><br/>Reason: Bad credentials</p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
</table>
</form></body></html>"""
when: "login success"
super.setup()
request.servletPath = "/login"
@@ -142,33 +106,15 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
request.method = "GET"
springSecurityFilterChain.doFilter(request,response,chain)
then: "sent to default success page"
response.getContentAsString() == """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
</head>
<body>
<div class="container">
<form class="form-signin" method="post" action="/login">
<h2 class="form-signin-heading">Please sign in</h2>
<div class="alert alert-success" role="alert">You have been signed out</div> <p>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
</p>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</body></html>"""
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<p style='color:green;'>You have been logged out</p><h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
</table>
</form></body></html>"""
}
@Configuration
@@ -245,34 +191,16 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
request.requestURI = "/login"
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
</head>
<body>
<div class="container">
<form class="form-signin" method="post" action="/login">
<h2 class="form-signin-heading">Please sign in</h2>
<p>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
</p>
<p><input type='checkbox' name='remember-me'/> Remember me on this computer.</p>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</body></html>"""
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td><input type='checkbox' name='remember-me'/></td><td>Remember me on this computer.</td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
</table>
</form></body></html>"""
}
@Configuration
@@ -296,29 +224,13 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
request.requestURI = "/login"
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
</head>
<body>
<div class="container">
<form name="oidf" class="form-signin" method="post" action="/login/openid">
<h2 class="form-signin-heading">Login with OpenID Identity</h2>
<p>
<label for="username" class="sr-only">Identity</label>
<input type="text" id="username" name="openid_identifier" class="form-control" placeholder="Username" required autofocus>
</p>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</body></html>"""
response.getContentAsString() == """<html><head><title>Login Page</title></head><h3>Login with OpenID Identity</h3><form name='oidf' action='/login/openid' method='POST'>
<table>
<tr><td>Identity:</td><td><input type='text' size='30' name='openid_identifier'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
</table>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
</form></body></html>"""
}
@Configuration
@@ -340,44 +252,23 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
request.requestURI = "/login"
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous"/>
</head>
<body>
<div class="container">
<form class="form-signin" method="post" action="/login">
<h2 class="form-signin-heading">Please sign in</h2>
<p>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
</p>
<p><input type='checkbox' name='remember-me'/> Remember me on this computer.</p>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
<form name="oidf" class="form-signin" method="post" action="/login/openid">
<h2 class="form-signin-heading">Login with OpenID Identity</h2>
<p>
<label for="username" class="sr-only">Identity</label>
<input type="text" id="username" name="openid_identifier" class="form-control" placeholder="Username" required autofocus>
</p>
<p><input type='checkbox' name='remember-me'/> Remember me on this computer.</p>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</body></html>"""
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td><input type='checkbox' name='remember-me'/></td><td>Remember me on this computer.</td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
</table>
</form><h3>Login with OpenID Identity</h3><form name='oidf' action='/login/openid' method='POST'>
<table>
<tr><td>Identity:</td><td><input type='text' size='30' name='openid_identifier'/></td></tr>
<tr><td><input type='checkbox' name='remember-me'></td><td>Remember me on this computer.</td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
</table>
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
</form></body></html>"""
}
@Configuration
@@ -57,7 +57,7 @@ import spock.lang.Unroll
*
* @author Rob Winch
*/
class FormLoginConfigurerSpec extends BaseSpringSpec {
class FormLoginConfigurerTests extends BaseSpringSpec {
def "Form Login"() {
when: "load formLogin()"
context = new AnnotationConfigApplicationContext(FormLoginConfig)
@@ -46,7 +46,7 @@ public class NamespaceHttpFirewallTests extends BaseSpringSpec {
MockFilterChain chain
def setup() {
request = new MockHttpServletRequest("GET", "")
request = new MockHttpServletRequest()
response = new MockHttpServletResponse()
chain = new MockFilterChain()
}
@@ -44,7 +44,7 @@ public class NamespaceHttpPortMappingsTests extends BaseSpringSpec {
MockFilterChain chain
def setup() {
request = new MockHttpServletRequest("GET", "")
request = new MockHttpServletRequest()
request.setMethod("GET")
response = new MockHttpServletResponse()
chain = new MockFilterChain()
@@ -371,7 +371,7 @@ public class NamespaceRememberMeTests extends BaseSpringSpec {
}
Cookie createRememberMeCookie() {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "")
MockHttpServletRequest request = new MockHttpServletRequest()
MockHttpServletResponse response = new MockHttpServletResponse()
super.setupCsrf("CSRF_TOKEN", request, response)
@@ -270,7 +270,7 @@ public class RememberMeConfigurerTests extends BaseSpringSpec {
}
Cookie createRememberMeCookie() {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "")
MockHttpServletRequest request = new MockHttpServletRequest()
MockHttpServletResponse response = new MockHttpServletResponse()
super.setupCsrf("CSRF_TOKEN", request, response)
@@ -0,0 +1,33 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.config.doc
/**
* Represents a Spring Security XSD Attribute. It is created when parsing the current xsd to compare to the documented appendix.
*
* @author Rob Winch
* @see SpringSecurityXsdParser
* @see XsdDocumentedSpec
*/
class Attribute {
def name
def desc
def elmt
def getId() {
return "${elmt.id}-${name}".toString()
}
}
@@ -0,0 +1,90 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.config.doc
/**
* Represents a Spring Security XSD Element. It is created when parsing the current xsd to compare to the documented appendix.
*
* @author Rob Winch
* @see SpringSecurityXsdParser
* @see XsdDocumentedSpec
*/
class Element {
def name
def desc
def attrs
/**
* Contains the elements that extend this element (i.e. any-user-service contains ldap-user-service)
*/
def subGrps = []
def childElmts = [:]
def parentElmts = [:]
def getId() {
return "nsa-${name}".toString()
}
/**
* Gets all the ids related to this Element including attributes, parent elements, and child elements.
*
* <p>
* The expected ids to be found are documented below.
* <ul>
* <li>Elements - any xml element will have the nsa-&lt;element&gt;. For example the http element will have the id
* nsa-http</li>
* <li>Parent Section - Any element with a parent other than beans will have a section named
* nsa-&lt;element&gt;-parents. For example, authentication-provider would have a section id of
* nsa-authentication-provider-parents. The section would then contain a list of links pointing to the
* documentation for each parent element.</li>
* <li>Attributes Section - Any element with attributes will have a section with the id
* nsa-&lt;element&gt;-attributes. For example the http element would require a section with the id
* http-attributes.</li>
* <li>Attribute - Each attribute of an element would have an id of nsa-&lt;element&gt;-&lt;attributeName&gt;. For
* example the attribute create-session for the http attribute would have the id http-create-session.</li>
* <li>Child Section - Any element with a child element will have a section named nsa-&lt;element&gt;-children.
* For example, authentication-provider would have a section id of nsa-authentication-provider-children. The
* section would then contain a list of links pointing to the documentation for each child element.</li>
* </ul>
* @return
*/
def getIds() {
def ids = [id]
childElmts.values()*.ids.each { ids.addAll it }
attrs*.id.each { ids.add it }
if(childElmts) {
ids.add id+'-children'
}
if(attrs) {
ids.add id+'-attributes'
}
if(parentElmts) {
ids.add id+'-parents'
}
ids
}
def getAllChildElmts() {
def result = [:]
childElmts.values()*.subGrps*.each { elmt -> result.put(elmt.name,elmt) }
result + childElmts
}
def getAllParentElmts() {
def result = [:]
parentElmts.values()*.subGrps*.each { elmt -> result.put(elmt.name,elmt) }
result + parentElmts
}
}
@@ -0,0 +1,177 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.config.doc
import groovy.xml.Namespace
/**
* Parses the Spring Security Xsd Document
*
* @author Rob Winch
*/
class SpringSecurityXsdParser {
private def rootElement
private def xs = new Namespace("http://www.w3.org/2001/XMLSchema", 'xs')
private def attrElmts = [] as Set
private def elementNameToElement = [:] as Map
/**
* Returns a map of the element name to the {@link Element}.
* @return
*/
Map<String,Element> parse() {
elements(rootElement)
elementNameToElement
}
/**
* Creates a Map of the name to an Element object of all the children of element.
*
* @param element
* @return
*/
private def elements(element) {
def elementNameToElement = [:] as Map
element.children().each { c->
if(c.name() == 'element') {
def e = elmt(c)
elementNameToElement.put(e.name,e)
} else {
elementNameToElement.putAll(elements(c))
}
}
elementNameToElement
}
/**
* Any children that are attribute will be returned as an Attribute object.
* @param element
* @return a collection of Attribute objects that are children of element.
*/
private def attrs(element) {
def r = []
element.children().each { c->
if(c.name() == 'attribute') {
r.add(attr(c))
}else if(c.name() == 'element') {
}else {
r.addAll(attrs(c))
}
}
r
}
/**
* Any children will be searched for an attributeGroup, each of it's children will be returned as an Attribute
* @param element
* @return
*/
private def attrgrps(element) {
def r = []
element.children().each { c->
if(c.name() == 'element') {
}else if (c.name() == 'attributeGroup') {
if(c.attributes().get('name')) {
r.addAll(attrgrp(c))
} else {
def n = c.attributes().get('ref').split(':')[1]
def attrGrp = findNode(element,n)
r.addAll(attrgrp(attrGrp))
}
} else {
r.addAll(attrgrps(c))
}
}
r
}
private def findNode(c,name) {
def root = c
while(root.name() != 'schema') {
root = root.parent()
}
def result = root.breadthFirst().find { child-> name == child.@name?.text() }
assert result?.@name?.text() == name
result
}
/**
* Processes an individual attributeGroup by obtaining all the attributes and then looking for more attributeGroup elements and prcessing them.
* @param e
* @return all the attributes for a specific attributeGroup and any child attributeGroups
*/
private def attrgrp(e) {
def attrs = attrs(e)
attrs.addAll(attrgrps(e))
attrs
}
/**
* Obtains the description for a specific element
* @param element
* @return
*/
private def desc(element) {
return element['annotation']['documentation']
}
/**
* Given an element creates an attribute from it.
* @param n
* @return
*/
private def attr(n) {
new Attribute(desc: desc(n), name: n.@name.text())
}
/**
* Given an element creates an Element out of it by collecting all its attributes and child elements.
*
* @param n
* @return
*/
private def elmt(n) {
def name = n.@ref.text()
if(name) {
name = name.split(':')[1]
n = findNode(n,name)
} else {
name = n.@name.text()
}
if(elementNameToElement.containsKey(name)) {
return elementNameToElement.get(name)
}
attrElmts.add(name)
def e = new Element()
e.name = n.@name.text()
e.desc = desc(n)
e.childElmts = elements(n)
e.attrs = attrs(n)
e.attrs.addAll(attrgrps(n))
e.attrs*.elmt = e
e.childElmts.values()*.each { it.parentElmts.put(e.name,e) }
def subGrpName = n.@substitutionGroup.text()
if(subGrpName) {
def subGrp = elmt(findNode(n,subGrpName.split(":")[1]))
subGrp.subGrps.add(e)
}
elementNameToElement.put(name,e)
e
}
}
@@ -0,0 +1,222 @@
/*
* Copyright 2011-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.config.doc
import groovy.util.slurpersupport.GPathResult
import spock.lang.*
import org.springframework.security.config.http.SecurityFilters
/**
* Tests to ensure that the xsd is properly documented.
*
* @author Rob Winch
*/
class XsdDocumentedTests extends Specification {
def ignoredIds = [
'nsa-any-user-service',
'nsa-any-user-service-parents',
'nsa-authentication',
'nsa-websocket-security',
'nsa-ldap',
'nsa-method-security',
'nsa-web'
]
@Shared def reference = new File('../docs/manual/src/docs/asciidoc/index.adoc')
@Shared File schema31xDocument = new File('src/main/resources/org/springframework/security/config/spring-security-3.1.xsd')
@Shared File schemaDocument = new File('src/main/resources/org/springframework/security/config/spring-security-5.0.xsd')
@Shared Map<String,Element> elementNameToElement
@Shared GPathResult schemaRootElement
def setupSpec() {
schemaRootElement = new XmlSlurper().parse(schemaDocument)
elementNameToElement = new SpringSecurityXsdParser(rootElement: schemaRootElement).parse()
}
def cleanupSpec() {
reference = null
schema31xDocument = null
schemaDocument = null
elementNameToElement = null
schemaRootElement = null
}
def 'SEC-2139: named-security-filter are all defined and ordered properly'() {
setup:
def expectedFilters = (EnumSet.allOf(SecurityFilters) as List).sort { it.order }
when:
def nsf = schemaRootElement.simpleType.find { it.@name == 'named-security-filter' }
def nsfValues = nsf.children().children().collect { c ->
Enum.valueOf(SecurityFilters, c.@value.toString())
}
then:
expectedFilters == nsfValues
}
def 'SEC-2139: 3.1.x named-security-filter are all defined and ordered properly'() {
setup:
def expectedFilters = [
"FIRST",
"CHANNEL_FILTER",
"SECURITY_CONTEXT_FILTER",
"CONCURRENT_SESSION_FILTER",
"LOGOUT_FILTER",
"X509_FILTER",
"PRE_AUTH_FILTER",
"CAS_FILTER",
"FORM_LOGIN_FILTER",
"OPENID_FILTER",
"LOGIN_PAGE_FILTER",
"DIGEST_AUTH_FILTER",
"BASIC_AUTH_FILTER",
"REQUEST_CACHE_FILTER",
"SERVLET_API_SUPPORT_FILTER",
"JAAS_API_SUPPORT_FILTER",
"REMEMBER_ME_FILTER",
"ANONYMOUS_FILTER",
"SESSION_MANAGEMENT_FILTER",
"EXCEPTION_TRANSLATION_FILTER",
"FILTER_SECURITY_INTERCEPTOR",
"SWITCH_USER_FILTER",
"LAST"
].collect {
Enum.valueOf(SecurityFilters, it)
}
def schema31xRootElement = new XmlSlurper().parse(schema31xDocument)
when:
def nsf = schema31xRootElement.simpleType.find { it.@name == 'named-security-filter' }
def nsfValues = nsf.children().children().collect { c ->
Enum.valueOf(SecurityFilters, c.@value.toString())
}
then:
expectedFilters == nsfValues
}
/**
* This will check to ensure that the expected number of xsd documents are found to ensure that we are validating
* against the current xsd document. If this test fails, all that is needed is to update the schemaDocument
* and the expected size for this test.
* @return
*/
def 'the latest schema is being validated'() {
when: 'all the schemas are found'
def schemas = schemaDocument.getParentFile().list().findAll { it.endsWith('.xsd') }
then: 'the count is equal to 12, if not then schemaDocument needs updated'
schemas.size() == 12
}
/**
* This uses a naming convention for the ids of the appendix to ensure that the entire appendix is documented.
* The naming convention for the ids is documented in {@link Element#getIds()}.
* @return
*/
def 'the entire schema is included in the appendix documentation'() {
setup: 'get all the documented ids and the expected ids'
def documentedIds = []
reference.eachLine { line ->
if(line.matches("\\[\\[(nsa-.*)\\]\\]")) {
documentedIds.add(line.substring(2,line.length() - 2))
}
}
when: 'the schema is compared to the appendix documentation'
def expectedIds = [] as Set
elementNameToElement*.value*.ids*.each { expectedIds.addAll it }
documentedIds.removeAll ignoredIds
expectedIds.removeAll ignoredIds
def undocumentedIds = (expectedIds - documentedIds)
def shouldNotBeDocumented = (documentedIds - expectedIds)
then: 'all the elements and attributes are documented'
shouldNotBeDocumented.empty
undocumentedIds.empty
}
/**
* This test ensures that any element that has children or parents contains a section that has links pointing to that
* documentation.
* @return
*/
def 'validate parents and children are linked in the appendix documentation'() {
when: "get all the links for each element's children and parents"
def docAttrNameToChildren = [:]
def docAttrNameToParents = [:]
def currentDocAttrNameToElmt
def docAttrName
reference.eachLine { line ->
if(line.matches('^\\[\\[.*\\]\\]$')) {
def id = line.substring(2,line.length() - 2)
if(id.endsWith("-children")) {
docAttrName = id.substring(0,id.length() - 9)
currentDocAttrNameToElmt = docAttrNameToChildren
} else if(id.endsWith("-parents")) {
docAttrName = id.substring(0,id.length() - 8)
currentDocAttrNameToElmt = docAttrNameToParents
} else if(docAttrName && !id.startsWith(docAttrName)) {
currentDocAttrNameToElmt = null
docAttrName = null
}
}
if(docAttrName) {
def expression = '^\\* <<(nsa-.*),.*>>$'
if(line.matches(expression)) {
String elmtId = line.replaceAll(expression, '$1')
currentDocAttrNameToElmt.get(docAttrName, []).add(elmtId)
}
}
}
def schemaAttrNameToParents = [:]
def schemaAttrNameToChildren = [:]
elementNameToElement.each { entry ->
def key = 'nsa-'+entry.key
if(ignoredIds.contains(key)) {
return
}
def parentIds = entry.value.allParentElmts.values()*.id.findAll { !ignoredIds.contains(it) }.sort()
if(parentIds) {
schemaAttrNameToParents.put(key,parentIds)
}
def childIds = entry.value.allChildElmts.values()*.id.findAll { !ignoredIds.contains(it) }.sort()
if(childIds) {
schemaAttrNameToChildren.put(key,childIds)
}
}
then: "the expected parents and children are all documented"
schemaAttrNameToChildren.sort() == docAttrNameToChildren.sort()
schemaAttrNameToParents.sort() == docAttrNameToParents.sort()
}
/**
* This test checks each xsd element and ensures there is documentation for it.
* @return
*/
def 'entire xsd is documented'() {
when: "validate that the entire xsd contains documentation"
def notDocElmtIds = elementNameToElement.values().findAll {
!it.desc.text() && !ignoredIds.contains(it.id)
}*.id.sort().join("\n")
def notDocAttrIds = elementNameToElement.values()*.attrs.flatten().findAll {
!it.desc.text() && !ignoredIds.contains(it.id)
}*.id.sort().join("\n")
then: "all the elements and attributes have some documentation"
!notDocElmtIds
!notDocAttrIds
}
}
@@ -28,7 +28,7 @@ import javax.servlet.http.HttpServletRequest
*
*/
abstract class AbstractHttpConfigTests extends AbstractXmlConfigTests {
final int AUTO_CONFIG_FILTERS = 15;
final int AUTO_CONFIG_FILTERS = 14;
def httpAutoConfig(Closure c) {
xml.http(['auto-config': 'true', 'use-expressions':false], c)
@@ -67,7 +67,7 @@ abstract class AbstractHttpConfigTests extends AbstractXmlConfigTests {
}
FilterInvocation createFilterinvocation(String path, String method) {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod(method);
request.setRequestURI(null);
request.setServletPath(path);
@@ -0,0 +1,47 @@
package org.springframework.security.config.http
import org.springframework.beans.factory.BeanCreationException
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException
import org.springframework.security.web.access.AccessDeniedHandlerImpl
import org.springframework.security.web.access.ExceptionTranslationFilter
/**
*
* @author Luke Taylor
*/
class AccessDeniedConfigTests extends AbstractHttpConfigTests {
def invalidAccessDeniedUrlIsDetected() {
when:
httpAutoConfig() {
'access-denied-handler'('error-page':'noLeadingSlash')
}
createAppContext();
then:
thrown(BeanCreationException)
}
def accessDeniedHandlerIsSetCorectly() {
httpAutoConfig() {
'access-denied-handler'(ref: 'adh')
}
bean('adh', AccessDeniedHandlerImpl)
createAppContext();
def filter = getFilter(ExceptionTranslationFilter.class);
def adh = appContext.getBean("adh");
expect:
filter.accessDeniedHandler == adh
}
def void accessDeniedHandlerPageAndRefAreMutuallyExclusive() {
when:
httpAutoConfig {
'access-denied-handler'('error-page': '/go-away', ref: 'adh')
}
createAppContext();
bean('adh', AccessDeniedHandlerImpl)
then:
thrown(BeanDefinitionParsingException)
}
}
@@ -0,0 +1,342 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.security.config.http
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import spock.lang.Unroll
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.core.context.SecurityContextImpl
import org.springframework.security.web.access.AccessDeniedHandler
import org.springframework.security.web.context.HttpRequestResponseHolder
import org.springframework.security.web.context.HttpSessionSecurityContextRepository
import org.springframework.security.web.csrf.CsrfFilter
import org.springframework.security.web.csrf.CsrfToken
import org.springframework.security.web.csrf.CsrfTokenRepository
import org.springframework.security.web.csrf.DefaultCsrfToken
import org.springframework.security.web.util.matcher.RequestMatcher
import org.springframework.web.servlet.support.RequestDataValueProcessor
import static org.mockito.Matchers.*
import static org.mockito.Mockito.*
/**
*
* @author Rob Winch
*/
class CsrfConfigTests extends AbstractHttpConfigTests {
MockHttpServletRequest request = new MockHttpServletRequest()
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
@Unroll
def 'csrf is enabled by default'() {
setup:
httpAutoConfig {
}
createAppContext()
when:
request.method = httpMethod
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == httpStatus
where:
httpMethod | httpStatus
'POST' | HttpServletResponse.SC_FORBIDDEN
'PUT' | HttpServletResponse.SC_FORBIDDEN
'PATCH' | HttpServletResponse.SC_FORBIDDEN
'DELETE' | HttpServletResponse.SC_FORBIDDEN
'INVALID' | HttpServletResponse.SC_FORBIDDEN
'GET' | HttpServletResponse.SC_OK
'HEAD' | HttpServletResponse.SC_OK
'TRACE' | HttpServletResponse.SC_OK
'OPTIONS' | HttpServletResponse.SC_OK
}
def 'csrf disabled'() {
when:
httpAutoConfig { csrf(disabled:true) }
createAppContext()
then:
!getFilter(CsrfFilter)
}
@Unroll
def 'csrf defaults'() {
setup:
httpAutoConfig { 'csrf'() }
createAppContext()
when:
request.method = httpMethod
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == httpStatus
where:
httpMethod | httpStatus
'POST' | HttpServletResponse.SC_FORBIDDEN
'PUT' | HttpServletResponse.SC_FORBIDDEN
'PATCH' | HttpServletResponse.SC_FORBIDDEN
'DELETE' | HttpServletResponse.SC_FORBIDDEN
'INVALID' | HttpServletResponse.SC_FORBIDDEN
'GET' | HttpServletResponse.SC_OK
'HEAD' | HttpServletResponse.SC_OK
'TRACE' | HttpServletResponse.SC_OK
'OPTIONS' | HttpServletResponse.SC_OK
}
def 'csrf default creates CsrfRequestDataValueProcessor'() {
when:
httpAutoConfig { 'csrf'() }
createAppContext()
then:
appContext.getBean("requestDataValueProcessor",RequestDataValueProcessor)
}
def 'csrf custom AccessDeniedHandler'() {
setup:
httpAutoConfig {
'access-denied-handler'(ref:'adh')
'csrf'()
}
mockBean(AccessDeniedHandler,'adh')
createAppContext()
AccessDeniedHandler adh = appContext.getBean(AccessDeniedHandler)
request.method = "POST"
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
verify(adh).handle(any(HttpServletRequest),any(HttpServletResponse),any(AccessDeniedException))
response.status == HttpServletResponse.SC_OK // our mock doesn't do anything
}
def "csrf disables posts for RequestCache"() {
setup:
httpAutoConfig {
'csrf'('token-repository-ref':'repo')
'intercept-url'(pattern:"/**",access:'ROLE_USER')
}
mockBean(CsrfTokenRepository,'repo')
createAppContext()
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
CsrfToken token = new DefaultCsrfToken("X-CSRF-TOKEN","_csrf", "abc")
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
when(repo.generateToken(any(HttpServletRequest))).thenReturn(token)
request.setParameter(token.parameterName,token.token)
request.servletPath = "/some-url"
request.requestURI = "/some-url"
request.method = "POST"
when: "CSRF passes and our session times out"
springSecurityFilterChain.doFilter(request,response,chain)
then: "sent to the login page"
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
response.redirectedUrl == "http://localhost/login"
when: "authenticate successfully"
response = new MockHttpServletResponse()
request = new MockHttpServletRequest(session: request.session)
request.servletPath = "/login"
request.setParameter(token.parameterName,token.token)
request.setParameter("username","user")
request.setParameter("password","password")
request.method = "POST"
springSecurityFilterChain.doFilter(request,response,chain)
then: "sent to default success because we don't want csrf attempts made prior to authentication to pass"
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
response.redirectedUrl == "/"
}
def "csrf enables gets for RequestCache"() {
setup:
httpAutoConfig {
'csrf'('token-repository-ref':'repo')
'intercept-url'(pattern:"/**",access:'ROLE_USER')
}
mockBean(CsrfTokenRepository,'repo')
createAppContext()
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
CsrfToken token = new DefaultCsrfToken("X-CSRF-TOKEN","_csrf", "abc")
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
when(repo.generateToken(any(HttpServletRequest))).thenReturn(token)
request.setParameter(token.parameterName,token.token)
request.servletPath = "/some-url"
request.requestURI = "/some-url"
request.method = "GET"
when: "CSRF passes and our session times out"
springSecurityFilterChain.doFilter(request,response,chain)
then: "sent to the login page"
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
response.redirectedUrl == "http://localhost/login"
when: "authenticate successfully"
response = new MockHttpServletResponse()
request = new MockHttpServletRequest(session: request.session)
request.servletPath = "/login"
request.setParameter(token.parameterName,token.token)
request.setParameter("username","user")
request.setParameter("password","password")
request.method = "POST"
springSecurityFilterChain.doFilter(request,response,chain)
then: "sent to original URL since it was a GET"
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
response.redirectedUrl == "http://localhost/some-url"
}
def "SEC-2422: csrf expire CSRF token and session-management invalid-session-url"() {
setup:
httpAutoConfig {
'csrf'()
'session-management'('invalid-session-url': '/error/sessionError')
}
createAppContext()
request.setParameter("_csrf","abc")
request.method = "POST"
when: "No existing expected CsrfToken (session times out) and a POST"
springSecurityFilterChain.doFilter(request,response,chain)
then: "sent to the session timeout page page"
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
response.redirectedUrl == "/error/sessionError"
when: "Existing expected CsrfToken and a POST (invalid token provided)"
response = new MockHttpServletResponse()
request = new MockHttpServletRequest(session: request.session, method:'POST')
springSecurityFilterChain.doFilter(request,response,chain)
then: "Access Denied occurs"
response.status == HttpServletResponse.SC_FORBIDDEN
}
def "csrf requireCsrfProtectionMatcher"() {
setup:
httpAutoConfig { 'csrf'('request-matcher-ref':'matcher') }
mockBean(RequestMatcher,'matcher')
createAppContext()
request.method = 'POST'
RequestMatcher matcher = appContext.getBean("matcher",RequestMatcher)
when:
when(matcher.matches(any(HttpServletRequest))).thenReturn(false)
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_OK
when:
when(matcher.matches(any(HttpServletRequest))).thenReturn(true)
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_FORBIDDEN
}
def "csrf csrfTokenRepository default delays save"() {
setup:
httpAutoConfig {
}
createAppContext()
request.method = "GET"
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_OK
request.getSession(false) == null
}
def "csrf csrfTokenRepository"() {
setup:
httpAutoConfig { 'csrf'('token-repository-ref':'repo') }
mockBean(CsrfTokenRepository,'repo')
createAppContext()
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
CsrfToken token = new DefaultCsrfToken("X-CSRF-TOKEN","_csrf", "abc")
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
request.setParameter(token.parameterName,token.token)
request.method = "POST"
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_OK
when:
request.setParameter(token.parameterName,token.token+"INVALID")
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == HttpServletResponse.SC_FORBIDDEN
}
def "csrf clears on login"() {
setup:
httpAutoConfig { 'csrf'('token-repository-ref':'repo') }
mockBean(CsrfTokenRepository,'repo')
createAppContext()
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
CsrfToken token = new DefaultCsrfToken("X-CSRF-TOKEN","_csrf", "abc")
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
when(repo.generateToken(any(HttpServletRequest))).thenReturn(token)
request.setParameter(token.parameterName,token.token)
request.method = "POST"
request.setParameter("username","user")
request.setParameter("password","password")
request.servletPath = "/login"
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
verify(repo, atLeastOnce()).saveToken(eq(null),any(HttpServletRequest), any(HttpServletResponse))
}
def "csrf clears on logout"() {
setup:
httpAutoConfig { 'csrf'('token-repository-ref':'repo') }
mockBean(CsrfTokenRepository,'repo')
createAppContext()
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
CsrfToken token = new DefaultCsrfToken("X-CSRF-TOKEN","_csrf", "abc")
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
request.setParameter(token.parameterName,token.token)
request.method = "POST"
request.servletPath = "/logout"
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
verify(repo).saveToken(eq(null),any(HttpServletRequest), any(HttpServletResponse))
}
def "SEC-2495: csrf disables logout on GET"() {
setup:
httpAutoConfig { 'csrf'() }
createAppContext()
login()
request.method = "GET"
request.requestURI = "/logout"
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
getAuthentication(request) != null
}
def login(String username="user", String role="ROLE_USER") {
login(new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(role)))
}
def login(Authentication auth) {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository()
HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
repo.loadContext(requestResponseHolder)
repo.saveContext(new SecurityContextImpl(authentication:auth), requestResponseHolder.request, requestResponseHolder.response)
}
def getAuthentication(HttpServletRequest request) {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository()
HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
repo.loadContext(requestResponseHolder)?.authentication
}
}
@@ -0,0 +1,153 @@
package org.springframework.security.config.http
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.web.WebAttributes
/**
*
* @author Luke Taylor
*/
class FormLoginBeanDefinitionParserTests extends AbstractHttpConfigTests {
def 'form-login default login page'() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
httpAutoConfig {
csrf(disabled:true)
}
createAppContext()
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
</table>
</form></body></html>"""
}
def 'form-login default login page custom attributes'() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
httpAutoConfig {
'form-login'('login-processing-url':'/login_custom','username-parameter':'custom_user','password-parameter':'custom_password')
csrf(disabled:true)
}
createAppContext()
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.custom_user.focus();'>
<h3>Login with Username and Password</h3><form name='f' action='/login_custom' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='custom_user' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='custom_password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
</table>
</form></body></html>"""
}
def 'openid-login default login page'() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
httpAutoConfig {
'openid-login'()
csrf(disabled:true)
}
createAppContext()
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
</table>
</form><h3>Login with OpenID Identity</h3><form name='oidf' action='/login/openid' method='POST'>
<table>
<tr><td>Identity:</td><td><input type='text' size='30' name='openid_identifier'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
</table>
</form></body></html>"""
}
def 'openid-login default login page custom attributes'() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
httpAutoConfig {
'openid-login'('login-processing-url':'/login_custom')
csrf(disabled:true)
}
createAppContext()
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getContentAsString() == """<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
</table>
</form><h3>Login with OpenID Identity</h3><form name='oidf' action='/login_custom' method='POST'>
<table>
<tr><td>Identity:</td><td><input type='text' size='30' name='openid_identifier'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
</table>
</form></body></html>"""
}
def 'form-login forward authentication failure handler'() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'POST',servletPath:'/login')
request.setParameter("username", "bob")
request.setParameter("password", "invalidpassword")
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
httpAutoConfig {
'form-login'('authentication-failure-forward-url':'/failure_forward_url')
csrf(disabled:true)
}
createAppContext()
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getStatus() == 200
response.forwardedUrl == "/failure_forward_url"
request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) != null;
}
def 'form-login forward authentication success handler'() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'POST',servletPath:'/login')
request.setParameter("username", "bob")
request.setParameter("password", "bobspassword")
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
httpAutoConfig {
'form-login'('authentication-success-forward-url':'/success_forward_url')
csrf(disabled:true)
}
createAppContext()
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.getStatus() == 200
response.forwardedUrl == "/success_forward_url"
}
}
@@ -0,0 +1,161 @@
package org.springframework.security.config.http
import javax.servlet.http.HttpServletResponse
import org.springframework.beans.factory.BeanCreationException
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.util.FieldUtils
import org.springframework.security.web.access.ExceptionTranslationFilter
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
import spock.lang.Unroll;
/**
*
* @author Luke Taylor
*/
class FormLoginConfigTests extends AbstractHttpConfigTests {
def formLoginWithNoLoginPageAddsDefaultLoginPageFilter() {
httpAutoConfig('ant') {
form-login()
}
createAppContext()
filtersMatchExpectedAutoConfigList();
}
def 'Form login alwaysUseDefaultTarget sets correct property'() {
xml.http {
'form-login'('default-target-url':'/default', 'always-use-default-target': 'true')
}
createAppContext()
def filter = getFilter(UsernamePasswordAuthenticationFilter.class);
expect:
FieldUtils.getFieldValue(filter, 'successHandler.defaultTargetUrl') == '/default';
FieldUtils.getFieldValue(filter, 'successHandler.alwaysUseDefaultTargetUrl');
}
def 'form-login attributes support SpEL'() {
setup:
def spelUrl = '#{T(org.springframework.security.config.http.WebConfigUtilsTest).URL}'
def expectedUrl = WebConfigUtilsTest.URL
when:
xml.http {
'form-login'('default-target-url': spelUrl , 'authentication-failure-url': spelUrl, 'login-page': spelUrl)
}
createAppContext()
def unPwdFilter = getFilter(UsernamePasswordAuthenticationFilter)
def exTransFilter = getFilter(ExceptionTranslationFilter)
then:
unPwdFilter.successHandler.defaultTargetUrl == expectedUrl
unPwdFilter
FieldUtils.getFieldValue(unPwdFilter, 'successHandler.defaultTargetUrl') == expectedUrl
FieldUtils.getFieldValue(unPwdFilter, 'failureHandler.defaultFailureUrl') == expectedUrl
FieldUtils.getFieldValue(exTransFilter, 'authenticationEntryPoint.loginFormUrl') == expectedUrl
}
def invalidLoginPageIsDetected() {
when:
xml.http {
'form-login'('login-page': 'noLeadingSlash')
}
createAppContext()
then:
BeanCreationException e = thrown();
}
def invalidDefaultTargetUrlIsDetected() {
when:
xml.http {
'form-login'('default-target-url': 'noLeadingSlash')
}
createAppContext()
then:
BeanCreationException e = thrown();
}
def customSuccessAndFailureHandlersCanBeSetThroughTheNamespace() {
xml.http {
'form-login'('authentication-success-handler-ref': 'sh', 'authentication-failure-handler-ref':'fh')
}
bean('sh', SavedRequestAwareAuthenticationSuccessHandler.class.name)
bean('fh', SimpleUrlAuthenticationFailureHandler.class.name)
createAppContext()
def apf = getFilter(UsernamePasswordAuthenticationFilter.class);
expect:
FieldUtils.getFieldValue(apf, "successHandler") == appContext.getBean("sh");
FieldUtils.getFieldValue(apf, "failureHandler") == appContext.getBean("fh")
}
def usernameAndPasswordParametersCanBeSetThroughNamespace() {
xml.http {
'form-login'('username-parameter': 'xname', 'password-parameter':'xpass')
}
createAppContext()
def apf = getFilter(UsernamePasswordAuthenticationFilter.class);
expect:
apf.usernameParameter == 'xname';
apf.passwordParameter == 'xpass'
}
def 'SEC-2919: DefaultLoginGeneratingFilter should not be present if login-page="/login"'() {
when:
xml.http() {
'form-login'('login-page':'/login')
}
createAppContext()
then:
getFilter(DefaultLoginPageGeneratingFilter) == null
}
@Unroll
def 'Form Login requires CSRF Token #csrfDisabled'(int status, boolean csrfDisabled) {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'POST',servletPath:'/login')
request.setParameter('username','user')
request.setParameter('password','password')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
httpAutoConfig {
'form-login'()
csrf(disabled:csrfDisabled) {}
}
createAppContext()
when:
springSecurityFilterChain.doFilter(request,response,chain)
then:
response.status == status
where:
status | csrfDisabled
HttpServletResponse.SC_FORBIDDEN | false
HttpServletResponse.SC_MOVED_TEMPORARILY | true
}
def 'SEC-3147: authentication-failure-url should be contained "error" parameter if login-page="/login"'() {
xml.http {
'form-login'('login-page':'/login')
}
createAppContext()
def apf = getFilter(UsernamePasswordAuthenticationFilter.class);
expect:
apf.failureHandler.defaultFailureUrl == '/login?error'
}
}
@@ -0,0 +1,79 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.security.config.http
import static org.mockito.Matchers.any
import static org.mockito.Matchers.eq
import static org.mockito.Mockito.*
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponseWrapper
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
/**
*
* @author Rob Winch
*/
class HttpConfigTests extends AbstractHttpConfigTests {
MockHttpServletRequest request = new MockHttpServletRequest('GET','/secure')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
def 'http minimal configuration works'() {
setup:
xml.http() {}
createAppContext("""<user-service>
<user name="user" password="password" authorities="ROLE_USER" />
</user-service>""")
when: 'request protected URL'
springSecurityFilterChain.doFilter(request,response,chain)
then: 'sent to login page'
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
response.redirectedUrl == 'http://localhost/login'
}
def 'http disable-url-rewriting defaults to true'() {
setup:
xml.http() {}
createAppContext("""<user-service>
<user name="user" password="password" authorities="ROLE_USER" />
</user-service>""")
HttpServletResponse testResponse = new HttpServletResponseWrapper(response) {
public String encodeURL(String url) {
throw new RuntimeException("Unexpected invocation of encodeURL")
}
public String encodeRedirectURL(String url) {
throw new RuntimeException("Unexpected invocation of encodeURL")
}
public String encodeUrl(String url) {
throw new RuntimeException("Unexpected invocation of encodeURL")
}
public String encodeRedirectUrl(String url) {
throw new RuntimeException("Unexpected invocation of encodeURL")
}
}
when: 'request protected URL'
springSecurityFilterChain.doFilter(request,testResponse,{ request,response->
response.encodeURL("/url")
response.encodeRedirectURL("/url")
response.encodeUrl("/url")
response.encodeRedirectUrl("/url")
})
then: 'sent to login page'
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
response.redirectedUrl == 'http://localhost/login'
}
}
@@ -0,0 +1,171 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.security.config.http
import org.springframework.beans.factory.BeanCreationException
import javax.servlet.http.HttpServletResponse
import org.springframework.http.*
import org.springframework.mock.web.*
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint
import org.springframework.web.bind.annotation.*
import org.springframework.web.filter.CorsFilter
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
/**
*
* @author Rob Winch
* @author Tim Ysewyn
*/
class HttpCorsConfigTests extends AbstractHttpConfigTests {
MockHttpServletRequest request
MockHttpServletResponse response
MockFilterChain chain
def setup() {
request = new MockHttpServletRequest(method:"GET")
response = new MockHttpServletResponse()
chain = new MockFilterChain()
}
def "No MVC throws meaningful error"() {
when:
xml.http('entry-point-ref' : 'ep') {
'cors'()
'intercept-url'(pattern:'/**', access: 'authenticated')
}
bean('ep', Http403ForbiddenEntryPoint)
createAppContext()
then:
BeanCreationException success = thrown()
success.message.contains("Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext")
}
def "HandlerMappingIntrospector explicit"() {
setup:
xml.http('entry-point-ref' : 'ep') {
'cors'()
'intercept-url'(pattern:'/**', access: 'authenticated')
}
bean('ep', Http403ForbiddenEntryPoint)
bean('controller', CorsController)
xml.'mvc:annotation-driven'()
createAppContext()
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
when:
setup()
addCors(true)
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
response.status == HttpServletResponse.SC_OK
}
def "CorsConfigurationSource"() {
setup:
xml.http('entry-point-ref' : 'ep') {
'cors'('configuration-source-ref':'ccs')
'intercept-url'(pattern:'/**', access: 'authenticated')
}
bean('ep', Http403ForbiddenEntryPoint)
bean('ccs', MyCorsConfigurationSource)
createAppContext()
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
when:
setup()
addCors(true)
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
response.status == HttpServletResponse.SC_OK
}
def "CorsFilter"() {
setup:
xml.http('entry-point-ref' : 'ep') {
'cors'('ref' : 'cf')
'intercept-url'(pattern:'/**', access: 'authenticated')
}
xml.'b:bean'(id: 'cf', 'class': CorsFilter.name) {
'b:constructor-arg'(ref: 'ccs')
}
bean('ep', Http403ForbiddenEntryPoint)
bean('ccs', MyCorsConfigurationSource)
createAppContext()
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
when:
setup()
addCors(true)
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
response.status == HttpServletResponse.SC_OK
}
def addCors(boolean isPreflight=false) {
request.addHeader(HttpHeaders.ORIGIN,"https://example.com")
if(!isPreflight) {
return
}
request.method = HttpMethod.OPTIONS.name()
request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
}
def getResponseHeaders() {
def headers = [:]
response.headerNames.each { name ->
headers.put(name, response.getHeaderValues(name).join(','))
}
return headers
}
@RestController
@CrossOrigin(methods = [
RequestMethod.GET, RequestMethod.POST
])
static class CorsController {
@RequestMapping("/")
String hello() {
"Hello"
}
}
static class MyCorsConfigurationSource extends UrlBasedCorsConfigurationSource {
MyCorsConfigurationSource() {
registerCorsConfiguration('/**', new CorsConfiguration(allowedOrigins : ['*'], allowedMethods : [
RequestMethod.GET.name(),
RequestMethod.POST.name()
]))
}
}
}
@@ -0,0 +1,961 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.security.config.http
import org.springframework.beans.factory.BeanCreationException
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException
import org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.web.FilterChainProxy
import org.springframework.security.web.header.HeaderWriterFilter
import org.springframework.security.web.header.writers.StaticHeadersWriter
import org.springframework.security.web.util.matcher.AnyRequestMatcher
/**
*
* @author Rob Winch
* @author Tim Ysewyn
*/
class HttpHeadersConfigTests extends AbstractHttpConfigTests {
def defaultHeaders = ['X-Content-Type-Options':'nosniff',
'X-Frame-Options':'DENY',
'Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
'Expires' : '0',
'Pragma':'no-cache',
'X-XSS-Protection' : '1; mode=block']
def 'headers disabled'() {
setup:
httpAutoConfig {
'headers'(disabled:true)
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
then:
!hf
}
def 'headers disabled with child fails'() {
when:
httpAutoConfig {
'headers'(disabled:true) {
'content-type-options'()
}
}
createAppContext()
then:
thrown(BeanDefinitionParsingException)
}
def 'default headers'() {
httpAutoConfig {
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, defaultHeaders)
}
def 'http headers with empty headers'() {
setup:
httpAutoConfig {
'headers'()
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, defaultHeaders)
}
def 'http headers frame-options@policy=SAMEORIGIN with defaults'() {
httpAutoConfig {
'headers'() {
'frame-options'(policy:'SAMEORIGIN')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
def expectedHeaders = [:] << defaultHeaders
expectedHeaders['X-Frame-Options'] = 'SAMEORIGIN'
expect:
assertHeaders(response, expectedHeaders)
}
// --- defaults disabled
// gh-3986
def 'http headers defaults-disabled with no override'() {
httpAutoConfig {
'headers'('defaults-disabled':true) {
}
}
createAppContext()
expect:
getFilter(HeaderWriterFilter) == null
}
def 'http headers content-type-options'() {
httpAutoConfig {
'headers'('defaults-disabled':true) {
'content-type-options'()
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
expect:
assertHeaders(response, ['X-Content-Type-Options':'nosniff'])
}
def 'http headers frame-options defaults to DENY'() {
httpAutoConfig {
'headers'('defaults-disabled':true) {
'frame-options'()
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
expect:
assertHeaders(response, ['X-Frame-Options':'DENY'])
}
def 'http headers frame-options DENY'() {
httpAutoConfig {
'headers'('defaults-disabled':true) {
'frame-options'(policy : 'DENY')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
expect:
assertHeaders(response, ['X-Frame-Options':'DENY'])
}
def 'http headers frame-options SAMEORIGIN'() {
httpAutoConfig {
'headers'('defaults-disabled':true) {
'frame-options'(policy : 'SAMEORIGIN')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
expect:
assertHeaders(response, ['X-Frame-Options':'SAMEORIGIN'])
}
def 'http headers frame-options ALLOW-FROM no origin reports error'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'frame-options'(policy : 'ALLOW-FROM', strategy : 'static')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
then:
BeanDefinitionParsingException e = thrown()
e.message.contains "Strategy requires a 'value' to be set." // FIME better error message?
}
def 'http headers frame-options ALLOW-FROM spaces only origin reports error'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'frame-options'(policy : 'ALLOW-FROM', strategy: 'static', value : ' ')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
then:
BeanDefinitionParsingException e = thrown()
e.message.contains "Strategy requires a 'value' to be set." // FIME better error message?
}
def 'http headers frame-options ALLOW-FROM'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'frame-options'(policy : 'ALLOW-FROM', strategy: 'static', value : 'https://example.com')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['X-Frame-Options':'ALLOW-FROM https://example.com'])
}
def 'http headers frame-options ALLOW-FROM with whitelist strategy'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'frame-options'(policy : 'ALLOW-FROM', strategy: 'whitelist', value : 'https://example.com')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
def request = new MockHttpServletRequest()
request.setParameter("from", "https://example.com");
hf.doFilter(request, response, new MockFilterChain())
then:
assertHeaders(response, ['X-Frame-Options':'ALLOW-FROM https://example.com'])
}
def 'http headers header a=b'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'header'(name : 'a', value: 'b')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['a':'b'])
}
def 'http headers header a=b and c=d'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'header'(name : 'a', value: 'b')
'header'(name : 'c', value: 'd')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response , ['a':'b', 'c':'d'])
}
def 'http headers with ref'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'header'(ref:'headerWriter')
}
}
xml.'b:bean'(id: 'headerWriter', 'class': StaticHeadersWriter.name) {
'b:constructor-arg'(value:'abc') {}
'b:constructor-arg'(value:'def') {}
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['abc':'def'])
}
def 'http headers header no name produces error'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'header'(value: 'b')
}
}
createAppContext()
then:
thrown(BeanCreationException)
}
def 'http headers header no value produces error'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'header'(name: 'a')
}
}
createAppContext()
then:
thrown(BeanCreationException)
}
def 'http headers xss-protection defaults'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'xss-protection'()
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['X-XSS-Protection':'1; mode=block'])
}
def 'http headers xss-protection enabled=true'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'xss-protection'(enabled:'true')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['X-XSS-Protection':'1; mode=block'])
}
def 'http headers xss-protection enabled=false'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'xss-protection'(enabled:'false')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['X-XSS-Protection':'0'])
}
def 'http headers xss-protection enabled=false and block=true produces error'() {
when:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'xss-protection'(enabled:'false', block:'true')
}
}
createAppContext()
def hf = getFilter(HeaderWriterFilter)
then:
BeanCreationException e = thrown()
e.message.contains 'Cannot set block to true with enabled false'
}
def 'http headers cache-control'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'cache-control'()
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
'Expires' : '0',
'Pragma':'no-cache'])
}
def 'http headers hsts'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hsts'()
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, ['Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains'])
}
def 'http headers hsts default only invokes on HttpServletRequest.isSecure = true'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hsts'()
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
response.headerNames.empty
}
def 'http headers hsts custom'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hsts'('max-age-seconds':'1','include-subdomains':false, 'request-matcher-ref' : 'matcher')
}
}
xml.'b:bean'(id: 'matcher', 'class': AnyRequestMatcher.name)
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['Strict-Transport-Security': 'max-age=1'])
}
def 'http headers hpkp no pins'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'()
}
}
when:
createAppContext()
then:
XmlBeanDefinitionStoreException expected = thrown()
expected.message.contains 'The content of element \'hpkp\' is not complete'
}
def 'http headers hpkp no pin'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'() {
'pins'()
}
}
}
when:
createAppContext()
then:
XmlBeanDefinitionStoreException expected = thrown()
expected.message.contains 'The content of element \'pins\' is not complete'
}
def 'http headers hpkp'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'() {
'pins'() {
'pin'('algorithm':'sha256', 'd6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=')
}
}
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, ['Public-Key-Pins-Report-Only': 'max-age=5184000 ; pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="'])
}
def 'http headers hpkp with default algorithm'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'() {
'pins'() {
'pin'('d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=')
}
}
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, ['Public-Key-Pins-Report-Only': 'max-age=5184000 ; pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="'])
}
def 'http headers hpkp only invokes on HttpServletRequest.isSecure = true'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'() {
'pins'() {
'pin'('algorithm':'sha256', 'E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=')
}
}
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
response.headerNames.empty
}
def 'http headers hpkp with custom max age'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'('max-age-seconds':'604800') {
'pins'() {
'pin'('algorithm':'sha256', 'd6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=')
}
}
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, ['Public-Key-Pins-Report-Only': 'max-age=604800 ; pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="'])
}
def 'http headers hpkp@reportOnly=false'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'('report-only':'false') {
'pins'() {
'pin'('algorithm':'sha256', 'E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=')
}
}
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure: true), response, new MockFilterChain())
then:
assertHeaders(response, ['Public-Key-Pins': 'max-age=5184000 ; pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="'])
}
def 'http headers hpkp@includeSubDomains=true'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'('include-subdomains':'true') {
'pins'() {
'pin'('algorithm':'sha256', 'E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=')
}
}
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure: true), response, new MockFilterChain())
then:
assertHeaders(response, ['Public-Key-Pins-Report-Only': 'max-age=5184000 ; pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" ; includeSubDomains'])
}
def 'http headers hpkp with report-uri'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'hpkp'('report-uri':'http://example.net/pkp-report') {
'pins'() {
'pin'('algorithm':'sha256', 'E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=')
}
}
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure: true), response, new MockFilterChain())
then:
assertHeaders(response, ['Public-Key-Pins-Report-Only': 'max-age=5184000 ; pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" ; report-uri="http://example.net/pkp-report"'])
}
// --- disable single default header ---
def 'http headers cache-controls@disabled=true'() {
setup:
httpAutoConfig {
'headers'() {
'cache-control'(disabled:true)
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
def expectedHeaders = [:] << defaultHeaders
expectedHeaders.remove('Cache-Control')
expectedHeaders.remove('Expires')
expectedHeaders.remove('Pragma')
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, expectedHeaders)
}
def 'http headers content-type-options@disabled=true'() {
setup:
httpAutoConfig {
'headers'() {
'content-type-options'(disabled:true)
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
def expectedHeaders = [:] << defaultHeaders
expectedHeaders.remove('X-Content-Type-Options')
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, expectedHeaders)
}
def 'http headers hsts@disabled=true'() {
setup:
httpAutoConfig {
'headers'() {
'hsts'(disabled:true)
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
def expectedHeaders = [:] << defaultHeaders
expectedHeaders.remove('Strict-Transport-Security')
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, expectedHeaders)
}
def 'http headers hpkp@disabled=true'() {
setup:
httpAutoConfig {
'headers'() {
'hpkp'(disabled:true) {
'pins'() {
'pin'('algorithm':'sha256', 'E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=')
}
}
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
def expectedHeaders = [:] << defaultHeaders
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, expectedHeaders)
}
def 'http headers frame-options@disabled=true'() {
setup:
httpAutoConfig {
'headers'() {
'frame-options'(disabled:true)
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
def expectedHeaders = [:] << defaultHeaders
expectedHeaders.remove('X-Frame-Options')
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, expectedHeaders)
}
def 'http headers xss-protection@disabled=true'() {
setup:
httpAutoConfig {
'headers'() {
'xss-protection'(disabled:true)
}
}
createAppContext()
def springSecurityFilterChain = appContext.getBean(FilterChainProxy)
MockHttpServletResponse response = new MockHttpServletResponse()
def expectedHeaders = [:] << defaultHeaders
expectedHeaders.remove('X-XSS-Protection')
when:
springSecurityFilterChain.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, expectedHeaders)
}
// --- disable error handling ---
def 'http headers hsts@disabled=true no include-subdomains'() {
setup:
httpAutoConfig {
'headers'() {
'hsts'(disabled:true,'include-subdomains':true)
}
}
when:
createAppContext()
then:
BeanDefinitionParsingException expected = thrown()
expected.message.contains 'include-subdomains'
}
def 'http headers hsts@disabled=true no max-age'() {
setup:
httpAutoConfig {
'headers'() {
'hsts'(disabled:true,'max-age-seconds':123)
}
}
when:
createAppContext()
then:
BeanDefinitionParsingException expected = thrown()
expected.message.contains 'max-age'
}
def 'http headers hsts@disabled=true no matcher-ref'() {
setup:
httpAutoConfig {
'headers'() {
'hsts'(disabled:true,'request-matcher-ref':'matcher')
}
}
xml.'b:bean'(id: 'matcher', 'class': AnyRequestMatcher.name)
when:
createAppContext()
then:
BeanDefinitionParsingException expected = thrown()
expected.message.contains 'request-matcher-ref'
}
def 'http xss@disabled=true no enabled'() {
setup:
httpAutoConfig {
'headers'() {
'xss-protection'(disabled:true,'enabled':true)
}
}
when:
createAppContext()
then:
BeanDefinitionParsingException expected = thrown()
expected.message.contains 'enabled'
}
def 'http xss@disabled=true no block'() {
setup:
httpAutoConfig {
'headers'() {
'xss-protection'(disabled:true,'block':true)
}
}
when:
createAppContext()
then:
BeanDefinitionParsingException expected = thrown()
expected.message.contains 'block'
}
def 'http frame-options@disabled=true no policy'() {
setup:
httpAutoConfig {
'headers'() {
'frame-options'(disabled:true,'policy':'DENY')
}
}
when:
createAppContext()
then:
BeanDefinitionParsingException expected = thrown()
expected.message.contains 'policy'
}
def 'http headers defaults : content-security-policy'() {
setup:
httpAutoConfig {
'headers'() {
'content-security-policy'('policy-directives':'default-src \'self\'')
}
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
def expectedHeaders = [:] << defaultHeaders
expectedHeaders['Content-Security-Policy'] = 'default-src \'self\''
then:
assertHeaders(response, expectedHeaders)
}
def 'http headers disabled : content-security-policy not included'() {
setup:
httpAutoConfig {
'headers'(disabled:true) {
'content-security-policy'('policy-directives':'default-src \'self\'')
}
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
then:
!hf
}
def 'http headers defaults disabled : content-security-policy only'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'content-security-policy'('policy-directives':'default-src \'self\'')
}
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
then:
assertHeaders(response, ['Content-Security-Policy':'default-src \'self\''])
}
def 'http headers defaults : content-security-policy with empty directives'() {
when:
httpAutoConfig {
'headers'() {
'content-security-policy'('policy-directives':'')
}
}
createAppContext()
then:
thrown(BeanDefinitionParsingException)
}
def 'http headers defaults : content-security-policy report-only=true'() {
setup:
httpAutoConfig {
'headers'() {
'content-security-policy'('policy-directives':'default-src https:; report-uri https://example.com/', 'report-only':true)
}
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(secure:true), response, new MockFilterChain())
def expectedHeaders = [:] << defaultHeaders
expectedHeaders['Content-Security-Policy-Report-Only'] = 'default-src https:; report-uri https://example.com/'
then:
assertHeaders(response, expectedHeaders)
}
def 'http headers defaults : referrer-policy'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'referrer-policy'()
}
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['Referrer-Policy': 'no-referrer'])
}
def 'http headers defaults : referrer-policy same-origin'() {
setup:
httpAutoConfig {
'headers'('defaults-disabled':true) {
'referrer-policy'('policy': 'same-origin')
}
}
createAppContext()
when:
def hf = getFilter(HeaderWriterFilter)
MockHttpServletResponse response = new MockHttpServletResponse()
hf.doFilter(new MockHttpServletRequest(), response, new MockFilterChain())
then:
assertHeaders(response, ['Referrer-Policy': 'same-origin'])
}
def assertHeaders(MockHttpServletResponse response, Map<String,String> expected) {
assert response.headerNames == expected.keySet()
expected.each { headerName, value ->
assert response.getHeaderValues(headerName) == [value]
}
}
}
@@ -0,0 +1,166 @@
package org.springframework.security.config.http
import javax.servlet.http.HttpServletRequest
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.config.BeanIds
import org.springframework.security.openid.OpenIDAuthenticationFilter
import org.springframework.security.openid.OpenIDAuthenticationToken
import org.springframework.security.openid.OpenIDConsumer
import org.springframework.security.openid.OpenIDConsumerException
import org.springframework.security.web.access.ExceptionTranslationFilter
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
import javax.servlet.Filter
/**
*
* @author Luke Taylor
*/
class OpenIDConfigTests extends AbstractHttpConfigTests {
def openIDAndFormLoginWorkTogether() {
xml.http() {
'openid-login'()
'form-login'()
}
createAppContext()
def etf = getFilter(ExceptionTranslationFilter)
def ap = etf.getAuthenticationEntryPoint();
expect:
ap.loginFormUrl == "/login"
// Default login filter should be present since we haven't specified any login URLs
getFilter(DefaultLoginPageGeneratingFilter) != null
}
def formLoginEntryPointTakesPrecedenceIfLoginUrlIsSet() {
xml.http() {
'openid-login'()
'form-login'('login-page': '/form-page')
}
createAppContext()
expect:
getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl == '/form-page'
}
def openIDEntryPointTakesPrecedenceIfLoginUrlIsSet() {
xml.http() {
'openid-login'('login-page': '/openid-page')
'form-login'()
}
createAppContext()
expect:
getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl == '/openid-page'
}
def multipleLoginPagesCausesError() {
when:
xml.http() {
'openid-login'('login-page': '/openid-page')
'form-login'('login-page': '/form-page')
}
createAppContext()
then:
thrown(BeanDefinitionParsingException)
}
def openIDAndRememberMeWorkTogether() {
xml.debug()
xml.http() {
interceptUrl('/**', 'denyAll')
'openid-login'()
'remember-me'()
'csrf'(disabled:true)
}
createAppContext()
// Default login filter should be present since we haven't specified any login URLs
def loginFilter = getFilter(DefaultLoginPageGeneratingFilter)
def openIDFilter = getFilter(OpenIDAuthenticationFilter)
openIDFilter.setConsumer(new OpenIDConsumer() {
public String beginConsumption(HttpServletRequest req, String claimedIdentity, String returnToUrl, String realm)
throws OpenIDConsumerException {
return "http://testopenid.com?openid.return_to=" + returnToUrl;
}
public OpenIDAuthenticationToken endConsumption(HttpServletRequest req) throws OpenIDConsumerException {
throw new UnsupportedOperationException();
}
})
Set<String> returnToUrlParameters = new HashSet<String>()
returnToUrlParameters.add(AbstractRememberMeServices.DEFAULT_PARAMETER)
openIDFilter.setReturnToUrlParameters(returnToUrlParameters)
assert loginFilter.openIDrememberMeParameter != null
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET');
MockHttpServletResponse response = new MockHttpServletResponse();
when: "Initial request is made"
Filter fc = appContext.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)
request.setServletPath("/something.html")
fc.doFilter(request, response, new MockFilterChain())
then: "Redirected to login"
response.getRedirectedUrl().endsWith("/login")
when: "Login page is requested"
request.setServletPath("/login")
request.setRequestURI("/login")
response = new MockHttpServletResponse()
fc.doFilter(request, response, new MockFilterChain())
then: "Remember-me choice is added to page"
response.getContentAsString().contains(AbstractRememberMeServices.DEFAULT_PARAMETER)
when: "Login is submitted with remember-me selected"
request.servletPath = "/login/openid"
request.setParameter(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, "http://hey.openid.com/")
request.setParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "on")
response = new MockHttpServletResponse();
fc.doFilter(request, response, new MockFilterChain());
String expectedReturnTo = request.getRequestURL().append("?")
.append(AbstractRememberMeServices.DEFAULT_PARAMETER)
.append("=").append("on").toString();
then: "return_to URL contains remember-me choice"
response.getRedirectedUrl() == "http://testopenid.com?openid.return_to=" + expectedReturnTo
}
def openIDWithAttributeExchangeConfigurationIsParsedCorrectly() {
xml.http() {
'openid-login'() {
'attribute-exchange'() {
'openid-attribute'(name: 'nickname', type: 'http://schema.openid.net/namePerson/friendly')
'openid-attribute'(name: 'email', type: 'http://schema.openid.net/contact/email', required: 'true',
'count': '2')
}
}
}
createAppContext()
List attributes = getFilter(OpenIDAuthenticationFilter).consumer.attributesToFetchFactory.createAttributeList('http://someid')
expect:
attributes.size() == 2
attributes[0].name == 'nickname'
attributes[0].type == 'http://schema.openid.net/namePerson/friendly'
!attributes[0].required
attributes[1].required
attributes[1].getCount() == 2
}
def 'SEC-2919: DefaultLoginGeneratingFilter should not be present if login-page="/login"'() {
when:
xml.http() {
'openid-login'('login-page':'/login')
}
createAppContext()
then:
getFilter(DefaultLoginPageGeneratingFilter) == null
}
}
@@ -0,0 +1,400 @@
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.http
import javax.servlet.ServletContext
import javax.servlet.ServletRegistration
import javax.servlet.http.HttpServletResponse
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.mock.web.MockServletContext
import org.springframework.security.access.SecurityConfig
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import static org.mockito.Mockito.*
/**
*
* @author Rob Winch
*/
class InterceptUrlConfigTests extends AbstractHttpConfigTests {
def "SEC-2256: intercept-url method is not given priority"() {
when:
httpAutoConfig {
'intercept-url'(pattern: '/anyurl', access: "ROLE_USER")
'intercept-url'(pattern: '/anyurl', 'method':'GET',access: 'ROLE_ADMIN')
}
createAppContext()
def fids = getFilter(FilterSecurityInterceptor).securityMetadataSource
def attrs = fids.getAttributes(createFilterinvocation("/anyurl", "GET"))
def attrsPost = fids.getAttributes(createFilterinvocation("/anyurl", "POST"))
then:
attrs.size() == 1
attrs.contains(new SecurityConfig("ROLE_USER"))
attrsPost.size() == 1
attrsPost.contains(new SecurityConfig("ROLE_USER"))
}
def "SEC-2355: intercept-url support patch"() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
xml.http('use-expressions':false) {
'http-basic'()
'intercept-url'(pattern: '/**', 'method':'PATCH',access: 'ROLE_ADMIN')
csrf(disabled:true)
}
createAppContext()
when: 'Method other than PATCH is used'
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_OK
when: 'Method of PATCH is used'
request = new MockHttpServletRequest(method:'PATCH')
response = new MockHttpServletResponse()
chain = new MockFilterChain()
springSecurityFilterChain.doFilter(request, response, chain)
then: 'The response is unauthorized'
response.status == HttpServletResponse.SC_UNAUTHORIZED
}
def "intercept-url supports hasAnyRoles"() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
xml.http('use-expressions':true) {
'http-basic'()
'intercept-url'(pattern: '/**', access: "hasAnyRole('ROLE_DEVELOPER','ROLE_USER')")
csrf(disabled:true)
}
when:
createAppContext()
then: 'no error'
noExceptionThrown()
when: 'ROLE_USER can access'
login(request, 'user', 'password')
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_OK
when: 'ROLE_A cannot access'
request = new MockHttpServletRequest(method:'GET')
response = new MockHttpServletResponse()
chain = new MockFilterChain()
login(request, 'bob', 'bobspassword')
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is Forbidden'
response.status == HttpServletResponse.SC_FORBIDDEN
}
def "SEC-2256: intercept-url supports path variables"() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
xml.http('use-expressions':true) {
'http-basic'()
'intercept-url'(pattern: '/user/{un}/**', access: "#un == authentication.name")
'intercept-url'(pattern: '/**', access: "denyAll")
}
createAppContext()
login(request, 'user', 'password')
when: 'user can access'
request.servletPath = '/user/user/abc'
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_OK
when: 'user cannot access otheruser'
request = new MockHttpServletRequest(method:'GET', servletPath : '/user/otheruser/abc')
login(request, 'user', 'password')
response = new MockHttpServletResponse()
chain.reset()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_FORBIDDEN
when: 'user can access case insensitive URL'
request = new MockHttpServletRequest(method:'GET', servletPath : '/USER/user/abc')
login(request, 'user', 'password')
response = new MockHttpServletResponse()
chain.reset()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_FORBIDDEN
}
def "gh-3786 intercept-url supports cammel case path variables"() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
xml.http('use-expressions':true) {
'http-basic'()
'intercept-url'(pattern: '/user/{userName}/**', access: "#userName == authentication.name")
'intercept-url'(pattern: '/**', access: "denyAll")
}
createAppContext()
login(request, 'user', 'password')
when: 'user can access'
request.servletPath = '/user/user/abc'
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_OK
when: 'user cannot access otheruser'
request = new MockHttpServletRequest(method:'GET', servletPath : '/user/otheruser/abc')
login(request, 'user', 'password')
response = new MockHttpServletResponse()
chain.reset()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_FORBIDDEN
when: 'user can access case insensitive URL'
request = new MockHttpServletRequest(method:'GET', servletPath : '/USER/user/abc')
login(request, 'user', 'password')
response = new MockHttpServletResponse()
chain.reset()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_FORBIDDEN
}
def "SEC-2256: intercept-url supports path variable type conversion"() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
xml.http('use-expressions':true) {
'http-basic'()
'intercept-url'(pattern: '/user/{un}/**', access: "@id.isOne(#un)")
'intercept-url'(pattern: '/**', access: "denyAll")
}
bean('id', Id)
createAppContext()
login(request, 'user', 'password')
when: 'can access id == 1'
request.servletPath = '/user/1/abc'
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_OK
when: 'user cannot access 2'
request = new MockHttpServletRequest(method:'GET', servletPath : '/user/2/abc')
login(request, 'user', 'password')
chain.reset()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_FORBIDDEN
}
def "intercept-url supports mvc matchers"() {
setup:
MockServletContext servletContext = mockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
xml.http('request-matcher':'mvc') {
'http-basic'()
'intercept-url'(pattern: '/path', access: "denyAll")
}
bean('pathController',PathController)
xml.'mvc:annotation-driven'()
createWebAppContext(servletContext)
when:
request.servletPath = "/path"
springSecurityFilterChain.doFilter(request, response, chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
when:
request = new MockHttpServletRequest(method:'GET')
response = new MockHttpServletResponse()
chain = new MockFilterChain()
request.servletPath = "/path.html"
springSecurityFilterChain.doFilter(request, response, chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
when:
request = new MockHttpServletRequest(method:'GET')
response = new MockHttpServletResponse()
chain = new MockFilterChain()
request.servletPath = "/path/"
springSecurityFilterChain.doFilter(request, response, chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
}
def "intercept-url mvc supports path variables"() {
setup:
MockServletContext servletContext = mockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
xml.http('request-matcher':'mvc') {
'http-basic'()
'intercept-url'(pattern: '/user/{un}/**', access: "#un == 'user'")
}
xml.'mvc:annotation-driven'()
createWebAppContext(servletContext)
when: 'user can access'
request.servletPath = '/user/user/abc'
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_OK
when: 'cannot access otheruser'
request = new MockHttpServletRequest(method:'GET', servletPath : '/user/otheruser/abc')
login(request, 'user', 'password')
chain.reset()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_FORBIDDEN
when: 'user can access case insensitive URL'
request = new MockHttpServletRequest(method:'GET', servletPath : '/USER/user/abc')
login(request, 'user', 'password')
chain.reset()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'The response is OK'
response.status == HttpServletResponse.SC_FORBIDDEN
}
def "intercept-url mvc matchers with servlet path"() {
setup:
MockServletContext servletContext = mockServletContext("/spring");
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
xml.http('request-matcher':'mvc') {
'http-basic'()
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
}
bean('pathController',PathController)
xml.'mvc:annotation-driven'()
createWebAppContext(servletContext)
when:
request.servletPath = "/spring"
request.requestURI = "/spring/path"
springSecurityFilterChain.doFilter(request, response, chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
when:
request = new MockHttpServletRequest(method:'GET')
response = new MockHttpServletResponse()
chain = new MockFilterChain()
request.servletPath = "/spring"
request.requestURI = "/spring/path.html"
springSecurityFilterChain.doFilter(request, response, chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
when:
request = new MockHttpServletRequest(method:'GET')
response = new MockHttpServletResponse()
chain = new MockFilterChain()
request.servletPath = "/spring"
request.requestURI = "/spring/path/"
springSecurityFilterChain.doFilter(request, response, chain)
then:
response.status == HttpServletResponse.SC_UNAUTHORIZED
}
def "intercept-url ant matcher with servlet path fails"() {
when:
xml.http('request-matcher':'ant') {
'http-basic'()
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
}
createAppContext()
then:
thrown(BeanDefinitionParsingException)
}
def "intercept-url regex matcher with servlet path fails"() {
when:
xml.http('request-matcher':'regex') {
'http-basic'()
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
}
createAppContext()
then:
thrown(BeanDefinitionParsingException)
}
def "intercept-url ciRegex matcher with servlet path fails"() {
when:
xml.http('request-matcher':'ciRegex') {
'http-basic'()
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
}
createAppContext()
then:
thrown(BeanDefinitionParsingException)
}
def "intercept-url default matcher with servlet path fails"() {
when:
xml.http() {
'http-basic'()
'intercept-url'(pattern: '/path', access: "denyAll", 'servlet-path': "/spring")
}
createAppContext()
then:
thrown(BeanDefinitionParsingException)
}
public static class Id {
public boolean isOne(int i) {
return i == 1;
}
}
private ServletContext mockServletContext() {
return mockServletContext("/");
}
private ServletContext mockServletContext(String servletPath) {
MockServletContext servletContext = spy(new MockServletContext());
final ServletRegistration registration = mock(ServletRegistration.class);
when(registration.getMappings()).thenReturn(Collections.singleton(servletPath));
Answer<Map<String, ? extends ServletRegistration>> answer = new Answer<Map<String, ? extends ServletRegistration>>() {
@Override
public Map<String, ? extends ServletRegistration> answer(InvocationOnMock invocation) throws Throwable {
return Collections.<String, ServletRegistration>singletonMap("spring", registration);
}
};
when(servletContext.getServletRegistrations()).thenAnswer(answer);
return servletContext;
}
def login(MockHttpServletRequest request, String username, String password) {
String toEncode = username + ':' + password
request.addHeader('Authorization','Basic ' + Base64.encoder.encodeToString(toEncode.getBytes('UTF-8')))
}
@RestController
static class PathController {
@RequestMapping("/path")
public String path() {
return "path";
}
}
}
@@ -15,7 +15,6 @@
*/
package org.springframework.security.config.http
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter
import org.springframework.security.web.csrf.CsrfFilter
import org.springframework.security.web.header.HeaderWriterFilter
@@ -114,7 +113,6 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
Object authProcFilter = filters.next();
assert authProcFilter instanceof UsernamePasswordAuthenticationFilter
assert filters.next() instanceof DefaultLoginPageGeneratingFilter
assert filters.next() instanceof DefaultLogoutPageGeneratingFilter
assert filters.next() instanceof BasicAuthenticationFilter
assert filters.next() instanceof RequestCacheAwareFilter
assert filters.next() instanceof SecurityContextHolderAwareRequestFilter
@@ -144,7 +142,7 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
createAppContext()
then:
Filter debugFilter = appContext.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "")
MockHttpServletRequest request = new MockHttpServletRequest()
request.setServletPath("/unprotected");
debugFilter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
request.setServletPath("/nomatch");
@@ -191,7 +189,7 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
createAppContext()
expect:
getFilters("/anything")[9] instanceof AnonymousAuthenticationFilter
getFilters("/anything")[8] instanceof AnonymousAuthenticationFilter
}
def anonymousFilterIsRemovedIfDisabledFlagSet() {
@@ -202,7 +200,7 @@ class MiscHttpConfigTests extends AbstractHttpConfigTests {
createAppContext()
expect:
!(getFilters("/anything").get(9) instanceof AnonymousAuthenticationFilter)
!(getFilters("/anything").get(5) instanceof AnonymousAuthenticationFilter)
}
def anonymousCustomAttributesAreSetCorrectly() {
@@ -0,0 +1,133 @@
package org.springframework.security.config.http
import static org.mockito.Mockito.*
import org.powermock.api.mockito.internal.verification.VerifyNoMoreInteractions;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.BeanIds
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.FilterChainProxy
import org.junit.Assert
import org.springframework.beans.factory.BeanCreationException
import org.springframework.security.web.SecurityFilterChain
/**
* Tests scenarios with multiple &lt;http&gt; elements.
*
* @author Luke Taylor
*/
class MultiHttpBlockConfigTests extends AbstractHttpConfigTests {
def multipleHttpElementsAreSupported () {
when: "Two <http> elements are used"
xml.http(pattern: '/stateless/**', 'create-session': 'stateless') {
'http-basic'()
}
xml.http(pattern: '/stateful/**') {
'form-login'()
}
createAppContext()
FilterChainProxy fcp = appContext.getBean(BeanIds.FILTER_CHAIN_PROXY)
def filterChains = fcp.getFilterChains();
then:
filterChains.size() == 2
filterChains[0].requestMatcher.pattern == '/stateless/**'
}
def duplicateHttpElementsAreRejected () {
when: "Two <http> elements are used"
xml.http('create-session': 'stateless') {
'http-basic'()
}
xml.http() {
'form-login'()
}
createAppContext()
then:
BeanCreationException e = thrown()
e.cause instanceof IllegalArgumentException
}
def duplicatePatternsAreRejected () {
when: "Two <http> elements with the same pattern are used"
xml.http(pattern: '/stateless/**', 'create-session': 'stateless') {
'http-basic'()
}
xml.http(pattern: '/stateless/**') {
'form-login'()
}
createAppContext()
then:
BeanCreationException e = thrown()
e.cause instanceof IllegalArgumentException
}
def 'SEC-1937: http@authentication-manager-ref and multi authentication-mananager'() {
setup:
xml.http('authentication-manager-ref' : 'authManager', 'pattern' : '/first/**') {
'form-login'('login-processing-url': '/first/login')
csrf(disabled:true)
}
xml.http('authentication-manager-ref' : 'authManager2') {
'form-login'()
csrf(disabled:true)
}
mockBean(UserDetailsService,'uds')
mockBean(UserDetailsService,'uds2')
createAppContext("""
<authentication-manager id="authManager">
<authentication-provider user-service-ref="uds" />
</authentication-manager>
<authentication-manager id="authManager2">
<authentication-provider user-service-ref="uds2" />
</authentication-manager>
""")
UserDetailsService uds = appContext.getBean('uds')
UserDetailsService uds2 = appContext.getBean('uds2')
when:
MockHttpServletRequest request = new MockHttpServletRequest()
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
request.servletPath = "/first/login"
request.requestURI = "/first/login"
request.method = 'POST'
springSecurityFilterChain.doFilter(request,response,chain)
then:
verify(uds).loadUserByUsername(anyString()) || true
verifyZeroInteractions(uds2) || true
when:
MockHttpServletRequest request2 = new MockHttpServletRequest()
MockHttpServletResponse response2 = new MockHttpServletResponse()
MockFilterChain chain2 = new MockFilterChain()
request2.servletPath = "/login"
request2.requestURI = "/login"
request2.method = 'POST'
springSecurityFilterChain.doFilter(request2,response2,chain2)
then:
verify(uds2).loadUserByUsername(anyString()) || true
verifyNoMoreInteractions(uds) || true
}
def multipleAuthenticationManagersWorks () {
xml.http(name: 'basic', pattern: '/basic/**', ) {
'http-basic'()
}
xml.http(pattern: '/form/**') {
'form-login'()
}
createAppContext()
FilterChainProxy fcp = appContext.getBean(BeanIds.FILTER_CHAIN_PROXY)
SecurityFilterChain basicChain = fcp.filterChains[0];
expect:
Assert.assertSame (basicChain, appContext.getBean('basic'))
}
}
@@ -0,0 +1,156 @@
package org.springframework.security.config.http
import java.text.MessageFormat
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.access.SecurityConfig
import org.springframework.security.config.BeanIds
import org.springframework.security.util.FieldUtils
import org.springframework.security.web.PortMapperImpl
import org.springframework.security.web.access.ExceptionTranslationFilter
import org.springframework.security.web.access.channel.ChannelProcessingFilter
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
class PlaceHolderAndELConfigTests extends AbstractHttpConfigTests {
def setup() {
// Add a PropertyPlaceholderConfigurer to the context for all the tests
bean(PropertyPlaceholderConfigurer.class.name, PropertyPlaceholderConfigurer.class)
}
def unsecuredPatternSupportsPlaceholderForPattern() {
System.setProperty("pattern.nofilters", "/unprotected");
xml.http(pattern: '${pattern.nofilters}', security: 'none')
httpAutoConfig() {
interceptUrl('/**', 'ROLE_A')
}
createAppContext()
List filters = getFilters("/unprotected");
expect:
filters.size() == 0
}
// SEC-1201
def interceptUrlsAndFormLoginSupportPropertyPlaceholders() {
System.setProperty("secure.Url", "/secure");
System.setProperty("secure.role", "ROLE_A");
System.setProperty("login.page", "/loginPage");
System.setProperty("default.target", "/defaultTarget");
System.setProperty("auth.failure", "/authFailure");
xml.http(pattern: '${login.page}', security: 'none')
xml.http('use-expressions':false) {
interceptUrl('${secure.Url}', '${secure.role}')
'form-login'('login-page':'${login.page}', 'default-target-url': '${default.target}',
'authentication-failure-url':'${auth.failure}');
}
createAppContext();
expect:
propertyValuesMatchPlaceholders()
getFilters("/loginPage").size() == 0
}
// SEC-1309
def interceptUrlsAndFormLoginSupportEL() {
System.setProperty("secure.url", "/secure");
System.setProperty("secure.role", "ROLE_A");
System.setProperty("login.page", "/loginPage");
System.setProperty("default.target", "/defaultTarget");
System.setProperty("auth.failure", "/authFailure");
xml.http('use-expressions':false) {
interceptUrl("#{systemProperties['secure.url']}", "#{systemProperties['secure.role']}")
'form-login'('login-page':"#{systemProperties['login.page']}", 'default-target-url': "#{systemProperties['default.target']}",
'authentication-failure-url':"#{systemProperties['auth.failure']}");
}
createAppContext()
expect:
propertyValuesMatchPlaceholders()
}
private void propertyValuesMatchPlaceholders() {
// Check the security attribute
def fis = getFilter(FilterSecurityInterceptor);
def fids = fis.getSecurityMetadataSource();
Collection attrs = fids.getAttributes(createFilterinvocation("/secure", null));
assert attrs.size() == 1
assert attrs.contains(new SecurityConfig("ROLE_A"))
// Check the form login properties are set
def apf = getFilter(UsernamePasswordAuthenticationFilter)
assert FieldUtils.getFieldValue(apf, "successHandler.defaultTargetUrl") == '/defaultTarget'
assert "/authFailure" == FieldUtils.getFieldValue(apf, "failureHandler.defaultFailureUrl")
def etf = getFilter(ExceptionTranslationFilter)
assert "/loginPage"== etf.authenticationEntryPoint.loginFormUrl
}
def portMappingsWorkWithPlaceholdersAndEL() {
System.setProperty("http", "9080");
System.setProperty("https", "9443");
httpAutoConfig {
'port-mappings'() {
'port-mapping'(http: '#{systemProperties.http}', https: '${https}')
}
}
createAppContext();
def pm = (appContext.getBeansOfType(PortMapperImpl).values() as List)[0];
expect:
pm.getTranslatedPortMappings().size() == 1
pm.lookupHttpPort(9443) == 9080
pm.lookupHttpsPort(9080) == 9443
}
def requiresChannelSupportsPlaceholder() {
System.setProperty("secure.url", "/secure");
System.setProperty("required.channel", "https");
httpAutoConfig {
'intercept-url'(pattern: '${secure.url}', 'requires-channel': '${required.channel}')
}
createAppContext();
List filters = getFilters("/secure");
expect:
filters.size() == AUTO_CONFIG_FILTERS + 1
filters[0] instanceof ChannelProcessingFilter
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secure");
MockHttpServletResponse response = new MockHttpServletResponse();
filters[0].doFilter(request, response, new MockFilterChain());
response.getRedirectedUrl().startsWith("https")
}
def accessDeniedPageWorksWithPlaceholders() {
System.setProperty("accessDenied", "/go-away");
xml.http('auto-config': 'true') {
'access-denied-handler'('error-page' : '${accessDenied}') {}
}
createAppContext();
expect:
FieldUtils.getFieldValue(getFilter(ExceptionTranslationFilter.class), "accessDeniedHandler.errorPage") == '/go-away'
}
def accessDeniedHandlerPageWorksWithEL() {
httpAutoConfig {
'access-denied-handler'('error-page': "#{'/go' + '-away'}")
}
createAppContext()
expect:
getFilter(ExceptionTranslationFilter).accessDeniedHandler.errorPage == '/go-away'
}
}
@@ -0,0 +1,171 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.http
import static org.springframework.security.config.ConfigTestUtils.AUTH_PROVIDER_XML
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.access.ExceptionTranslationFilter
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
import org.springframework.security.web.context.HttpSessionSecurityContextRepository
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
/**
*
* @author Rob Winch
*/
class SecurityContextHolderAwareRequestConfigTests extends AbstractHttpConfigTests {
def withAutoConfig() {
httpAutoConfig () {
csrf(disabled:true)
}
createAppContext(AUTH_PROVIDER_XML)
def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
expect:
securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
securityContextAwareFilter.logoutHandlers.size() == 1
securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
}
def explicitEntryPoint() {
xml.http() {
'http-basic'('entry-point-ref': 'ep')
}
bean('ep', BasicAuthenticationEntryPoint.class.name, ['realmName':'whocares'],[:])
createAppContext(AUTH_PROVIDER_XML)
def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
expect:
securityContextAwareFilter.authenticationEntryPoint == getFilter(ExceptionTranslationFilter).authenticationEntryPoint
securityContextAwareFilter.authenticationManager == getFilter(BasicAuthenticationFilter).authenticationManager
securityContextAwareFilter.logoutHandlers == null
}
def formLogin() {
xml.http() {
'form-login'()
}
createAppContext(AUTH_PROVIDER_XML)
def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
expect:
securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
securityContextAwareFilter.logoutHandlers == null
}
def multiHttp() {
xml.http('authentication-manager-ref' : 'authManager', 'pattern' : '/first/**') {
'form-login'('login-page' : '/login')
'logout'('invalidate-session' : 'true')
csrf(disabled:true)
}
xml.http('authentication-manager-ref' : 'authManager2') {
'form-login'('login-page' : '/login2')
'logout'('invalidate-session' : 'false')
csrf(disabled:true)
}
String secondAuthManager = AUTH_PROVIDER_XML.replace("alias='authManager'", "id='authManager2'")
createAppContext(AUTH_PROVIDER_XML + secondAuthManager)
def securityContextAwareFilter = getFilters('/first/filters').find { it instanceof SecurityContextHolderAwareRequestFilter }
def secondSecurityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
expect:
securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == '/login'
securityContextAwareFilter.authenticationManager == getFilters('/first/filters').find { it instanceof UsernamePasswordAuthenticationFilter}.authenticationManager
securityContextAwareFilter.authenticationManager.parent == appContext.getBean('authManager')
securityContextAwareFilter.logoutHandlers.size() == 1
securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
securityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == true
secondSecurityContextAwareFilter.authenticationEntryPoint.loginFormUrl == '/login2'
secondSecurityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
secondSecurityContextAwareFilter.authenticationManager.parent == appContext.getBean('authManager2')
securityContextAwareFilter.logoutHandlers.size() == 1
secondSecurityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
secondSecurityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == false
}
def logoutCustom() {
xml.http() {
'form-login'('login-page' : '/login')
'logout'('invalidate-session' : 'false', 'logout-success-url' : '/login?logout', 'delete-cookies' : 'JSESSIONID')
csrf(disabled:true)
}
createAppContext(AUTH_PROVIDER_XML)
def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
expect:
securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
securityContextAwareFilter.logoutHandlers.size() == 2
securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
securityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == false
securityContextAwareFilter.logoutHandlers[1].class == CookieClearingLogoutHandler
securityContextAwareFilter.logoutHandlers[1].cookiesToClear == ['JSESSIONID']
}
def 'SEC-2926: Role Prefix is set'() {
setup:
httpAutoConfig () {
}
createAppContext(AUTH_PROVIDER_XML)
MockFilterChain chain = new MockFilterChain() {
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
assert request.isUserInRole("USER")
super.doFilter(request,response)
}
}
MockHttpServletRequest request = new MockHttpServletRequest(method:'GET')
SecurityContext context = SecurityContextHolder.createEmptyContext()
context.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER"))
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context)
when:
springSecurityFilterChain.doFilter(request, new MockHttpServletResponse(), chain)
then:
chain.request != null
}
}
@@ -0,0 +1,430 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.http
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.session.SessionRegistry
import org.springframework.security.core.session.SessionRegistryImpl
import org.springframework.security.core.userdetails.User
import org.springframework.security.util.FieldUtils
import org.springframework.security.web.FilterChainProxy
import org.springframework.security.web.authentication.RememberMeServices
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler
import org.springframework.security.web.authentication.logout.LogoutFilter
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy
import org.springframework.security.web.context.NullSecurityContextRepository
import org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper
import org.springframework.security.web.context.SecurityContextPersistenceFilter
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter
import org.springframework.security.web.session.ConcurrentSessionFilter
import org.springframework.security.web.session.SessionManagementFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import static org.junit.Assert.assertSame
import static org.mockito.Matchers.any
import static org.mockito.Mockito.verify
/**
* Tests session-related functionality for the &lt;http&gt; namespace element and &lt;session-management&gt;
*
* @author Luke Taylor
* @author Rob Winch
*/
class SessionManagementConfigTests extends AbstractHttpConfigTests {
def settingCreateSessionToAlwaysSetsFilterPropertiesCorrectly() {
httpCreateSession('always') { }
createAppContext();
def filter = getFilter(SecurityContextPersistenceFilter.class);
expect:
filter.forceEagerSessionCreation
filter.repo.allowSessionCreation
filter.repo.disableUrlRewriting
}
def settingCreateSessionToNeverSetsFilterPropertiesCorrectly() {
httpCreateSession('never') { }
createAppContext();
def filter = getFilter(SecurityContextPersistenceFilter.class);
expect:
!filter.forceEagerSessionCreation
!filter.repo.allowSessionCreation
}
def settingCreateSessionToStatelessSetsFilterPropertiesCorrectly() {
httpCreateSession('stateless') { }
createAppContext();
def filter = getFilter(SecurityContextPersistenceFilter.class);
expect:
!filter.forceEagerSessionCreation
filter.repo instanceof NullSecurityContextRepository
getFilter(SessionManagementFilter.class) == null
getFilter(RequestCacheAwareFilter.class) == null
}
def settingCreateSessionToIfRequiredDoesntCreateASessionForPublicInvocation() {
httpCreateSession('ifRequired') { }
createAppContext();
def filter = getFilter(SecurityContextPersistenceFilter.class);
expect:
!filter.forceEagerSessionCreation
filter.repo.allowSessionCreation
}
def 'SEC-1208: Session is not created when rejecting user due to max sessions exceeded'() {
setup:
httpCreateSession('never') {
'session-management'() {
'concurrency-control'('max-sessions':1,'error-if-maximum-exceeded':'true')
}
csrf(disabled:true)
}
createAppContext()
SessionRegistry registry = appContext.getBean(SessionRegistry)
registry.registerNewSession("1", new User("user","password",AuthorityUtils.createAuthorityList("ROLE_USER")))
MockHttpServletRequest request = new MockHttpServletRequest()
MockHttpServletResponse response = new MockHttpServletResponse()
String credentials = "user:password"
request.addHeader("Authorization", "Basic " + credentials.bytes.encodeBase64())
when: "exceed max authentication attempts"
appContext.getBean(FilterChainProxy).doFilter(request, response, new MockFilterChain())
then: "no new session is created"
request.getSession(false) == null
response.status == HttpServletResponse.SC_UNAUTHORIZED
}
def 'SEC-2137: disable session fixation and enable concurrency control'() {
setup: "context where session fixation is disabled and concurrency control is enabled"
httpAutoConfig {
'session-management'('session-fixation-protection':'none') {
'concurrency-control'('max-sessions':'1','error-if-maximum-exceeded':'true')
}
}
createAppContext()
MockHttpServletRequest request = new MockHttpServletRequest()
MockHttpServletResponse response = new MockHttpServletResponse()
String originalSessionId = request.session.id
String credentials = "user:password"
request.addHeader("Authorization", "Basic " + credentials.bytes.encodeBase64())
when: "authenticate"
appContext.getBean(FilterChainProxy).doFilter(request, response, new MockFilterChain())
then: "session invalidate is not called"
request.session.id == originalSessionId
}
def httpCreateSession(String create, Closure c) {
xml.http(['auto-config': 'true', 'create-session': create], c)
}
def concurrentSessionSupportAddsFilterAndExpectedBeans() {
when:
httpAutoConfig {
'session-management'() {
'concurrency-control'('session-registry-alias':'sr', 'expired-url': '/expired')
}
csrf(disabled:true)
}
createAppContext();
List filters = getFilters("/someurl");
def concurrentSessionFilter = filters.get(1)
then:
concurrentSessionFilter instanceof ConcurrentSessionFilter
concurrentSessionFilter.sessionInformationExpiredStrategy.destinationUrl == '/expired'
appContext.getBean("sr") != null
getFilter(SessionManagementFilter.class) != null
sessionRegistryIsValid();
concurrentSessionFilter.handlers.logoutHandlers.size() == 1
def logoutHandler = concurrentSessionFilter.handlers.logoutHandlers[0]
logoutHandler instanceof SecurityContextLogoutHandler
logoutHandler.invalidateHttpSession
}
def 'concurrency-control adds custom logout handlers'() {
when: 'Custom logout and remember-me'
httpAutoConfig {
'session-management'() {
'concurrency-control'()
}
'logout'('invalidate-session': false, 'delete-cookies': 'testCookie')
'remember-me'()
csrf(disabled:true)
}
createAppContext()
List filters = getFilters("/someurl")
ConcurrentSessionFilter concurrentSessionFilter = filters.get(1)
def logoutHandlers = concurrentSessionFilter.handlers.logoutHandlers
then: 'ConcurrentSessionFilter contains the customized LogoutHandlers'
logoutHandlers.size() == 3
def securityCtxlogoutHandler = logoutHandlers.find { it instanceof SecurityContextLogoutHandler }
securityCtxlogoutHandler.invalidateHttpSession == false
def cookieClearingLogoutHandler = logoutHandlers.find { it instanceof CookieClearingLogoutHandler }
cookieClearingLogoutHandler.cookiesToClear == ['testCookie']
def remembermeLogoutHandler = logoutHandlers.find { it instanceof RememberMeServices }
remembermeLogoutHandler == getFilter(RememberMeAuthenticationFilter.class).rememberMeServices
}
def 'concurrency-control with remember-me and no LogoutFilter contains SecurityContextLogoutHandler and RememberMeServices as LogoutHandlers'() {
when: 'RememberMe and No LogoutFilter'
xml.http(['entry-point-ref': 'entryPoint'], {
'session-management'() {
'concurrency-control'()
}
'remember-me'()
csrf(disabled:true)
})
bean('entryPoint', 'org.springframework.security.web.authentication.Http403ForbiddenEntryPoint')
createAppContext()
List filters = getFilters("/someurl")
ConcurrentSessionFilter concurrentSessionFilter = filters.get(1)
def logoutHandlers = concurrentSessionFilter.handlers.logoutHandlers
then: 'SecurityContextLogoutHandler and RememberMeServices are in ConcurrentSessionFilter logoutHandlers'
!filters.find { it instanceof LogoutFilter }
logoutHandlers.size() == 2
def securityCtxlogoutHandler = logoutHandlers.find { it instanceof SecurityContextLogoutHandler }
securityCtxlogoutHandler.invalidateHttpSession == true
logoutHandlers.find { it instanceof RememberMeServices } == getFilter(RememberMeAuthenticationFilter).rememberMeServices
}
def 'concurrency-control with no remember-me or LogoutFilter contains SecurityContextLogoutHandler as LogoutHandlers'() {
when: 'No Logout Filter or RememberMe'
xml.http(['entry-point-ref': 'entryPoint'], {
'session-management'() {
'concurrency-control'()
}
})
bean('entryPoint', 'org.springframework.security.web.authentication.Http403ForbiddenEntryPoint')
createAppContext()
List filters = getFilters("/someurl")
ConcurrentSessionFilter concurrentSessionFilter = filters.get(1)
def logoutHandlers = concurrentSessionFilter.handlers.logoutHandlers
then: 'Only SecurityContextLogoutHandler is found in ConcurrentSessionFilter logoutHandlers'
!filters.find { it instanceof LogoutFilter }
logoutHandlers.size() == 1
def securityCtxlogoutHandler = logoutHandlers.find { it instanceof SecurityContextLogoutHandler }
securityCtxlogoutHandler.invalidateHttpSession == true
}
def 'SEC-2057: ConcurrentSessionFilter is after SecurityContextPersistenceFilter'() {
httpAutoConfig {
'session-management'() {
'concurrency-control'()
}
}
createAppContext()
List filters = getFilters("/someurl")
expect:
filters.get(0) instanceof SecurityContextPersistenceFilter
filters.get(1) instanceof ConcurrentSessionFilter
}
def 'concurrency-control handles default expired-url as null'() {
httpAutoConfig {
'session-management'() {
'concurrency-control'('session-registry-alias':'sr')
}
}
createAppContext();
List filters = getFilters("/someurl");
expect:
filters.get(1).sessionInformationExpiredStrategy.class.name == 'org.springframework.security.web.session.ConcurrentSessionFilter$ResponseBodySessionInformationExpiredStrategy'
}
def externalSessionStrategyIsSupported() {
setup:
httpAutoConfig {
'session-management'('session-authentication-strategy-ref':'ss')
csrf(disabled:true)
}
mockBean(SessionAuthenticationStrategy,'ss')
createAppContext()
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession();
request.servletPath = "/login"
request.setMethod("POST");
request.setParameter("username", "user");
request.setParameter("password", "password");
SessionAuthenticationStrategy sessionAuthStrategy = appContext.getBean('ss',SessionAuthenticationStrategy)
FilterChainProxy springSecurityFilterChain = appContext.getBean(FilterChainProxy)
when:
springSecurityFilterChain.doFilter(request,new MockHttpServletResponse(), new MockFilterChain())
then: "CustomSessionAuthenticationStrategy has seen the request (although REQUEST is a wrapped request)"
verify(sessionAuthStrategy).onAuthentication(any(Authentication), any(HttpServletRequest), any(HttpServletResponse))
}
def externalSessionRegistryBeanIsConfiguredCorrectly() {
httpAutoConfig {
'session-management'() {
'concurrency-control'('session-registry-ref':'sr')
}
csrf(disabled:true)
}
bean('sr', SessionRegistryImpl.class.name)
createAppContext();
expect:
sessionRegistryIsValid();
}
def sessionRegistryIsValid() {
Object sessionRegistry = appContext.getBean("sr");
Object sessionRegistryFromConcurrencyFilter = FieldUtils.getFieldValue(
getFilter(ConcurrentSessionFilter.class), "sessionRegistry");
Object sessionRegistryFromFormLoginFilter = FieldUtils.getFieldValue(getFilter(UsernamePasswordAuthenticationFilter),"sessionStrategy").delegateStrategies[0].sessionRegistry
Object sessionRegistryFromMgmtFilter = FieldUtils.getFieldValue(getFilter(SessionManagementFilter),"sessionAuthenticationStrategy").delegateStrategies[0].sessionRegistry
assertSame(sessionRegistry, sessionRegistryFromConcurrencyFilter);
assertSame(sessionRegistry, sessionRegistryFromMgmtFilter);
// SEC-1143
assertSame(sessionRegistry, sessionRegistryFromFormLoginFilter);
true;
}
def concurrentSessionMaxSessionsIsCorrectlyConfigured() {
setup:
httpAutoConfig {
'session-management'('session-authentication-error-url':'/max-exceeded') {
'concurrency-control'('max-sessions': '2', 'error-if-maximum-exceeded':'true')
}
}
createAppContext();
def seshFilter = getFilter(SessionManagementFilter.class);
def auth = new UsernamePasswordAuthenticationToken("bob", "pass");
SecurityContextHolder.getContext().setAuthentication(auth);
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
def response = new SaveContextOnUpdateOrErrorResponseWrapper(mockResponse, false) {
protected void saveContext(SecurityContext context) {
}
};
when: "First session is established"
seshFilter.doFilter(new MockHttpServletRequest(), response, new MockFilterChain());
then: "ok"
mockResponse.redirectedUrl == null
when: "Second session is established"
seshFilter.doFilter(new MockHttpServletRequest(), response, new MockFilterChain());
then: "ok"
mockResponse.redirectedUrl == null
when: "Third session is established"
seshFilter.doFilter(new MockHttpServletRequest(), response, new MockFilterChain());
then: "Rejected"
mockResponse.redirectedUrl == "/max-exceeded";
}
def disablingSessionProtectionRemovesSessionManagementFilterIfNoInvalidSessionUrlSet() {
httpAutoConfig {
'session-management'('session-fixation-protection': 'none')
csrf(disabled:true)
}
createAppContext()
expect:
!(getFilters("/someurl").find { it instanceof SessionManagementFilter})
}
def 'session-fixation-protection=none'() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'POST')
request.session.id = '123'
request.setParameter('username', 'user')
request.setParameter('password', 'password')
request.servletPath = '/login'
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
httpAutoConfig {
'session-management'('session-fixation-protection': 'none')
csrf(disabled:true)
}
createAppContext()
request.session.id = '123'
when:
springSecurityFilterChain.doFilter(request,response, chain)
then:
request.session.id == '123'
}
def 'session-fixation-protection=migrateSession'() {
setup:
MockHttpServletRequest request = new MockHttpServletRequest(method:'POST')
request.setParameter('username', 'user')
request.setParameter('password', 'password')
request.servletPath = '/login'
MockHttpServletResponse response = new MockHttpServletResponse()
MockFilterChain chain = new MockFilterChain()
httpAutoConfig {
'session-management'('session-fixation-protection': 'migrateSession')
csrf(disabled:true)
}
createAppContext()
String originalId = request.session.id
when:
springSecurityFilterChain.doFilter(request,response, chain)
then:
request.session.id != originalId
}
def disablingSessionProtectionRetainsSessionManagementFilterInvalidSessionUrlSet() {
httpAutoConfig {
'session-management'('session-fixation-protection': 'none', 'invalid-session-url': '/timeoutUrl')
csrf(disabled:true)
}
createAppContext()
def filter = getFilters("/someurl")[10]
expect:
filter instanceof SessionManagementFilter
filter.invalidSessionStrategy.destinationUrl == '/timeoutUrl'
}
}
@@ -0,0 +1,560 @@
package org.springframework.security.config.websocket
import static org.mockito.Mockito.*
import org.springframework.beans.BeansException
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException
import org.springframework.beans.factory.support.BeanDefinitionRegistry
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor
import org.springframework.beans.factory.support.RootBeanDefinition
import org.springframework.core.MethodParameter
import org.springframework.core.task.SyncTaskExecutor
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.messaging.Message
import org.springframework.messaging.MessageDeliveryException
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver
import org.springframework.messaging.simp.SimpMessageHeaderAccessor
import org.springframework.messaging.simp.SimpMessageType
import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler
import org.springframework.messaging.support.ChannelInterceptor
import org.springframework.messaging.support.GenericMessage
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.access.expression.SecurityExpressionOperations;
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.config.AbstractXmlConfigTests
import org.springframework.security.core.Authentication
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.messaging.access.expression.DefaultMessageSecurityExpressionHandler;
import org.springframework.security.messaging.access.expression.MessageSecurityExpressionRoot;
import org.springframework.security.web.csrf.CsrfToken
import org.springframework.security.web.csrf.DefaultCsrfToken
import org.springframework.security.web.csrf.InvalidCsrfTokenException
import org.springframework.stereotype.Controller
import org.springframework.util.AntPathMatcher
import org.springframework.web.servlet.HandlerMapping
import org.springframework.web.socket.WebSocketHandler
import org.springframework.web.socket.server.HandshakeFailureException
import org.springframework.web.socket.server.HandshakeHandler
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor
import org.springframework.web.socket.server.support.WebSocketHttpRequestHandler
import org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler
import org.springframework.web.socket.sockjs.transport.handler.SockJsWebSocketHandler
import spock.lang.Unroll
/**
*
* @author Rob Winch
*/
class WebSocketMessageBrokerConfigTests extends AbstractXmlConfigTests {
Authentication messageUser = new TestingAuthenticationToken('user','pass','ROLE_USER')
boolean useSockJS = false
CsrfToken csrfToken = new DefaultCsrfToken('headerName', 'paramName', 'token')
def cleanup() {
SecurityContextHolder.clearContext()
}
def 'websocket with no id automatically integrates with clientInboundChannel'() {
setup:
websocket {
'intercept-message'(pattern:'/permitAll',access:'permitAll')
'intercept-message'(pattern:'/denyAll',access:'denyAll')
}
when: 'message is sent to the denyAll endpoint'
clientInboundChannel.send(message('/denyAll'))
then: 'access is denied to the denyAll endpoint'
def e = thrown(MessageDeliveryException)
e.cause instanceof AccessDeniedException
and: 'access is granted to the permitAll endpoint'
clientInboundChannel.send(message('/permitAll'))
}
def 'anonymous authentication supported'() {
setup:
websocket {
'intercept-message'(pattern:'/permitAll',access:'permitAll')
'intercept-message'(pattern:'/denyAll',access:'denyAll')
}
messageUser = null
when: 'message is sent to the permitAll endpoint with no user'
clientInboundChannel.send(message('/permitAll'))
then: 'access is granted'
noExceptionThrown()
}
@Unroll
def "message type - #type"(SimpMessageType type) {
setup:
websocket {
'intercept-message'('type': type.toString(), access:'permitAll')
'intercept-message'(pattern:'/**', access:'denyAll')
}
messageUser = null
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(type)
if(SimpMessageType.CONNECT == type) {
headers.setNativeHeader(csrfToken.headerName, csrfToken.token)
}
Message message = message(headers, '/permitAll')
when: 'message is sent to the permitAll endpoint with no user'
clientInboundChannel.send(message)
then: 'access is granted'
noExceptionThrown()
where:
type << SimpMessageType.values()
}
@Unroll
def "pattern and message type - #type"(SimpMessageType type) {
setup:
websocket {
'intercept-message'(pattern: '/permitAll', 'type': type.toString(), access:'permitAll')
'intercept-message'(pattern:'/**', access:'denyAll')
}
when: 'message is sent to the permitAll endpoint with no user'
clientInboundChannel.send(message('/permitAll', type))
then: 'access is granted'
noExceptionThrown()
when: 'message sent to other message type'
clientInboundChannel.send(message('/permitAll', SimpMessageType.UNSUBSCRIBE))
then: 'does not match'
MessageDeliveryException e = thrown()
e.cause instanceof AccessDeniedException
when: 'message is sent to other pattern'
clientInboundChannel.send(message('/other', type))
then: 'does not match'
MessageDeliveryException eOther = thrown()
eOther.cause instanceof AccessDeniedException
where:
type << [SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE]
}
@Unroll
def "intercept-message with invalid type and pattern - #type"(SimpMessageType type) {
when:
websocket {
'intercept-message'(pattern : '/**', 'type': type.toString(), access:'permitAll')
}
then:
thrown(BeanDefinitionParsingException)
where:
type << [SimpMessageType.CONNECT, SimpMessageType.CONNECT_ACK, SimpMessageType.DISCONNECT, SimpMessageType.DISCONNECT_ACK, SimpMessageType.HEARTBEAT, SimpMessageType.OTHER, SimpMessageType.UNSUBSCRIBE ]
}
def 'messages with no id automatically adds Authentication argument resolver'() {
setup:
def id = 'authenticationController'
bean(id,MyController)
bean('inPostProcessor',InboundExecutorPostProcessor)
websocket {
'intercept-message'(pattern:'/**',access:'permitAll')
}
when: 'message is sent to the authentication endpoint'
clientInboundChannel.send(message('/authentication'))
then: 'the AuthenticationPrincipal is resolved'
def controller = appContext.getBean(id)
controller.authenticationPrincipal == messageUser.name
}
def 'messages of type CONNECT use CsrfTokenHandshakeInterceptor'() {
setup:
def id = 'authenticationController'
bean(id,MyController)
bean('inPostProcessor',InboundExecutorPostProcessor)
websocket {
'intercept-message'(pattern:'/**',access:'permitAll')
}
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT)
Message<?> message = message(headers,'/authentication')
WebSocketHttpRequestHandler handler = appContext.getBean(WebSocketHttpRequestHandler)
MockHttpServletRequest request = new MockHttpServletRequest()
String sessionAttr = "sessionAttr"
request.getSession().setAttribute(sessionAttr,"sessionValue")
CsrfToken token = new DefaultCsrfToken("header", "param", "token")
request.setAttribute(CsrfToken.name, token)
when:
handler.handleRequest(request , new MockHttpServletResponse())
TestHandshakeHandler handshakeHandler = appContext.getBean(TestHandshakeHandler)
then: 'CsrfToken is populated'
handshakeHandler.attributes.get(CsrfToken.name) == token
and: 'Explicitly listed HandshakeInterceptor are not overridden'
handshakeHandler.attributes.get(sessionAttr) == request.getSession().getAttribute(sessionAttr)
}
def 'messages of type CONNECT use CsrfTokenHandshakeInterceptor with SockJS'() {
setup:
useSockJS = true
def id = 'authenticationController'
bean(id,MyController)
bean('inPostProcessor',InboundExecutorPostProcessor)
websocket {
'intercept-message'(pattern:'/**',access:'permitAll')
}
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT)
Message<?> message = message(headers,'/authentication')
SockJsHttpRequestHandler handler = appContext.getBean(SockJsHttpRequestHandler)
MockHttpServletRequest request = new MockHttpServletRequest()
String sessionAttr = "sessionAttr"
request.getSession().setAttribute(sessionAttr,"sessionValue")
CsrfToken token = new DefaultCsrfToken("header", "param", "token")
request.setAttribute(CsrfToken.name, token)
request.setMethod("GET")
request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/289/tpyx6mde/websocket")
when:
handler.handleRequest(request , new MockHttpServletResponse())
TestHandshakeHandler handshakeHandler = appContext.getBean(TestHandshakeHandler)
then: 'CsrfToken is populated'
handshakeHandler.attributes?.get(CsrfToken.name) == token
and: 'Explicitly listed HandshakeInterceptor are not overridden'
handshakeHandler.attributes?.get(sessionAttr) == request.getSession().getAttribute(sessionAttr)
}
def 'messages of type CONNECT require valid CsrfToken'() {
setup:
def id = 'authenticationController'
bean(id,MyController)
bean('inPostProcessor',InboundExecutorPostProcessor)
websocket {
'intercept-message'(pattern:'/**',access:'permitAll')
}
when: 'websocket of type CONNECTION is sent without CsrfTOken'
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT)
Message<?> message = message(headers,'/authentication')
clientInboundChannel.send(message)
then: 'CSRF Protection blocks the Message'
MessageDeliveryException expected = thrown()
expected.cause instanceof InvalidCsrfTokenException
}
def 'messages of type CONNECT disabled valid CsrfToken'() {
setup:
def id = 'authenticationController'
bean(id,MyController)
bean('inPostProcessor',InboundExecutorPostProcessor)
websocket('same-origin-disabled':true) {
'intercept-message'(pattern:'/**',access:'permitAll')
}
when: 'websocket of type CONNECTION is sent without CsrfTOken'
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT)
Message<?> message = message(headers,'/authentication')
clientInboundChannel.send(message)
then: 'CSRF Protection blocks the Message'
noExceptionThrown()
}
def 'websocket with no id does not override customArgumentResolvers'() {
setup:
def id = 'authenticationController'
bean(id,MyController)
bean('inPostProcessor',InboundExecutorPostProcessor)
bean('mcar', MyCustomArgumentResolver)
xml.'websocket:message-broker' {
'websocket:transport' {}
'websocket:stomp-endpoint'(path:'/app') {
'websocket:handshake-handler'(ref:'testHandler') {}
}
'websocket:simple-broker'(prefix:"/queue, /topic"){}
'websocket:argument-resolvers' {
'b:ref'(bean:'mcar')
}
}
websocket {
'intercept-message'(pattern:'/**',access:'permitAll')
}
when: 'websocket is sent to the myCustom endpoint'
clientInboundChannel.send(message('/myCustom'))
then: 'myCustomArgument is resolved'
def controller = appContext.getBean(id)
controller.myCustomArgument!= null
}
def 'websocket defaults pathMatcher'() {
setup:
bean('pathMatcher',AntPathMatcher.name,['.'])
bean('testHandler', TestHandshakeHandler)
xml.'websocket:message-broker'('path-matcher':'pathMatcher') {
'websocket:transport' {}
'websocket:stomp-endpoint'(path:'/app') {
'websocket:handshake-handler'(ref:'testHandler') {}
}
'websocket:simple-broker'(prefix:"/queue, /topic"){}
}
xml.'websocket-message-broker' {
'intercept-message'(pattern:'/denyAll.*',access:'denyAll')
}
createAppContext()
when: 'sent to denyAll.a'
appContext.getBean(SimpAnnotationMethodMessageHandler)
clientInboundChannel.send(message('/denyAll.a'))
then: 'access is denied'
MessageDeliveryException expected = thrown()
expected.cause instanceof AccessDeniedException
when: 'sent to denyAll.a.b'
clientInboundChannel.send(message('/denyAll.a.b'))
then: 'access is allowed'
noExceptionThrown()
}
def 'websocket with id does not integrate with clientInboundChannel'() {
setup:
websocket([id:'inCsi']) {
'intercept-message'(pattern:'/**',access:'denyAll')
}
when:
def success = clientInboundChannel.send(message('/denyAll'))
then:
success
}
def 'websocket with id can be explicitly integrated with clientInboundChannel'() {
setup: 'websocket security explicitly setup'
xml.'websocket:message-broker' {
'websocket:transport' {}
'websocket:stomp-endpoint'(path:'/app') {
'websocket:sockjs' {}
}
'websocket:simple-broker'(prefix:"/queue, /topic"){}
'websocket:client-inbound-channel' {
'websocket:interceptors' {
'b:bean'(class:'org.springframework.security.messaging.context.SecurityContextChannelInterceptor'){}
'b:ref'(bean:'inCsi'){}
}
}
}
xml.'websocket-message-broker'(id:'inCsi') {
'intercept-message'(pattern:'/**',access:'denyAll')
}
createAppContext()
when:
clientInboundChannel.send(message('/denyAll'))
then:
def e = thrown(MessageDeliveryException)
e.cause instanceof AccessDeniedException
}
def 'automatic integration with clientInboundChannel does not override exisiting websocket:interceptors'() {
setup:
mockBean(ChannelInterceptor,'mci')
xml.'websocket:message-broker'('application-destination-prefix':'/app',
'user-destination-prefix':'/user') {
'websocket:transport' {}
'websocket:stomp-endpoint'(path:'/foo') {
'websocket:sockjs' {}
}
'websocket:simple-broker'(prefix:"/queue, /topic"){}
'websocket:client-inbound-channel' {
'websocket:interceptors' {
'b:ref'(bean:'mci'){}
}
}
}
xml.'websocket-message-broker' {
'intercept-message'(pattern:'/denyAll',access:'denyAll')
'intercept-message'(pattern:'/permitAll',access:'permitAll')
}
createAppContext()
ChannelInterceptor mci = appContext.getBean('mci')
when:
Message<?> message = message('/permitAll')
clientInboundChannel.send(message)
then:
verify(mci).preSend(message, clientInboundChannel) || true
}
def websocket(Map<String,Object> attrs=[:], Closure c) {
bean('testHandler', TestHandshakeHandler)
xml.'websocket:message-broker' {
'websocket:transport' {}
'websocket:stomp-endpoint'(path:'/app') {
'websocket:handshake-handler'(ref:'testHandler') {}
'websocket:handshake-interceptors' {
'b:bean'('class':HttpSessionHandshakeInterceptor.name) {}
}
if(useSockJS) {
'websocket:sockjs' {}
}
}
'websocket:simple-broker'(prefix:"/queue, /topic"){}
}
xml.'websocket-message-broker'(attrs, c)
createAppContext()
}
def 'custom expressions'() {
setup:
bean('expressionHandler', DenyRobMessageSecurityExpressionHandler)
websocket {
'expression-handler' (ref: 'expressionHandler') {}
'intercept-message'(pattern:'/**',access:'denyRob()')
}
when: 'message is sent with user'
clientInboundChannel.send(message('/message'))
then: 'access is allowed to custom expression'
noExceptionThrown()
when:
messageUser = new TestingAuthenticationToken('rob', 'pass', 'ROLE_USER')
clientInboundChannel.send(message('/message'))
then:
def e = thrown(MessageDeliveryException)
e.cause instanceof AccessDeniedException
}
def getClientInboundChannel() {
appContext.getBean("clientInboundChannel")
}
def message(String destination, SimpMessageType type=SimpMessageType.MESSAGE) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(type)
message(headers, destination)
}
def message(SimpMessageHeaderAccessor headers, String destination) {
headers.sessionId = '123'
headers.sessionAttributes = [:]
headers.destination = destination
if(messageUser != null) {
headers.user = messageUser
}
if(csrfToken != null) {
headers.sessionAttributes[CsrfToken.name] = csrfToken
}
new GenericMessage<String>("hi",headers.messageHeaders)
}
@Controller
static class MyController {
String authenticationPrincipal
MyCustomArgument myCustomArgument
@MessageMapping('/authentication')
public void authentication(@AuthenticationPrincipal String un) {
this.authenticationPrincipal = un
}
@MessageMapping('/myCustom')
public void myCustom(MyCustomArgument myCustomArgument) {
this.myCustomArgument = myCustomArgument
}
}
static class MyCustomArgument {
MyCustomArgument(String notDefaultConstr) {}
}
static class MyCustomArgumentResolver implements HandlerMethodArgumentResolver {
@Override
boolean supportsParameter(MethodParameter parameter) {
parameter.parameterType.isAssignableFrom(MyCustomArgument)
}
@Override
Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
new MyCustomArgument("")
}
}
static class TestHandshakeHandler implements HandshakeHandler {
Map<String, Object> attributes;
boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException {
this.attributes = attributes
if(wsHandler instanceof SockJsWebSocketHandler) {
// work around SPR-12716
SockJsWebSocketHandler sockJs = (SockJsWebSocketHandler) wsHandler;
this.attributes = sockJs.sockJsSession.attributes
}
true
}
}
/**
* Changes the clientInboundChannel Executor to be synchronous
*/
static class InboundExecutorPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
BeanDefinition inbound = registry.getBeanDefinition("clientInboundChannel")
inbound.getConstructorArgumentValues().addIndexedArgumentValue(0, new RootBeanDefinition(SyncTaskExecutor));
}
@Override
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
static class DenyRobMessageSecurityExpressionHandler extends DefaultMessageSecurityExpressionHandler<Object> {
@Override
protected SecurityExpressionOperations createSecurityExpressionRoot(
Authentication authentication,
Message<Object> invocation) {
return new MessageSecurityExpressionRoot(authentication, invocation) {
public boolean denyRob() {
Authentication auth = getAuthentication();
return auth != null && !"rob".equals(auth.getName());
}
};
}
}
}
@@ -152,7 +152,7 @@ public class FilterChainProxyConfigTests {
}
private void doNormalOperation(FilterChainProxy filterChainProxy) throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/foo/secure/super/somefile.html");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -24,7 +24,7 @@ import java.util.List;
/**
* @author Rob Winch
* @since 5.0.2
* @since 5.0
*/
public class MockEventListener<T extends ApplicationEvent>
implements ApplicationListener<T> {
@@ -78,7 +78,7 @@ public class AuthenticationManagerBuilderTests {
verify(opp, never()).postProcess(provider);
}
// https://github.com/spring-projects/spring-security-javaconfig/issues/132
// https://github.com/SpringSource/spring-security-javaconfig/issues/132
@Test
public void customAuthenticationEventPublisherWithWeb() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
@@ -52,7 +52,6 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import java.util.ArrayList;
import java.util.Arrays;
@@ -61,8 +60,6 @@ import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -398,35 +395,6 @@ public class AuthenticationConfigurationTests {
}
}
@Test
public void getAuthenticationWhenUserDetailsServiceAndPasswordManagerThenManagerUsed() throws Exception {
UserDetails user = new User("user", "{noop}password",
AuthorityUtils.createAuthorityList("ROLE_USER"));
this.spring.register(UserDetailsPasswordManagerBeanConfig.class).autowire();
UserDetailsPasswordManagerBeanConfig.Manager manager = this.spring.getContext().getBean(UserDetailsPasswordManagerBeanConfig.Manager.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
when(manager.loadUserByUsername("user")).thenReturn(User.withUserDetails(user).build(), User.withUserDetails(user).build());
when(manager.updatePassword(any(), any())).thenReturn(user);
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
verify(manager).updatePassword(eq(user), startsWith("{bcrypt}"));
}
@Configuration
@Import({AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class})
static class UserDetailsPasswordManagerBeanConfig {
Manager manager = mock(Manager.class);
@Bean
UserDetailsService userDetailsService() {
return this.manager;
}
interface Manager extends UserDetailsService, UserDetailsPasswordService {
}
}
//gh-3091
@Test
public void getAuthenticationWhenAuthenticationProviderBeanThenUsed() throws Exception {

Some files were not shown because too many files have changed in this diff Show More