diff --git a/docs/en/spring-security/community.md b/docs/en/spring-security/community.md new file mode 100644 index 0000000000000000000000000000000000000000..2e24cb34e667f2210ddfa4851a0b8e63610ad6e9 --- /dev/null +++ b/docs/en/spring-security/community.md @@ -0,0 +1,36 @@ +# Spring Security Community + +Welcome to the Spring Security Community! +This section discusses how you can make the most of our vast community. + +## Getting Help + +If you need help with Spring Security, we are here to help. +The following are some of the best ways to get help: + +* Read through this documentation. + +* Try one of our many [sample applications](samples.html#samples). + +* Ask a question on [https://stackoverflow.com](https://stackoverflow.com/questions/tagged/spring-security) with the `spring-security` tag. + +* Report bugs and enhancement requests at [https://github.com/spring-projects/spring-security/issues](https://github.com/spring-projects/spring-security/issues) + +## Becoming Involved + +We welcome your involvement in the Spring Security project. +There are many ways to contribute, including answering questions on Stack Overflow, writing new code, improving existing code, assisting with documentation, developing samples or tutorials, reporting bugs, or simply making suggestions. +For more information, see our [Contributing](https://github.com/spring-projects/spring-security/blob/main/CONTRIBUTING.adoc) documentation. + +## Source Code + +You can find Spring Security’s source code on GitHub at [https://github.com/spring-projects/spring-security/](https://github.com/spring-projects/spring-security/) + +## Apache 2 License + +Spring Security is Open Source software released under the [Apache 2.0 license](https://www.apache.org/licenses/LICENSE-2.0.html). + +## Social Media + +You can follow [@SpringSecurity](https://twitter.com/SpringSecurity) and the [Spring Security team](https://twitter.com/SpringSecurity/lists/team) on Twitter to stay up to date with the latest news. +You can also follow [@SpringCentral](https://twitter.com/SpringCentral) to keep up to date with the entire Spring portfolio. \ No newline at end of file diff --git a/docs/en/spring-security/features-authentication-password-storage.md b/docs/en/spring-security/features-authentication-password-storage.md new file mode 100644 index 0000000000000000000000000000000000000000..b1a7c97ebd5c0b16e2cd0e663378091bbb34b24a --- /dev/null +++ b/docs/en/spring-security/features-authentication-password-storage.md @@ -0,0 +1,509 @@ +# Password Storage + +Spring Security’s `PasswordEncoder` interface is used to perform a one way transformation of a password to allow the password to be stored securely. +Given `PasswordEncoder` is a one way transformation, it is not intended when the password transformation needs to be two way (i.e. storing credentials used to authenticate to a database). +Typically `PasswordEncoder` is used for storing a password that needs to be compared to a user provided password at the time of authentication. + +## Password Storage History + +Throughout the years the standard mechanism for storing passwords has evolved. +In the beginning passwords were stored in plain text. +The passwords were assumed to be safe because the data store the passwords were saved in required credentials to access it. +However, malicious users were able to find ways to get large "data dumps" of usernames and passwords using attacks like SQL Injection. +As more and more user credentials became public security experts realized we needed to do more to protect users' passwords. + +Developers were then encouraged to store passwords after running them through a one way hash such as SHA-256. +When a user tried to authenticate, the hashed password would be compared to the hash of the password that they typed. +This meant that the system only needed to store the one way hash of the password. +If a breach occurred, then only the one way hashes of the passwords were exposed. +Since the hashes were one way and it was computationally difficult to guess the passwords given the hash, it would not be worth the effort to figure out each password in the system. +To defeat this new system malicious users decided to create lookup tables known as [Rainbow Tables](https://en.wikipedia.org/wiki/Rainbow_table). +Rather than doing the work of guessing each password every time, they computed the password once and stored it in a lookup table. + +To mitigate the effectiveness of Rainbow Tables, developers were encouraged to use salted passwords. +Instead of using just the password as input to the hash function, random bytes (known as salt) would be generated for every users' password. +The salt and the user’s password would be ran through the hash function which produced a unique hash. +The salt would be stored alongside the user’s password in clear text. +Then when a user tried to authenticate, the hashed password would be compared to the hash of the stored salt and the password that they typed. +The unique salt meant that Rainbow Tables were no longer effective because the hash was different for every salt and password combination. + +In modern times we realize that cryptographic hashes (like SHA-256) are no longer secure. +The reason is that with modern hardware we can perform billions of hash calculations a second. +This means that we can crack each password individually with ease. + +Developers are now encouraged to leverage adaptive one-way functions to store a password. +Validation of passwords with adaptive one-way functions are intentionally resource (i.e. CPU, memory, etc) intensive. +An adaptive one-way function allows configuring a "work factor" which can grow as hardware gets better. +It is recommended that the "work factor" be tuned to take about 1 second to verify a password on your system. +This trade off is to make it difficult for attackers to crack the password, but not so costly it puts excessive burden on your own system. +Spring Security has attempted to provide a good starting point for the "work factor", but users are encouraged to customize the "work factor" for their own system since the performance will vary drastically from system to system. +Examples of adaptive one-way functions that should be used include [bcrypt](#authentication-password-storage-bcrypt), [PBKDF2](#authentication-password-storage-pbkdf2), [scrypt](#authentication-password-storage-scrypt), and [argon2](#authentication-password-storage-argon2). + +Because adaptive one-way functions are intentionally resource intensive, validating a username and password for every request will degrade performance of an application significantly. +There is nothing Spring Security (or any other library) can do to speed up the validation of the password since security is gained by making the validation resource intensive. +Users are encouraged to exchange the long term credentials (i.e. username and password) for a short term credential (i.e. session, OAuth Token, etc). +The short term credential can be validated quickly without any loss in security. + +## DelegatingPasswordEncoder + +Prior to Spring Security 5.0 the default `PasswordEncoder` was `NoOpPasswordEncoder` which required plain text passwords. +Based upon the [Password History](#authentication-password-storage-history) section you might expect that the default `PasswordEncoder` is now something like `BCryptPasswordEncoder`. +However, this ignores three real world problems: + +* There are many applications using old password encodings that cannot easily migrate + +* The best practice for password storage will change again + +* As a framework Spring Security cannot make breaking changes frequently + +Instead Spring Security introduces `DelegatingPasswordEncoder` which solves all of the problems by: + +* Ensuring that passwords are encoded using the current password storage recommendations + +* Allowing for validating passwords in modern and legacy formats + +* Allowing for upgrading the encoding in the future + +You can easily construct an instance of `DelegatingPasswordEncoder` using `PasswordEncoderFactories`. + +Example 1. Create Default DelegatingPasswordEncoder + +Java + +``` +PasswordEncoder passwordEncoder = + PasswordEncoderFactories.createDelegatingPasswordEncoder(); +``` + +Kotlin + +``` +val passwordEncoder: PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder() +``` + +Alternatively, you may create your own custom instance. For example: + +Example 2. Create Custom DelegatingPasswordEncoder + +Java + +``` +String idForEncode = "bcrypt"; +Map encoders = new HashMap<>(); +encoders.put(idForEncode, new BCryptPasswordEncoder()); +encoders.put("noop", NoOpPasswordEncoder.getInstance()); +encoders.put("pbkdf2", new Pbkdf2PasswordEncoder()); +encoders.put("scrypt", new SCryptPasswordEncoder()); +encoders.put("sha256", new StandardPasswordEncoder()); + +PasswordEncoder passwordEncoder = + new DelegatingPasswordEncoder(idForEncode, encoders); +``` + +Kotlin + +``` +val idForEncode = "bcrypt" +val encoders: MutableMap = mutableMapOf() +encoders[idForEncode] = BCryptPasswordEncoder() +encoders["noop"] = NoOpPasswordEncoder.getInstance() +encoders["pbkdf2"] = Pbkdf2PasswordEncoder() +encoders["scrypt"] = SCryptPasswordEncoder() +encoders["sha256"] = StandardPasswordEncoder() + +val passwordEncoder: PasswordEncoder = DelegatingPasswordEncoder(idForEncode, encoders) +``` + +### Password Storage Format + +The general format for a password is: + +Example 3. DelegatingPasswordEncoder Storage Format + +``` +{id}encodedPassword +``` + +Such that `id` is an identifier used to look up which `PasswordEncoder` should be used and `encodedPassword` is the original encoded password for the selected `PasswordEncoder`. +The `id` must be at the beginning of the password, start with `{` and end with `}`. +If the `id` cannot be found, the `id` will be null. +For example, the following might be a list of passwords encoded using different `id`. +All of the original passwords are "password". + +Example 4. DelegatingPasswordEncoder Encoded Passwords Example + +``` +{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG (1) +{noop}password (2) +{pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc (3) +{scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc= (4) +{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0 (5) +``` + +|**1**| The first password would have a `PasswordEncoder` id of `bcrypt` and encodedPassword of `$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG`.
When matching it would delegate to `BCryptPasswordEncoder` | +|-----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**| The second password would have a `PasswordEncoder` id of `noop` and encodedPassword of `password`.
When matching it would delegate to `NoOpPasswordEncoder` | +|**3**| The third password would have a `PasswordEncoder` id of `pbkdf2` and encodedPassword of `5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc`.
When matching it would delegate to `Pbkdf2PasswordEncoder` | +|**4**|The fourth password would have a `PasswordEncoder` id of `scrypt` and encodedPassword of `$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=`When matching it would delegate to `SCryptPasswordEncoder`| +|**5**| The final password would have a `PasswordEncoder` id of `sha256` and encodedPassword of `97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0`.
When matching it would delegate to `StandardPasswordEncoder` | + +| |Some users might be concerned that the storage format is provided for a potential hacker.
This is not a concern because the storage of the password does not rely on the algorithm being a secret.
Additionally, most formats are easy for an attacker to figure out without the prefix.
For example, BCrypt passwords often start with `$2a$`.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Password Encoding + +The `idForEncode` passed into the constructor determines which `PasswordEncoder` will be used for encoding passwords. +In the `DelegatingPasswordEncoder` we constructed above, that means that the result of encoding `password` would be delegated to `BCryptPasswordEncoder` and be prefixed with `{bcrypt}`. +The end result would look like: + +Example 5. DelegatingPasswordEncoder Encode Example + +``` +{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG +``` + +### Password Matching + +Matching is done based upon the `{id}` and the mapping of the `id` to the `PasswordEncoder` provided in the constructor. +Our example in [Password Storage Format](#authentication-password-storage-dpe-format) provides a working example of how this is done. +By default, the result of invoking `matches(CharSequence, String)` with a password and an `id` that is not mapped (including a null id) will result in an `IllegalArgumentException`. +This behavior can be customized using `DelegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(PasswordEncoder)`. + +By using the `id` we can match on any password encoding, but encode passwords using the most modern password encoding. +This is important, because unlike encryption, password hashes are designed so that there is no simple way to recover the plaintext. +Since there is no way to recover the plaintext, it makes it difficult to migrate the passwords. +While it is simple for users to migrate `NoOpPasswordEncoder`, we chose to include it by default to make it simple for the getting started experience. + +### Getting Started Experience + +If you are putting together a demo or a sample, it is a bit cumbersome to take time to hash the passwords of your users. +There are convenience mechanisms to make this easier, but this is still not intended for production. + +Example 6. withDefaultPasswordEncoder Example + +Java + +``` +User user = User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .roles("user") + .build(); +System.out.println(user.getPassword()); +// {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG +``` + +Kotlin + +``` +val user = User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .roles("user") + .build() +println(user.password) +// {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG +``` + +If you are creating multiple users, you can also reuse the builder. + +Example 7. withDefaultPasswordEncoder Reusing the Builder + +Java + +``` +UserBuilder users = User.withDefaultPasswordEncoder(); +User user = users + .username("user") + .password("password") + .roles("USER") + .build(); +User admin = users + .username("admin") + .password("password") + .roles("USER","ADMIN") + .build(); +``` + +Kotlin + +``` +val users = User.withDefaultPasswordEncoder() +val user = users + .username("user") + .password("password") + .roles("USER") + .build() +val admin = users + .username("admin") + .password("password") + .roles("USER", "ADMIN") + .build() +``` + +This does hash the password that is stored, but the passwords are still exposed in memory and in the compiled source code. +Therefore, it is still not considered secure for a production environment. +For production, you should [hash your passwords externally](#authentication-password-storage-boot-cli). + +### Encode with Spring Boot CLI + +The easiest way to properly encode your password is to use the [Spring Boot CLI](https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-cli.html). + +For example, the following will encode the password of `password` for use with [DelegatingPasswordEncoder](#authentication-password-storage-dpe): + +Example 8. Spring Boot CLI encodepassword Example + +``` +spring encodepassword password +{bcrypt}$2a$10$X5wFBtLrL/kHcmrOGGTrGufsBX8CJ0WpQpF3pgeuxBB/H73BK1DW6 +``` + +### Troubleshooting + +The following error occurs when one of the passwords that are stored has no id as described in [Password Storage Format](#authentication-password-storage-dpe-format). + +``` +java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" + at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:233) + at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:196) +``` + +The easiest way to resolve the error is to switch to explicitly providing the `PasswordEncoder` that your passwords are encoded with. +The easiest way to resolve it is to figure out how your passwords are currently being stored and explicitly provide the correct `PasswordEncoder`. + +If you are migrating from Spring Security 4.2.x you can revert to the previous behavior by [exposing a `NoOpPasswordEncoder` bean](#authentication-password-storage-configuration). + +Alternatively, you can prefix all of your passwords with the correct id and continue to use `DelegatingPasswordEncoder`. +For example, if you are using BCrypt, you would migrate your password from something like: + +``` +$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG +``` + +to + +``` +{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG +``` + +For a complete listing of the mappings refer to the Javadoc on[PasswordEncoderFactories](https://docs.spring.io/spring-security/site/docs/5.0.x/api/org/springframework/security/crypto/factory/PasswordEncoderFactories.html). + +## BCryptPasswordEncoder + +The `BCryptPasswordEncoder` implementation uses the widely supported [bcrypt](https://en.wikipedia.org/wiki/Bcrypt) algorithm to hash the passwords. +In order to make it more resistent to password cracking, bcrypt is deliberately slow. +Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. +The default implementation of `BCryptPasswordEncoder` uses strength 10 as mentioned in the Javadoc of [BCryptPasswordEncoder](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.html). You are encouraged to +tune and test the strength parameter on your own system so that it takes roughly 1 second to verify a password. + +Example 9. BCryptPasswordEncoder + +Java + +``` +// Create an encoder with strength 16 +BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +``` + +Kotlin + +``` +// Create an encoder with strength 16 +val encoder = BCryptPasswordEncoder(16) +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +``` + +## Argon2PasswordEncoder + +The `Argon2PasswordEncoder` implementation uses the [Argon2](https://en.wikipedia.org/wiki/Argon2) algorithm to hash the passwords. +Argon2 is the winner of the [Password Hashing Competition](https://en.wikipedia.org/wiki/Password_Hashing_Competition). +In order to defeat password cracking on custom hardware, Argon2 is a deliberately slow algorithm that requires large amounts of memory. +Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. +The current implementation of the `Argon2PasswordEncoder` requires BouncyCastle. + +Example 10. Argon2PasswordEncoder + +Java + +``` +// Create an encoder with all the defaults +Argon2PasswordEncoder encoder = new Argon2PasswordEncoder(); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +``` + +Kotlin + +``` +// Create an encoder with all the defaults +val encoder = Argon2PasswordEncoder() +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +``` + +## Pbkdf2PasswordEncoder + +The `Pbkdf2PasswordEncoder` implementation uses the [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) algorithm to hash the passwords. +In order to defeat password cracking PBKDF2 is a deliberately slow algorithm. +Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. +This algorithm is a good choice when FIPS certification is required. + +Example 11. Pbkdf2PasswordEncoder + +Java + +``` +// Create an encoder with all the defaults +Pbkdf2PasswordEncoder encoder = new Pbkdf2PasswordEncoder(); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +``` + +Kotlin + +``` +// Create an encoder with all the defaults +val encoder = Pbkdf2PasswordEncoder() +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +``` + +## SCryptPasswordEncoder + +The `SCryptPasswordEncoder` implementation uses [scrypt](https://en.wikipedia.org/wiki/Scrypt) algorithm to hash the passwords. +In order to defeat password cracking on custom hardware scrypt is a deliberately slow algorithm that requires large amounts of memory. +Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. + +Example 12. SCryptPasswordEncoder + +Java + +``` +// Create an encoder with all the defaults +SCryptPasswordEncoder encoder = new SCryptPasswordEncoder(); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +``` + +Kotlin + +``` +// Create an encoder with all the defaults +val encoder = SCryptPasswordEncoder() +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +``` + +## Other PasswordEncoders + +There are a significant number of other `PasswordEncoder` implementations that exist entirely for backward compatibility. +They are all deprecated to indicate that they are no longer considered secure. +However, there are no plans to remove them since it is difficult to migrate existing legacy systems. + +## Password Storage Configuration + +Spring Security uses [DelegatingPasswordEncoder](#authentication-password-storage-dpe) by default. +However, this can be customized by exposing a `PasswordEncoder` as a Spring bean. + +If you are migrating from Spring Security 4.2.x you can revert to the previous behavior by exposing a `NoOpPasswordEncoder` bean. + +| |Reverting to `NoOpPasswordEncoder` is not considered to be secure.
You should instead migrate to using `DelegatingPasswordEncoder` to support secure password encoding.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Example 13. NoOpPasswordEncoder + +Java + +``` +@Bean +public static PasswordEncoder passwordEncoder() { + return NoOpPasswordEncoder.getInstance(); +} +``` + +XML + +``` + +``` + +Kotlin + +``` +@Bean +fun passwordEncoder(): PasswordEncoder { + return NoOpPasswordEncoder.getInstance(); +} +``` + +| |XML Configuration requires the `NoOpPasswordEncoder` bean name to be `passwordEncoder`.| +|---|---------------------------------------------------------------------------------------| + +## Change Password Configuration + +Most applications that allow a user to specify a password also require a feature for updating that password. + +[A Well-Know URL for Changing Passwords](https://w3c.github.io/webappsec-change-password-url/) indicates a mechanism by which password managers can discover the password update endpoint for a given application. + +You can configure Spring Security to provide this discovery endpoint. +For example, if the change password endpoint in your application is `/change-password`, then you can configure Spring Security like so: + +Example 14. Default Change Password Endpoint + +Java + +``` +http + .passwordManagement(Customizer.withDefaults()) +``` + +XML + +``` + +``` + +Kotlin + +``` +http { + passwordManagement { } +} +``` + +Then, when a password manager navigates to `/.well-known/change-password` then Spring Security will redirect your endpoint, `/change-password`. + +Or, if your endpoint is something other than `/change-password`, you can also specify that like so: + +Example 15. Change Password Endpoint + +Java + +``` +http + .passwordManagement((management) -> management + .changePasswordPage("/update-password") + ) +``` + +XML + +``` + +``` + +Kotlin + +``` +http { + passwordManagement { + changePasswordPage = "/update-password" + } +} +``` + +With the above configuration, when a password manager navigates to `/.well-known/change-password`, then Spring Security will redirect to `/update-password`. \ No newline at end of file diff --git a/docs/en/spring-security/features-authentication.md b/docs/en/spring-security/features-authentication.md new file mode 100644 index 0000000000000000000000000000000000000000..0275fcd24eafd1033a2674eb78929c8617240269 --- /dev/null +++ b/docs/en/spring-security/features-authentication.md @@ -0,0 +1,10 @@ +# Authentication + +Spring Security provides comprehensive support for [authentication](https://en.wikipedia.org/wiki/Authentication). +Authentication is how we verify the identity of who is trying to access a particular resource. +A common way to authenticate users is by requiring the user to enter a username and password. +Once authentication is performed we know the identity and can perform authorization. + +Spring Security provides built in support for authenticating users. +This section is dedicated to generic authentication support that applies in both Servlet and WebFlux environments. +Refer to the sections on authentication for [Servlet](../../servlet/authentication/index.html#servlet-authentication) and WebFlux for details on what is supported for each stack. \ No newline at end of file diff --git a/docs/en/spring-security/features-exploits-csrf.md b/docs/en/spring-security/features-exploits-csrf.md new file mode 100644 index 0000000000000000000000000000000000000000..3fdc83a3095036e26aa11475e51979467c3439ab --- /dev/null +++ b/docs/en/spring-security/features-exploits-csrf.md @@ -0,0 +1,373 @@ +# Cross Site Request Forgery (CSRF) + +Spring provides comprehensive support for protecting against [Cross Site Request Forgery (CSRF)](https://en.wikipedia.org/wiki/Cross-site_request_forgery) attacks. +In the following sections we will explore: + +* [What is a CSRF Attack?](#csrf-explained) + +* [Protecting Against CSRF Attacks](#csrf-protection) + +* [CSRF Considerations](#csrf-considerations) + +| |This portion of the documentation discusses the general topic of CSRF protection.
Refer to the relevant sections for specific information on CSRF protection for [servlet](../../servlet/exploits/csrf.html#servlet-csrf) and [WebFlux](../../reactive/exploits/csrf.html#webflux-csrf) based applications.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## What is a CSRF Attack? + +The best way to understand a CSRF attack is by taking a look at a concrete example. + +Assume that your bank’s website provides a form that allows transferring money from the currently logged in user to another bank account. +For example, the transfer form might look like: + +Example 1. Transfer form + +``` +
+ + + + +
+``` + +The corresponding HTTP request might look like: + +Example 2. Transfer HTTP request + +``` +POST /transfer HTTP/1.1 +Host: bank.example.com +Cookie: JSESSIONID=randomid +Content-Type: application/x-www-form-urlencoded + +amount=100.00&routingNumber=1234&account=9876 +``` + +Now pretend you authenticate to your bank’s website and then, without logging out, visit an evil website. +The evil website contains an HTML page with the following form: + +Example 3. Evil transfer form + +``` +
+ + + + +
+``` + +You like to win money, so you click on the submit button. +In the process, you have unintentionally transferred $100 to a malicious user. +This happens because, while the evil website cannot see your cookies, the cookies associated with your bank are still sent along with the request. + +Worst yet, this whole process could have been automated using JavaScript. +This means you didn’t even need to click on the button. +Furthermore, it could just as easily happen when visiting an honest site that is a victim of a [XSS attack](https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)). +So how do we protect our users from such attacks? + +## Protecting Against CSRF Attacks + +The reason that a CSRF attack is possible is that the HTTP request from the victim’s website and the request from the attacker’s website are exactly the same. +This means there is no way to reject requests coming from the evil website and allow requests coming from the bank’s website. +To protect against CSRF attacks we need to ensure there is something in the request that the evil site is unable to provide so we can differentiate the two requests. + +Spring provides two mechanisms to protect against CSRF attacks: + +* The [Synchronizer Token Pattern](#csrf-protection-stp) + +* Specifying the [SameSite Attribute](#csrf-protection-ssa) on your session cookie + +| |Both protections require that [Safe Methods Must be Idempotent](#csrf-protection-idempotent)| +|---|--------------------------------------------------------------------------------------------| + +### Safe Methods Must be Idempotent + +In order for [either protection](#csrf-protection) against CSRF to work, the application must ensure that ["safe" HTTP methods are idempotent](https://tools.ietf.org/html/rfc7231#section-4.2.1). +This means that requests with the HTTP method `GET`, `HEAD`, `OPTIONS`, and `TRACE` should not change the state of the application. + +### Synchronizer Token Pattern + +The predominant and most comprehensive way to protect against CSRF attacks is to use the [Synchronizer Token Pattern](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#synchronizer-token-pattern). +This solution is to ensure that each HTTP request requires, in addition to our session cookie, a secure random generated value called a CSRF token must be present in the HTTP request. + +When an HTTP request is submitted, the server must look up the expected CSRF token and compare it against the actual CSRF token in the HTTP request. +If the values do not match, the HTTP request should be rejected. + +The key to this working is that the actual CSRF token should be in a part of the HTTP request that is not automatically included by the browser. +For example, requiring the actual CSRF token in an HTTP parameter or an HTTP header will protect against CSRF attacks. +Requiring the actual CSRF token in a cookie does not work because cookies are automatically included in the HTTP request by the browser. + +We can relax the expectations to only require the actual CSRF token for each HTTP request that updates state of the application. +For that to work, our application must ensure that [safe HTTP methods are idempotent](#csrf-protection-idempotent). +This improves usability since we want to allow linking to our website using links from external sites. +Additionally, we do not want to include the random token in HTTP GET as this can cause the tokens to be leaked. + +Let’s take a look at how [our example](#csrf-explained) would change when using the Synchronizer Token Pattern. +Assume the actual CSRF token is required to be in an HTTP parameter named `_csrf`. +Our application’s transfer form would look like: + +Example 4. Synchronizer Token Form + +``` +
+ + + + + +
+``` + +The form now contains a hidden input with the value of the CSRF token. +External sites cannot read the CSRF token since the same origin policy ensures the evil site cannot read the response. + +The corresponding HTTP request to transfer money would look like this: + +Example 5. Synchronizer Token request + +``` +POST /transfer HTTP/1.1 +Host: bank.example.com +Cookie: JSESSIONID=randomid +Content-Type: application/x-www-form-urlencoded + +amount=100.00&routingNumber=1234&account=9876&_csrf=4bfd1575-3ad1-4d21-96c7-4ef2d9f86721 +``` + +You will notice that the HTTP request now contains the `_csrf` parameter with a secure random value. +The evil website will not be able to provide the correct value for the `_csrf` parameter (which must be explicitly provided on the evil website) and the transfer will fail when the server compares the actual CSRF token to the expected CSRF token. + +### SameSite Attribute + +An emerging way to protect against [CSRF Attacks](#csrf) is to specify the [SameSite Attribute](https://tools.ietf.org/html/draft-west-first-party-cookies) on cookies. +A server can specify the `SameSite` attribute when setting a cookie to indicate that the cookie should not be sent when coming from external sites. + +| |Spring Security does not directly control the creation of the session cookie, so it does not provide support for the SameSite attribute.[Spring Session](https://spring.io/projects/spring-session) provides support for the `SameSite` attribute in servlet based applications.
Spring Framework’s [CookieWebSessionIdResolver](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/server/session/CookieWebSessionIdResolver.html) provides out of the box support for the `SameSite` attribute in WebFlux based applications.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +An example, HTTP response header with the `SameSite` attribute might look like: + +Example 6. SameSite HTTP response + +``` +Set-Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly; SameSite=Lax +``` + +Valid values for the `SameSite` attribute are: + +* `Strict` - when specified any request coming from the [same-site](https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-2.1) will include the cookie. + Otherwise, the cookie will not be included in the HTTP request. + +* `Lax` - when specified cookies will be sent when coming from the [same-site](https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-2.1) or when the request comes from top-level navigations and the [method is idempotent](#csrf-protection-idempotent). + Otherwise, the cookie will not be included in the HTTP request. + +Let’s take a look at how [our example](#csrf-explained) could be protected using the `SameSite` attribute. +The bank application can protect against CSRF by specifying the `SameSite` attribute on the session cookie. + +With the `SameSite` attribute set on our session cookie, the browser will continue to send the `JSESSIONID` cookie with requests coming from the banking website. +However, the browser will no longer send the `JSESSIONID` cookie with a transfer request coming from the evil website. +Since the session is no longer present in the transfer request coming from the evil website, the application is protected from the CSRF attack. + +There are some important [considerations](https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-5) that one should be aware about when using `SameSite` attribute to protect against CSRF attacks. + +Setting the `SameSite` attribute to `Strict` provides a stronger defense but can confuse users. +Consider a user that stays logged into a social media site hosted at [https://social.example.com](https://social.example.com). +The user receives an email at [https://email.example.org](https://email.example.org) that includes a link to the social media site. +If the user clicks on the link, they would rightfully expect to be authenticated to the social media site. +However, if the `SameSite` attribute is `Strict` the cookie would not be sent and so the user would not be authenticated. + +| |We could improve the protection and usability of `SameSite` protection against CSRF attacks by implementing [gh-7537](https://github.com/spring-projects/spring-security/issues/7537).| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Another obvious consideration is that in order for the `SameSite` attribute to protect users, the browser must support the `SameSite` attribute. +Most modern browsers do [support the SameSite attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/headers/Set-Cookie#Browser_compatibility). +However, older browsers that are still in use may not. + +For this reason, it is generally recommended to use the `SameSite` attribute as a defense in depth rather than the sole protection against CSRF attacks. + +## When to use CSRF protection + +When should you use CSRF protection? +Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. +If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection. + +### CSRF protection and JSON + +A common question is "do I need to protect JSON requests made by javascript?" +The short answer is, it depends. +However, you must be very careful as there are CSRF exploits that can impact JSON requests. +For example, a malicious user can create a [CSRF with JSON using the following form](http://blog.opensecurityresearch.com/2012/02/json-csrf-with-parameter-padding.html): + +Example 7. CSRF with JSON form + +``` +
+ + +
+``` + +This will produce the following JSON structure + +Example 8. CSRF with JSON request + +``` +{ "amount": 100, +"routingNumber": "evilsRoutingNumber", +"account": "evilsAccountNumber", +"ignore_me": "=test" +} +``` + +If an application were not validating the Content-Type, then it would be exposed to this exploit. +Depending on the setup, a Spring MVC application that validates the Content-Type could still be exploited by updating the URL suffix to end with `.json` as shown below: + +Example 9. CSRF with JSON Spring MVC form + +``` +
+ + +
+``` + +### CSRF and Stateless Browser Applications + +What if my application is stateless? +That doesn’t necessarily mean you are protected. +In fact, if a user does not need to perform any actions in the web browser for a given request, they are likely still vulnerable to CSRF attacks. + +For example, consider an application that uses a custom cookie that contains all the state within it for authentication instead of the JSESSIONID. +When the CSRF attack is made the custom cookie will be sent with the request in the same manner that the JSESSIONID cookie was sent in our previous example. +This application will be vulnerable to CSRF attacks. + +Applications that use basic authentication are also vulnerable to CSRF attacks. +The application is vulnerable since the browser will automatically include the username and password in any requests in the same manner that the JSESSIONID cookie was sent in our previous example. + +## CSRF Considerations + +There are a few special considerations to consider when implementing protection against CSRF attacks. + +### Logging In + +In order to protect against [forging log in requests](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests) the log in HTTP request should be protected against CSRF attacks. +Protecting against forging log in requests is necessary so that a malicious user cannot read a victim’s sensitive information. +The attack is performed as follows: + +* A malicious user performs a CSRF log in using the malicious user’s credentials. + The victim is now authenticated as the malicious user. + +* The malicious user then tricks the victim to visit the compromised website and enter sensitive information + +* The information is associated to the malicious user’s account so the malicious user can log in with their own credentials and view the vicitim’s sensitive information + +A possible complication to ensuring log in HTTP requests are protected against CSRF attacks is that the user might experience a session timeout that causes the request to be rejected. +A session timeout is surprising to users who do not expect to need to have a session in order to log in. +For more information refer to [CSRF and Session Timeouts](#csrf-considerations-timeouts). + +### Logging Out + +In order to protect against forging log out requests, the log out HTTP request should be protected against CSRF attacks. +Protecting against forging log out requests is necessary so a malicious user cannot read a victim’s sensitive information. +For details on the attack refer to [this blog post](https://labs.detectify.com/2017/03/15/loginlogout-csrf-time-to-reconsider/). + +A possible complication to ensuring log out HTTP requests are protected against CSRF attacks is that the user might experience a session timeout that causes the request to be rejected. +A session timeout is surprising to users who do not expect to need to have a session in order to log out. +For more information refer to [CSRF and Session Timeouts](#csrf-considerations-timeouts). + +### CSRF and Session Timeouts + +More often than not, the expected CSRF token is stored in the session. +This means that as soon as the session expires the server will not find an expected CSRF token and reject the HTTP request. +There are a number of options to solve timeouts each of which come with trade offs. + +* The best way to mitigate the timeout is by using JavaScript to request a CSRF token on form submission. + The form is then updated with the CSRF token and submitted. + +* Another option is to have some JavaScript that lets the user know their session is about to expire. + The user can click a button to continue and refresh the session. + +* Finally, the expected CSRF token could be stored in a cookie. + This allows the expected CSRF token to outlive the session. + + One might ask why the expected CSRF token isn’t stored in a cookie by default. + This is because there are known exploits in which headers (for example, to specify the cookies) can be set by another domain. + This is the same reason Ruby on Rails [no longer skips CSRF checks when the header X-Requested-With is present](https://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails/). + See [this webappsec.org thread](https://web.archive.org/web/20210221120355/https://lists.webappsec.org/pipermail/websecurity_lists.webappsec.org/2011-February/007533.html) for details on how to perform the exploit. + Another disadvantage is that by removing the state (that is, the timeout), you lose the ability to forcibly invalidate the token if it is compromised. + +### + +Protecting multipart requests (file uploads) from CSRF attacks causes a [chicken and the egg](https://en.wikipedia.org/wiki/Chicken_or_the_egg) problem. +In order to prevent a CSRF attack from occurring, the body of the HTTP request must be read to obtain actual CSRF token. +However, reading the body means that the file will be uploaded which means an external site can upload a file. + +There are two options to using CSRF protection with multipart/form-data. +Each option has its trade-offs. + +* [Place CSRF Token in the Body](#csrf-considerations-multipart-body) + +* [Place CSRF Token in the URL](#csrf-considerations-multipart-url) + +| |Before you integrate Spring Security’s CSRF protection with multipart file upload, ensure that you can upload without the CSRF protection first.
More information about using multipart forms with Spring can be found within the [1.1.11. Multipart Resolver](https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web.html#mvc-multipart) section of the Spring reference and the [MultipartFilter javadoc](https://docs.spring.io/spring/docs/5.2.x/javadoc-api/org/springframework/web/multipart/support/MultipartFilter.html).| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +#### Place CSRF Token in the Body + +The first option is to include the actual CSRF token in the body of the request. +By placing the CSRF token in the body, the body will be read before authorization is performed. +This means that anyone can place temporary files on your server. +However, only authorized users will be able to submit a file that is processed by your application. +In general, this is the recommended approach because the temporary file upload should have a negligible impact on most servers. + +#### Include CSRF Token in URL + +If allowing unauthorized users to upload temporary files is not acceptable, an alternative is to include the expected CSRF token as a query parameter in the action attribute of the form. +The disadvantage to this approach is that query parameters can be leaked. +More generally, it is considered best practice to place sensitive data within the body or headers to ensure it is not leaked. +Additional information can be found in [RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI’s](https://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3). + +#### HiddenHttpMethodFilter + +In some applications a form parameter can be used to override the HTTP method. +For example, the form below could be used to treat the HTTP method as a `delete` rather than a `post`. + +Example 10. CSRF Hidden HTTP Method Form + +``` +
+ + +
+``` + +Overriding the HTTP method occurs in a filter. +That filter must be placed before Spring Security’s support. +Note that overriding only happens on a `post`, so this is actually unlikely to cause any real problems. +However, it is still best practice to ensure it is placed before Spring Security’s filters. \ No newline at end of file diff --git a/docs/en/spring-security/features-exploits-headers.md b/docs/en/spring-security/features-exploits-headers.md new file mode 100644 index 0000000000000000000000000000000000000000..65348362d1a2ae676e74b8dd70024b817830eccd --- /dev/null +++ b/docs/en/spring-security/features-exploits-headers.md @@ -0,0 +1,310 @@ +# Security HTTP Response Headers + +| |This portion of the documentation discusses the general topic of Security HTTP Response Headers.
Refer to the relevant sections for specific information on Security HTTP Response Headers [servlet](../../servlet/exploits/headers.html#servlet-headers) and [WebFlux](../../reactive/exploits/headers.html#webflux-headers) based applications.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +There are many [HTTP response headers](https://owasp.org/www-project-secure-headers/#div-headers) that can be used to increase the security of web applications. +This section is dedicated to the various HTTP response headers that Spring Security provides explicit support for. +If necessary, Spring Security can also be configured to provide [custom headers](#headers-custom). + +## Default Security Headers + +| |Refer to the relevant sections to see how to customize the defaults for both [servlet](../../servlet/exploits/headers.html#servlet-headers-default) and [webflux](../../reactive/exploits/headers.html#webflux-headers-default) based applications.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Spring Security provides a default set of security related HTTP response headers to provide secure defaults. + +The default for Spring Security is to include the following headers: + +Example 1. Default Security HTTP Response Headers + +``` +Cache-Control: no-cache, no-store, max-age=0, must-revalidate +Pragma: no-cache +Expires: 0 +X-Content-Type-Options: nosniff +Strict-Transport-Security: max-age=31536000 ; includeSubDomains +X-Frame-Options: DENY +X-XSS-Protection: 1; mode=block +``` + +| |Strict-Transport-Security is only added on HTTPS requests| +|---|---------------------------------------------------------| + +If the defaults do not meet your needs, you can easily remove, modify, or add headers from these defaults. +For additional details on each of these headers, refer to the corresponding sections: + +* [Cache Control](#headers-cache-control) + +* [Content Type Options](#headers-content-type-options) + +* [HTTP Strict Transport Security](#headers-hsts) + +* [X-Frame-Options](#headers-frame-options) + +* [X-XSS-Protection](#headers-xss-protection) + +## Cache Control + +| |Refer to the relevant sections to see how to customize the defaults for both [servlet](../../servlet/exploits/headers.html#servlet-headers-cache-control) and [webflux](../../reactive/exploits/headers.html#webflux-headers-cache-control) based applications.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Spring Security’s default is to disable caching to protect user’s content. + +If a user authenticates to view sensitive information and then logs out, we don’t want a malicious user to be able to click the back button to view the sensitive information. +The cache control headers that are sent by default are: + +Example 2. Default Cache Control HTTP Response Headers + +``` +Cache-Control: no-cache, no-store, max-age=0, must-revalidate +Pragma: no-cache +Expires: 0 +``` + +In order to be secure by default, Spring Security adds these headers by default. +However, if your application provides its own cache control headers Spring Security will back out of the way. +This allows for applications to ensure that static resources like CSS and JavaScript can be cached. + +## Content Type Options + +| |Refer to the relevant sections to see how to customize the defaults for both [servlet](../../servlet/exploits/headers.html#servlet-headers-content-type-options) and [webflux](../../reactive/exploits/headers.html#webflux-headers-content-type-options) based applications.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Historically browsers, including Internet Explorer, would try to guess the content type of a request using [content sniffing](https://en.wikipedia.org/wiki/Content_sniffing). +This allowed browsers to improve the user experience by guessing the content type on resources that had not specified the content type. +For example, if a browser encountered a JavaScript file that did not have the content type specified, it would be able to guess the content type and then run it. + +| |There are many additional things one should do (i.e. only display the document in a distinct domain, ensure Content-Type header is set, sanitize the document, etc) when allowing content to be uploaded.
However, these measures are out of the scope of what Spring Security provides.
It is also important to point out when disabling content sniffing, you must specify the content type in order for things to work properly.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The problem with content sniffing is that this allowed malicious users to use polyglots (i.e. a file that is valid as multiple content types) to perform XSS attacks. +For example, some sites may allow users to submit a valid postscript document to a website and view it. +A malicious user might create a [postscript document that is also a valid JavaScript file](http://webblaze.cs.berkeley.edu/papers/barth-caballero-song.pdf) and perform a XSS attack with it. + +Spring Security disables content sniffing by default by adding the following header to HTTP responses: + +Example 3. nosniff HTTP Response Header + +``` +X-Content-Type-Options: nosniff +``` + +## + +| |Refer to the relevant sections to see how to customize the defaults for both [servlet](../../servlet/exploits/headers.html#servlet-headers-hsts) and [webflux](../../reactive/exploits/headers.html#webflux-headers-hsts) based applications.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +When you type in your bank’s website, do you enter mybank.example.com or do you enter [https://mybank.example.com](https://mybank.example.com)? +If you omit the https protocol, you are potentially vulnerable to [Man in the Middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). +Even if the website performs a redirect to [https://mybank.example.com](https://mybank.example.com) a malicious user could intercept the initial HTTP request and manipulate the response (e.g. redirect to [https://mibank.example.com](https://mibank.example.com) and steal their credentials). + +Many users omit the https protocol and this is why [HTTP Strict Transport Security (HSTS)](https://tools.ietf.org/html/rfc6797) was created. +Once mybank.example.com is added as a [HSTS host](https://tools.ietf.org/html/rfc6797#section-5.1), a browser can know ahead of time that any request to mybank.example.com should be interpreted as [https://mybank.example.com](https://mybank.example.com). +This greatly reduces the possibility of a Man in the Middle attack occurring. + +| |In accordance with [RFC6797](https://tools.ietf.org/html/rfc6797#section-7.2), the HSTS header is only injected into HTTPS responses.
In order for the browser to acknowledge the header, the browser must first trust the CA that signed the SSL certificate used to make the connection (not just the SSL certificate).| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +One way for a site to be marked as a HSTS host is to have the host preloaded into the browser. +Another is to add the `Strict-Transport-Security` header to the response. +For example, Spring Security’s default behavior is to add the following header which instructs the browser to treat the domain as an HSTS host for a year (there are approximately 31536000 seconds in a year): + +Example 4. Strict Transport Security HTTP Response Header + +``` +Strict-Transport-Security: max-age=31536000 ; includeSubDomains ; preload +``` + +The optional `includeSubDomains` directive instructs the browser that subdomains (e.g. secure.mybank.example.com) should also be treated as an HSTS domain. + +The optional `preload` directive instructs the browser that domain should be preloaded in browser as HSTS domain. +For more details on HSTS preload please see [https://hstspreload.org](https://hstspreload.org). + +## + +| |In order to remain passive Spring Security still provides [support for HPKP in servlet environments](../../servlet/exploits/headers.html#servlet-headers-hpkp), but for the reasons listed above HPKP is no longer recommended by the security team.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[HTTP Public Key Pinning (HPKP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning) specifies to a web client which public key to use with certain web server to prevent Man in the Middle (MITM) attacks with forged certificates. +When used correctly, HPKP could add additional layers of protection against compromised certificates. +However, due to the complexity of HPKP many experts no longer recommend using it and [Chrome has even removed support](https://www.chromestatus.com/feature/5903385005916160) for it. + +For additional details around why HPKP is no longer recommended read [Is HTTP Public Key Pinning Dead?](https://blog.qualys.com/ssllabs/2016/09/06/is-http-public-key-pinning-dead) and [I’m giving up on HPKP](https://scotthelme.co.uk/im-giving-up-on-hpkp/). + +## X-Frame-Options + +| |Refer to the relevant sections to see how to customize the defaults for both [servlet](../../servlet/exploits/headers.html#servlet-headers-frame-options) and [webflux](../../reactive/exploits/headers.html#webflux-headers-frame-options) based applications.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Allowing your website to be added to a frame can be a security issue. +For example, using clever CSS styling users could be tricked into clicking on something that they were not intending. +For example, a user that is logged into their bank might click a button that grants access to other users. +This sort of attack is known as [Clickjacking](https://en.wikipedia.org/wiki/Clickjacking). + +| |Another modern approach to dealing with clickjacking is to use [Content Security Policy (CSP)](#headers-csp).| +|---|-------------------------------------------------------------------------------------------------------------| + +There are a number ways to mitigate clickjacking attacks. +For example, to protect legacy browsers from clickjacking attacks you can use [frame breaking code](https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Best-for-now_Legacy_Browser_Frame_Breaking_Script). +While not perfect, the frame breaking code is the best you can do for the legacy browsers. + +A more modern approach to address clickjacking is to use [X-Frame-Options](https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options) header. +By default Spring Security disables rendering pages within an iframe using with the following header: + +``` +X-Frame-Options: DENY +``` + +## X-XSS-Protection + +| |Refer to the relevant sections to see how to customize the defaults for both [servlet](../../servlet/exploits/headers.html#servlet-headers-xss-protection) and [webflux](../../reactive/exploits/headers.html#webflux-headers-xss-protection) based applications.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Some browsers have built in support for filtering out [reflected XSS attacks](https://www.owasp.org/index.php/Testing_for_Reflected_Cross_site_scripting_(OWASP-DV-001)). +This is by no means foolproof, but does assist in XSS protection. + +The filtering is typically enabled by default, so adding the header typically just ensures it is enabled and instructs the browser what to do when a XSS attack is detected. +For example, the filter might try to change the content in the least invasive way to still render everything. +At times, this type of replacement can become a [XSS vulnerability in itself](https://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/). +Instead, it is best to block the content rather than attempt to fix it. +By default Spring Security blocks the content using the following header: + +``` +X-XSS-Protection: 1; mode=block +``` + +## + +| |Refer to the relevant sections to see how to configure both [servlet](../../servlet/exploits/headers.html#servlet-headers-csp) and [webflux](../../reactive/exploits/headers.html#webflux-headers-csp) based applications.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Content Security Policy (CSP)](https://www.w3.org/TR/CSP2/) is a mechanism that web applications can leverage to mitigate content injection vulnerabilities, such as cross-site scripting (XSS). +CSP is a declarative policy that provides a facility for web application authors to declare and ultimately inform the client (user-agent) about the sources from which the web application expects to load resources. + +| |Content Security Policy is not intended to solve all content injection vulnerabilities.
Instead, CSP can be leveraged to help reduce the harm caused by content injection attacks.
As a first line of defense, web application authors should validate their input and encode their output.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +A web application may employ the use of CSP by including one of the following HTTP headers in the response: + +* `Content-Security-Policy` + +* `Content-Security-Policy-Report-Only` + +Each of these headers are used as a mechanism to deliver a security policy to the client. +A security policy contains a set of security policy directives, each responsible for declaring the restrictions for a particular resource representation. + +For example, a web application can declare that it expects to load scripts from specific, trusted sources, by including the following header in the response: + +Example 5. Content Security Policy Example + +``` +Content-Security-Policy: script-src https://trustedscripts.example.com +``` + +An attempt to load a script from another source other than what is declared in the `script-src` directive will be blocked by the user-agent. +Additionally, if the [report-uri](https://www.w3.org/TR/CSP2/#directive-report-uri) directive is declared in the security policy, then the violation will be reported by the user-agent to the declared URL. + +For example, if a web application violates the declared security policy, the following response header will instruct the user-agent to send violation reports to the URL specified in the policy’s `report-uri` directive. + +Example 6. Content Security Policy with report-uri + +``` +Content-Security-Policy: script-src https://trustedscripts.example.com; report-uri /csp-report-endpoint/ +``` + +[Violation reports](https://www.w3.org/TR/CSP2/#violation-reports) are standard JSON structures that can be captured either by the web application’s own API or by a publicly hosted CSP violation reporting service, such as, [https://report-uri.com/](https://report-uri.com/). + +The `Content-Security-Policy-Report-Only` header provides the capability for web application authors and administrators to monitor security policies, rather than enforce them. +This header is typically used when experimenting and/or developing security policies for a site. +When a policy is deemed effective, it can be enforced by using the `Content-Security-Policy` header field instead. + +Given the following response header, the policy declares that scripts may be loaded from one of two possible sources. + +Example 7. Content Security Policy Report Only + +``` +Content-Security-Policy-Report-Only: script-src 'self' https://trustedscripts.example.com; report-uri /csp-report-endpoint/ +``` + +If the site violates this policy, by attempting to load a script from *evil.com*, the user-agent will send a violation report to the declared URL specified by the *report-uri* directive, but still allow the violating resource to load nevertheless. + +Applying Content Security Policy to a web application is often a non-trivial undertaking. +The following resources may provide further assistance in developing effective security policies for your site. + +[An Introduction to Content Security Policy](https://www.html5rocks.com/en/tutorials/security/content-security-policy/) + +[CSP Guide - Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/Security/CSP) + +[W3C Candidate Recommendation](https://www.w3.org/TR/CSP2/) + +## Referrer Policy + +| |Refer to the relevant sections to see how to configure both [servlet](../../servlet/exploits/headers.html#servlet-headers-referrer) and [webflux](../../reactive/exploits/headers.html#webflux-headers-referrer) based applications.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Referrer Policy](https://www.w3.org/TR/referrer-policy) is a mechanism that web applications can leverage to manage the referrer field, which contains the last +page the user was on. + +Spring Security’s approach is to use [Referrer Policy](https://www.w3.org/TR/referrer-policy/) header, which provides different [policies](https://www.w3.org/TR/referrer-policy/#referrer-policies): + +Example 8. Referrer Policy Example + +``` +Referrer-Policy: same-origin +``` + +The Referrer-Policy response header instructs the browser to let the destination knows the source where the user was previously. + +## Feature Policy + +| |Refer to the relevant sections to see how to configure both [servlet](../../servlet/exploits/headers.html#servlet-headers-feature) and [webflux](../../reactive/exploits/headers.html#webflux-headers-feature) based applications.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Feature Policy](https://wicg.github.io/feature-policy/) is a mechanism that allows web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser. + +Example 9. Feature Policy Example + +``` +Feature-Policy: geolocation 'self' +``` + +With Feature Policy, developers can opt-in to a set of "policies" for the browser to enforce on specific features used throughout your site. +These policies restrict what APIs the site can access or modify the browser’s default behavior for certain features. + +## Permissions Policy + +| |Refer to the relevant sections to see how to configure both [servlet](../../servlet/exploits/headers.html#servlet-headers-permissions) and [webflux](../../reactive/exploits/headers.html#webflux-headers-permissions) based applications.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Permissions Policy](https://w3c.github.io/webappsec-permissions-policy/) is a mechanism that allows web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser. + +Example 10. Permissions Policy Example + +``` +Permissions-Policy: geolocation=(self) +``` + +With Permissions Policy, developers can opt-in to a set of "policies" for the browser to enforce on specific features used throughout your site. +These policies restrict what APIs the site can access or modify the browser’s default behavior for certain features. + +## Clear Site Data + +| |Refer to the relevant sections to see how to configure both [servlet](../../servlet/exploits/headers.html#servlet-headers-clear-site-data) and [webflux](../../reactive/exploits/headers.html#webflux-headers-clear-site-data) based applications.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Clear Site Data](https://www.w3.org/TR/clear-site-data/) is a mechanism by which any browser-side data - cookies, local storage, and the like - can be removed when an HTTP response contains this header: + +``` +Clear-Site-Data: "cache", "cookies", "storage", "executionContexts" +``` + +This is a nice clean-up action to perform on logout. + +## Custom Headers + +| |Refer to the relevant section to see how to configure [servlet](../../servlet/exploits/headers.html#servlet-headers-custom) based applications.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------| + +Spring Security has mechanisms to make it convenient to add the more common security headers to your application. +However, it also provides hooks to enable adding custom headers. \ No newline at end of file diff --git a/docs/en/spring-security/features-exploits-http.md b/docs/en/spring-security/features-exploits-http.md new file mode 100644 index 0000000000000000000000000000000000000000..8c9b4a90ae58845d62b91a7aa9b2e2eade12cbd7 --- /dev/null +++ b/docs/en/spring-security/features-exploits-http.md @@ -0,0 +1,28 @@ +# HTTP + +All HTTP based communication, including [static resources](https://www.troyhunt.com/heres-why-your-static-website-needs-https/), should be protected [using TLS](https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html). + +As a framework, Spring Security does not handle HTTP connections and thus does not provide support for HTTPS directly. +However, it does provide a number of features that help with HTTPS usage. + +## Redirect to HTTPS + +When a client uses HTTP, Spring Security can be configured to redirect to HTTPS both [Servlet](../../servlet/exploits/http.html#servlet-http-redirect) and [WebFlux](../../reactive/exploits/http.html#webflux-http-redirect) environments. + +## Strict Transport Security + +Spring Security provides support for [Strict Transport Security](headers.html#headers-hsts) and enables it by default. + +## Proxy Server Configuration + +When using a proxy server it is important to ensure that you have configured your application properly. +For example, many applications will have a load balancer that responds to request for [https://example.com/](https://example.com/) by forwarding the request to an application server at [https://192.168.1:8080](https://192.168.1:8080). +Without proper configuration, the application server will not know that the load balancer exists and treat the request as though [https://192.168.1:8080](https://192.168.1:8080) was requested by the client. + +To fix this you can use [RFC 7239](https://tools.ietf.org/html/rfc7239) to specify that a load balancer is being used. +To make the application aware of this, you need to either configure your application server aware of the X-Forwarded headers. +For example Tomcat uses the [RemoteIpValve](https://tomcat.apache.org/tomcat-8.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html) and Jetty uses [ForwardedRequestCustomizer](https://www.eclipse.org/jetty/javadoc/jetty-9/org/eclipse/jetty/server/ForwardedRequestCustomizer.html). +Alternatively, Spring users can leverage [ForwardedHeaderFilter](https://github.com/spring-projects/spring-framework/blob/v4.3.3.RELEASE/spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java). + +Spring Boot users may use the `server.use-forward-headers` property to configure the application. +See the [Spring Boot documentation](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-use-tomcat-behind-a-proxy-server) for further details. \ No newline at end of file diff --git a/docs/en/spring-security/features-exploits.md b/docs/en/spring-security/features-exploits.md new file mode 100644 index 0000000000000000000000000000000000000000..3b5a928845d08a9e530c6361a1b03f0ca8bf6267 --- /dev/null +++ b/docs/en/spring-security/features-exploits.md @@ -0,0 +1,11 @@ +# Protection Against Exploits + +Spring Security provides protection against common exploits. +Whenever possible, the protection is enabled by default. +Below you will find high level description of the various exploits that Spring Security protects against. + +## Section Summary + +* [CSRF](csrf.html) +* [HTTP Headers](headers.html) +* [HTTP Requests](http.html) \ No newline at end of file diff --git a/docs/en/spring-security/features-integrations-concurrency.md b/docs/en/spring-security/features-integrations-concurrency.md new file mode 100644 index 0000000000000000000000000000000000000000..fb0078465d6cc29c2af44b65d31def848a2d9792 --- /dev/null +++ b/docs/en/spring-security/features-integrations-concurrency.md @@ -0,0 +1,258 @@ +# Concurrency Support + +In most environments, Security is stored on a per `Thread` basis. +This means that when work is done on a new `Thread`, the `SecurityContext` is lost. +Spring Security provides some infrastructure to help make this much easier for users. +Spring Security provides low level abstractions for working with Spring Security in multi-threaded environments. +In fact, this is what Spring Security builds on to integration with [AsyncContext.start(Runnable)](../../servlet/integrations/servlet-api.html#servletapi-start-runnable) and [Spring MVC Async Integration](../../servlet/integrations/mvc.html#mvc-async). + +## DelegatingSecurityContextRunnable + +One of the most fundamental building blocks within Spring Security’s concurrency support is the `DelegatingSecurityContextRunnable`. +It wraps a delegate `Runnable` in order to initialize the `SecurityContextHolder` with a specified `SecurityContext` for the delegate. +It then invokes the delegate Runnable ensuring to clear the `SecurityContextHolder` afterwards. +The `DelegatingSecurityContextRunnable` looks something like this: + +Java + +``` +public void run() { +try { + SecurityContextHolder.setContext(securityContext); + delegate.run(); +} finally { + SecurityContextHolder.clearContext(); +} +} +``` + +Kotlin + +``` +fun run() { + try { + SecurityContextHolder.setContext(securityContext) + delegate.run() + } finally { + SecurityContextHolder.clearContext() + } +} +``` + +While very simple, it makes it seamless to transfer the SecurityContext from one Thread to another. +This is important since, in most cases, the SecurityContextHolder acts on a per Thread basis. +For example, you might have used Spring Security’s [\](../../servlet/appendix/namespace/method-security.html#nsa-global-method-security) support to secure one of your services. +You can now easily transfer the `SecurityContext` of the current `Thread` to the `Thread` that invokes the secured service. +An example of how you might do this can be found below: + +Java + +``` +Runnable originalRunnable = new Runnable() { +public void run() { + // invoke secured service +} +}; + +SecurityContext context = SecurityContextHolder.getContext(); +DelegatingSecurityContextRunnable wrappedRunnable = + new DelegatingSecurityContextRunnable(originalRunnable, context); + +new Thread(wrappedRunnable).start(); +``` + +Kotlin + +``` +val originalRunnable = Runnable { + // invoke secured service +} +val context: SecurityContext = SecurityContextHolder.getContext() +val wrappedRunnable = DelegatingSecurityContextRunnable(originalRunnable, context) + +Thread(wrappedRunnable).start() +``` + +The code above performs the following steps: + +* Creates a `Runnable` that will be invoking our secured service. + Notice that it is not aware of Spring Security + +* Obtains the `SecurityContext` that we wish to use from the `SecurityContextHolder` and initializes the `DelegatingSecurityContextRunnable` + +* Use the `DelegatingSecurityContextRunnable` to create a Thread + +* Start the Thread we created + +Since it is quite common to create a `DelegatingSecurityContextRunnable` with the `SecurityContext` from the `SecurityContextHolder` there is a shortcut constructor for it. +The following code is the same as the code above: + +Java + +``` +Runnable originalRunnable = new Runnable() { +public void run() { + // invoke secured service +} +}; + +DelegatingSecurityContextRunnable wrappedRunnable = + new DelegatingSecurityContextRunnable(originalRunnable); + +new Thread(wrappedRunnable).start(); +``` + +Kotlin + +``` +val originalRunnable = Runnable { + // invoke secured service +} + +val wrappedRunnable = DelegatingSecurityContextRunnable(originalRunnable) + +Thread(wrappedRunnable).start() +``` + +The code we have is simple to use, but it still requires knowledge that we are using Spring Security. +In the next section we will take a look at how we can utilize `DelegatingSecurityContextExecutor` to hide the fact that we are using Spring Security. + +## DelegatingSecurityContextExecutor + +In the previous section we found that it was easy to use the `DelegatingSecurityContextRunnable`, but it was not ideal since we had to be aware of Spring Security in order to use it. +Let’s take a look at how `DelegatingSecurityContextExecutor` can shield our code from any knowledge that we are using Spring Security. + +The design of `DelegatingSecurityContextExecutor` is very similar to that of `DelegatingSecurityContextRunnable` except it accepts a delegate `Executor` instead of a delegate `Runnable`. +You can see an example of how it might be used below: + +Java + +``` +SecurityContext context = SecurityContextHolder.createEmptyContext(); +Authentication authentication = + new UsernamePasswordAuthenticationToken("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER")); +context.setAuthentication(authentication); + +SimpleAsyncTaskExecutor delegateExecutor = + new SimpleAsyncTaskExecutor(); +DelegatingSecurityContextExecutor executor = + new DelegatingSecurityContextExecutor(delegateExecutor, context); + +Runnable originalRunnable = new Runnable() { +public void run() { + // invoke secured service +} +}; + +executor.execute(originalRunnable); +``` + +Kotlin + +``` +val context: SecurityContext = SecurityContextHolder.createEmptyContext() +val authentication: Authentication = + UsernamePasswordAuthenticationToken("user", "doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER")) +context.authentication = authentication + +val delegateExecutor = SimpleAsyncTaskExecutor() +val executor = DelegatingSecurityContextExecutor(delegateExecutor, context) + +val originalRunnable = Runnable { + // invoke secured service +} + +executor.execute(originalRunnable) +``` + +The code performs the following steps: + +* Creates the `SecurityContext` to be used for our `DelegatingSecurityContextExecutor`. + Note that in this example we simply create the `SecurityContext` by hand. + However, it does not matter where or how we get the `SecurityContext` (i.e. we could obtain it from the `SecurityContextHolder` if we wanted). + +* Creates a delegateExecutor that is in charge of executing submitted `Runnable`s + +* Finally we create a `DelegatingSecurityContextExecutor` which is in charge of wrapping any Runnable that is passed into the execute method with a `DelegatingSecurityContextRunnable`. + It then passes the wrapped Runnable to the delegateExecutor. + In this instance, the same `SecurityContext` will be used for every Runnable submitted to our `DelegatingSecurityContextExecutor`. + This is nice if we are running background tasks that need to be run by a user with elevated privileges. + +* At this point you may be asking yourself "How does this shield my code of any knowledge of Spring Security?" Instead of creating the `SecurityContext` and the `DelegatingSecurityContextExecutor` in our own code, we can inject an already initialized instance of `DelegatingSecurityContextExecutor`. + +Java + +``` +@Autowired +private Executor executor; // becomes an instance of our DelegatingSecurityContextExecutor + +public void submitRunnable() { +Runnable originalRunnable = new Runnable() { + public void run() { + // invoke secured service + } +}; +executor.execute(originalRunnable); +} +``` + +Kotlin + +``` +@Autowired +lateinit var executor: Executor // becomes an instance of our DelegatingSecurityContextExecutor + +fun submitRunnable() { + val originalRunnable = Runnable { + // invoke secured service + } + executor.execute(originalRunnable) +} +``` + +Now our code is unaware that the `SecurityContext` is being propagated to the `Thread`, then the `originalRunnable` is run, and then the `SecurityContextHolder` is cleared out. +In this example, the same user is being used to run each thread. +What if we wanted to use the user from `SecurityContextHolder` at the time we invoked `executor.execute(Runnable)` (i.e. the currently logged in user) to process `originalRunnable`? +This can be done by removing the `SecurityContext` argument from our `DelegatingSecurityContextExecutor` constructor. +For example: + +Java + +``` +SimpleAsyncTaskExecutor delegateExecutor = new SimpleAsyncTaskExecutor(); +DelegatingSecurityContextExecutor executor = + new DelegatingSecurityContextExecutor(delegateExecutor); +``` + +Kotlin + +``` +val delegateExecutor = SimpleAsyncTaskExecutor() +val executor = DelegatingSecurityContextExecutor(delegateExecutor) +``` + +Now anytime `executor.execute(Runnable)` is executed the `SecurityContext` is first obtained by the `SecurityContextHolder` and then that `SecurityContext` is used to create our `DelegatingSecurityContextRunnable`. +This means that we are running our `Runnable` with the same user that was used to invoke the `executor.execute(Runnable)` code. + +## Spring Security Concurrency Classes + +Refer to the Javadoc for additional integrations with both the Java concurrent APIs and the Spring Task abstractions. +They are quite self-explanatory once you understand the previous code. + +* `DelegatingSecurityContextCallable` + +* `DelegatingSecurityContextExecutor` + +* `DelegatingSecurityContextExecutorService` + +* `DelegatingSecurityContextRunnable` + +* `DelegatingSecurityContextScheduledExecutorService` + +* `DelegatingSecurityContextSchedulingTaskExecutor` + +* `DelegatingSecurityContextAsyncTaskExecutor` + +* `DelegatingSecurityContextTaskExecutor` + +* `DelegatingSecurityContextTaskScheduler` \ No newline at end of file diff --git a/docs/en/spring-security/features-integrations-cryptography.md b/docs/en/spring-security/features-integrations-cryptography.md new file mode 100644 index 0000000000000000000000000000000000000000..a8e33792d09f03de84ca92b2c2e8216e89401675 --- /dev/null +++ b/docs/en/spring-security/features-integrations-cryptography.md @@ -0,0 +1,248 @@ +# Spring Security Crypto Module + +## Introduction + +The Spring Security Crypto module provides support for symmetric encryption, key generation, and password encoding. +The code is distributed as part of the core module but has no dependencies on any other Spring Security (or Spring) code. + +## Encryptors + +The Encryptors class provides factory methods for constructing symmetric encryptors. +Using this class, you can create ByteEncryptors to encrypt data in raw byte[] form. +You can also construct TextEncryptors to encrypt text strings. +Encryptors are thread-safe. + +### BytesEncryptor + +Use the `Encryptors.stronger` factory method to construct a BytesEncryptor: + +Example 1. BytesEncryptor + +Java + +``` +Encryptors.stronger("password", "salt"); +``` + +Kotlin + +``` +Encryptors.stronger("password", "salt") +``` + +The "stronger" encryption method creates an encryptor using 256 bit AES encryption with +Galois Counter Mode (GCM). +It derives the secret key using PKCS #5’s PBKDF2 (Password-Based Key Derivation Function #2). +This method requires Java 6. +The password used to generate the SecretKey should be kept in a secure place and not be shared. +The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised. +A 16-byte random initialization vector is also applied so each encrypted message is unique. + +The provided salt should be in hex-encoded String form, be random, and be at least 8 bytes in length. +Such a salt may be generated using a KeyGenerator: + +Example 2. Generating a key + +Java + +``` +String salt = KeyGenerators.string().generateKey(); // generates a random 8-byte salt that is then hex-encoded +``` + +Kotlin + +``` +val salt = KeyGenerators.string().generateKey() // generates a random 8-byte salt that is then hex-encoded +``` + +Users may also use the `standard` encryption method, which is 256-bit AES in Cipher Block Chaining (CBC) Mode. +This mode is not [authenticated](https://en.wikipedia.org/wiki/Authenticated_encryption) and does not provide any +guarantees about the authenticity of the data. +For a more secure alternative, users should prefer `Encryptors.stronger`. + +### TextEncryptor + +Use the Encryptors.text factory method to construct a standard TextEncryptor: + +Example 3. TextEncryptor + +Java + +``` +Encryptors.text("password", "salt"); +``` + +Kotlin + +``` +Encryptors.text("password", "salt") +``` + +A TextEncryptor uses a standard BytesEncryptor to encrypt text data. +Encrypted results are returned as hex-encoded strings for easy storage on the filesystem or in the database. + +Use the Encryptors.queryableText factory method to construct a "queryable" TextEncryptor: + +Example 4. Queryable TextEncryptor + +Java + +``` +Encryptors.queryableText("password", "salt"); +``` + +Kotlin + +``` +Encryptors.queryableText("password", "salt") +``` + +The difference between a queryable TextEncryptor and a standard TextEncryptor has to do with initialization vector (iv) handling. +The iv used in a queryable TextEncryptor#encrypt operation is shared, or constant, and is not randomly generated. +This means the same text encrypted multiple times will always produce the same encryption result. +This is less secure, but necessary for encrypted data that needs to be queried against. +An example of queryable encrypted text would be an OAuth apiKey. + +## Key Generators + +The KeyGenerators class provides a number of convenience factory methods for constructing different types of key generators. +Using this class, you can create a BytesKeyGenerator to generate byte[] keys. +You can also construct a StringKeyGenerator to generate string keys. +KeyGenerators are thread-safe. + +### BytesKeyGenerator + +Use the KeyGenerators.secureRandom factory methods to generate a BytesKeyGenerator backed by a SecureRandom instance: + +Example 5. BytesKeyGenerator + +Java + +``` +BytesKeyGenerator generator = KeyGenerators.secureRandom(); +byte[] key = generator.generateKey(); +``` + +Kotlin + +``` +val generator = KeyGenerators.secureRandom() +val key = generator.generateKey() +``` + +The default key length is 8 bytes. +There is also a KeyGenerators.secureRandom variant that provides control over the key length: + +Example 6. KeyGenerators.secureRandom + +Java + +``` +KeyGenerators.secureRandom(16); +``` + +Kotlin + +``` +KeyGenerators.secureRandom(16) +``` + +Use the KeyGenerators.shared factory method to construct a BytesKeyGenerator that always returns the same key on every invocation: + +Example 7. KeyGenerators.shared + +Java + +``` +KeyGenerators.shared(16); +``` + +Kotlin + +``` +KeyGenerators.shared(16) +``` + +### StringKeyGenerator + +Use the KeyGenerators.string factory method to construct a 8-byte, SecureRandom KeyGenerator that hex-encodes each key as a String: + +Example 8. StringKeyGenerator + +Java + +``` +KeyGenerators.string(); +``` + +Kotlin + +``` +KeyGenerators.string() +``` + +## Password Encoding + +The password package of the spring-security-crypto module provides support for encoding passwords.`PasswordEncoder` is the central service interface and has the following signature: + +``` +public interface PasswordEncoder { + +String encode(String rawPassword); + +boolean matches(String rawPassword, String encodedPassword); +} +``` + +The matches method returns true if the rawPassword, once encoded, equals the encodedPassword. +This method is designed to support password-based authentication schemes. + +The `BCryptPasswordEncoder` implementation uses the widely supported "bcrypt" algorithm to hash the passwords. +Bcrypt uses a random 16 byte salt value and is a deliberately slow algorithm, in order to hinder password crackers. +The amount of work it does can be tuned using the "strength" parameter which takes values from 4 to 31. +The higher the value, the more work has to be done to calculate the hash. +The default value is 10. +You can change this value in your deployed system without affecting existing passwords, as the value is also stored in the encoded hash. + +Example 9. BCryptPasswordEncoder + +Java + +``` +// Create an encoder with strength 16 +BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +``` + +Kotlin + +``` +// Create an encoder with strength 16 +val encoder = BCryptPasswordEncoder(16) +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +``` + +The `Pbkdf2PasswordEncoder` implementation uses PBKDF2 algorithm to hash the passwords. +In order to defeat password cracking PBKDF2 is a deliberately slow algorithm and should be tuned to take about .5 seconds to verify a password on your system. + +Example 10. Pbkdf2PasswordEncoder + +Java + +``` +// Create an encoder with all the defaults +Pbkdf2PasswordEncoder encoder = new Pbkdf2PasswordEncoder(); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +``` + +Kotlin + +``` +// Create an encoder with all the defaults +val encoder = Pbkdf2PasswordEncoder() +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +``` \ No newline at end of file diff --git a/docs/en/spring-security/features-integrations-data.md b/docs/en/spring-security/features-integrations-data.md new file mode 100644 index 0000000000000000000000000000000000000000..8d601724c9cea81ce731c8bde8413bfcf715b550 --- /dev/null +++ b/docs/en/spring-security/features-integrations-data.md @@ -0,0 +1,62 @@ +# Spring Data Integration + +Spring Security provides Spring Data integration that allows referring to the current user within your queries. +It is not only useful but necessary to include the user in the queries to support paged results since filtering the results afterwards would not scale. + +## Spring Data & Spring Security Configuration + +To use this support, add `org.springframework.security:spring-security-data` dependency and provide a bean of type `SecurityEvaluationContextExtension`. +In Java Configuration, this would look like: + +Java + +``` +@Bean +public SecurityEvaluationContextExtension securityEvaluationContextExtension() { + return new SecurityEvaluationContextExtension(); +} +``` + +Kotlin + +``` +@Bean +fun securityEvaluationContextExtension(): SecurityEvaluationContextExtension { + return SecurityEvaluationContextExtension() +} +``` + +In XML Configuration, this would look like: + +``` + +``` + +## Security Expressions within @Query + +Now Spring Security can be used within your queries. +For example: + +Java + +``` +@Repository +public interface MessageRepository extends PagingAndSortingRepository { + @Query("select m from Message m where m.to.id = ?#{ principal?.id }") + Page findInbox(Pageable pageable); +} +``` + +Kotlin + +``` +@Repository +interface MessageRepository : PagingAndSortingRepository { + @Query("select m from Message m where m.to.id = ?#{ principal?.id }") + fun findInbox(pageable: Pageable?): Page? +} +``` + +This checks to see if the `Authentication.getPrincipal().getId()` is equal to the recipient of the `Message`. +Note that this example assumes you have customized the principal to be an Object that has an id property. +By exposing the `SecurityEvaluationContextExtension` bean, all of the [Common Security Expressions](../../servlet/authorization/expression-based.html#common-expressions) are available within the Query. \ No newline at end of file diff --git a/docs/en/spring-security/features-integrations-jackson.md b/docs/en/spring-security/features-integrations-jackson.md new file mode 100644 index 0000000000000000000000000000000000000000..f00c8bd015ad3d47fac5926dd99e8bb30abe1ada --- /dev/null +++ b/docs/en/spring-security/features-integrations-jackson.md @@ -0,0 +1,37 @@ +# Jackson Support + +Spring Security provides Jackson support for persisting Spring Security related classes. +This can improve the performance of serializing Spring Security related classes when working with distributed sessions (i.e. session replication, Spring Session, etc). + +To use it, register the `SecurityJackson2Modules.getModules(ClassLoader)` with `ObjectMapper` ([jackson-databind](https://github.com/FasterXML/jackson-databind)): + +Java + +``` +ObjectMapper mapper = new ObjectMapper(); +ClassLoader loader = getClass().getClassLoader(); +List modules = SecurityJackson2Modules.getModules(loader); +mapper.registerModules(modules); + +// ... use ObjectMapper as normally ... +SecurityContext context = new SecurityContextImpl(); +// ... +String json = mapper.writeValueAsString(context); +``` + +Kotlin + +``` +val mapper = ObjectMapper() +val loader = javaClass.classLoader +val modules: MutableList = SecurityJackson2Modules.getModules(loader) +mapper.registerModules(modules) + +// ... use ObjectMapper as normally ... +val context: SecurityContext = SecurityContextImpl() +// ... +val json: String = mapper.writeValueAsString(context) +``` + +| |The following Spring Security modules provide Jackson support:

* spring-security-core (`CoreJackson2Module`)

* spring-security-web (`WebJackson2Module`, `WebServletJackson2Module`, `WebServerJackson2Module`)

* [ spring-security-oauth2-client](../../servlet/oauth2/client/index.html#oauth2client) (`OAuth2ClientJackson2Module`)

* spring-security-cas (`CasJackson2Module`)| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| \ No newline at end of file diff --git a/docs/en/spring-security/features-integrations-localization.md b/docs/en/spring-security/features-integrations-localization.md new file mode 100644 index 0000000000000000000000000000000000000000..604919a4872f5abdafc701267a6b40ae8e15397f --- /dev/null +++ b/docs/en/spring-security/features-integrations-localization.md @@ -0,0 +1,33 @@ +# Localization + +If you need to support other locales, everything you need to know is contained in this section. + +All exception messages can be localized, including messages related to authentication failures and access being denied (authorization failures). +Exceptions and logging messages that are focused on developers or system deplopers (including incorrect attributes, interface contract violations, using incorrect constructors, startup time validation, debug-level logging) are not localized and instead are hard-coded in English within Spring Security’s code. + +Shipping in the `spring-security-core-xx.jar` you will find an `org.springframework.security` package that in turn contains a `messages.properties` file, as well as localized versions for some common languages. +This should be referred to by your `ApplicationContext`, as Spring Security classes implement Spring’s `MessageSourceAware` interface and expect the message resolver to be dependency injected at application context startup time. +Usually all you need to do is register a bean inside your application context to refer to the messages. +An example is shown below: + +``` + + + +``` + +The `messages.properties` is named in accordance with standard resource bundles and represents the default language supported by Spring Security messages. +This default file is in English. + +If you wish to customize the `messages.properties` file, or support other languages, you should copy the file, rename it accordingly, and register it inside the above bean definition. +There are not a large number of message keys inside this file, so localization should not be considered a major initiative. +If you do perform localization of this file, please consider sharing your work with the community by logging a JIRA task and attaching your appropriately-named localized version of `messages.properties`. + +Spring Security relies on Spring’s localization support in order to actually lookup the appropriate message. +In order for this to work, you have to make sure that the locale from the incoming request is stored in Spring’s `org.springframework.context.i18n.LocaleContextHolder`. +Spring MVC’s `DispatcherServlet` does this for your application automatically, but since Spring Security’s filters are invoked before this, the `LocaleContextHolder` needs to be set up to contain the correct `Locale` before the filters are called. +You can either do this in a filter yourself (which must come before the Spring Security filters in `web.xml`) or you can use Spring’s `RequestContextFilter`. +Please refer to the Spring Framework documentation for further details on using localization with Spring. + +The "contacts" sample application is set up to use localized messages. \ No newline at end of file diff --git a/docs/en/spring-security/features-integrations.md b/docs/en/spring-security/features-integrations.md new file mode 100644 index 0000000000000000000000000000000000000000..0b6e2373499ede87ced51fed14c57b67a111e950 --- /dev/null +++ b/docs/en/spring-security/features-integrations.md @@ -0,0 +1,13 @@ +# Integrations + +Spring Security provides integrations with numerous frameworks and APIs. +In this section, we discuss generic integrations that are not specific to Servlet or Reactive environments. +To see specific integrations, refer to the [Servlet](../../servlet/integrations/index.html) and [Reactive](../../servlet/integrations/index.html) Integrations sections. + +## Section Summary + +* [Cryptography](cryptography.html) +* [Spring Data](data.html) +* [Java’s Concurrency APIs](concurrency.html) +* [Jackson](jackson.html) +* [Localization](localization.html) \ No newline at end of file diff --git a/docs/en/spring-security/features.md b/docs/en/spring-security/features.md new file mode 100644 index 0000000000000000000000000000000000000000..b3036348a875755471742b6d5948dcb8720c35dd --- /dev/null +++ b/docs/en/spring-security/features.md @@ -0,0 +1,12 @@ +# Features + +Spring Security provides comprehensive support for [authentication](authentication/index.html), [authorization](authorization/index.html), and protection against [common exploits](exploits/index.html#exploits). +It also provides integration with other libraries to simplify its usage. + +## Section Summary + +* [Authentication](authentication/index.html) +* [Protection Against Exploits](exploits/index.html) +* [Integrations](integrations/index.html) + +[Getting Spring Security](../getting-spring-security.html)[Authentication](authentication/index.html) \ No newline at end of file diff --git a/docs/en/spring-security/getting-spring-security.md b/docs/en/spring-security/getting-spring-security.md new file mode 100644 index 0000000000000000000000000000000000000000..ec6351c142f1cb06d0744818cbc82093eb0a844e --- /dev/null +++ b/docs/en/spring-security/getting-spring-security.md @@ -0,0 +1,293 @@ +# Getting Spring Security + +This section discusses all you need to know about getting the Spring Security binaries. +See [Source Code](community.html#community-source) for how to obtain the source code. + +## Release Numbering + +Spring Security versions are formatted as MAJOR.MINOR.PATCH such that: + +* MAJOR versions may contain breaking changes. + Typically, these are done to provide improved security to match modern security practices. + +* MINOR versions contain enhancements but are considered passive updates + +* PATCH level should be perfectly compatible, forwards and backwards, with the possible exception of changes that fix bugs. + +## Usage with Maven + +As most open source projects, Spring Security deploys its dependencies as Maven artifacts. +The topics in this section provide detail on how to consume Spring Security when using Maven. + +### Spring Boot with Maven + +Spring Boot provides a `spring-boot-starter-security` starter that aggregates Spring Security-related dependencies together. +The simplest and preferred way to use the starter is to use [Spring Initializr](https://docs.spring.io/initializr/docs/current/reference/html/) by using an IDE integration ([Eclipse](https://joshlong.com/jl/blogPost/tech_tip_geting_started_with_spring_boot.html), [IntelliJ](https://www.jetbrains.com/help/idea/spring-boot.html#d1489567e2), [NetBeans](https://github.com/AlexFalappa/nb-springboot/wiki/Quick-Tour)) or through [https://start.spring.io](https://start.spring.io). + +Alternatively, you can manually add the starter, as the following example shows: + +Example 1. pom.xml + +``` + + + + org.springframework.boot + spring-boot-starter-security + + +``` + +Since Spring Boot provides a Maven BOM to manage dependency versions, you do not need to specify a version. +If you wish to override the Spring Security version, you may do so by providing a Maven property, as the following example shows: + +Example 2. pom.xml + +``` + + + 5.6.2 + +``` + +Since Spring Security makes breaking changes only in major releases, it is safe to use a newer version of Spring Security with Spring Boot. +However, at times, you may need to update the version of Spring Framework as well. +You can do so by adding a Maven property, as the following example shows: + +Example 3. pom.xml + +``` + + + 5.3.16 + +``` + +If you use additional features (such as LDAP, OpenID, and others), you need to also include the appropriate [Project Modules and Dependencies](modules.html#modules). + +### Maven Without Spring Boot + +When you use Spring Security without Spring Boot, the preferred way is to use Spring Security’s BOM to ensure a consistent version of Spring Security is used throughout the entire project. The following example shows how to do so: + +Example 4. pom.xml + +``` + + + + + org.springframework.security + spring-security-bom + {spring-security-version} + pom + import + + + +``` + +A minimal Spring Security Maven set of dependencies typically looks like the following: + +Example 5. pom.xml + +``` + + + + org.springframework.security + spring-security-web + + + org.springframework.security + spring-security-config + + +``` + +If you use additional features (such as LDAP, OpenID, and others), you need to also include the appropriate [Project Modules and Dependencies](modules.html#modules). + +Spring Security builds against Spring Framework 5.3.16 but should generally work with any newer version of Spring Framework 5.x. +Many users are likely to run afoul of the fact that Spring Security’s transitive dependencies resolve Spring Framework 5.3.16, which can cause strange classpath problems. +The easiest way to resolve this is to use the `spring-framework-bom` within the `` section of your `pom.xml` as the following example shows: + +Example 6. pom.xml + +``` + + + + + org.springframework + spring-framework-bom + 5.3.16 + pom + import + + + +``` + +The preceding example ensures that all the transitive dependencies of Spring Security use the Spring 5.3.16 modules. + +| |This approach uses Maven’s “bill of materials” (BOM) concept and is only available in Maven 2.0.9+.
For additional details about how dependencies are resolved, see [Maven’s Introduction to the Dependency Mechanism documentation](https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html).| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Maven Repositories + +All GA releases (that is, versions ending in .RELEASE) are deployed to Maven Central, so no additional Maven repositories need to be declared in your pom. + +If you use a SNAPSHOT version, you need to ensure that you have the Spring Snapshot repository defined, as the following example shows: + +Example 7. pom.xml + +``` + + + + spring-snapshot + Spring Snapshot Repository + https://repo.spring.io/snapshot + + +``` + +If you use a milestone or release candidate version, you need to ensure that you have the Spring Milestone repository defined, as the following example shows: + +Example 8. pom.xml + +``` + + + + spring-milestone + Spring Milestone Repository + https://repo.spring.io/milestone + + +``` + +## Gradle + +As most open source projects, Spring Security deploys its dependencies as Maven artifacts, which allows for first-class Gradle support. +The following topics provide detail on how to consume Spring Security when using Gradle. + +### Spring Boot with Gradle + +Spring Boot provides a `spring-boot-starter-security` starter that aggregates Spring Security related dependencies together. +The simplest and preferred method to use the starter is to use [Spring Initializr](https://docs.spring.io/initializr/docs/current/reference/html/) by using an IDE integration ([Eclipse](https://joshlong.com/jl/blogPost/tech_tip_geting_started_with_spring_boot.html), [IntelliJ](https://www.jetbrains.com/help/idea/spring-boot.html#d1489567e2), [NetBeans](https://github.com/AlexFalappa/nb-springboot/wiki/Quick-Tour)) or through [https://start.spring.io](https://start.spring.io). + +Alternatively, you can manually add the starter, as the following example shows: + +Example 9. build.gradle + +``` +dependencies { + compile "org.springframework.boot:spring-boot-starter-security" +} +``` + +Since Spring Boot provides a Maven BOM to manage dependency versions, you need not specify a version. +If you wish to override the Spring Security version, you may do so by providing a Gradle property, as the following example shows: + +Example 10. build.gradle + +``` +ext['spring-security.version']='5.6.2' +``` + +Since Spring Security makes breaking changes only in major releases, it is safe to use a newer version of Spring Security with Spring Boot. +However, at times, you may need to update the version of Spring Framework as well. +You can do so by adding a Gradle property, as the following example shows: + +Example 11. build.gradle + +``` +ext['spring.version']='5.3.16' +``` + +If you use additional features (such as LDAP, OpenID, and others), you need to also include the appropriate [Project Modules and Dependencies](modules.html#modules). + +### Gradle Without Spring Boot + +When you use Spring Security without Spring Boot, the preferred way is to use Spring Security’s BOM to ensure a consistent version of Spring Security is used throughout the entire project. +You can do so by using the [Dependency Management Plugin](https://github.com/spring-gradle-plugins/dependency-management-plugin), as the following example shows: + +Example 12. build.gradle + +``` +plugins { + id "io.spring.dependency-management" version "1.0.6.RELEASE" +} + +dependencyManagement { + imports { + mavenBom 'org.springframework.security:spring-security-bom:5.6.2' + } +} +``` + +A minimal Spring Security Maven set of dependencies typically looks like the following: + +Example 13. build.gradle + +``` +dependencies { + compile "org.springframework.security:spring-security-web" + compile "org.springframework.security:spring-security-config" +} +``` + +If you use additional features (such as LDAP, OpenID, and others), you need to also include the appropriate [Project Modules and Dependencies](modules.html#modules). + +Spring Security builds against Spring Framework 5.3.16 but should generally work with any newer version of Spring Framework 5.x. +Many users are likely to run afoul of the fact that Spring Security’s transitive dependencies resolve Spring Framework 5.3.16, which can cause strange classpath problems. +The easiest way to resolve this is to use the `spring-framework-bom` within your `` section of your `pom.xml`. +You can do so by using the [Dependency Management Plugin](https://github.com/spring-gradle-plugins/dependency-management-plugin), as the following example shows: + +Example 14. build.gradle + +``` +plugins { + id "io.spring.dependency-management" version "1.0.6.RELEASE" +} + +dependencyManagement { + imports { + mavenBom 'org.springframework:spring-framework-bom:5.3.16' + } +} +``` + +The preceding example ensures that all the transitive dependencies of Spring Security use the Spring 5.3.16 modules. + +### Gradle Repositories + +All GA releases (that is, versions ending in .RELEASE) are deployed to Maven Central, so using the mavenCentral() repository is sufficient for GA releases. The following example shows how to do so: + +Example 15. build.gradle + +``` +repositories { + mavenCentral() +} +``` + +If you use a SNAPSHOT version, you need to ensure you have the Spring Snapshot repository defined, as the following example shows: + +Example 16. build.gradle + +``` +repositories { + maven { url 'https://repo.spring.io/snapshot' } +} +``` + +If you use a milestone or release candidate version, you need to ensure that you have the Spring Milestone repository defined, as the following example shows: + +Example 17. build.gradle + +``` +repositories { + maven { url 'https://repo.spring.io/milestone' } +} +``` \ No newline at end of file diff --git a/docs/en/spring-security/modules.md b/docs/en/spring-security/modules.md new file mode 100644 index 0000000000000000000000000000000000000000..93ec2e72f69720a7c22b451d88115a6756dcc980 --- /dev/null +++ b/docs/en/spring-security/modules.md @@ -0,0 +1,197 @@ +# Project Modules and Dependencies + +Even if you do not use Maven, we recommend that you consult the `pom.xml` files to get an idea of third-party dependencies and versions. +Another good idea is to examine the libraries that are included in the sample applications. + +This section provides a reference of the modules in Spring Security and the additional dependencies that they require in order to function in a running application. +We don’t include dependencies that are only used when building or testing Spring Security itself. +Nor do we include transitive dependencies which are required by external dependencies. + +The version of Spring required is listed on the project website, so the specific versions are omitted for Spring dependencies below. +Note that some of the dependencies listed as "optional" below may still be required for other non-security functionality in a Spring application. +Also dependencies listed as "optional" may not actually be marked as such in the project’s Maven POM files if they are used in most applications. +They are "optional" only in the sense that you don’t need them unless you are using the specified functionality. + +Where a module depends on another Spring Security module, the non-optional dependencies of the module it depends on are also assumed to be required and are not listed separately. + +## Core — `spring-security-core.jar` + +This module contains core authentication and access-contol classes and interfaces, remoting support, and basic provisioning APIs. +It is required by any application that uses Spring Security. +It supports standalone applications, remote clients, method (service layer) security, and JDBC user provisioning. +It contains the following top-level packages: + +* `org.springframework.security.core` + +* `org.springframework.security.access` + +* `org.springframework.security.authentication` + +* `org.springframework.security.provisioning` + +| Dependency |Version| Description | +|-----------------|-------|---------------------------------------------------------------------------| +| ehcache | 1.6.2 |Required if the Ehcache-based user cache implementation is used (optional).| +| spring-aop | | Method security is based on Spring AOP | +| spring-beans | | Required for Spring configuration | +|spring-expression| | Required for expression-based method security (optional) | +| spring-jdbc | | Required if using a database to store user data (optional). | +| spring-tx | | Required if using a database to store user data (optional). | +| aspectjrt |1.6.10 | Required if using AspectJ support (optional). | +| jsr250-api | 1.0 | Required if you are using JSR-250 method-security annotations (optional). | + +## Remoting — `spring-security-remoting.jar` + +This module provides integration with Spring Remoting. +You do not need this unless you are writing a remote client that uses Spring Remoting. +The main package is `org.springframework.security.remoting`. + +| Dependency |Version| Description | +|--------------------|-------|-----------------------------------------------------| +|spring-security-core| | | +| spring-web | |Required for clients which use HTTP remoting support.| + +## Web — `spring-security-web.jar` + +This module contains filters and related web-security infrastructure code. +It contains anything with a servlet API dependency. +You need it if you require Spring Security web authentication services and URL-based access-control. +The main package is `org.springframework.security.web`. + +| Dependency |Version| Description | +|--------------------|-------|-------------------------------------------------------------------------------| +|spring-security-core| | | +| spring-web | | Spring web support classes are used extensively. | +| spring-jdbc | | Required for JDBC-based persistent remember-me token repository (optional). | +| spring-tx | |Required by remember-me persistent token repository implementations (optional).| + +## Config — `spring-security-config.jar` + +This module contains the security namespace parsing code and Java configuration code. +You need it if you use the Spring Security XML namespace for configuration or Spring Security’s Java Configuration support. +The main package is `org.springframework.security.config`. +None of the classes are intended for direct use in an application. + +| Dependency |Version| Description | +|----------------------|-------|-----------------------------------------------------------------------------| +| spring-security-core | | | +| spring-security-web | |Required if you are using any web-related namespace configuration (optional).| +| spring-security-ldap | | Required if you are using the LDAP namespace options (optional). | +|spring-security-openid| | Required if you are using OpenID authentication (optional). | +| aspectjweaver |1.6.10 | Required if using the protect-pointcut namespace syntax (optional). | + +## LDAP — `spring-security-ldap.jar` + +This module provides LDAP authentication and provisioning code. +It is required if you need to use LDAP authentication or manage LDAP user entries. +The top-level package is `org.springframework.security.ldap`. + +| Dependency |Version| Description | +|-----------------------------------------------------------------------------------------------------------------------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------| +| spring-security-core | | | +| spring-ldap-core | 1.3.0 | LDAP support is based on Spring LDAP. | +| spring-tx | | Data exception classes are required. | +|apache-ds [1]| 1.5.5 | Required if you are using an embedded LDAP server (optional). | +| shared-ldap |0.9.15 | Required if you are using an embedded LDAP server (optional). | +| ldapsdk | 4.1 |Mozilla LdapSDK.
Used for decoding LDAP password policy controls if you are using password-policy functionality with OpenLDAP, for example.| + +## OAuth 2.0 Core — `spring-security-oauth2-core.jar` + +`spring-security-oauth2-core.jar` contains core classes and interfaces that provide support for the OAuth 2.0 Authorization Framework and for OpenID Connect Core 1.0. +It is required by applications that use OAuth 2.0 or OpenID Connect Core 1.0, such as client, resource server, and authorization server. +The top-level package is `org.springframework.security.oauth2.core`. + +## OAuth 2.0 Client — `spring-security-oauth2-client.jar` + +`spring-security-oauth2-client.jar` contains Spring Security’s client support for OAuth 2.0 Authorization Framework and OpenID Connect Core 1.0. +It is required by applications that use OAuth 2.0 Login or OAuth Client support. +The top-level package is `org.springframework.security.oauth2.client`. + +## OAuth 2.0 JOSE — `spring-security-oauth2-jose.jar` + +`spring-security-oauth2-jose.jar` contains Spring Security’s support for the JOSE (Javascript Object Signing and Encryption) framework. +The JOSE framework is intended to provide a method to securely transfer claims between parties. +It is built from a collection of specifications: + +* JSON Web Token (JWT) + +* JSON Web Signature (JWS) + +* JSON Web Encryption (JWE) + +* JSON Web Key (JWK) + +It contains the following top-level packages: + +* `org.springframework.security.oauth2.jwt` + +* `org.springframework.security.oauth2.jose` + +## OAuth 2.0 Resource Server — `spring-security-oauth2-resource-server.jar` + +`spring-security-oauth2-resource-server.jar` contains Spring Security’s support for OAuth 2.0 Resource Servers. +It is used to protect APIs via OAuth 2.0 Bearer Tokens. +The top-level package is `org.springframework.security.oauth2.server.resource`. + +## ACL — `spring-security-acl.jar` + +This module contains a specialized domain object ACL implementation. +It is used to apply security to specific domain object instances within your application. +The top-level package is `org.springframework.security.acls`. + +| Dependency |Version| Description | +|--------------------|-------|-------------------------------------------------------------------------------------------------------------------| +|spring-security-core| | | +| ehcache | 1.6.2 |Required if the Ehcache-based ACL cache implementation is used (optional if you are using your own implementation).| +| spring-jdbc | | Required if you are using the default JDBC-based AclService (optional if you implement your own). | +| spring-tx | | Required if you are using the default JDBC-based AclService (optional if you implement your own). | + +## CAS — `spring-security-cas.jar` + +This module contains Spring Security’s CAS client integration. +You should use it if you want to use Spring Security web authentication with a CAS single sign-on server. +The top-level package is `org.springframework.security.cas`. + +| Dependency |Version| Description | +|--------------------|-------|--------------------------------------------------------------------------------| +|spring-security-core| | | +|spring-security-web | | | +| cas-client-core |3.1.12 |The JA-SIG CAS Client.
This is the basis of the Spring Security integration.| +| ehcache | 1.6.2 | Required if you are using the Ehcache-based ticket cache (optional). | + +## OpenID — `spring-security-openid.jar` + +| |The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------| + +This module contains OpenID web authentication support. +It is used to authenticate users against an external OpenID server. +The top-level package is `org.springframework.security.openid`. +It requires OpenID4Java. + +| Dependency |Version| Description | +|--------------------|-------|------------------------------------------------------| +|spring-security-core| | | +|spring-security-web | | | +| openid4java-nodeps | 0.9.6 |Spring Security’s OpenID integration uses OpenID4Java.| +| httpclient | 4.1.1 | openid4java-nodeps depends on HttpClient 4. | +| guice | 2.0 | openid4java-nodeps depends on Guice 2. | + +## Test — `spring-security-test.jar` + +This module contains support for testing with Spring Security. + +## Taglibs — `spring-secuity-taglibs.jar` + +Provides Spring Security’s JSP tag implementations. + +| Dependency |Version| Description | +|--------------------|-------|------------------------------------------------------------------------------------------------------------| +|spring-security-core| | | +|spring-security-web | | | +|spring-security-acl | |Required if you are using the `accesscontrollist` tag or `hasPermission()` expressions with ACLs (optional).| +| spring-expression | | Required if you are using SPEL expressions in your tag access constraints. | + +--- + +[1](#_footnoteref_1). The modules `apacheds-core`, `apacheds-core-entry`, `apacheds-protocol-shared`, `apacheds-protocol-ldap` and `apacheds-server-jndi` are required. \ No newline at end of file diff --git a/docs/en/spring-security/overview.md b/docs/en/spring-security/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..f6b8663b7261c82f86f93764c672cb1834a5c667 --- /dev/null +++ b/docs/en/spring-security/overview.md @@ -0,0 +1,14 @@ +# Spring Security + +Spring Security is a framework that provides [authentication](features/authentication/index.html), [authorization](features/authorization/index.html), and [protection against common attacks](features/exploits/index.html). +With first class support for securing both [imperative](servlet/index.html) and [reactive](reactive/index.html) applications, it is the de-facto standard for securing Spring-based applications. + +For a complete list of features, see the [Features](features/index.html) section of the reference. + +## Getting Started + +If you are ready to start securing an application see the Getting Started sections for [servlet](servlet/getting-started.html) and [reactive](reactive/getting-started.html). These sections will walk you through creating your first Spring Security applications. + +If you want to understand how Spring Security works, you can refer to the [Architecture](servlet/architecture.html) section. + +If you have any questions, there is a wonderful [community](community.html) that would love to help you! \ No newline at end of file diff --git a/docs/en/spring-security/prerequisites.md b/docs/en/spring-security/prerequisites.md new file mode 100644 index 0000000000000000000000000000000000000000..f293461286284529ce42a280e754b9d18d08e8fc --- /dev/null +++ b/docs/en/spring-security/prerequisites.md @@ -0,0 +1,11 @@ +# Prerequisites + +Spring Security requires a Java 8 or higher Runtime Environment. + +As Spring Security aims to operate in a self-contained manner, you do not need to place any special configuration files in your Java Runtime Environment. +In particular, you need not configure a special Java Authentication and Authorization Service (JAAS) policy file or place Spring Security into common classpath locations. + +Similarly, if you use an EJB Container or Servlet Container, you need not put any special configuration files anywhere nor include Spring Security in a server classloader. +All the required files are contained within your application. + +This design offers maximum deployment time flexibility, as you can copy your target artifact (be it a JAR, WAR, or EAR) from one system to another and it immediately works. \ No newline at end of file diff --git a/docs/en/spring-security/reactive-authentication-logout.md b/docs/en/spring-security/reactive-authentication-logout.md new file mode 100644 index 0000000000000000000000000000000000000000..2dbac4156dbdb14ae4cc15a1d12f99d6d5260c7b --- /dev/null +++ b/docs/en/spring-security/reactive-authentication-logout.md @@ -0,0 +1,27 @@ +# Logout + +Spring Security provides a logout endpoint by default. +Once logged in, you can `GET /logout` to see a default logout confirmation page, or you can `POST /logout` to initiate logout. +This will: + +* clear the `ServerCsrfTokenRepository`, `ServerSecurityContextRepository`, and + +* redirect back to the login page + +Often, you will want to also invalidate the session on logout. +To achieve this, you can add the `WebSessionServerLogoutHandler` to your logout configuration, like so: + +``` +@Bean +SecurityWebFilterChain http(ServerHttpSecurity http) throws Exception { + DelegatingServerLogoutHandler logoutHandler = new DelegatingServerLogoutHandler( + new WebSessionServerLogoutHandler(), new SecurityContextServerLogoutHandler() + ); + + http + .authorizeExchange((exchange) -> exchange.anyExchange().authenticated()) + .logout((logout) -> logout.logoutHandler(logoutHandler)); + + return http.build(); +} +``` \ No newline at end of file diff --git a/docs/en/spring-security/reactive-authentication-x509.md b/docs/en/spring-security/reactive-authentication-x509.md new file mode 100644 index 0000000000000000000000000000000000000000..62be7bacfe9a6f1a26ec74764d8e5f149f1490e0 --- /dev/null +++ b/docs/en/spring-security/reactive-authentication-x509.md @@ -0,0 +1,91 @@ +# Reactive X.509 Authentication + +Similar to [Servlet X.509 authentication](../../servlet/authentication/x509.html#servlet-x509), reactive x509 authentication filter allows extracting an authentication token from a certificate provided by a client. + +Below is an example of a reactive x509 security configuration: + +Java + +``` +@Bean +public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .x509(withDefaults()) + .authorizeExchange(exchanges -> exchanges + .anyExchange().permitAll() + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + x509 { } + authorizeExchange { + authorize(anyExchange, authenticated) + } + } +} +``` + +In the configuration above, when neither `principalExtractor` nor `authenticationManager` is provided defaults will be used. The default principal extractor is `SubjectDnX509PrincipalExtractor` which extracts the CN (common name) field from a certificate provided by a client. The default authentication manager is `ReactivePreAuthenticatedAuthenticationManager` which performs user account validation, checking that user account with a name extracted by `principalExtractor` exists and it is not locked, disabled, or expired. + +The next example demonstrates how these defaults can be overridden. + +Java + +``` +@Bean +public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + SubjectDnX509PrincipalExtractor principalExtractor = + new SubjectDnX509PrincipalExtractor(); + + principalExtractor.setSubjectDnRegex("OU=(.*?)(?:,|$)"); + + ReactiveAuthenticationManager authenticationManager = authentication -> { + authentication.setAuthenticated("Trusted Org Unit".equals(authentication.getName())); + return Mono.just(authentication); + }; + + http + .x509(x509 -> x509 + .principalExtractor(principalExtractor) + .authenticationManager(authenticationManager) + ) + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? { + val customPrincipalExtractor = SubjectDnX509PrincipalExtractor() + customPrincipalExtractor.setSubjectDnRegex("OU=(.*?)(?:,|$)") + val customAuthenticationManager = ReactiveAuthenticationManager { authentication: Authentication -> + authentication.isAuthenticated = "Trusted Org Unit" == authentication.name + Mono.just(authentication) + } + return http { + x509 { + principalExtractor = customPrincipalExtractor + authenticationManager = customAuthenticationManager + } + authorizeExchange { + authorize(anyExchange, authenticated) + } + } +} +``` + +In this example, a username is extracted from the OU field of a client certificate instead of CN, and account lookup using `ReactiveUserDetailsService` is not performed at all. Instead, if the provided certificate issued to an OU named "Trusted Org Unit", a request will be authenticated. + +For an example of configuring Netty and `WebClient` or `curl` command-line tool to use mutual TLS and enable X.509 authentication, please refer to [https://github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration/authentication/x509](https://github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration/authentication/x509). \ No newline at end of file diff --git a/docs/en/spring-security/reactive-authorization-authorize-http-requests.md b/docs/en/spring-security/reactive-authorization-authorize-http-requests.md new file mode 100644 index 0000000000000000000000000000000000000000..7e2e68efcc102c6c811f1ba7d99425708ad4c3b8 --- /dev/null +++ b/docs/en/spring-security/reactive-authorization-authorize-http-requests.md @@ -0,0 +1,94 @@ +# Authorize ServerHttpRequest + +Spring Security provides support for authorizing the incoming HTTP requests. +By default, Spring Security’s authorization will require all requests to be authenticated. +The explicit configuration looks like: + +Example 1. All Requests Require Authenticated User + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .httpBasic(withDefaults()) + .formLogin(withDefaults()); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + formLogin { } + httpBasic { } + } +} +``` + +We can configure Spring Security to have different rules by adding more rules in order of precedence. + +Example 2. Multiple Authorize Requests Rules + +Java + +``` +import static org.springframework.security.authorization.AuthorityReactiveAuthorizationManager.hasRole; +// ... +@Bean +SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) { + // @formatter:off + http + // ... + .authorizeExchange((authorize) -> authorize (1) + .pathMatchers("/resources/**", "/signup", "/about").permitAll() (2) + .pathMatchers("/admin/**").hasRole("ADMIN") (3) + .pathMatchers("/db/**").access((authentication, context) -> (4) + hasRole("ADMIN").check(authentication, context) + .filter(decision -> !decision.isGranted()) + .switchIfEmpty(hasRole("DBA").check(authentication, context)) + ) + .anyExchange().denyAll() (5) + ); + // @formatter:on + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { (1) + authorize(pathMatchers("/resources/**", "/signup", "/about"), permitAll) (2) + authorize("/admin/**", hasRole("ADMIN")) (3) + authorize("/db/**", { authentication, context -> (4) + hasRole("ADMIN").check(authentication, context) + .filter({ decision -> !decision.isGranted() }) + .switchIfEmpty(hasRole("DBA").check(authentication, context)) + }) + authorize(anyExchange, denyAll) (5) + } + // ... + } +} +``` + +|**1**| There are multiple authorization rules specified.
Each rule is considered in the order they were declared. | +|-----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**| We specified multiple URL patterns that any user can access.
Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about". | +|**3**| Any URL that starts with "/admin/" will be restricted to users who have the authority "ROLE\_ADMIN".
You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE\_" prefix. | +|**4**|Any URL that starts with "/db/" requires the user to have both "ROLE\_ADMIN" and "ROLE\_DBA".
This demonstrates the flexibility of providing a custom `ReactiveAuthorizationManager` allowing us to implement arbitrary authorization logic.
For simplicity, the sample uses a lambda and delegate to the existing `AuthorityReactiveAuthorizationManager.hasRole` implementation.
However, in a real world situation applications would likely implement the logic in a proper class implementing `ReactiveAuthorizationManager`.| +|**5**| Any URL that has not already been matched on is denied access.
This is a good strategy if you do not want to accidentally forget to update your authorization rules. | \ No newline at end of file diff --git a/docs/en/spring-security/reactive-authorization-method.md b/docs/en/spring-security/reactive-authorization-method.md new file mode 100644 index 0000000000000000000000000000000000000000..6706218723ad5a38f143bd6b713cb6ee08a8d075 --- /dev/null +++ b/docs/en/spring-security/reactive-authorization-method.md @@ -0,0 +1,217 @@ +# EnableReactiveMethodSecurity + +Spring Security supports method security using [Reactor’s Context](https://projectreactor.io/docs/core/release/reference/#context) which is setup using `ReactiveSecurityContextHolder`. +For example, this demonstrates how to retrieve the currently logged in user’s message. + +| |For this to work the return type of the method must be a `org.reactivestreams.Publisher` (i.e. `Mono`/`Flux`) or the function must be a Kotlin coroutine function.
This is necessary to integrate with Reactor’s `Context`.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Java + +``` +Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER"); + +Mono messageByUsername = ReactiveSecurityContextHolder.getContext() + .map(SecurityContext::getAuthentication) + .map(Authentication::getName) + .flatMap(this::findMessageByUsername) + // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter` + .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)); + +StepVerifier.create(messageByUsername) + .expectNext("Hi user") + .verifyComplete(); +``` + +Kotlin + +``` +val authentication: Authentication = TestingAuthenticationToken("user", "password", "ROLE_USER") + +val messageByUsername: Mono = ReactiveSecurityContextHolder.getContext() + .map(SecurityContext::getAuthentication) + .map(Authentication::getName) + .flatMap(this::findMessageByUsername) // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter` + .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)) + +StepVerifier.create(messageByUsername) + .expectNext("Hi user") + .verifyComplete() +``` + +with `this::findMessageByUsername` defined as: + +Java + +``` +Mono findMessageByUsername(String username) { + return Mono.just("Hi " + username); +} +``` + +Kotlin + +``` +fun findMessageByUsername(username: String): Mono { + return Mono.just("Hi $username") +} +``` + +Below is a minimal method security configuration when using method security in reactive applications. + +Java + +``` +@EnableReactiveMethodSecurity +public class SecurityConfig { + @Bean + public MapReactiveUserDetailsService userDetailsService() { + User.UserBuilder userBuilder = User.withDefaultPasswordEncoder(); + UserDetails rob = userBuilder.username("rob") + .password("rob") + .roles("USER") + .build(); + UserDetails admin = userBuilder.username("admin") + .password("admin") + .roles("USER","ADMIN") + .build(); + return new MapReactiveUserDetailsService(rob, admin); + } +} +``` + +Kotlin + +``` +@EnableReactiveMethodSecurity +class SecurityConfig { + @Bean + fun userDetailsService(): MapReactiveUserDetailsService { + val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder() + val rob = userBuilder.username("rob") + .password("rob") + .roles("USER") + .build() + val admin = userBuilder.username("admin") + .password("admin") + .roles("USER", "ADMIN") + .build() + return MapReactiveUserDetailsService(rob, admin) + } +} +``` + +Consider the following class: + +Java + +``` +@Component +public class HelloWorldMessageService { + @PreAuthorize("hasRole('ADMIN')") + public Mono findMessage() { + return Mono.just("Hello World!"); + } +} +``` + +Kotlin + +``` +@Component +class HelloWorldMessageService { + @PreAuthorize("hasRole('ADMIN')") + fun findMessage(): Mono { + return Mono.just("Hello World!") + } +} +``` + +Or, the following class using Kotlin coroutines: + +Kotlin + +``` +@Component +class HelloWorldMessageService { + @PreAuthorize("hasRole('ADMIN')") + suspend fun findMessage(): String { + delay(10) + return "Hello World!" + } +} +``` + +Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` will ensure that `findByMessage` is only invoked by a user with the role `ADMIN`. +It is important to note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`. +However, at this time we only support return type of `Boolean` or `boolean` of the expression. +This means that the expression must not block. + +When integrating with [WebFlux Security](../configuration/webflux.html#jc-webflux), the Reactor Context is automatically established by Spring Security according to the authenticated user. + +Java + +``` +@EnableWebFluxSecurity +@EnableReactiveMethodSecurity +public class SecurityConfig { + + @Bean + SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception { + return http + // Demonstrate that method security works + // Best practice to use both for defense in depth + .authorizeExchange(exchanges -> exchanges + .anyExchange().permitAll() + ) + .httpBasic(withDefaults()) + .build(); + } + + @Bean + MapReactiveUserDetailsService userDetailsService() { + User.UserBuilder userBuilder = User.withDefaultPasswordEncoder(); + UserDetails rob = userBuilder.username("rob") + .password("rob") + .roles("USER") + .build(); + UserDetails admin = userBuilder.username("admin") + .password("admin") + .roles("USER","ADMIN") + .build(); + return new MapReactiveUserDetailsService(rob, admin); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +@EnableReactiveMethodSecurity +class SecurityConfig { + @Bean + open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, permitAll) + } + httpBasic { } + } + } + + @Bean + fun userDetailsService(): MapReactiveUserDetailsService { + val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder() + val rob = userBuilder.username("rob") + .password("rob") + .roles("USER") + .build() + val admin = userBuilder.username("admin") + .password("admin") + .roles("USER", "ADMIN") + .build() + return MapReactiveUserDetailsService(rob, admin) + } +} +``` \ No newline at end of file diff --git a/docs/en/spring-security/reactive-configuration-webflux.md b/docs/en/spring-security/reactive-configuration-webflux.md new file mode 100644 index 0000000000000000000000000000000000000000..77ef39ffb1cad458841ad9f3da05ae4bb818a204 --- /dev/null +++ b/docs/en/spring-security/reactive-configuration-webflux.md @@ -0,0 +1,221 @@ +# WebFlux Security + +Spring Security’s WebFlux support relies on a `WebFilter` and works the same for Spring WebFlux and Spring WebFlux.Fn. +You can find a few sample applications that demonstrate the code below: + +* Hello WebFlux [hellowebflux](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/reactive/webflux/java/hello-security) + +* Hello WebFlux.Fn [hellowebfluxfn](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/reactive/webflux-fn/hello-security) + +* Hello WebFlux Method [hellowebflux-method](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/reactive/webflux/java/method) + +## Minimal WebFlux Security Configuration + +You can find a minimal WebFlux Security configuration below: + +Example 1. Minimal WebFlux Security Configuration + +Java + +``` +@EnableWebFluxSecurity +public class HelloWebfluxSecurityConfig { + + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User.withDefaultPasswordEncoder() + .username("user") + .password("user") + .roles("USER") + .build(); + return new MapReactiveUserDetailsService(user); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class HelloWebfluxSecurityConfig { + + @Bean + fun userDetailsService(): ReactiveUserDetailsService { + val userDetails = User.withDefaultPasswordEncoder() + .username("user") + .password("user") + .roles("USER") + .build() + return MapReactiveUserDetailsService(userDetails) + } +} +``` + +This configuration provides form and http basic authentication, sets up authorization to require an authenticated user for accessing any page, sets up a default log in page and a default log out page, sets up security related HTTP headers, CSRF protection, and more. + +## Explicit WebFlux Security Configuration + +You can find an explicit version of the minimal WebFlux Security configuration below: + +Example 2. Explicit WebFlux Security Configuration + +Java + +``` +@Configuration +@EnableWebFluxSecurity +public class HelloWebfluxSecurityConfig { + + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User.withDefaultPasswordEncoder() + .username("user") + .password("user") + .roles("USER") + .build(); + return new MapReactiveUserDetailsService(user); + } + + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .httpBasic(withDefaults()) + .formLogin(withDefaults()); + return http.build(); + } +} +``` + +Kotlin + +``` +@Configuration +@EnableWebFluxSecurity +class HelloWebfluxSecurityConfig { + + @Bean + fun userDetailsService(): ReactiveUserDetailsService { + val userDetails = User.withDefaultPasswordEncoder() + .username("user") + .password("user") + .roles("USER") + .build() + return MapReactiveUserDetailsService(userDetails) + } + + @Bean + fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + formLogin { } + httpBasic { } + } + } +} +``` + +This configuration explicitly sets up all the same things as our minimal configuration. +From here you can easily make the changes to the defaults. + +You can find more examples of explicit configuration in unit tests, by searching [EnableWebFluxSecurity in the `config/src/test/` directory](https://github.com/spring-projects/spring-security/search?q=path%3Aconfig%2Fsrc%2Ftest%2F+EnableWebFluxSecurity). + +### Multiple Chains Support + +You can configure multiple `SecurityWebFilterChain` instances to separate configuration by `RequestMatcher`s. + +For example, you can isolate configuration for URLs that start with `/api`, like so: + +Java + +``` +@Configuration +@EnableWebFluxSecurity +static class MultiSecurityHttpConfig { + + @Order(Ordered.HIGHEST_PRECEDENCE) (1) + @Bean + SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) { + http + .securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")) (2) + .authorizeExchange((exchanges) -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt); (3) + return http.build(); + } + + @Bean + SecurityWebFilterChain webHttpSecurity(ServerHttpSecurity http) { (4) + http + .authorizeExchange((exchanges) -> exchanges + .anyExchange().authenticated() + ) + .httpBasic(withDefaults()); (5) + return http.build(); + } + + @Bean + ReactiveUserDetailsService userDetailsService() { + return new MapReactiveUserDetailsService( + PasswordEncodedUser.user(), PasswordEncodedUser.admin()); + } + +} +``` + +Kotlin + +``` +@Configuration +@EnableWebFluxSecurity +open class MultiSecurityHttpConfig { + @Order(Ordered.HIGHEST_PRECEDENCE) (1) + @Bean + open fun apiHttpSecurity(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + securityMatcher(PathPatternParserServerWebExchangeMatcher("/api/**")) (2) + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + jwt { } (3) + } + } + } + + @Bean + open fun webHttpSecurity(http: ServerHttpSecurity): SecurityWebFilterChain { (4) + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + httpBasic { } (5) + } + } + + @Bean + open fun userDetailsService(): ReactiveUserDetailsService { + return MapReactiveUserDetailsService( + PasswordEncodedUser.user(), PasswordEncodedUser.admin() + ) + } +} +``` + +|**1**| Configure a `SecurityWebFilterChain` with an `@Order` to specify which `SecurityWebFilterChain` Spring Security should consider first | +|-----|------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**|Use `PathPatternParserServerWebExchangeMatcher` to state that this `SecurityWebFilterChain` will only apply to URL paths that start with `/api/`| +|**3**| Specify the authentication mechanisms that will be used for `/api/**` endpoints | +|**4**| Create another instance of `SecurityWebFilterChain` with lower precedence to match all other URLs | +|**5**| Specify the authentication mechanisms that will be used for the rest of the application | + +Spring Security will select one `SecurityWebFilterChain` `@Bean` for each request. +It will match the requests in order by the `securityMatcher` definition. + +In this case, that means that if the URL path starts with `/api`, then Spring Security will use `apiHttpSecurity`. +If the URL does not start with `/api` then Spring Security will default to `webHttpSecurity`, which has an implied `securityMatcher` that matches any request. \ No newline at end of file diff --git a/docs/en/spring-security/reactive-exploits-csrf.md b/docs/en/spring-security/reactive-exploits-csrf.md new file mode 100644 index 0000000000000000000000000000000000000000..25c0946270bcf4f627af6564a5d9ea19cffa6f8b --- /dev/null +++ b/docs/en/spring-security/reactive-exploits-csrf.md @@ -0,0 +1,371 @@ +# Cross Site Request Forgery (CSRF) for WebFlux Environments + +This section discusses Spring Security’s [Cross Site Request Forgery (CSRF)](../../features/exploits/csrf.html#csrf) support for WebFlux environments. + +## Using Spring Security CSRF Protection + +The steps to using Spring Security’s CSRF protection are outlined below: + +* [Use proper HTTP verbs](#webflux-csrf-idempotent) + +* [Configure CSRF Protection](#webflux-csrf-configure) + +* [Include the CSRF Token](#webflux-csrf-include) + +### Use proper HTTP verbs + +The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. +This is covered in detail in [Safe Methods Must be Idempotent](../../features/exploits/csrf.html#csrf-protection-idempotent). + +### Configure CSRF Protection + +The next step is to configure Spring Security’s CSRF protection within your application. +Spring Security’s CSRF protection is enabled by default, but you may need to customize the configuration. +Below are a few common customizations. + +#### Custom CsrfTokenRepository + +By default Spring Security stores the expected CSRF token in the `WebSession` using `WebSessionServerCsrfTokenRepository`. +There can be cases where users will want to configure a custom `ServerCsrfTokenRepository`. +For example, it might be desirable to persist the `CsrfToken` in a cookie to [support a JavaScript based application](#webflux-csrf-include-ajax-auto). + +By default the `CookieServerCsrfTokenRepository` will write to a cookie named `XSRF-TOKEN` and read it from a header named `X-XSRF-TOKEN` or the HTTP parameter `_csrf`. +These defaults come from [AngularJS](https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection) + +You can configure `CookieServerCsrfTokenRepository` in Java Configuration using: + +Example 1. Store CSRF Token in a Cookie + +Java + +``` +@Bean +public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .csrf(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse())) + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + csrf { + csrfTokenRepository = CookieServerCsrfTokenRepository.withHttpOnlyFalse() + } + } +} +``` + +| |The sample explicitly sets `cookieHttpOnly=false`.
This is necessary to allow JavaScript (i.e. AngularJS) to read it.
If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit `cookieHttpOnly=false` (by using `new CookieServerCsrfTokenRepository()` instead) to improve security.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +#### Disable CSRF Protection + +CSRF protection is enabled by default. +However, it is simple to disable CSRF protection if it [makes sense for your application](../../features/exploits/csrf.html#csrf-when). + +The Java configuration below will disable CSRF protection. + +Example 2. Disable CSRF Configuration + +Java + +``` +@Bean +public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .csrf(csrf -> csrf.disable())) + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + csrf { + disable() + } + } +} +``` + +### Include the CSRF Token + +In order for the [synchronizer token pattern](../../features/exploits/csrf.html#csrf-protection-stp) to protect against CSRF attacks, we must include the actual CSRF token in the HTTP request. +This must be included in a part of the request (i.e. form parameter, HTTP header, etc) that is not automatically included in the HTTP request by the browser. + +Spring Security’s [CsrfWebFilter](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/server/csrf/CsrfWebFilter.html) exposes a [Mono\](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfToken.html) as a `ServerWebExchange` attribute named `org.springframework.security.web.server.csrf.CsrfToken`. +This means that any view technology can access the `Mono` to expose the expected token as either a [form](#webflux-csrf-include-form-attr) or [meta tag](#webflux-csrf-include-ajax-meta). + +If your view technology does not provide a simple way to subscribe to the `Mono`, a common pattern is to use Spring’s `@ControllerAdvice` to expose the `CsrfToken` directly. +For example, the following code will place the `CsrfToken` on the default attribute name (`_csrf`) used by Spring Security’s [CsrfRequestDataValueProcessor](#webflux-csrf-include-form-auto) to automatically include the CSRF token as a hidden input. + +Example 3. `CsrfToken` as `@ModelAttribute` + +Java + +``` +@ControllerAdvice +public class SecurityControllerAdvice { + @ModelAttribute + Mono csrfToken(ServerWebExchange exchange) { + Mono csrfToken = exchange.getAttribute(CsrfToken.class.getName()); + return csrfToken.doOnSuccess(token -> exchange.getAttributes() + .put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, token)); + } +} +``` + +Kotlin + +``` +@ControllerAdvice +class SecurityControllerAdvice { + @ModelAttribute + fun csrfToken(exchange: ServerWebExchange): Mono { + val csrfToken: Mono? = exchange.getAttribute(CsrfToken::class.java.name) + return csrfToken!!.doOnSuccess { token -> + exchange.attributes[CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME] = token + } + } +} +``` + +Fortunately, Thymeleaf provides [integration](#webflux-csrf-include-form-auto) that works without any additional work. + +#### Form URL Encoded + +In order to post an HTML form the CSRF token must be included in the form as a hidden input. +For example, the rendered HTML might look like: + +Example 4. CSRF Token HTML + +``` + +``` + +Next we will discuss various ways of including the CSRF token in a form as a hidden input. + +##### Automatic CSRF Token Inclusion + +Spring Security’s CSRF support provides integration with Spring’s [RequestDataValueProcessor](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/result/view/RequestDataValueProcessor.html) via its [CsrfRequestDataValueProcessor](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessor.html). +In order for `CsrfRequestDataValueProcessor` to work, the `Mono` must be subscribed to and the `CsrfToken` must be [exposed as an attribute](#webflux-csrf-include-subscribe) that matches [DEFAULT\_CSRF\_ATTR\_NAME](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessor.html#DEFAULT_CSRF_ATTR_NAME). + +Fortunately, Thymeleaf [provides support](https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#integration-with-requestdatavalueprocessor) to take care of all the boilerplate for you by integrating with `RequestDataValueProcessor` to ensure that forms that have an unsafe HTTP method (i.e. post) will automatically include the actual CSRF token. + +##### CsrfToken Request Attribute + +If the [other options](#webflux-csrf-include) for including the actual CSRF token in the request do not work, you can take advantage of the fact that the `Mono` [is exposed](#webflux-csrf-include) as a `ServerWebExchange` attribute named `org.springframework.security.web.server.csrf.CsrfToken`. + +The Thymeleaf sample below assumes that you [expose](#webflux-csrf-include-subscribe) the `CsrfToken` on an attribute named `_csrf`. + +Example 5. CSRF Token in Form with Request Attribute + +``` +
+ + +
+``` + +#### Ajax and JSON Requests + +If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. +Instead you can submit the token within a HTTP header. + +In the following sections we will discuss various ways of including the CSRF token as an HTTP request header in JavaScript based applications. + +##### Automatic Inclusion + +Spring Security can easily be [configured](#webflux-csrf-configure-custom-repository) to store the expected CSRF token in a cookie. +By storing the expected CSRF in a cookie, JavaScript frameworks like [AngularJS](https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection) will automatically include the actual CSRF token in the HTTP request headers. + +##### Meta tags + +An alternative pattern to [exposing the CSRF in a cookie](#webflux-csrf-include-form-auto) is to include the CSRF token within your `meta` tags. +The HTML might look something like this: + +Example 6. CSRF meta tag HTML + +``` + + + + + + + +``` + +Once the meta tags contained the CSRF token, the JavaScript code would read the meta tags and include the CSRF token as a header. +If you were using jQuery, this could be done with the following: + +Example 7. AJAX send CSRF Token + +``` +$(function () { + var token = $("meta[name='_csrf']").attr("content"); + var header = $("meta[name='_csrf_header']").attr("content"); + $(document).ajaxSend(function(e, xhr, options) { + xhr.setRequestHeader(header, token); + }); +}); +``` + +The sample below assumes that you [expose](#webflux-csrf-include-subscribe) the `CsrfToken` on an attribute named `_csrf`. +An example of doing this with Thymeleaf is shown below: + +Example 8. CSRF meta tag JSP + +``` + + + + + + + + +``` + +## CSRF Considerations + +There are a few special considerations to consider when implementing protection against CSRF attacks. +This section discusses those considerations as it pertains to WebFlux environments. +Refer to [CSRF Considerations](../../features/exploits/csrf.html#csrf-considerations) for a more general discussion. + +### Logging In + +It is important to [require CSRF for log in](../../features/exploits/csrf.html#csrf-considerations-login) requests to protect against forging log in attempts. +Spring Security’s WebFlux support does this out of the box. + +### Logging Out + +It is important to [require CSRF for log out](../../features/exploits/csrf.html#csrf-considerations-logout) requests to protect against forging log out attempts. +By default Spring Security’s `LogoutWebFilter` only processes HTTP post requests. +This ensures that log out requires a CSRF token and that a malicious user cannot forcibly log out your users. + +The easiest approach is to use a form to log out. +If you really want a link, you can use JavaScript to have the link perform a POST (i.e. maybe on a hidden form). +For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that will perform the POST. + +If you really want to use HTTP GET with logout you can do so, but remember this is generally not recommended. +For example, the following Java Configuration will perform logout with the URL `/logout` is requested with any HTTP method: + +Example 9. Log out with HTTP GET + +Java + +``` +@Bean +public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .logout(logout -> logout.requiresLogout(new PathPatternParserServerWebExchangeMatcher("/logout"))) + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + logout { + requiresLogout = PathPatternParserServerWebExchangeMatcher("/logout") + } + } +} +``` + +### CSRF and Session Timeouts + +By default Spring Security stores the CSRF token in the `WebSession`. +This can lead to a situation where the session expires which means there is not an expected CSRF token to validate against. + +We’ve already discussed [general solutions](../../features/exploits/csrf.html#csrf-considerations-login) to session timeouts. +This section discusses the specifics of CSRF timeouts as it pertains to the WebFlux support. + +It is simple to change storage of the expected CSRF token to be in a cookie. +For details, refer to the [Custom CsrfTokenRepository](#webflux-csrf-configure-custom-repository) section. + +### + +We have [already discussed](../../features/exploits/csrf.html#csrf-considerations-multipart) how protecting multipart requests (file uploads) from CSRF attacks causes a [chicken and the egg](https://en.wikipedia.org/wiki/Chicken_or_the_egg) problem. +This section discusses how to implement placing the CSRF token in the [body](#webflux-csrf-considerations-multipart-body) and [url](#webflux-csrf-considerations-multipart-url) within a WebFlux application. + +| |More information about using multipart forms with Spring can be found within the [Multipart Data](https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web-reactive.html#webflux-multipart) section of the Spring reference.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +#### Place CSRF Token in the Body + +We have [already discussed](../../features/exploits/csrf.html#csrf-considerations-multipart) the trade-offs of placing the CSRF token in the body. + +In a WebFlux application, this can be configured with the following configuration: + +Example 10. Enable obtaining CSRF token from multipart/form-data + +Java + +``` +@Bean +public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .csrf(csrf -> csrf.tokenFromMultipartDataEnabled(true)) + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + csrf { + tokenFromMultipartDataEnabled = true + } + } +} +``` + +#### Include CSRF Token in URL + +We have [already discussed](../../features/exploits/csrf.html#csrf-considerations-multipart) the trade-offs of placing the CSRF token in the URL. +Since the `CsrfToken` is exposed as an `ServerHttpRequest` [request attribute](#webflux-csrf-include), we can use that to create an `action` with the CSRF token in it. +An example with Thymeleaf is shown below: + +Example 11. CSRF Token in Action + +``` +
+``` + +### HiddenHttpMethodFilter + +We have [already discussed](../../features/exploits/csrf.html#csrf-considerations-override-method) overriding the HTTP method. + +In a Spring WebFlux application, overriding the HTTP method is done using [HiddenHttpMethodFilter](https://docs.spring.io/spring-framework/docs/5.2.x/javadoc-api/org/springframework/web/filter/reactive/HiddenHttpMethodFilter.html). \ No newline at end of file diff --git a/docs/en/spring-security/reactive-exploits-headers.md b/docs/en/spring-security/reactive-exploits-headers.md new file mode 100644 index 0000000000000000000000000000000000000000..169f41f9ba3fa794e8c4acae10340caa8cdfd5a7 --- /dev/null +++ b/docs/en/spring-security/reactive-exploits-headers.md @@ -0,0 +1,549 @@ +# Security HTTP Response Headers + +[Security HTTP Response Headers](../../features/exploits/headers.html#headers) can be used to increase the security of web applications. +This section is dedicated to WebFlux based support for Security HTTP Response Headers. + +## Default Security Headers + +Spring Security provides a [default set of Security HTTP Response Headers](../../features/exploits/headers.html#headers-default) to provide secure defaults. +While each of these headers are considered best practice, it should be noted that not all clients utilize the headers, so additional testing is encouraged. + +You can customize specific headers. +For example, assume that you want the defaults except you wish to specify `SAMEORIGIN` for [X-Frame-Options](../../servlet/exploits/headers.html#servlet-headers-frame-options). + +You can easily do this with the following Configuration: + +Example 1. Customize Default Security Headers + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .frameOptions(frameOptions -> frameOptions + .mode(Mode.SAMEORIGIN) + ) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + frameOptions { + mode = Mode.SAMEORIGIN + } + } + } +} +``` + +If you do not want the defaults to be added and want explicit control over what should be used, you can disable the defaults. +An example is provided below: + +Example 2. Disable HTTP Security Response Headers + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers.disable()); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + disable() + } + } +} +``` + +## Cache Control + +Spring Security includes [Cache Control](../../features/exploits/headers.html#headers-cache-control) headers by default. + +However, if you actually want to cache specific responses, your application can selectively add them to the [ServerHttpResponse](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/server/reactive/ServerHttpResponse.html) to override the header set by Spring Security. +This is useful to ensure things like CSS, JavaScript, and images are properly cached. + +When using Spring WebFlux, this is typically done within your configuration. +Details on how to do this can be found in the [Static Resources](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web-reactive.html#webflux-config-static-resources) portion of the Spring Reference documentation + +If necessary, you can also disable Spring Security’s cache control HTTP response headers. + +Example 3. Cache Control Disabled + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .cache(cache -> cache.disable()) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + cache { + disable() + } + } + } +} +``` + +## Content Type Options + +Spring Security includes [Content-Type](../../features/exploits/headers.html#headers-content-type-options) headers by default. +However, you can disable it with: + +Example 4. Content Type Options Disabled + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .contentTypeOptions(contentTypeOptions -> contentTypeOptions.disable()) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + contentTypeOptions { + disable() + } + } + } +} +``` + +## + +Spring Security provides the [Strict Transport Security](../../features/exploits/headers.html#headers-hsts) header by default. +However, you can customize the results explicitly. +For example, the following is an example of explicitly providing HSTS: + +Example 5. Strict Transport Security + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .hsts(hsts -> hsts + .includeSubdomains(true) + .preload(true) + .maxAge(Duration.ofDays(365)) + ) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + hsts { + includeSubdomains = true + preload = true + maxAge = Duration.ofDays(365) + } + } + } +} +``` + +## X-Frame-Options + +By default, Spring Security disables rendering within an iframe using [X-Frame-Options](../../features/exploits/headers.html#headers-frame-options). + +You can customize frame options to use the same origin using the following: + +Example 6. X-Frame-Options: SAMEORIGIN + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .frameOptions(frameOptions -> frameOptions + .mode(SAMEORIGIN) + ) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + frameOptions { + mode = SAMEORIGIN + } + } + } +} +``` + +## X-XSS-Protection + +By default, Spring Security instructs browsers to block reflected XSS attacks using the \<\. +You can disable `X-XSS-Protection` with the following Configuration: + +Example 7. X-XSS-Protection Customization + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .xssProtection(xssProtection -> xssProtection.disable()) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + xssProtection { + disable() + } + } + } +} +``` + +## + +Spring Security does not add [Content Security Policy](../../features/exploits/headers.html#headers-csp) by default, because a reasonable default is impossible to know without context of the application. +The web application author must declare the security policy(s) to enforce and/or monitor for the protected resources. + +For example, given the following security policy: + +Example 8. Content Security Policy Example + +``` +Content-Security-Policy: script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/ +``` + +You can enable the CSP header as shown below: + +Example 9. Content Security Policy + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .contentSecurityPolicy(policy -> policy + .policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/") + ) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + contentSecurityPolicy { + policyDirectives = "script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/" + } + } + } +} +``` + +To enable the CSP `report-only` header, provide the following configuration: + +Example 10. Content Security Policy Report Only + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .contentSecurityPolicy(policy -> policy + .policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/") + .reportOnly() + ) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + contentSecurityPolicy { + policyDirectives = "script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/" + reportOnly = true + } + } + } +} +``` + +## Referrer Policy + +Spring Security does not add [Referrer Policy](../../features/exploits/headers.html#headers-referrer) headers by default. +You can enable the Referrer Policy header using configuration as shown below: + +Example 11. Referrer Policy Configuration + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .referrerPolicy(referrer -> referrer + .policy(ReferrerPolicy.SAME_ORIGIN) + ) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + referrerPolicy { + policy = ReferrerPolicy.SAME_ORIGIN + } + } + } +} +``` + +## Feature Policy + +Spring Security does not add [Feature Policy](../../features/exploits/headers.html#headers-feature) headers by default. +The following `Feature-Policy` header: + +Example 12. Feature-Policy Example + +``` +Feature-Policy: geolocation 'self' +``` + +You can enable the Feature Policy header as shown below: + +Example 13. Feature-Policy Configuration + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .featurePolicy("geolocation 'self'") + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + featurePolicy("geolocation 'self'") + } + } +} +``` + +## Permissions Policy + +Spring Security does not add [Permissions Policy](../../features/exploits/headers.html#headers-permissions) headers by default. +The following `Permissions-Policy` header: + +Example 14. Permissions-Policy Example + +``` +Permissions-Policy: geolocation=(self) +``` + +You can enable the Permissions Policy header as shown below: + +Example 15. Permissions-Policy Configuration + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .headers(headers -> headers + .permissionsPolicy(permissions -> permissions + .policy("geolocation=(self)") + ) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + headers { + permissionsPolicy { + policy = "geolocation=(self)" + } + } + } +} +``` + +## Clear Site Data + +Spring Security does not add [Clear-Site-Data](../../features/exploits/headers.html#headers-clear-site-data) headers by default. +The following Clear-Site-Data header: + +Example 16. Clear-Site-Data Example + +``` +Clear-Site-Data: "cache", "cookies" +``` + +can be sent on log out with the following configuration: + +Example 17. Clear-Site-Data Configuration + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + ServerLogoutHandler securityContext = new SecurityContextServerLogoutHandler(); + ClearSiteDataServerHttpHeadersWriter writer = new ClearSiteDataServerHttpHeadersWriter(CACHE, COOKIES); + ServerLogoutHandler clearSiteData = new HeaderWriterServerLogoutHandler(writer); + DelegatingServerLogoutHandler logoutHandler = new DelegatingServerLogoutHandler(securityContext, clearSiteData); + + http + // ... + .logout() + .logoutHandler(logoutHandler); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + val securityContext: ServerLogoutHandler = SecurityContextServerLogoutHandler() + val writer = ClearSiteDataServerHttpHeadersWriter(CACHE, COOKIES) + val clearSiteData: ServerLogoutHandler = HeaderWriterServerLogoutHandler(writer) + val customLogoutHandler = DelegatingServerLogoutHandler(securityContext, clearSiteData) + + return http { + // ... + logout { + logoutHandler = customLogoutHandler + } + } +} +``` \ No newline at end of file diff --git a/docs/en/spring-security/reactive-exploits-http.md b/docs/en/spring-security/reactive-exploits-http.md new file mode 100644 index 0000000000000000000000000000000000000000..385e3343097c22267fc931af05033dc1480e325f --- /dev/null +++ b/docs/en/spring-security/reactive-exploits-http.md @@ -0,0 +1,81 @@ +# HTTP + +All HTTP based communication should be protected [using TLS](../../features/exploits/http.html#http). + +Below you can find details around WebFlux specific features that assist with HTTPS usage. + +## Redirect to HTTPS + +If a client makes a request using HTTP rather than HTTPS, Spring Security can be configured to redirect to HTTPS. + +For example, the following Java configuration will redirect any HTTP requests to HTTPS: + +Example 1. Redirect to HTTPS + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .redirectToHttps(withDefaults()); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + redirectToHttps { } + } +} +``` + +The configuration can easily be wrapped around an if statement to only be turned on in production. +Alternatively, it can be enabled by looking for a property about the request that only happens in production. +For example, if the production environment adds a header named `X-Forwarded-Proto` the following Java Configuration could be used: + +Example 2. Redirect to HTTPS when X-Forwarded + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .redirectToHttps(redirect -> redirect + .httpsRedirectWhen(e -> e.getRequest().getHeaders().containsKey("X-Forwarded-Proto")) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + redirectToHttps { + httpsRedirectWhen { + it.request.headers.containsKey("X-Forwarded-Proto") + } + } + } +} +``` + +## Strict Transport Security + +Spring Security provides support for [Strict Transport Security](../../servlet/exploits/headers.html#servlet-headers-hsts) and enables it by default. + +## Proxy Server Configuration + +Spring Security [integrates with proxy servers](../../features/exploits/http.html#http-proxy-server). \ No newline at end of file diff --git a/docs/en/spring-security/reactive-exploits.md b/docs/en/spring-security/reactive-exploits.md new file mode 100644 index 0000000000000000000000000000000000000000..1f755c775774daafd3fbecf7f23756644ee5d3ed --- /dev/null +++ b/docs/en/spring-security/reactive-exploits.md @@ -0,0 +1,10 @@ +# Protection Against Exploits + +Spring Security provides protection against numerous exploits. +This section discusses WebFlux specific support for: + +* [CSRF](csrf.html) + +* [Headers](headers.html) + +* [HTTP Requests](http.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-getting-started.md b/docs/en/spring-security/reactive-getting-started.md new file mode 100644 index 0000000000000000000000000000000000000000..3a34c713d4b02744d45187e0d353e0474b30e91c --- /dev/null +++ b/docs/en/spring-security/reactive-getting-started.md @@ -0,0 +1,68 @@ +# Getting Started with WebFlux Applications + +This section covers the minimum setup for how to use Spring Security with Spring Boot in a reactive application. + +| |The completed application can be found [in our samples repository](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/reactive/webflux/java/hello-security).
For your convenience, you can download a minimal Reactive Spring Boot + Spring Security application by [clicking here](https://start.spring.io/starter.zip?type=maven-project&language=java&packaging=jar&jvmVersion=1.8&groupId=example&artifactId=hello-security&name=hello-security&description=Hello%20Security&packageName=example.hello-security&dependencies=webflux,security).| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## Updating Dependencies + +You can add Spring Security to your Spring Boot project by adding `spring-boot-starter-security`. + +Maven + +``` + + org.springframework.boot + spring-boot-starter-security + +``` + +Gradle + +``` + implementation 'org.springframework.boot:spring-boot-starter-security' +``` + +## Starting Hello Spring Security Boot + +You can now [run the Spring Boot application](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-running-with-the-maven-plugin) by using the Maven Plugin’s `run` goal. +The following example shows how to do so (and the beginning of the output from doing so): + +Example 1. Running Spring Boot Application + +Maven + +``` +$ ./mvnw spring-boot:run +... +INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration : + +Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336 + +... +``` + +Gradle + +``` +$ ./gradlew bootRun +... +INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration : + +Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336 + +... +``` + +## Authenticating + +You can access the application at [http://localhost:8080/](http://localhost:8080/) which will redirect the browser to the default log in page. You can provide the default username of `user` with the randomly generated password that is logged to the console. The browser is then taken to the orginally requested page. + +To log out you can visit [http://localhost:8080/logout](http://localhost:8080/logout) and then confirming you wish to log out. + +## Spring Boot Auto Configuration + +Spring Boot automatically adds Spring Security which requires all requests be authenticated. It also generates a user with a randomly generated password that is logged to the console which can be used to authenticate using form or basic authentication. + +[Reactive Applications](index.html)[X.509 Authentication](authentication/x509.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-integrations-cors.md b/docs/en/spring-security/reactive-integrations-cors.md new file mode 100644 index 0000000000000000000000000000000000000000..c8b9ee0ad6507b5a22ae086eb993072694694151 --- /dev/null +++ b/docs/en/spring-security/reactive-integrations-cors.md @@ -0,0 +1,67 @@ +# CORS + +Spring Framework provides [first class support for CORS](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-cors-intro). +CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the `JSESSIONID`). +If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it. + +The easiest way to ensure that CORS is handled first is to use the `CorsWebFilter`. +Users can integrate the `CorsWebFilter` with Spring Security by providing a `CorsConfigurationSource`. +For example, the following will integrate CORS support within Spring Security: + +Java + +``` +@Bean +CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Arrays.asList("https://example.com")); + configuration.setAllowedMethods(Arrays.asList("GET","POST")); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; +} +``` + +Kotlin + +``` +@Bean +fun corsConfigurationSource(): CorsConfigurationSource { + val configuration = CorsConfiguration() + configuration.allowedOrigins = listOf("https://example.com") + configuration.allowedMethods = listOf("GET", "POST") + val source = UrlBasedCorsConfigurationSource() + source.registerCorsConfiguration("/**", configuration) + return source +} +``` + +The following will disable the CORS integration within Spring Security: + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + // ... + .cors(cors -> cors.disable()); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + // ... + cors { + disable() + } + } +} +``` + +[HTTP Requests](../exploits/http.html)[RSocket](rsocket.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-integrations-rsocket.md b/docs/en/spring-security/reactive-integrations-rsocket.md new file mode 100644 index 0000000000000000000000000000000000000000..6795a7862c4ffd3a89495fae98e6d6f42f273c2b --- /dev/null +++ b/docs/en/spring-security/reactive-integrations-rsocket.md @@ -0,0 +1,384 @@ +# RSocket Security + +Spring Security’s RSocket support relies on a `SocketAcceptorInterceptor`. +The main entry point into security is found in the `PayloadSocketAcceptorInterceptor` which adapts the RSocket APIs to allow intercepting a `PayloadExchange` with `PayloadInterceptor` implementations. + +You can find a few sample applications that demonstrate the code below: + +* Hello RSocket [hellorsocket](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/reactive/rsocket/hello-security) + +* [Spring Flights](https://github.com/rwinch/spring-flights/tree/security) + +## Minimal RSocket Security Configuration + +You can find a minimal RSocket Security configuration below: + +Java + +``` +@Configuration +@EnableRSocketSecurity +public class HelloRSocketSecurityConfig { + + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User.withDefaultPasswordEncoder() + .username("user") + .password("user") + .roles("USER") + .build(); + return new MapReactiveUserDetailsService(user); + } +} +``` + +Kotlin + +``` +@Configuration +@EnableRSocketSecurity +open class HelloRSocketSecurityConfig { + @Bean + open fun userDetailsService(): MapReactiveUserDetailsService { + val user = User.withDefaultPasswordEncoder() + .username("user") + .password("user") + .roles("USER") + .build() + return MapReactiveUserDetailsService(user) + } +} +``` + +This configuration enables [simple authentication](#rsocket-authentication-simple) and sets up [rsocket-authorization](#rsocket-authorization) to require an authenticated user for any request. + +## Adding SecuritySocketAcceptorInterceptor + +For Spring Security to work we need to apply `SecuritySocketAcceptorInterceptor` to the `ServerRSocketFactory`. +This is what connects our `PayloadSocketAcceptorInterceptor` we created with the RSocket infrastructure. +In a Spring Boot application this is done automatically using `RSocketSecurityAutoConfiguration` with the following code. + +``` +@Bean +RSocketServerCustomizer springSecurityRSocketSecurity(SecuritySocketAcceptorInterceptor interceptor) { + return (server) -> server.interceptors((registry) -> registry.forSocketAcceptor(interceptor)); +} +``` + +## RSocket Authentication + +RSocket authentication is performed with `AuthenticationPayloadInterceptor` which acts as a controller to invoke a `ReactiveAuthenticationManager` instance. + +### Authentication at Setup vs Request Time + +Generally, authentication can occur at setup time and/or request time. + +Authentication at setup time makes sense in a few scenarios. +A common scenarios is when a single user (i.e. mobile connection) is leveraging an RSocket connection. +In this case only a single user is leveraging the connection, so authentication can be done once at connection time. + +In a scenario where the RSocket connection is shared it makes sense to send credentials on each request. +For example, a web application that connects to an RSocket server as a downstream service would make a single connection that all users leverage. +In this case, if the RSocket server needs to perform authorization based on the web application’s users credentials per request makes sense. + +In some scenarios authentication at setup and per request makes sense. +Consider a web application as described previously. +If we need to restrict the connection to the web application itself, we can provide a credential with a `SETUP` authority at connection time. +Then each user would have different authorities but not the `SETUP` authority. +This means that individual users can make requests but not make additional connections. + +### Simple Authentication + +Spring Security has support for [Simple Authentication Metadata Extension](https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Simple.md). + +| |Basic Authentication drafts evolved into Simple Authentication and is only supported for backward compatibility.
See `RSocketSecurity.basicAuthentication(Customizer)` for setting it up.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The RSocket receiver can decode the credentials using `AuthenticationPayloadExchangeConverter` which is automatically setup using the `simpleAuthentication` portion of the DSL. +An explicit configuration can be found below. + +Java + +``` +@Bean +PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) { + rsocket + .authorizePayload(authorize -> + authorize + .anyRequest().authenticated() + .anyExchange().permitAll() + ) + .simpleAuthentication(Customizer.withDefaults()); + return rsocket.build(); +} +``` + +Kotlin + +``` +@Bean +open fun rsocketInterceptor(rsocket: RSocketSecurity): PayloadSocketAcceptorInterceptor { + rsocket + .authorizePayload { authorize -> authorize + .anyRequest().authenticated() + .anyExchange().permitAll() + } + .simpleAuthentication(withDefaults()) + return rsocket.build() +} +``` + +The RSocket sender can send credentials using `SimpleAuthenticationEncoder` which can be added to Spring’s `RSocketStrategies`. + +Java + +``` +RSocketStrategies.Builder strategies = ...; +strategies.encoder(new SimpleAuthenticationEncoder()); +``` + +Kotlin + +``` +var strategies: RSocketStrategies.Builder = ... +strategies.encoder(SimpleAuthenticationEncoder()) +``` + +It can then be used to send a username and password to the receiver in the setup: + +Java + +``` +MimeType authenticationMimeType = + MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString()); +UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password"); +Mono requester = RSocketRequester.builder() + .setupMetadata(credentials, authenticationMimeType) + .rsocketStrategies(strategies.build()) + .connectTcp(host, port); +``` + +Kotlin + +``` +val authenticationMimeType: MimeType = + MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.string) +val credentials = UsernamePasswordMetadata("user", "password") +val requester: Mono = RSocketRequester.builder() + .setupMetadata(credentials, authenticationMimeType) + .rsocketStrategies(strategies.build()) + .connectTcp(host, port) +``` + +Alternatively or additionally, a username and password can be sent in a request. + +Java + +``` +Mono requester; +UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password"); + +public Mono findRadar(String code) { + return this.requester.flatMap(req -> + req.route("find.radar.{code}", code) + .metadata(credentials, authenticationMimeType) + .retrieveMono(AirportLocation.class) + ); +} +``` + +Kotlin + +``` +import org.springframework.messaging.rsocket.retrieveMono + +// ... + +var requester: Mono? = null +var credentials = UsernamePasswordMetadata("user", "password") + +open fun findRadar(code: String): Mono { + return requester!!.flatMap { req -> + req.route("find.radar.{code}", code) + .metadata(credentials, authenticationMimeType) + .retrieveMono() + } +} +``` + +### JWT + +Spring Security has support for [Bearer Token Authentication Metadata Extension](https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Bearer.md). +The support comes in the form of authenticating a JWT (determining the JWT is valid) and then using the JWT to make authorization decisions. + +The RSocket receiver can decode the credentials using `BearerPayloadExchangeConverter` which is automatically setup using the `jwt` portion of the DSL. +An example configuration can be found below: + +Java + +``` +@Bean +PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) { + rsocket + .authorizePayload(authorize -> + authorize + .anyRequest().authenticated() + .anyExchange().permitAll() + ) + .jwt(Customizer.withDefaults()); + return rsocket.build(); +} +``` + +Kotlin + +``` +@Bean +fun rsocketInterceptor(rsocket: RSocketSecurity): PayloadSocketAcceptorInterceptor { + rsocket + .authorizePayload { authorize -> authorize + .anyRequest().authenticated() + .anyExchange().permitAll() + } + .jwt(withDefaults()) + return rsocket.build() +} +``` + +The configuration above relies on the existence of a `ReactiveJwtDecoder` `@Bean` being present. +An example of creating one from the issuer can be found below: + +Java + +``` +@Bean +ReactiveJwtDecoder jwtDecoder() { + return ReactiveJwtDecoders + .fromIssuerLocation("https://example.com/auth/realms/demo"); +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + return ReactiveJwtDecoders + .fromIssuerLocation("https://example.com/auth/realms/demo") +} +``` + +The RSocket sender does not need to do anything special to send the token because the value is just a simple String. +For example, the token can be sent at setup time: + +Java + +``` +MimeType authenticationMimeType = + MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString()); +BearerTokenMetadata token = ...; +Mono requester = RSocketRequester.builder() + .setupMetadata(token, authenticationMimeType) + .connectTcp(host, port); +``` + +Kotlin + +``` +val authenticationMimeType: MimeType = + MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.string) +val token: BearerTokenMetadata = ... + +val requester = RSocketRequester.builder() + .setupMetadata(token, authenticationMimeType) + .connectTcp(host, port) +``` + +Alternatively or additionally, the token can be sent in a request. + +Java + +``` +MimeType authenticationMimeType = + MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString()); +Mono requester; +BearerTokenMetadata token = ...; + +public Mono findRadar(String code) { + return this.requester.flatMap(req -> + req.route("find.radar.{code}", code) + .metadata(token, authenticationMimeType) + .retrieveMono(AirportLocation.class) + ); +} +``` + +Kotlin + +``` +val authenticationMimeType: MimeType = + MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.string) +var requester: Mono? = null +val token: BearerTokenMetadata = ... + +open fun findRadar(code: String): Mono { + return this.requester!!.flatMap { req -> + req.route("find.radar.{code}", code) + .metadata(token, authenticationMimeType) + .retrieveMono() + } +} +``` + +## RSocket Authorization + +RSocket authorization is performed with `AuthorizationPayloadInterceptor` which acts as a controller to invoke a `ReactiveAuthorizationManager` instance. +The DSL can be used to setup authorization rules based upon the `PayloadExchange`. +An example configuration can be found below: + +Java + +``` +rsocket + .authorizePayload(authz -> + authz + .setup().hasRole("SETUP") (1) + .route("fetch.profile.me").authenticated() (2) + .matcher(payloadExchange -> isMatch(payloadExchange)) (3) + .hasRole("CUSTOM") + .route("fetch.profile.{username}") (4) + .access((authentication, context) -> checkFriends(authentication, context)) + .anyRequest().authenticated() (5) + .anyExchange().permitAll() (6) + ); +``` + +Kotlin + +``` +rsocket + .authorizePayload { authz -> + authz + .setup().hasRole("SETUP") (1) + .route("fetch.profile.me").authenticated() (2) + .matcher { payloadExchange -> isMatch(payloadExchange) } (3) + .hasRole("CUSTOM") + .route("fetch.profile.{username}") (4) + .access { authentication, context -> checkFriends(authentication, context) } + .anyRequest().authenticated() (5) + .anyExchange().permitAll() + } (6) +``` + +|**1**| Setting up a connection requires the authority `ROLE_SETUP` | +|-----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**| If the route is `fetch.profile.me` authorization only requires the user be authenticated | +|**3**| In this rule we setup a custom matcher where authorization requires the user to have the authority `ROLE_CUSTOM` | +|**4**|This rule leverages custom authorization.
The matcher expresses a variable with the name `username` that is made available in the `context`.
A custom authorization rule is exposed in the `checkFriends` method.| +|**5**| This rule ensures that request that does not already have a rule will require the user to be authenticated.
A request is where the metadata is included.
It would not include additional payloads. | +|**6**| This rule ensures that any exchange that does not already have a rule is allowed for anyone.
In this example, it means that payloads that have no metadata have no authorization rules. | + +It is important to understand that authorization rules are performed in order. +Only the first authorization rule that matches will be invoked. + +[CORS](cors.html)[Testing](../test/index.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-oauth2-client-authorization-grants.md b/docs/en/spring-security/reactive-oauth2-client-authorization-grants.md new file mode 100644 index 0000000000000000000000000000000000000000..bcf696ddf8cead52dff20d14867536a57e18dc19 --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-client-authorization-grants.md @@ -0,0 +1,1037 @@ +# Authorization Grant Support + +## Authorization Code + +| |Please refer to the OAuth 2.0 Authorization Framework for further details on the [Authorization Code](https://tools.ietf.org/html/rfc6749#section-1.3.1) grant.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Obtaining Authorization + +| |Please refer to the [Authorization Request/Response](https://tools.ietf.org/html/rfc6749#section-4.1.1) protocol flow for the Authorization Code grant.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Initiating the Authorization Request + +The `OAuth2AuthorizationRequestRedirectWebFilter` uses a `ServerOAuth2AuthorizationRequestResolver` to resolve an `OAuth2AuthorizationRequest` and initiate the Authorization Code grant flow by redirecting the end-user’s user-agent to the Authorization Server’s Authorization Endpoint. + +The primary role of the `ServerOAuth2AuthorizationRequestResolver` is to resolve an `OAuth2AuthorizationRequest` from the provided web request. +The default implementation `DefaultServerOAuth2AuthorizationRequestResolver` matches on the (default) path `/oauth2/authorization/{registrationId}` extracting the `registrationId` and using it to build the `OAuth2AuthorizationRequest` for the associated `ClientRegistration`. + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + authorization-grant-type: authorization_code + redirect-uri: "{baseUrl}/authorized/okta" + scope: read, write + provider: + okta: + authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize + token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token +``` + +A request with the base path `/oauth2/authorization/okta` will initiate the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectWebFilter` and ultimately start the Authorization Code grant flow. + +| |The `AuthorizationCodeReactiveOAuth2AuthorizedClientProvider` is an implementation of `ReactiveOAuth2AuthorizedClientProvider` for the Authorization Code grant,
which also initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectWebFilter`.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +If the OAuth 2.0 Client is a [Public Client](https://tools.ietf.org/html/rfc6749#section-2.1), then configure the OAuth 2.0 Client registration as follows: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-authentication-method: none + authorization-grant-type: authorization_code + redirect-uri: "{baseUrl}/authorized/okta" + ... +``` + +Public Clients are supported using [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636) (PKCE). +If the client is running in an untrusted environment (eg. native application or web browser-based application) and therefore incapable of maintaining the confidentiality of it’s credentials, PKCE will automatically be used when the following conditions are true: + +1. `client-secret` is omitted (or empty) + +2. `client-authentication-method` is set to "none" (`ClientAuthenticationMethod.NONE`) + +The `DefaultServerOAuth2AuthorizationRequestResolver` also supports `URI` template variables for the `redirect-uri` using `UriComponentsBuilder`. + +The following configuration uses all the supported `URI` template variables: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + ... + redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}" + ... +``` + +| |`{baseUrl}` resolves to `{baseScheme}://{baseHost}{basePort}{basePath}`| +|---|-----------------------------------------------------------------------| + +Configuring the `redirect-uri` with `URI` template variables is especially useful when the OAuth 2.0 Client is running behind a [Proxy Server](../../../features/exploits/http.html#http-proxy-server). +This ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`. + +### Customizing the Authorization Request + +One of the primary use cases a `ServerOAuth2AuthorizationRequestResolver` can realize is the ability to customize the Authorization Request with additional parameters above the standard parameters defined in the OAuth 2.0 Authorization Framework. + +For example, OpenID Connect defines additional OAuth 2.0 request parameters for the [Authorization Code Flow](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest) extending from the standard parameters defined in the [OAuth 2.0 Authorization Framework](https://tools.ietf.org/html/rfc6749#section-4.1.1). +One of those extended parameters is the `prompt` parameter. + +| |OPTIONAL. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent. The defined values are: none, login, consent, select\_account| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The following example shows how to configure the `DefaultServerOAuth2AuthorizationRequestResolver` with a `Consumer` that customizes the Authorization Request for `oauth2Login()`, by including the request parameter `prompt=consent`. + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Autowired + private ReactiveClientRegistrationRepository clientRegistrationRepository; + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(oauth2 -> oauth2 + .authorizationRequestResolver( + authorizationRequestResolver(this.clientRegistrationRepository) + ) + ); + return http.build(); + } + + private ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver( + ReactiveClientRegistrationRepository clientRegistrationRepository) { + + DefaultServerOAuth2AuthorizationRequestResolver authorizationRequestResolver = + new DefaultServerOAuth2AuthorizationRequestResolver( + clientRegistrationRepository); + authorizationRequestResolver.setAuthorizationRequestCustomizer( + authorizationRequestCustomizer()); + + return authorizationRequestResolver; + } + + private Consumer authorizationRequestCustomizer() { + return customizer -> customizer + .additionalParameters(params -> params.put("prompt", "consent")); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class SecurityConfig { + + @Autowired + private lateinit var customClientRegistrationRepository: ReactiveClientRegistrationRepository + + @Bean + fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { + authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository) + } + } + } + + private fun authorizationRequestResolver( + clientRegistrationRepository: ReactiveClientRegistrationRepository): ServerOAuth2AuthorizationRequestResolver { + val authorizationRequestResolver = DefaultServerOAuth2AuthorizationRequestResolver( + clientRegistrationRepository) + authorizationRequestResolver.setAuthorizationRequestCustomizer( + authorizationRequestCustomizer()) + return authorizationRequestResolver + } + + private fun authorizationRequestCustomizer(): Consumer { + return Consumer { customizer -> + customizer + .additionalParameters { params -> params["prompt"] = "consent" } + } + } +} +``` + +For the simple use case, where the additional request parameter is always the same for a specific provider, it may be added directly in the `authorization-uri` property. + +For example, if the value for the request parameter `prompt` is always `consent` for the provider `okta`, than simply configure as follows: + +``` +spring: + security: + oauth2: + client: + provider: + okta: + authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent +``` + +The preceding example shows the common use case of adding a custom parameter on top of the standard parameters. +Alternatively, if your requirements are more advanced, you can take full control in building the Authorization Request URI by simply overriding the `OAuth2AuthorizationRequest.authorizationRequestUri` property. + +| |`OAuth2AuthorizationRequest.Builder.build()` constructs the `OAuth2AuthorizationRequest.authorizationRequestUri`, which represents the Authorization Request URI including all query parameters using the `application/x-www-form-urlencoded` format.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example, and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property. + +Java + +``` +private Consumer authorizationRequestCustomizer() { + return customizer -> customizer + .authorizationRequestUri(uriBuilder -> uriBuilder + .queryParam("prompt", "consent").build()); +} +``` + +Kotlin + +``` +private fun authorizationRequestCustomizer(): Consumer { + return Consumer { customizer: OAuth2AuthorizationRequest.Builder -> + customizer + .authorizationRequestUri { uriBuilder: UriBuilder -> + uriBuilder + .queryParam("prompt", "consent").build() + } + } +} +``` + +### Storing the Authorization Request + +The `ServerAuthorizationRequestRepository` is responsible for the persistence of the `OAuth2AuthorizationRequest` from the time the Authorization Request is initiated to the time the Authorization Response is received (the callback). + +| |The `OAuth2AuthorizationRequest` is used to correlate and validate the Authorization Response.| +|---|----------------------------------------------------------------------------------------------| + +The default implementation of `ServerAuthorizationRequestRepository` is `WebSessionOAuth2ServerAuthorizationRequestRepository`, which stores the `OAuth2AuthorizationRequest` in the `WebSession`. + +If you have a custom implementation of `ServerAuthorizationRequestRepository`, you may configure it as shown in the following example: + +Example 1. ServerAuthorizationRequestRepository Configuration + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2ClientSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .oauth2Client(oauth2 -> oauth2 + .authorizationRequestRepository(this.authorizationRequestRepository()) + ... + ); + return http.build(); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2ClientSecurityConfig { + + @Bean + fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + oauth2Client { + authorizationRequestRepository = authorizationRequestRepository() + } + } + } +} +``` + +### Requesting an Access Token + +| |Please refer to the [Access Token Request/Response](https://tools.ietf.org/html/rfc6749#section-4.1.3) protocol flow for the Authorization Code grant.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------| + +The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the Authorization Code grant is `WebClientReactiveAuthorizationCodeTokenResponseClient`, which uses a `WebClient` for exchanging an authorization code for an access token at the Authorization Server’s Token Endpoint. + +The `WebClientReactiveAuthorizationCodeTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. + +### Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveAuthorizationCodeTokenResponseClient.setParametersConverter()` with a custom `Converter>`. +The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard [OAuth 2.0 Access Token Request](https://tools.ietf.org/html/rfc6749#section-4.1.3) which is used to construct the request. Other parameters required by the Authorization Code grant are added directly to the body of the request by the `WebClientReactiveAuthorizationCodeTokenResponseClient`. +However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s). + +| |If you prefer to only add additional parameters, you can instead provide `WebClientReactiveAuthorizationCodeTokenResponseClient.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +| |The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------| + +### Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveAuthorizationCodeTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. +The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. + +### Customizing the `WebClient` + +Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveAuthorizationCodeTokenResponseClient.setWebClient()` with a custom configured `WebClient`. + +Whether you customize `WebClientReactiveAuthorizationCodeTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example: + +Example 2. Access Token Response Configuration + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2ClientSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .oauth2Client(oauth2 -> oauth2 + .authenticationManager(this.authorizationCodeAuthenticationManager()) + ... + ); + return http.build(); + } + + private ReactiveAuthenticationManager authorizationCodeAuthenticationManager() { + WebClientReactiveAuthorizationCodeTokenResponseClient accessTokenResponseClient = + new WebClientReactiveAuthorizationCodeTokenResponseClient(); + ... + + return new OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2ClientSecurityConfig { + + @Bean + fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + oauth2Client { + authenticationManager = authorizationCodeAuthenticationManager() + } + } + } + + private fun authorizationCodeAuthenticationManager(): ReactiveAuthenticationManager { + val accessTokenResponseClient = WebClientReactiveAuthorizationCodeTokenResponseClient() + ... + + return OAuth2AuthorizationCodeReactiveAuthenticationManager(accessTokenResponseClient) + } +} +``` + +## Refresh Token + +| |Please refer to the OAuth 2.0 Authorization Framework for further details on the [Refresh Token](https://tools.ietf.org/html/rfc6749#section-1.5).| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------| + +### Refreshing an Access Token + +| |Please refer to the [Access Token Request/Response](https://tools.ietf.org/html/rfc6749#section-6) protocol flow for the Refresh Token grant.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------| + +The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the Refresh Token grant is `WebClientReactiveRefreshTokenTokenResponseClient`, which uses a `WebClient` when refreshing an access token at the Authorization Server’s Token Endpoint. + +The `WebClientReactiveRefreshTokenTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. + +### Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveRefreshTokenTokenResponseClient.setParametersConverter()` with a custom `Converter>`. +The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard [OAuth 2.0 Access Token Request](https://tools.ietf.org/html/rfc6749#section-6) which is used to construct the request. Other parameters required by the Refresh Token grant are added directly to the body of the request by the `WebClientReactiveRefreshTokenTokenResponseClient`. +However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s). + +| |If you prefer to only add additional parameters, you can instead provide `WebClientReactiveRefreshTokenTokenResponseClient.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +| |The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------| + +### Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveRefreshTokenTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. +The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. + +### Customizing the `WebClient` + +Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveRefreshTokenTokenResponseClient.setWebClient()` with a custom configured `WebClient`. + +Whether you customize `WebClientReactiveRefreshTokenTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example: + +Example 3. Access Token Response Configuration + +Java + +``` +// Customize +ReactiveOAuth2AccessTokenResponseClient refreshTokenTokenResponseClient = ... + +ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient)) + .build(); + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); +``` + +Kotlin + +``` +// Customize +val refreshTokenTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient = ... + +val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) } + .build() + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) +``` + +| |`ReactiveOAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenReactiveOAuth2AuthorizedClientProvider`,
which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Refresh Token grant.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The `OAuth2RefreshToken` may optionally be returned in the Access Token Response for the `authorization_code` and `password` grant types. +If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2AuthorizedClient.getAccessToken()` is expired, it will automatically be refreshed by the `RefreshTokenReactiveOAuth2AuthorizedClientProvider`. + +## Client Credentials + +| |Please refer to the OAuth 2.0 Authorization Framework for further details on the [Client Credentials](https://tools.ietf.org/html/rfc6749#section-1.3.4) grant.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Requesting an Access Token + +| |Please refer to the [Access Token Request/Response](https://tools.ietf.org/html/rfc6749#section-4.4.2) protocol flow for the Client Credentials grant.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------| + +The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the Client Credentials grant is `WebClientReactiveClientCredentialsTokenResponseClient`, which uses a `WebClient` when requesting an access token at the Authorization Server’s Token Endpoint. + +The `WebClientReactiveClientCredentialsTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. + +### Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveClientCredentialsTokenResponseClient.setParametersConverter()` with a custom `Converter>`. +The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard [OAuth 2.0 Access Token Request](https://tools.ietf.org/html/rfc6749#section-4.4.2) which is used to construct the request. Other parameters required by the Client Credentials grant are added directly to the body of the request by the `WebClientReactiveClientCredentialsTokenResponseClient`. +However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s). + +| |If you prefer to only add additional parameters, you can instead provide `WebClientReactiveClientCredentialsTokenResponseClient.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +| |The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------| + +### Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveClientCredentialsTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. +The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. + +### Customizing the `WebClient` + +Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveClientCredentialsTokenResponseClient.setWebClient()` with a custom configured `WebClient`. + +Whether you customize `WebClientReactiveClientCredentialsTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example: + +Java + +``` +// Customize +ReactiveOAuth2AccessTokenResponseClient clientCredentialsTokenResponseClient = ... + +ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient)) + .build(); + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); +``` + +Kotlin + +``` +// Customize +val clientCredentialsTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient = ... + +val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) } + .build() + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) +``` + +| |`ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsReactiveOAuth2AuthorizedClientProvider`,
which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Client Credentials grant.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Using the Access Token + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + authorization-grant-type: client_credentials + scope: read, write + provider: + okta: + token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token +``` + +…​and the `ReactiveOAuth2AuthorizedClientManager` `@Bean`: + +Java + +``` +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build(); + + DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +``` + +Kotlin + +``` +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build() + val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +``` + +You may obtain the `OAuth2AccessToken` as follows: + +Java + +``` +@Controller +public class OAuth2ClientController { + + @Autowired + private ReactiveOAuth2AuthorizedClientManager authorizedClientManager; + + @GetMapping("/") + public Mono index(Authentication authentication, ServerWebExchange exchange) { + OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(authentication) + .attribute(ServerWebExchange.class.getName(), exchange) + .build(); + + return this.authorizedClientManager.authorize(authorizeRequest) + .map(OAuth2AuthorizedClient::getAccessToken) + ... + .thenReturn("index"); + } +} +``` + +Kotlin + +``` +class OAuth2ClientController { + + @Autowired + private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager + + @GetMapping("/") + fun index(authentication: Authentication, exchange: ServerWebExchange): Mono { + val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(authentication) + .attribute(ServerWebExchange::class.java.name, exchange) + .build() + + return authorizedClientManager.authorize(authorizeRequest) + .map { it.accessToken } + ... + .thenReturn("index") + } +} +``` + +| |`ServerWebExchange` is an OPTIONAL attribute.
If not provided, it will be obtained from the [Reactor’s Context](https://projectreactor.io/docs/core/release/reference/#context) via the key `ServerWebExchange.class`.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## Resource Owner Password Credentials + +| |Please refer to the OAuth 2.0 Authorization Framework for further details on the [Resource Owner Password Credentials](https://tools.ietf.org/html/rfc6749#section-1.3.3) grant.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Requesting an Access Token + +| |Please refer to the [Access Token Request/Response](https://tools.ietf.org/html/rfc6749#section-4.3.2) protocol flow for the Resource Owner Password Credentials grant.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the Resource Owner Password Credentials grant is `WebClientReactivePasswordTokenResponseClient`, which uses a `WebClient` when requesting an access token at the Authorization Server’s Token Endpoint. + +The `WebClientReactivePasswordTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. + +### Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactivePasswordTokenResponseClient.setParametersConverter()` with a custom `Converter>`. +The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard [OAuth 2.0 Access Token Request](https://tools.ietf.org/html/rfc6749#section-4.4.2) which is used to construct the request. Other parameters required by the Resource Owner Password Credentials grant are added directly to the body of the request by the `WebClientReactivePasswordTokenResponseClient`. +However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s). + +| |If you prefer to only add additional parameters, you can instead provide `WebClientReactivePasswordTokenResponseClient.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +| |The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------| + +### Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactivePasswordTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. +The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. + +### Customizing the `WebClient` + +Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactivePasswordTokenResponseClient.setWebClient()` with a custom configured `WebClient`. + +Whether you customize `WebClientReactivePasswordTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example: + +Java + +``` +// Customize +ReactiveOAuth2AccessTokenResponseClient passwordTokenResponseClient = ... + +ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient)) + .refreshToken() + .build(); + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); +``` + +Kotlin + +``` +val passwordTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient = ... + +val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .password { it.accessTokenResponseClient(passwordTokenResponseClient) } + .refreshToken() + .build() + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) +``` + +| |`ReactiveOAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordReactiveOAuth2AuthorizedClientProvider`,
which is an implementation of a `ReactiveOAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Using the Access Token + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + authorization-grant-type: password + scope: read, write + provider: + okta: + token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token +``` + +…​and the `ReactiveOAuth2AuthorizedClientManager` `@Bean`: + +Java + +``` +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build(); + + DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters, + // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()); + + return authorizedClientManager; +} + +private Function>> contextAttributesMapper() { + return authorizeRequest -> { + Map contextAttributes = Collections.emptyMap(); + ServerWebExchange exchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName()); + ServerHttpRequest request = exchange.getRequest(); + String username = request.getQueryParams().getFirst(OAuth2ParameterNames.USERNAME); + String password = request.getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD); + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = new HashMap<>(); + + // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username); + contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password); + } + return Mono.just(contextAttributes); + }; +} +``` + +Kotlin + +``` +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build() + val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + + // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters, + // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()) + return authorizedClientManager +} + +private fun contextAttributesMapper(): Function>> { + return Function { authorizeRequest -> + var contextAttributes: MutableMap = mutableMapOf() + val exchange: ServerWebExchange = authorizeRequest.getAttribute(ServerWebExchange::class.java.name)!! + val request: ServerHttpRequest = exchange.request + val username: String? = request.queryParams.getFirst(OAuth2ParameterNames.USERNAME) + val password: String? = request.queryParams.getFirst(OAuth2ParameterNames.PASSWORD) + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = hashMapOf() + + // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username!! + contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password!! + } + Mono.just(contextAttributes) + } +} +``` + +You may obtain the `OAuth2AccessToken` as follows: + +Java + +``` +@Controller +public class OAuth2ClientController { + + @Autowired + private ReactiveOAuth2AuthorizedClientManager authorizedClientManager; + + @GetMapping("/") + public Mono index(Authentication authentication, ServerWebExchange exchange) { + OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(authentication) + .attribute(ServerWebExchange.class.getName(), exchange) + .build(); + + return this.authorizedClientManager.authorize(authorizeRequest) + .map(OAuth2AuthorizedClient::getAccessToken) + ... + .thenReturn("index"); + } +} +``` + +Kotlin + +``` +@Controller +class OAuth2ClientController { + @Autowired + private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager + + @GetMapping("/") + fun index(authentication: Authentication, exchange: ServerWebExchange): Mono { + val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(authentication) + .attribute(ServerWebExchange::class.java.name, exchange) + .build() + + return authorizedClientManager.authorize(authorizeRequest) + .map { it.accessToken } + ... + .thenReturn("index") + } +} +``` + +| |`ServerWebExchange` is an OPTIONAL attribute.
If not provided, it will be obtained from the [Reactor’s Context](https://projectreactor.io/docs/core/release/reference/#context) via the key `ServerWebExchange.class`.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## JWT Bearer + +| |Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on the [JWT Bearer](https://datatracker.ietf.org/doc/html/rfc7523) grant.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Requesting an Access Token + +| |Please refer to the [Access Token Request/Response](https://datatracker.ietf.org/doc/html/rfc7523#section-2.1) protocol flow for the JWT Bearer grant.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------| + +The default implementation of `ReactiveOAuth2AccessTokenResponseClient` for the JWT Bearer grant is `WebClientReactiveJwtBearerTokenResponseClient`, which uses a `WebClient` when requesting an access token at the Authorization Server’s Token Endpoint. + +The `WebClientReactiveJwtBearerTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. + +### Customizing the Access Token Request + +If you need to customize the pre-processing of the Token Request, you can provide `WebClientReactiveJwtBearerTokenResponseClient.setParametersConverter()` with a custom `Converter>`. +The default implementation builds a `MultiValueMap` containing only the `grant_type` parameter of a standard [OAuth 2.0 Access Token Request](https://tools.ietf.org/html/rfc6749#section-4.4.2) which is used to construct the request. Other parameters required by the JWT Bearer grant are added directly to the body of the request by the `WebClientReactiveJwtBearerTokenResponseClient`. +However, providing a custom `Converter`, would allow you to extend the standard Token Request and add custom parameter(s). + +| |If you prefer to only add additional parameters, you can instead provide `WebClientReactiveJwtBearerTokenResponseClient.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +| |The custom `Converter` must return valid parameters of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------| + +### Customizing the Access Token Response + +On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `WebClientReactiveJwtBearerTokenResponseClient.setBodyExtractor()` with a custom configured `BodyExtractor, ReactiveHttpInputMessage>` that is used for converting the OAuth 2.0 Access Token Response to an `OAuth2AccessTokenResponse`. +The default implementation provided by `OAuth2BodyExtractors.oauth2AccessTokenResponse()` parses the response and handles errors accordingly. + +### Customizing the `WebClient` + +Alternatively, if your requirements are more advanced, you can take full control of the request/response by simply providing `WebClientReactiveJwtBearerTokenResponseClient.setWebClient()` with a custom configured `WebClient`. + +Whether you customize `WebClientReactiveJwtBearerTokenResponseClient` or provide your own implementation of `ReactiveOAuth2AccessTokenResponseClient`, you’ll need to configure it as shown in the following example: + +Java + +``` +// Customize +ReactiveOAuth2AccessTokenResponseClient jwtBearerTokenResponseClient = ... + +JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerReactiveOAuth2AuthorizedClientProvider(); +jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient); + +ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .provider(jwtBearerAuthorizedClientProvider) + .build(); + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); +``` + +Kotlin + +``` +// Customize +val jwtBearerTokenResponseClient: ReactiveOAuth2AccessTokenResponseClient = ... + +val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider() +jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient) + +val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .provider(jwtBearerAuthorizedClientProvider) + .build() + +... + +authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) +``` + +### Using the Access Token + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer + scope: read + provider: + okta: + token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token +``` + +…​and the `OAuth2AuthorizedClientManager` `@Bean`: + +Java + +``` +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { + + JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = + new JwtBearerReactiveOAuth2AuthorizedClientProvider(); + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .provider(jwtBearerAuthorizedClientProvider) + .build(); + + DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +``` + +Kotlin + +``` +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { + val jwtBearerAuthorizedClientProvider = JwtBearerReactiveOAuth2AuthorizedClientProvider() + val authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .provider(jwtBearerAuthorizedClientProvider) + .build() + val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +``` + +You may obtain the `OAuth2AccessToken` as follows: + +Java + +``` +@RestController +public class OAuth2ResourceServerController { + + @Autowired + private ReactiveOAuth2AuthorizedClientManager authorizedClientManager; + + @GetMapping("/resource") + public Mono resource(JwtAuthenticationToken jwtAuthentication, ServerWebExchange exchange) { + OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(jwtAuthentication) + .build(); + + return this.authorizedClientManager.authorize(authorizeRequest) + .map(OAuth2AuthorizedClient::getAccessToken) + ... + } +} +``` + +Kotlin + +``` +class OAuth2ResourceServerController { + + @Autowired + private lateinit var authorizedClientManager: ReactiveOAuth2AuthorizedClientManager + + @GetMapping("/resource") + fun resource(jwtAuthentication: JwtAuthenticationToken, exchange: ServerWebExchange): Mono { + val authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta") + .principal(jwtAuthentication) + .build() + return authorizedClientManager.authorize(authorizeRequest) + .map { it.accessToken } + ... + } +} +``` + +[Core Interfaces and Classes](core.html)[OAuth2 Client Authentication](client-authentication.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-oauth2-client-authorized-clients.md b/docs/en/spring-security/reactive-oauth2-client-authorized-clients.md new file mode 100644 index 0000000000000000000000000000000000000000..7226dac931ec4d513ffb388a366afc1b92195539 --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-client-authorized-clients.md @@ -0,0 +1,241 @@ +# Authorized Clients + +## Resolving an Authorized Client + +The `@RegisteredOAuth2AuthorizedClient` annotation provides the capability of resolving a method parameter to an argument value of type `OAuth2AuthorizedClient`. +This is a convenient alternative compared to accessing the `OAuth2AuthorizedClient` using the `ReactiveOAuth2AuthorizedClientManager` or `ReactiveOAuth2AuthorizedClientService`. + +Java + +``` +@Controller +public class OAuth2ClientController { + + @GetMapping("/") + public Mono index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { + return Mono.just(authorizedClient.getAccessToken()) + ... + .thenReturn("index"); + } +} +``` + +Kotlin + +``` +@Controller +class OAuth2ClientController { + @GetMapping("/") + fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): Mono { + return Mono.just(authorizedClient.accessToken) + ... + .thenReturn("index") + } +} +``` + +The `@RegisteredOAuth2AuthorizedClient` annotation is handled by `OAuth2AuthorizedClientArgumentResolver`, which directly uses a [ReactiveOAuth2AuthorizedClientManager](#oauth2Client-authorized-manager-provider) and therefore inherits it’s capabilities. + +## WebClient integration for Reactive Environments + +The OAuth 2.0 Client support integrates with `WebClient` using an `ExchangeFilterFunction`. + +The `ServerOAuth2AuthorizedClientExchangeFilterFunction` provides a simple mechanism for requesting protected resources by using an `OAuth2AuthorizedClient` and including the associated `OAuth2AccessToken` as a Bearer Token. +It directly uses an [ReactiveOAuth2AuthorizedClientManager](#oauth2Client-authorized-manager-provider) and therefore inherits the following capabilities: + +* An `OAuth2AccessToken` will be requested if the client has not yet been authorized. + + * `authorization_code` - triggers the Authorization Request redirect to initiate the flow + + * `client_credentials` - the access token is obtained directly from the Token Endpoint + + * `password` - the access token is obtained directly from the Token Endpoint + +* If the `OAuth2AccessToken` is expired, it will be refreshed (or renewed) if a `ReactiveOAuth2AuthorizedClientProvider` is available to perform the authorization + +The following code shows an example of how to configure `WebClient` with OAuth 2.0 Client support: + +Java + +``` +@Bean +WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + return WebClient.builder() + .filter(oauth2Client) + .build(); +} +``` + +Kotlin + +``` +@Bean +fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { + val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + return WebClient.builder() + .filter(oauth2Client) + .build() +} +``` + +### Providing the Authorized Client + +The `ServerOAuth2AuthorizedClientExchangeFilterFunction` determines the client to use (for a request) by resolving the `OAuth2AuthorizedClient` from the `ClientRequest.attributes()` (request attributes). + +The following code shows how to set an `OAuth2AuthorizedClient` as a request attribute: + +Java + +``` +@GetMapping("/") +public Mono index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { + String resourceUri = ... + + return webClient + .get() + .uri(resourceUri) + .attributes(oauth2AuthorizedClient(authorizedClient)) (1) + .retrieve() + .bodyToMono(String.class) + ... + .thenReturn("index"); +} +``` + +Kotlin + +``` +@GetMapping("/") +fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): Mono { + val resourceUri: String = ... + + return webClient + .get() + .uri(resourceUri) + .attributes(oauth2AuthorizedClient(authorizedClient)) (1) + .retrieve() + .bodyToMono() + ... + .thenReturn("index") +} +``` + +|**1**|`oauth2AuthorizedClient()` is a `static` method in `ServerOAuth2AuthorizedClientExchangeFilterFunction`.| +|-----|--------------------------------------------------------------------------------------------------------| + +The following code shows how to set the `ClientRegistration.getRegistrationId()` as a request attribute: + +Java + +``` +@GetMapping("/") +public Mono index() { + String resourceUri = ... + + return webClient + .get() + .uri(resourceUri) + .attributes(clientRegistrationId("okta")) (1) + .retrieve() + .bodyToMono(String.class) + ... + .thenReturn("index"); +} +``` + +Kotlin + +``` +@GetMapping("/") +fun index(): Mono { + val resourceUri: String = ... + + return webClient + .get() + .uri(resourceUri) + .attributes(clientRegistrationId("okta")) (1) + .retrieve() + .bodyToMono() + ... + .thenReturn("index") +} +``` + +|**1**|`clientRegistrationId()` is a `static` method in `ServerOAuth2AuthorizedClientExchangeFilterFunction`.| +|-----|------------------------------------------------------------------------------------------------------| + +### Defaulting the Authorized Client + +If neither `OAuth2AuthorizedClient` or `ClientRegistration.getRegistrationId()` is provided as a request attribute, the `ServerOAuth2AuthorizedClientExchangeFilterFunction` can determine the *default* client to use depending on it’s configuration. + +If `setDefaultOAuth2AuthorizedClient(true)` is configured and the user has authenticated using `ServerHttpSecurity.oauth2Login()`, the `OAuth2AccessToken` associated with the current `OAuth2AuthenticationToken` is used. + +The following code shows the specific configuration: + +Java + +``` +@Bean +WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + oauth2Client.setDefaultOAuth2AuthorizedClient(true); + return WebClient.builder() + .filter(oauth2Client) + .build(); +} +``` + +Kotlin + +``` +@Bean +fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { + val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + oauth2Client.setDefaultOAuth2AuthorizedClient(true) + return WebClient.builder() + .filter(oauth2Client) + .build() +} +``` + +| |It is recommended to be cautious with this feature since all HTTP requests will receive the access token.| +|---|---------------------------------------------------------------------------------------------------------| + +Alternatively, if `setDefaultClientRegistrationId("okta")` is configured with a valid `ClientRegistration`, the `OAuth2AccessToken` associated with the `OAuth2AuthorizedClient` is used. + +The following code shows the specific configuration: + +Java + +``` +@Bean +WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + oauth2Client.setDefaultClientRegistrationId("okta"); + return WebClient.builder() + .filter(oauth2Client) + .build(); +} +``` + +Kotlin + +``` +@Bean +fun webClient(authorizedClientManager: ReactiveOAuth2AuthorizedClientManager): WebClient { + val oauth2Client = ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + oauth2Client.setDefaultClientRegistrationId("okta") + return WebClient.builder() + .filter(oauth2Client) + .build() +} +``` + +| |It is recommended to be cautious with this feature since all HTTP requests will receive the access token.| +|---|---------------------------------------------------------------------------------------------------------| + +[OAuth2 Client Authentication](client-authentication.html)[OAuth2 Resource Server](../resource-server/index.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-oauth2-client-client-authentication.md b/docs/en/spring-security/reactive-oauth2-client-client-authentication.md new file mode 100644 index 0000000000000000000000000000000000000000..55a58ecc19bb90bd01bd4a2604596f45ce37c5cd --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-client-client-authentication.md @@ -0,0 +1,142 @@ +# Client Authentication Support + +## JWT Bearer + +| |Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on [JWT Bearer](https://datatracker.ietf.org/doc/html/rfc7523#section-2.2) Client Authentication.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The default implementation for JWT Bearer Client Authentication is `NimbusJwtClientAuthenticationParametersConverter`, +which is a `Converter` that customizes the Token Request parameters by adding +a signed JSON Web Token (JWS) in the `client_assertion` parameter. + +The `java.security.PrivateKey` or `javax.crypto.SecretKey` used for signing the JWS +is supplied by the `com.nimbusds.jose.jwk.JWK` resolver associated with `NimbusJwtClientAuthenticationParametersConverter`. + +### Authenticate using `private_key_jwt` + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-authentication-method: private_key_jwt + authorization-grant-type: authorization_code + ... +``` + +The following example shows how to configure `WebClientReactiveAuthorizationCodeTokenResponseClient`: + +Java + +``` +Function jwkResolver = (clientRegistration) -> { + if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { + // Assuming RSA key type + RSAPublicKey publicKey = ... + RSAPrivateKey privateKey = ... + return new RSAKey.Builder(publicKey) + .privateKey(privateKey) + .keyID(UUID.randomUUID().toString()) + .build(); + } + return null; +}; + +WebClientReactiveAuthorizationCodeTokenResponseClient tokenResponseClient = + new WebClientReactiveAuthorizationCodeTokenResponseClient(); +tokenResponseClient.addParametersConverter( + new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); +``` + +Kotlin + +``` +val jwkResolver: Function = + Function { clientRegistration -> + if (clientRegistration.clientAuthenticationMethod.equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { + // Assuming RSA key type + var publicKey: RSAPublicKey = ... + var privateKey: RSAPrivateKey = ... + RSAKey.Builder(publicKey) + .privateKey(privateKey) + .keyID(UUID.randomUUID().toString()) + .build() + } + null + } + +val tokenResponseClient = WebClientReactiveAuthorizationCodeTokenResponseClient() +tokenResponseClient.addParametersConverter( + NimbusJwtClientAuthenticationParametersConverter(jwkResolver) +) +``` + +### Authenticate using `client_secret_jwt` + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + client-authentication-method: client_secret_jwt + authorization-grant-type: client_credentials + ... +``` + +The following example shows how to configure `WebClientReactiveClientCredentialsTokenResponseClient`: + +Java + +``` +Function jwkResolver = (clientRegistration) -> { + if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_JWT)) { + SecretKeySpec secretKey = new SecretKeySpec( + clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), + "HmacSHA256"); + return new OctetSequenceKey.Builder(secretKey) + .keyID(UUID.randomUUID().toString()) + .build(); + } + return null; +}; + +WebClientReactiveClientCredentialsTokenResponseClient tokenResponseClient = + new WebClientReactiveClientCredentialsTokenResponseClient(); +tokenResponseClient.addParametersConverter( + new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); +``` + +Kotlin + +``` +val jwkResolver = Function { clientRegistration: ClientRegistration -> + if (clientRegistration.clientAuthenticationMethod == ClientAuthenticationMethod.CLIENT_SECRET_JWT) { + val secretKey = SecretKeySpec( + clientRegistration.clientSecret.toByteArray(StandardCharsets.UTF_8), + "HmacSHA256" + ) + OctetSequenceKey.Builder(secretKey) + .keyID(UUID.randomUUID().toString()) + .build() + } + null +} + +val tokenResponseClient = WebClientReactiveClientCredentialsTokenResponseClient() +tokenResponseClient.addParametersConverter( + NimbusJwtClientAuthenticationParametersConverter(jwkResolver) +) +``` + +[OAuth2 Authorization Grants](authorization-grants.html)[OAuth2 Authorized Clients](authorized-clients.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-oauth2-client-core.md b/docs/en/spring-security/reactive-oauth2-client-core.md new file mode 100644 index 0000000000000000000000000000000000000000..438c5879bd47f8fb4f8b9554984ff71e16d36d3e --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-client-core.md @@ -0,0 +1,405 @@ +# Core Interfaces / Classes + +## ClientRegistration + +`ClientRegistration` is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. + +A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details. + +`ClientRegistration` and its properties are defined as follows: + +``` +public final class ClientRegistration { + private String registrationId; (1) + private String clientId; (2) + private String clientSecret; (3) + private ClientAuthenticationMethod clientAuthenticationMethod; (4) + private AuthorizationGrantType authorizationGrantType; (5) + private String redirectUri; (6) + private Set scopes; (7) + private ProviderDetails providerDetails; + private String clientName; (8) + + public class ProviderDetails { + private String authorizationUri; (9) + private String tokenUri; (10) + private UserInfoEndpoint userInfoEndpoint; + private String jwkSetUri; (11) + private String issuerUri; (12) + private Map configurationMetadata; (13) + + public class UserInfoEndpoint { + private String uri; (14) + private AuthenticationMethod authenticationMethod; (15) + private String userNameAttributeName; (16) + + } + } +} +``` + +|**1** | `registrationId`: The ID that uniquely identifies the `ClientRegistration`. | +|------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2** | `clientId`: The client identifier. | +|**3** | `clientSecret`: The client secret. | +|**4** | `clientAuthenticationMethod`: The method used to authenticate the Client with the Provider.
The supported values are **client\_secret\_basic**, **client\_secret\_post**, **private\_key\_jwt**, **client\_secret\_jwt** and **none** [(public clients)](https://tools.ietf.org/html/rfc6749#section-2.1). | +|**5** |`authorizationGrantType`: The OAuth 2.0 Authorization Framework defines four [Authorization Grant](https://tools.ietf.org/html/rfc6749#section-1.3) types.
The supported values are `authorization_code`, `client_credentials`, `password`, as well as, extension grant type `urn:ietf:params:oauth:grant-type:jwt-bearer`.| +|**6** | `redirectUri`: The client’s registered redirect URI that the *Authorization Server* redirects the end-user’s user-agent
to after the end-user has authenticated and authorized access to the client. | +|**7** | `scopes`: The scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile. | +|**8** | `clientName`: A descriptive name used for the client.
The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page. | +|**9** | `authorizationUri`: The Authorization Endpoint URI for the Authorization Server. | +|**10**| `tokenUri`: The Token Endpoint URI for the Authorization Server. | +|**11**| `jwkSetUri`: The URI used to retrieve the [JSON Web Key (JWK)](https://tools.ietf.org/html/rfc7517) Set from the Authorization Server,
which contains the cryptographic key(s) used to verify the [JSON Web Signature (JWS)](https://tools.ietf.org/html/rfc7515) of the ID Token and optionally the UserInfo Response. | +|**12**| `issuerUri`: Returns the issuer identifier uri for the OpenID Connect 1.0 provider or the OAuth 2.0 Authorization Server. | +|**13**| `configurationMetadata`: The [OpenID Provider Configuration Information](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig).
This information will only be available if the Spring Boot 2.x property `spring.security.oauth2.client.provider.[providerId].issuerUri` is configured. | +|**14**| `(userInfoEndpoint)uri`: The UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user. | +|**15**| `(userInfoEndpoint)authenticationMethod`: The authentication method used when sending the access token to the UserInfo Endpoint.
The supported values are **header**, **form** and **query**. | +|**16**| `userNameAttributeName`: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user. | + +A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider’s [Configuration endpoint](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) or an Authorization Server’s [Metadata endpoint](https://tools.ietf.org/html/rfc8414#section-3). + +`ClientRegistrations` provides convenience methods for configuring a `ClientRegistration` in this way, as can be seen in the following example: + +Java + +``` +ClientRegistration clientRegistration = + ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build(); +``` + +Kotlin + +``` +val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build() +``` + +The above code will query in series `[https://idp.example.com/issuer/.well-known/openid-configuration](https://idp.example.com/issuer/.well-known/openid-configuration)`, and then `[https://idp.example.com/.well-known/openid-configuration/issuer](https://idp.example.com/.well-known/openid-configuration/issuer)`, and finally `[https://idp.example.com/.well-known/oauth-authorization-server/issuer](https://idp.example.com/.well-known/oauth-authorization-server/issuer)`, stopping at the first to return a 200 response. + +As an alternative, you can use `ClientRegistrations.fromOidcIssuerLocation()` to only query the OpenID Connect Provider’s Configuration endpoint. + +## ReactiveClientRegistrationRepository + +The `ReactiveClientRegistrationRepository` serves as a repository for OAuth 2.0 / OpenID Connect 1.0 `ClientRegistration`(s). + +| |Client registration information is ultimately stored and owned by the associated Authorization Server.
This repository provides the ability to retrieve a sub-set of the primary client registration information, which is stored with the Authorization Server.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Spring Boot 2.x auto-configuration binds each of the properties under `spring.security.oauth2.client.registration.*[registrationId]*` to an instance of `ClientRegistration` and then composes each of the `ClientRegistration` instance(s) within a `ReactiveClientRegistrationRepository`. + +| |The default implementation of `ReactiveClientRegistrationRepository` is `InMemoryReactiveClientRegistrationRepository`.| +|---|-----------------------------------------------------------------------------------------------------------------------| + +The auto-configuration also registers the `ReactiveClientRegistrationRepository` as a `@Bean` in the `ApplicationContext` so that it is available for dependency-injection, if needed by the application. + +The following listing shows an example: + +Java + +``` +@Controller +public class OAuth2ClientController { + + @Autowired + private ReactiveClientRegistrationRepository clientRegistrationRepository; + + @GetMapping("/") + public Mono index() { + return this.clientRegistrationRepository.findByRegistrationId("okta") + ... + .thenReturn("index"); + } +} +``` + +Kotlin + +``` +@Controller +class OAuth2ClientController { + + @Autowired + private lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository + + @GetMapping("/") + fun index(): Mono { + return this.clientRegistrationRepository.findByRegistrationId("okta") + ... + .thenReturn("index") + } +} +``` + +## OAuth2AuthorizedClient + +`OAuth2AuthorizedClient` is a representation of an Authorized Client. +A client is considered to be authorized when the end-user (Resource Owner) has granted authorization to the client to access its protected resources. + +`OAuth2AuthorizedClient` serves the purpose of associating an `OAuth2AccessToken` (and optional `OAuth2RefreshToken`) to a `ClientRegistration` (client) and resource owner, who is the `Principal` end-user that granted the authorization. + +## ServerOAuth2AuthorizedClientRepository / ReactiveOAuth2AuthorizedClientService + +`ServerOAuth2AuthorizedClientRepository` is responsible for persisting `OAuth2AuthorizedClient`(s) between web requests. +Whereas, the primary role of `ReactiveOAuth2AuthorizedClientService` is to manage `OAuth2AuthorizedClient`(s) at the application-level. + +From a developer perspective, the `ServerOAuth2AuthorizedClientRepository` or `ReactiveOAuth2AuthorizedClientService` provides the capability to lookup an `OAuth2AccessToken` associated with a client so that it may be used to initiate a protected resource request. + +The following listing shows an example: + +Java + +``` +@Controller +public class OAuth2ClientController { + + @Autowired + private ReactiveOAuth2AuthorizedClientService authorizedClientService; + + @GetMapping("/") + public Mono index(Authentication authentication) { + return this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()) + .map(OAuth2AuthorizedClient::getAccessToken) + ... + .thenReturn("index"); + } +} +``` + +Kotlin + +``` +@Controller +class OAuth2ClientController { + + @Autowired + private lateinit var authorizedClientService: ReactiveOAuth2AuthorizedClientService + + @GetMapping("/") + fun index(authentication: Authentication): Mono { + return this.authorizedClientService.loadAuthorizedClient("okta", authentication.name) + .map { it.accessToken } + ... + .thenReturn("index") + } +} +``` + +| |Spring Boot 2.x auto-configuration registers an `ServerOAuth2AuthorizedClientRepository` and/or `ReactiveOAuth2AuthorizedClientService` `@Bean` in the `ApplicationContext`.
However, the application may choose to override and register a custom `ServerOAuth2AuthorizedClientRepository` or `ReactiveOAuth2AuthorizedClientService` `@Bean`.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The default implementation of `ReactiveOAuth2AuthorizedClientService` is `InMemoryReactiveOAuth2AuthorizedClientService`, which stores `OAuth2AuthorizedClient`(s) in-memory. + +Alternatively, the R2DBC implementation `R2dbcReactiveOAuth2AuthorizedClientService` may be configured for persisting `OAuth2AuthorizedClient`(s) in a database. + +| |`R2dbcReactiveOAuth2AuthorizedClientService` depends on the table definition described in [ OAuth 2.0 Client Schema](../../../servlet/appendix/database-schema.html#dbschema-oauth2-client).| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## ReactiveOAuth2AuthorizedClientManager / ReactiveOAuth2AuthorizedClientProvider + +The `ReactiveOAuth2AuthorizedClientManager` is responsible for the overall management of `OAuth2AuthorizedClient`(s). + +The primary responsibilities include: + +* Authorizing (or re-authorizing) an OAuth 2.0 Client, using a `ReactiveOAuth2AuthorizedClientProvider`. + +* Delegating the persistence of an `OAuth2AuthorizedClient`, typically using a `ReactiveOAuth2AuthorizedClientService` or `ServerOAuth2AuthorizedClientRepository`. + +* Delegating to a `ReactiveOAuth2AuthorizationSuccessHandler` when an OAuth 2.0 Client has been successfully authorized (or re-authorized). + +* Delegating to a `ReactiveOAuth2AuthorizationFailureHandler` when an OAuth 2.0 Client fails to authorize (or re-authorize). + +A `ReactiveOAuth2AuthorizedClientProvider` implements a strategy for authorizing (or re-authorizing) an OAuth 2.0 Client. +Implementations will typically implement an authorization grant type, eg. `authorization_code`, `client_credentials`, etc. + +The default implementation of `ReactiveOAuth2AuthorizedClientManager` is `DefaultReactiveOAuth2AuthorizedClientManager`, which is associated with a `ReactiveOAuth2AuthorizedClientProvider` that may support multiple authorization grant types using a delegation-based composite. +The `ReactiveOAuth2AuthorizedClientProviderBuilder` may be used to configure and build the delegation-based composite. + +The following code shows an example of how to configure and build a `ReactiveOAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: + +Java + +``` +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build(); + + DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +``` + +Kotlin + +``` +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build() + val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +``` + +When an authorization attempt succeeds, the `DefaultReactiveOAuth2AuthorizedClientManager` will delegate to the `ReactiveOAuth2AuthorizationSuccessHandler`, which (by default) will save the `OAuth2AuthorizedClient` via the `ServerOAuth2AuthorizedClientRepository`. +In the case of a re-authorization failure, eg. a refresh token is no longer valid, the previously saved `OAuth2AuthorizedClient` will be removed from the `ServerOAuth2AuthorizedClientRepository` via the `RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler`. +The default behaviour may be customized via `setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler)` and `setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler)`. + +The `DefaultReactiveOAuth2AuthorizedClientManager` is also associated with a `contextAttributesMapper` of type `Function>>`, which is responsible for mapping attribute(s) from the `OAuth2AuthorizeRequest` to a `Map` of attributes to be associated to the `OAuth2AuthorizationContext`. +This can be useful when you need to supply a `ReactiveOAuth2AuthorizedClientProvider` with required (supported) attribute(s), eg. the `PasswordReactiveOAuth2AuthorizedClientProvider` requires the resource owner’s `username` and `password` to be available in `OAuth2AuthorizationContext.getAttributes()`. + +The following code shows an example of the `contextAttributesMapper`: + +Java + +``` +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build(); + + DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters, + // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()); + + return authorizedClientManager; +} + +private Function>> contextAttributesMapper() { + return authorizeRequest -> { + Map contextAttributes = Collections.emptyMap(); + ServerWebExchange exchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName()); + ServerHttpRequest request = exchange.getRequest(); + String username = request.getQueryParams().getFirst(OAuth2ParameterNames.USERNAME); + String password = request.getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD); + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = new HashMap<>(); + + // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username); + contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password); + } + return Mono.just(contextAttributes); + }; +} +``` + +Kotlin + +``` +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .password() + .refreshToken() + .build() + val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + + // Assuming the `username` and `password` are supplied as `ServerHttpRequest` parameters, + // map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()` + authorizedClientManager.setContextAttributesMapper(contextAttributesMapper()) + return authorizedClientManager +} + +private fun contextAttributesMapper(): Function>> { + return Function { authorizeRequest -> + var contextAttributes: MutableMap = mutableMapOf() + val exchange: ServerWebExchange = authorizeRequest.getAttribute(ServerWebExchange::class.java.name)!! + val request: ServerHttpRequest = exchange.request + val username: String? = request.queryParams.getFirst(OAuth2ParameterNames.USERNAME) + val password: String? = request.queryParams.getFirst(OAuth2ParameterNames.PASSWORD) + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + contextAttributes = hashMapOf() + + // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes + contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username!! + contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password!! + } + Mono.just(contextAttributes) + } +} +``` + +The `DefaultReactiveOAuth2AuthorizedClientManager` is designed to be used ***within*** the context of a `ServerWebExchange`. +When operating ***outside*** of a `ServerWebExchange` context, use `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager` instead. + +A *service application* is a common use case for when to use an `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager`. +Service applications often run in the background, without any user interaction, and typically run under a system-level account instead of a user account. +An OAuth 2.0 Client configured with the `client_credentials` grant type can be considered a type of service application. + +The following code shows an example of how to configure an `AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager` that provides support for the `client_credentials` grant type: + +Java + +``` +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ReactiveOAuth2AuthorizedClientService authorizedClientService) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build(); + + AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientService); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +``` + +Kotlin + +``` +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientService: ReactiveOAuth2AuthorizedClientService): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build() + val authorizedClientManager = AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientService) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +``` + +[OAuth2 Client](index.html)[OAuth2 Authorization Grants](authorization-grants.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-oauth2-client.md b/docs/en/spring-security/reactive-oauth2-client.md new file mode 100644 index 0000000000000000000000000000000000000000..5d71df7b0d6d9b202ad6b55165179a17f8ac68ae --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-client.md @@ -0,0 +1,132 @@ +# OAuth 2.0 Client + +The OAuth 2.0 Client features provide support for the Client role as defined in the [OAuth 2.0 Authorization Framework](https://tools.ietf.org/html/rfc6749#section-1.1). + +At a high-level, the core features available are: + +Authorization Grant support + +* [Authorization Code](https://tools.ietf.org/html/rfc6749#section-1.3.1) + +* [Refresh Token](https://tools.ietf.org/html/rfc6749#section-6) + +* [Client Credentials](https://tools.ietf.org/html/rfc6749#section-1.3.4) + +* [Resource Owner Password Credentials](https://tools.ietf.org/html/rfc6749#section-1.3.3) + +* [JWT Bearer](https://datatracker.ietf.org/doc/html/rfc7523#section-2.1) + +Client Authentication support + +* [JWT Bearer](https://datatracker.ietf.org/doc/html/rfc7523#section-2.2) + +HTTP Client support + +* [`WebClient` integration for Reactive Environments](#oauth2Client-webclient-webflux) (for requesting protected resources) + +The `ServerHttpSecurity.oauth2Client()` DSL provides a number of configuration options for customizing the core components used by OAuth 2.0 Client. + +The following code shows the complete configuration options provided by the `ServerHttpSecurity.oauth2Client()` DSL: + +Example 1. OAuth2 Client Configuration Options + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2ClientSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .oauth2Client(oauth2 -> oauth2 + .clientRegistrationRepository(this.clientRegistrationRepository()) + .authorizedClientRepository(this.authorizedClientRepository()) + .authorizationRequestRepository(this.authorizationRequestRepository()) + .authenticationConverter(this.authenticationConverter()) + .authenticationManager(this.authenticationManager()) + ); + + return http.build(); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2ClientSecurityConfig { + + @Bean + fun securityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + oauth2Client { + clientRegistrationRepository = clientRegistrationRepository() + authorizedClientRepository = authorizedClientRepository() + authorizationRequestRepository = authorizedRequestRepository() + authenticationConverter = authenticationConverter() + authenticationManager = authenticationManager() + } + } + } +} +``` + +The `ReactiveOAuth2AuthorizedClientManager` is responsible for managing the authorization (or re-authorization) of an OAuth 2.0 Client, in collaboration with one or more `ReactiveOAuth2AuthorizedClientProvider`(s). + +The following code shows an example of how to register a `ReactiveOAuth2AuthorizedClientManager` `@Bean` and associate it with a `ReactiveOAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: + +Java + +``` +@Bean +public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( + ReactiveClientRegistrationRepository clientRegistrationRepository, + ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { + + ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = + ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build(); + + DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +``` + +Kotlin + +``` +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ReactiveClientRegistrationRepository, + authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { + val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build() + val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +``` + +## Section Summary + +* [Core Interfaces and Classes](core.html) +* [OAuth2 Authorization Grants](authorization-grants.html) +* [OAuth2 Client Authentication](client-authentication.html) +* [OAuth2 Authorized Clients](authorized-clients.html) + +[Advanced Configuration](../login/advanced.html)[Core Interfaces and Classes](core.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-oauth2-login-advanced.md b/docs/en/spring-security/reactive-oauth2-login-advanced.md new file mode 100644 index 0000000000000000000000000000000000000000..c8f2d0ca689e5a2f510630d00c17d4bb399eefae --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-login-advanced.md @@ -0,0 +1,682 @@ +# Advanced Configuration + +The OAuth 2.0 Authorization Framework defines the [Protocol Endpoints](https://tools.ietf.org/html/rfc6749#section-3) as follows: + +The authorization process utilizes two authorization server endpoints (HTTP resources): + +* Authorization Endpoint: Used by the client to obtain authorization from the resource owner via user-agent redirection. + +* Token Endpoint: Used by the client to exchange an authorization grant for an access token, typically with client authentication. + +As well as one client endpoint: + +* Redirection Endpoint: Used by the authorization server to return responses containing authorization credentials to the client via the resource owner user-agent. + +The OpenID Connect Core 1.0 specification defines the [UserInfo Endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) as follows: + +The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns claims about the authenticated end-user. +To obtain the requested claims about the end-user, the client makes a request to the UserInfo Endpoint by using an access token obtained through OpenID Connect Authentication. +These claims are normally represented by a JSON object that contains a collection of name-value pairs for the claims. + +`ServerHttpSecurity.oauth2Login()` provides a number of configuration options for customizing OAuth 2.0 Login. + +The following code shows the complete configuration options available for the `oauth2Login()` DSL: + +Example 1. OAuth2 Login Configuration Options + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .oauth2Login(oauth2 -> oauth2 + .authenticationConverter(this.authenticationConverter()) + .authenticationMatcher(this.authenticationMatcher()) + .authenticationManager(this.authenticationManager()) + .authenticationSuccessHandler(this.authenticationSuccessHandler()) + .authenticationFailureHandler(this.authenticationFailureHandler()) + .clientRegistrationRepository(this.clientRegistrationRepository()) + .authorizedClientRepository(this.authorizedClientRepository()) + .authorizedClientService(this.authorizedClientService()) + .authorizationRequestResolver(this.authorizationRequestResolver()) + .authorizationRequestRepository(this.authorizationRequestRepository()) + .securityContextRepository(this.securityContextRepository()) + ); + + return http.build(); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + oauth2Login { + authenticationConverter = authenticationConverter() + authenticationMatcher = authenticationMatcher() + authenticationManager = authenticationManager() + authenticationSuccessHandler = authenticationSuccessHandler() + authenticationFailureHandler = authenticationFailureHandler() + clientRegistrationRepository = clientRegistrationRepository() + authorizedClientRepository = authorizedClientRepository() + authorizedClientService = authorizedClientService() + authorizationRequestResolver = authorizationRequestResolver() + authorizationRequestRepository = authorizationRequestRepository() + securityContextRepository = securityContextRepository() + } + } + } +} +``` + +The following sections go into more detail on each of the configuration options available: + +* [OAuth 2.0 Login Page](#webflux-oauth2-login-advanced-login-page) + +* [Redirection Endpoint](#webflux-oauth2-login-advanced-redirection-endpoint) + +* [UserInfo Endpoint](#webflux-oauth2-login-advanced-userinfo-endpoint) + +* [ID Token Signature Verification](#webflux-oauth2-login-advanced-idtoken-verify) + +* [OpenID Connect 1.0 Logout](#webflux-oauth2-login-advanced-oidc-logout) + +## OAuth 2.0 Login Page + +By default, the OAuth 2.0 Login Page is auto-generated by the `LoginPageGeneratingWebFilter`. +The default login page shows each configured OAuth Client with its `ClientRegistration.clientName` as a link, which is capable of initiating the Authorization Request (or OAuth 2.0 Login). + +| |In order for `LoginPageGeneratingWebFilter` to show links for configured OAuth Clients, the registered `ReactiveClientRegistrationRepository` needs to also implement `Iterable`.
See `InMemoryReactiveClientRegistrationRepository` for reference.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The link’s destination for each OAuth Client defaults to the following: + +`"/oauth2/authorization/{registrationId}"` + +The following line shows an example: + +``` +Google +``` + +To override the default login page, configure the `exceptionHandling().authenticationEntryPoint()` and (optionally) `oauth2Login().authorizationRequestResolver()`. + +The following listing shows an example: + +Example 2. OAuth2 Login Page Configuration + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .exceptionHandling(exceptionHandling -> exceptionHandling + .authenticationEntryPoint(new RedirectServerAuthenticationEntryPoint("/login/oauth2")) + ) + .oauth2Login(oauth2 -> oauth2 + .authorizationRequestResolver(this.authorizationRequestResolver()) + ); + + return http.build(); + } + + private ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver() { + ServerWebExchangeMatcher authorizationRequestMatcher = + new PathPatternParserServerWebExchangeMatcher( + "/login/oauth2/authorization/{registrationId}"); + + return new DefaultServerOAuth2AuthorizationRequestResolver( + this.clientRegistrationRepository(), authorizationRequestMatcher); + } + + ... +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + exceptionHandling { + authenticationEntryPoint = RedirectServerAuthenticationEntryPoint("/login/oauth2") + } + oauth2Login { + authorizationRequestResolver = authorizationRequestResolver() + } + } + } + + private fun authorizationRequestResolver(): ServerOAuth2AuthorizationRequestResolver { + val authorizationRequestMatcher: ServerWebExchangeMatcher = PathPatternParserServerWebExchangeMatcher( + "/login/oauth2/authorization/{registrationId}" + ) + + return DefaultServerOAuth2AuthorizationRequestResolver( + clientRegistrationRepository(), authorizationRequestMatcher + ) + } + + ... +} +``` + +| |You need to provide a `@Controller` with a `@RequestMapping("/login/oauth2")` that is capable of rendering the custom login page.| +|---|---------------------------------------------------------------------------------------------------------------------------------| + +| |As noted earlier, configuring `oauth2Login().authorizationRequestResolver()` is optional.
However, if you choose to customize it, ensure the link to each OAuth Client matches the pattern provided through the `ServerWebExchangeMatcher`.

The following line shows an example:

```
Google
```| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## Redirection Endpoint + +The Redirection Endpoint is used by the Authorization Server for returning the Authorization Response (which contains the authorization credentials) to the client via the Resource Owner user-agent. + +| |OAuth 2.0 Login leverages the Authorization Code Grant.
Therefore, the authorization credential is the authorization code.| +|---|------------------------------------------------------------------------------------------------------------------------------| + +The default Authorization Response redirection endpoint is `/login/oauth2/code/{registrationId}`. + +If you would like to customize the Authorization Response redirection endpoint, configure it as shown in the following example: + +Example 3. Redirection Endpoint Configuration + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .oauth2Login(oauth2 -> oauth2 + .authenticationMatcher(new PathPatternParserServerWebExchangeMatcher("/login/oauth2/callback/{registrationId}")) + ); + + return http.build(); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + oauth2Login { + authenticationMatcher = PathPatternParserServerWebExchangeMatcher("/login/oauth2/callback/{registrationId}") + } + } + } +} +``` + +| |You also need to ensure the `ClientRegistration.redirectUri` matches the custom Authorization Response redirection endpoint.

The following listing shows an example:

Java

```
return CommonOAuth2Provider.GOOGLE.getBuilder("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}")
.build();
```

Kotlin

```
return CommonOAuth2Provider.GOOGLE.getBuilder("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}")
.build()
```| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## UserInfo Endpoint + +The UserInfo Endpoint includes a number of configuration options, as described in the following sub-sections: + +* [Mapping User Authorities](#webflux-oauth2-login-advanced-map-authorities) + +* [OAuth 2.0 UserService](#webflux-oauth2-login-advanced-oauth2-user-service) + +* [OpenID Connect 1.0 UserService](#webflux-oauth2-login-advanced-oidc-user-service) + +### Mapping User Authorities + +After the user successfully authenticates with the OAuth 2.0 Provider, the `OAuth2User.getAuthorities()` (or `OidcUser.getAuthorities()`) may be mapped to a new set of `GrantedAuthority` instances, which will be supplied to `OAuth2AuthenticationToken` when completing the authentication. + +| |`OAuth2AuthenticationToken.getAuthorities()` is used for authorizing requests, such as in `hasRole('USER')` or `hasRole('ADMIN')`.| +|---|----------------------------------------------------------------------------------------------------------------------------------| + +There are a couple of options to choose from when mapping user authorities: + +* [Using a GrantedAuthoritiesMapper](#webflux-oauth2-login-advanced-map-authorities-grantedauthoritiesmapper) + +* [Delegation-based strategy with ReactiveOAuth2UserService](#webflux-oauth2-login-advanced-map-authorities-reactiveoauth2userservice) + +#### Using a GrantedAuthoritiesMapper + +Register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the configuration, as shown in the following example: + +Example 4. Granted Authorities Mapper Configuration + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public GrantedAuthoritiesMapper userAuthoritiesMapper() { + return (authorities) -> { + Set mappedAuthorities = new HashSet<>(); + + authorities.forEach(authority -> { + if (OidcUserAuthority.class.isInstance(authority)) { + OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority; + + OidcIdToken idToken = oidcUserAuthority.getIdToken(); + OidcUserInfo userInfo = oidcUserAuthority.getUserInfo(); + + // Map the claims found in idToken and/or userInfo + // to one or more GrantedAuthority's and add it to mappedAuthorities + + } else if (OAuth2UserAuthority.class.isInstance(authority)) { + OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority; + + Map userAttributes = oauth2UserAuthority.getAttributes(); + + // Map the attributes found in userAttributes + // to one or more GrantedAuthority's and add it to mappedAuthorities + + } + }); + + return mappedAuthorities; + }; + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + oauth2Login { } + } + } + + @Bean + fun userAuthoritiesMapper(): GrantedAuthoritiesMapper = GrantedAuthoritiesMapper { authorities: Collection -> + val mappedAuthorities = emptySet() + + authorities.forEach { authority -> + if (authority is OidcUserAuthority) { + val idToken = authority.idToken + val userInfo = authority.userInfo + // Map the claims found in idToken and/or userInfo + // to one or more GrantedAuthority's and add it to mappedAuthorities + } else if (authority is OAuth2UserAuthority) { + val userAttributes = authority.attributes + // Map the attributes found in userAttributes + // to one or more GrantedAuthority's and add it to mappedAuthorities + } + } + + mappedAuthorities + } +} +``` + +#### Delegation-based strategy with ReactiveOAuth2UserService + +This strategy is advanced compared to using a `GrantedAuthoritiesMapper`, however, it’s also more flexible as it gives you access to the `OAuth2UserRequest` and `OAuth2User` (when using an OAuth 2.0 UserService) or `OidcUserRequest` and `OidcUser` (when using an OpenID Connect 1.0 UserService). + +The `OAuth2UserRequest` (and `OidcUserRequest`) provides you access to the associated `OAuth2AccessToken`, which is very useful in the cases where the *delegator* needs to fetch authority information from a protected resource before it can map the custom authorities for the user. + +The following example shows how to implement and configure a delegation-based strategy using an OpenID Connect 1.0 UserService: + +Example 5. ReactiveOAuth2UserService Configuration + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveOAuth2UserService oidcUserService() { + final OidcReactiveOAuth2UserService delegate = new OidcReactiveOAuth2UserService(); + + return (userRequest) -> { + // Delegate to the default implementation for loading a user + return delegate.loadUser(userRequest) + .flatMap((oidcUser) -> { + OAuth2AccessToken accessToken = userRequest.getAccessToken(); + Set mappedAuthorities = new HashSet<>(); + + // TODO + // 1) Fetch the authority information from the protected resource using accessToken + // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities + + // 3) Create a copy of oidcUser but use the mappedAuthorities instead + oidcUser = new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo()); + + return Mono.just(oidcUser); + }); + }; + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + oauth2Login { } + } + } + + @Bean + fun oidcUserService(): ReactiveOAuth2UserService { + val delegate = OidcReactiveOAuth2UserService() + + return ReactiveOAuth2UserService { userRequest -> + // Delegate to the default implementation for loading a user + delegate.loadUser(userRequest) + .flatMap { oidcUser -> + val accessToken = userRequest.accessToken + val mappedAuthorities = mutableSetOf() + + // TODO + // 1) Fetch the authority information from the protected resource using accessToken + // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities + // 3) Create a copy of oidcUser but use the mappedAuthorities instead + val mappedOidcUser = DefaultOidcUser(mappedAuthorities, oidcUser.idToken, oidcUser.userInfo) + + Mono.just(mappedOidcUser) + } + } + } +} +``` + +### OAuth 2.0 UserService + +`DefaultReactiveOAuth2UserService` is an implementation of a `ReactiveOAuth2UserService` that supports standard OAuth 2.0 Provider’s. + +| |`ReactiveOAuth2UserService` obtains the user attributes of the end-user (the resource owner) from the UserInfo Endpoint (by using the access token granted to the client during the authorization flow) and returns an `AuthenticatedPrincipal` in the form of an `OAuth2User`.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +`DefaultReactiveOAuth2UserService` uses a `WebClient` when requesting the user attributes at the UserInfo Endpoint. + +If you need to customize the pre-processing of the UserInfo Request and/or the post-handling of the UserInfo Response, you will need to provide `DefaultReactiveOAuth2UserService.setWebClient()` with a custom configured `WebClient`. + +Whether you customize `DefaultReactiveOAuth2UserService` or provide your own implementation of `ReactiveOAuth2UserService`, you’ll need to configure it as shown in the following example: + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveOAuth2UserService oauth2UserService() { + ... + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + oauth2Login { } + } + } + + @Bean + fun oauth2UserService(): ReactiveOAuth2UserService { + // ... + } +} +``` + +### OpenID Connect 1.0 UserService + +`OidcReactiveOAuth2UserService` is an implementation of a `ReactiveOAuth2UserService` that supports OpenID Connect 1.0 Provider’s. + +The `OidcReactiveOAuth2UserService` leverages the `DefaultReactiveOAuth2UserService` when requesting the user attributes at the UserInfo Endpoint. + +If you need to customize the pre-processing of the UserInfo Request and/or the post-handling of the UserInfo Response, you will need to provide `OidcReactiveOAuth2UserService.setOauth2UserService()` with a custom configured `ReactiveOAuth2UserService`. + +Whether you customize `OidcReactiveOAuth2UserService` or provide your own implementation of `ReactiveOAuth2UserService` for OpenID Connect 1.0 Provider’s, you’ll need to configure it as shown in the following example: + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveOAuth2UserService oidcUserService() { + ... + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + oauth2Login { } + } + } + + @Bean + fun oidcUserService(): ReactiveOAuth2UserService { + // ... + } +} +``` + +## ID Token Signature Verification + +OpenID Connect 1.0 Authentication introduces the [ID Token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken), which is a security token that contains Claims about the Authentication of an End-User by an Authorization Server when used by a Client. + +The ID Token is represented as a [JSON Web Token](https://tools.ietf.org/html/rfc7519) (JWT) and MUST be signed using [JSON Web Signature](https://tools.ietf.org/html/rfc7515) (JWS). + +The `ReactiveOidcIdTokenDecoderFactory` provides a `ReactiveJwtDecoder` used for `OidcIdToken` signature verification. The default algorithm is `RS256` but may be different when assigned during client registration. +For these cases, a resolver may be configured to return the expected JWS algorithm assigned for a specific client. + +The JWS algorithm resolver is a `Function` that accepts a `ClientRegistration` and returns the expected `JwsAlgorithm` for the client, eg. `SignatureAlgorithm.RS256` or `MacAlgorithm.HS256` + +The following code shows how to configure the `OidcIdTokenDecoderFactory` `@Bean` to default to `MacAlgorithm.HS256` for all `ClientRegistration`: + +Java + +``` +@Bean +public ReactiveJwtDecoderFactory idTokenDecoderFactory() { + ReactiveOidcIdTokenDecoderFactory idTokenDecoderFactory = new ReactiveOidcIdTokenDecoderFactory(); + idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> MacAlgorithm.HS256); + return idTokenDecoderFactory; +} +``` + +Kotlin + +``` +@Bean +fun idTokenDecoderFactory(): ReactiveJwtDecoderFactory { + val idTokenDecoderFactory = ReactiveOidcIdTokenDecoderFactory() + idTokenDecoderFactory.setJwsAlgorithmResolver { MacAlgorithm.HS256 } + return idTokenDecoderFactory +} +``` + +| |For MAC based algorithms such as `HS256`, `HS384` or `HS512`, the `client-secret` corresponding to the `client-id` is used as the symmetric key for signature verification.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +| |If more than one `ClientRegistration` is configured for OpenID Connect 1.0 Authentication, the JWS algorithm resolver may evaluate the provided `ClientRegistration` to determine which algorithm to return.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## OpenID Connect 1.0 Logout + +OpenID Connect Session Management 1.0 allows the ability to log out the End-User at the Provider using the Client. +One of the strategies available is [RP-Initiated Logout](https://openid.net/specs/openid-connect-session-1_0.html#RPLogout). + +If the OpenID Provider supports both Session Management and [Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html), the client may obtain the `end_session_endpoint` `URL` from the OpenID Provider’s [Discovery Metadata](https://openid.net/specs/openid-connect-session-1_0.html#OPMetadata). +This can be achieved by configuring the `ClientRegistration` with the `issuer-uri`, as in the following example: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + ... + provider: + okta: + issuer-uri: https://dev-1234.oktapreview.com +``` + +…​and the `OidcClientInitiatedServerLogoutSuccessHandler`, which implements RP-Initiated Logout, may be configured as follows: + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Autowired + private ReactiveClientRegistrationRepository clientRegistrationRepository; + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()) + .logout(logout -> logout + .logoutSuccessHandler(oidcLogoutSuccessHandler()) + ); + + return http.build(); + } + + private ServerLogoutSuccessHandler oidcLogoutSuccessHandler() { + OidcClientInitiatedServerLogoutSuccessHandler oidcLogoutSuccessHandler = + new OidcClientInitiatedServerLogoutSuccessHandler(this.clientRegistrationRepository); + + // Sets the location that the End-User's User Agent will be redirected to + // after the logout has been performed at the Provider + oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}"); + + return oidcLogoutSuccessHandler; + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Autowired + private lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + logout { + logoutSuccessHandler = oidcLogoutSuccessHandler() + } + } + } + + private fun oidcLogoutSuccessHandler(): ServerLogoutSuccessHandler { + val oidcLogoutSuccessHandler = OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository) + + // Sets the location that the End-User's User Agent will be redirected to + // after the logout has been performed at the Provider + oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}") + return oidcLogoutSuccessHandler + } +} +``` + +| |`OidcClientInitiatedServerLogoutSuccessHandler` supports the `{baseUrl}` placeholder.
If used, the application’s base URL, like `[https://app.example.org](https://app.example.org)`, will replace it at request time.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Core Configuration](core.html)[OAuth2 Client](../client/index.html) \ No newline at end of file diff --git a/docs/en/spring-security/reactive-oauth2-login-core.md b/docs/en/spring-security/reactive-oauth2-login-core.md new file mode 100644 index 0000000000000000000000000000000000000000..123d3d9bb48b796d94b5d1d599f7198f011bb6fe --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-login-core.md @@ -0,0 +1,486 @@ +# Core Configuration + +## Spring Boot 2.x Sample + +Spring Boot 2.x brings full auto-configuration capabilities for OAuth 2.0 Login. + +This section shows how to configure the [**OAuth 2.0 Login WebFlux sample**](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/reactive/webflux/java/oauth2/login) using *Google* as the *Authentication Provider* and covers the following topics: + +* [Initial setup](#webflux-oauth2-login-sample-setup) + +* [Setting the redirect URI](#webflux-oauth2-login-sample-redirect) + +* [Configure `application.yml`](#webflux-oauth2-login-sample-config) + +* [Boot up the application](#webflux-oauth2-login-sample-start) + +### Initial setup + +To use Google’s OAuth 2.0 authentication system for login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials. + +| |[Google’s OAuth 2.0 implementation](https://developers.google.com/identity/protocols/OpenIDConnect) for authentication conforms to the [OpenID Connect 1.0](https://openid.net/connect/) specification and is [OpenID Certified](https://openid.net/certification/).| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Follow the instructions on the [OpenID Connect](https://developers.google.com/identity/protocols/OpenIDConnect) page, starting in the section, "Setting up OAuth 2.0". + +After completing the "Obtain OAuth 2.0 credentials" instructions, you should have a new OAuth Client with credentials consisting of a Client ID and a Client Secret. + +### Setting the redirect URI + +The redirect URI is the path in the application that the end-user’s user-agent is redirected back to after they have authenticated with Google and have granted access to the OAuth Client *([created in the previous step](#webflux-oauth2-login-sample-setup))* on the Consent page. + +In the "Set a redirect URI" sub-section, ensure that the **Authorized redirect URIs** field is set to `[http://localhost:8080/login/oauth2/code/google](http://localhost:8080/login/oauth2/code/google)`. + +| |The default redirect URI template is `{baseUrl}/login/oauth2/code/{registrationId}`.
The ***registrationId*** is a unique identifier for the [ClientRegistration](../client/core.html#oauth2Client-client-registration).
For our example, the `registrationId` is `google`.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +| |If the OAuth Client is running behind a proxy server, it is recommended to check [Proxy Server Configuration](../../../features/exploits/http.html#http-proxy-server) to ensure the application is correctly configured.
Also, see the supported [`URI` template variables](../client/authorization-grants.html#oauth2Client-auth-code-redirect-uri) for `redirect-uri`.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Configure `application.yml` + +Now that you have a new OAuth Client with Google, you need to configure the application to use the OAuth Client for the *authentication flow*. +To do so: + +1. Go to `application.yml` and set the following configuration: + + ``` + spring: + security: + oauth2: + client: + registration: (1) + google: (2) + client-id: google-client-id + client-secret: google-client-secret + ``` + + Example 1. OAuth Client properties + + |**1**| `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties. | + |-----|--------------------------------------------------------------------------------------------------------------------------------------------------| + |**2**|Following the base property prefix is the ID for the [`ClientRegistration`](../client/core.html#oauth2Client-client-registration), such as google.| + +2. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. + +### Boot up the application + +Launch the Spring Boot 2.x sample and go to `[http://localhost:8080](http://localhost:8080)`. +You are then redirected to the default *auto-generated* login page, which displays a link for Google. + +Click on the Google link, and you are then redirected to Google for authentication. + +After authenticating with your Google account credentials, the next page presented to you is the Consent screen. +The Consent screen asks you to either allow or deny access to the OAuth Client you created earlier. +Click **Allow** to authorize the OAuth Client to access your email address and basic profile information. + +At this point, the OAuth Client retrieves your email address and basic profile information from the [UserInfo Endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) and establishes an authenticated session. + +## Spring Boot 2.x Property Mappings + +The following table outlines the mapping of the Spring Boot 2.x OAuth Client properties to the [ClientRegistration](../client/core.html#oauth2Client-client-registration) properties. + +| Spring Boot 2.x | ClientRegistration | +|--------------------------------------------------------------------------------------------|--------------------------------------------------------| +| `spring.security.oauth2.client.registration.*[registrationId]*` | `registrationId` | +| `spring.security.oauth2.client.registration.*[registrationId]*.client-id` | `clientId` | +| `spring.security.oauth2.client.registration.*[registrationId]*.client-secret` | `clientSecret` | +|`spring.security.oauth2.client.registration.*[registrationId]*.client-authentication-method`| `clientAuthenticationMethod` | +| `spring.security.oauth2.client.registration.*[registrationId]*.authorization-grant-type` | `authorizationGrantType` | +| `spring.security.oauth2.client.registration.*[registrationId]*.redirect-uri` | `redirectUri` | +| `spring.security.oauth2.client.registration.*[registrationId]*.scope` | `scopes` | +| `spring.security.oauth2.client.registration.*[registrationId]*.client-name` | `clientName` | +| `spring.security.oauth2.client.provider.*[providerId]*.authorization-uri` | `providerDetails.authorizationUri` | +| `spring.security.oauth2.client.provider.*[providerId]*.token-uri` | `providerDetails.tokenUri` | +| `spring.security.oauth2.client.provider.*[providerId]*.jwk-set-uri` | `providerDetails.jwkSetUri` | +| `spring.security.oauth2.client.provider.*[providerId]*.issuer-uri` | `providerDetails.issuerUri` | +| `spring.security.oauth2.client.provider.*[providerId]*.user-info-uri` | `providerDetails.userInfoEndpoint.uri` | +| `spring.security.oauth2.client.provider.*[providerId]*.user-info-authentication-method` |`providerDetails.userInfoEndpoint.authenticationMethod` | +| `spring.security.oauth2.client.provider.*[providerId]*.user-name-attribute` |`providerDetails.userInfoEndpoint.userNameAttributeName`| + +| |A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider’s [Configuration endpoint](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) or an Authorization Server’s [Metadata endpoint](https://tools.ietf.org/html/rfc8414#section-3), by specifying the `spring.security.oauth2.client.provider.*[providerId]*.issuer-uri` property.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## CommonOAuth2Provider + +`CommonOAuth2Provider` pre-defines a set of default client properties for a number of well known providers: Google, GitHub, Facebook, and Okta. + +For example, the `authorization-uri`, `token-uri`, and `user-info-uri` do not change often for a Provider. +Therefore, it makes sense to provide default values in order to reduce the required configuration. + +As demonstrated previously, when we [configured a Google client](#webflux-oauth2-login-sample-config), only the `client-id` and `client-secret` properties are required. + +The following listing shows an example: + +``` +spring: + security: + oauth2: + client: + registration: + google: + client-id: google-client-id + client-secret: google-client-secret +``` + +| |The auto-defaulting of client properties works seamlessly here because the `registrationId` (`google`) matches the `GOOGLE` `enum` (case-insensitive) in `CommonOAuth2Provider`.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +For cases where you may want to specify a different `registrationId`, such as `google-login`, you can still leverage auto-defaulting of client properties by configuring the `provider` property. + +The following listing shows an example: + +``` +spring: + security: + oauth2: + client: + registration: + google-login: (1) + provider: google (2) + client-id: google-client-id + client-secret: google-client-secret +``` + +|**1**| The `registrationId` is set to `google-login`. | +|-----|-----------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**|The `provider` property is set to `google`, which will leverage the auto-defaulting of client properties set in `CommonOAuth2Provider.GOOGLE.getBuilder()`.| + +## Configuring Custom Provider Properties + +There are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain). + +For example, an OAuth Client registered with Okta is assigned to a specific sub-domain and have their own protocol endpoints. + +For these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: `spring.security.oauth2.client.provider.*[providerId]*`. + +The following listing shows an example: + +``` +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + provider: + okta: (1) + authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize + token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token + user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo + user-name-attribute: sub + jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys +``` + +|**1**|The base property (`spring.security.oauth2.client.provider.okta`) allows for custom configuration of protocol endpoint locations.| +|-----|---------------------------------------------------------------------------------------------------------------------------------| + +## Overriding Spring Boot 2.x Auto-configuration + +The Spring Boot 2.x auto-configuration class for OAuth Client support is `ReactiveOAuth2ClientAutoConfiguration`. + +It performs the following tasks: + +* Registers a `ReactiveClientRegistrationRepository` `@Bean` composed of `ClientRegistration`(s) from the configured OAuth Client properties. + +* Registers a `SecurityWebFilterChain` `@Bean` and enables OAuth 2.0 Login through `serverHttpSecurity.oauth2Login()`. + +If you need to override the auto-configuration based on your specific requirements, you may do so in the following ways: + +* [Register a ReactiveClientRegistrationRepository @Bean](#webflux-oauth2-login-register-reactiveclientregistrationrepository-bean) + +* [Register a SecurityWebFilterChain @Bean](#webflux-oauth2-login-register-securitywebfilterchain-bean) + +* [Completely Override the Auto-configuration](#webflux-oauth2-login-completely-override-autoconfiguration) + +### Register a ReactiveClientRegistrationRepository @Bean + +The following example shows how to register a `ReactiveClientRegistrationRepository` `@Bean`: + +Java + +``` +@Configuration +public class OAuth2LoginConfig { + + @Bean + public ReactiveClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration()); + } + + private ClientRegistration googleClientRegistration() { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build(); + } +} +``` + +Kotlin + +``` +@Configuration +class OAuth2LoginConfig { + + @Bean + fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { + return InMemoryReactiveClientRegistrationRepository(googleClientRegistration()) + } + + private fun googleClientRegistration(): ClientRegistration { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build() + } +} +``` + +### Register a SecurityWebFilterChain @Bean + +The following example shows how to register a `SecurityWebFilterChain` `@Bean` with `@EnableWebFluxSecurity` and enable OAuth 2.0 login through `serverHttpSecurity.oauth2Login()`: + +Example 2. OAuth2 Login Configuration + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()); + + return http.build(); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + } + } +} +``` + +### Completely Override the Auto-configuration + +The following example shows how to completely override the auto-configuration by registering a `ReactiveClientRegistrationRepository` `@Bean` and a `SecurityWebFilterChain` `@Bean`. + +Example 3. Overriding the auto-configuration + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration()); + } + + private ClientRegistration googleClientRegistration() { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build(); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + } + } + + @Bean + fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { + return InMemoryReactiveClientRegistrationRepository(googleClientRegistration()) + } + + private fun googleClientRegistration(): ClientRegistration { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build() + } +} +``` + +## Java Configuration without Spring Boot 2.x + +If you are not able to use Spring Boot 2.x and would like to configure one of the pre-defined providers in `CommonOAuth2Provider` (for example, Google), apply the following configuration: + +Example 4. OAuth2 Login Configuration + +Java + +``` +@EnableWebFluxSecurity +public class OAuth2LoginConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration()); + } + + @Bean + public ReactiveOAuth2AuthorizedClientService authorizedClientService( + ReactiveClientRegistrationRepository clientRegistrationRepository) { + return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository); + } + + @Bean + public ServerOAuth2AuthorizedClientRepository authorizedClientRepository( + ReactiveOAuth2AuthorizedClientService authorizedClientService) { + return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService); + } + + private ClientRegistration googleClientRegistration() { + return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .build(); + } +} +``` + +Kotlin + +``` +@EnableWebFluxSecurity +class OAuth2LoginConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + } + } + + @Bean + fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { + return InMemoryReactiveClientRegistrationRepository(googleClientRegistration()) + } + + @Bean + fun authorizedClientService( + clientRegistrationRepository: ReactiveClientRegistrationRepository + ): ReactiveOAuth2AuthorizedClientService { + return InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository) + } + + @Bean + fun authorizedClientRepository( + authorizedClientService: ReactiveOAuth2AuthorizedClientService + ): ServerOAuth2AuthorizedClientRepository { + return AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService) + } + + private fun googleClientRegistration(): ClientRegistration { + return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .build() + } +} +``` + +[OAuth2 Log In](index.html)[Advanced Configuration](advanced.html) + diff --git a/docs/en/spring-security/reactive-oauth2-login.md b/docs/en/spring-security/reactive-oauth2-login.md new file mode 100644 index 0000000000000000000000000000000000000000..b9b4a50e0d5a9d2c8d6d020af717f891745deba5 --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-login.md @@ -0,0 +1,15 @@ +# OAuth 2.0 Login + +The OAuth 2.0 Login feature provides an application with the capability to have users log in to the application by using their existing account at an OAuth 2.0 Provider (e.g. GitHub) or OpenID Connect 1.0 Provider (such as Google). +OAuth 2.0 Login implements the use cases: "Login with Google" or "Login with GitHub". + +| |OAuth 2.0 Login is implemented by using the **Authorization Code Grant**, as specified in the [OAuth 2.0 Authorization Framework](https://tools.ietf.org/html/rfc6749#section-4.1) and [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth).| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## Section Summary + +* [Core Configuration](core.html) +* [Advanced Configuration](advanced.html) + +[OAuth2](../index.html)[Core Configuration](core.html) + diff --git a/docs/en/spring-security/reactive-oauth2-resource-server-bearer-tokens.md b/docs/en/spring-security/reactive-oauth2-resource-server-bearer-tokens.md new file mode 100644 index 0000000000000000000000000000000000000000..4ac8e1587c839da87452b35d4c4b31e036f1c553 --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-resource-server-bearer-tokens.md @@ -0,0 +1,116 @@ +# OAuth 2.0 Resource Server Bearer Tokens + +## Bearer Token Resolution + +By default, Resource Server looks for a bearer token in the `Authorization` header. +This, however, can be customized. + +For example, you may have a need to read the bearer token from a custom header. +To achieve this, you can wire an instance of `ServerBearerTokenAuthenticationConverter` into the DSL, as you can see in the following example: + +Example 1. Custom Bearer Token Header + +Java + +``` +ServerBearerTokenAuthenticationConverter converter = new ServerBearerTokenAuthenticationConverter(); +converter.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION); +http + .oauth2ResourceServer(oauth2 -> oauth2 + .bearerTokenConverter(converter) + ); +``` + +Kotlin + +``` +val converter = ServerBearerTokenAuthenticationConverter() +converter.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION) +return http { + oauth2ResourceServer { + bearerTokenConverter = converter + } +} +``` + +## Bearer Token Propagation + +Now that you’re in possession of a bearer token, it might be handy to pass that to downstream services. +This is quite simple with `[ServerBearerExchangeFilterFunction](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.html)`, which you can see in the following example: + +Java + +``` +@Bean +public WebClient rest() { + return WebClient.builder() + .filter(new ServerBearerExchangeFilterFunction()) + .build(); +} +``` + +Kotlin + +``` +@Bean +fun rest(): WebClient { + return WebClient.builder() + .filter(ServerBearerExchangeFilterFunction()) + .build() +} +``` + +When the above `WebClient` is used to perform requests, Spring Security will look up the current `Authentication` and extract any `[AbstractOAuth2Token](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/core/AbstractOAuth2Token.html)` credential. +Then, it will propagate that token in the `Authorization` header. + +For example: + +Java + +``` +this.rest.get() + .uri("https://other-service.example.com/endpoint") + .retrieve() + .bodyToMono(String.class) +``` + +Kotlin + +``` +this.rest.get() + .uri("https://other-service.example.com/endpoint") + .retrieve() + .bodyToMono() +``` + +Will invoke the `[https://other-service.example.com/endpoint](https://other-service.example.com/endpoint)`, adding the bearer token `Authorization` header for you. + +In places where you need to override this behavior, it’s a simple matter of supplying the header yourself, like so: + +Java + +``` +this.rest.get() + .uri("https://other-service.example.com/endpoint") + .headers(headers -> headers.setBearerAuth(overridingToken)) + .retrieve() + .bodyToMono(String.class) +``` + +Kotlin + +``` +rest.get() + .uri("https://other-service.example.com/endpoint") + .headers { it.setBearerAuth(overridingToken) } + .retrieve() + .bodyToMono() +``` + +In this case, the filter will fall back and simply forward the request onto the rest of the web filter chain. + +| |Unlike the [OAuth 2.0 Client filter function](https://docs.spring.io/spring-security/site/docs/current-SNAPSHOT/api/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.html), this filter function makes no attempt to renew the token, should it be expired.
To obtain this level of support, please use the OAuth 2.0 Client filter.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Multitenancy](multitenancy.html)[Protection Against Exploits](../../exploits/index.html) + diff --git a/docs/en/spring-security/reactive-oauth2-resource-server-jwt.md b/docs/en/spring-security/reactive-oauth2-resource-server-jwt.md new file mode 100644 index 0000000000000000000000000000000000000000..8d06819414086684a4df1fc7af452764423f815d --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-resource-server-jwt.md @@ -0,0 +1,824 @@ +# OAuth 2.0 Resource Server JWT + +## Minimal Dependencies for JWT + +Most Resource Server support is collected into `spring-security-oauth2-resource-server`. +However, the support for decoding and verifying JWTs is in `spring-security-oauth2-jose`, meaning that both are necessary in order to have a working resource server that supports JWT-encoded Bearer Tokens. + +## Minimal Configuration for JWTs + +When using [Spring Boot](https://spring.io/projects/spring-boot), configuring an application as a resource server consists of two basic steps. +First, include the needed dependencies and second, indicate the location of the authorization server. + +### Specifying the Authorization Server + +In a Spring Boot application, to specify which authorization server to use, simply do: + +``` +spring: + security: + oauth2: + resourceserver: + jwt: + issuer-uri: https://idp.example.com/issuer +``` + +Where `[https://idp.example.com/issuer](https://idp.example.com/issuer)` is the value contained in the `iss` claim for JWT tokens that the authorization server will issue. +Resource Server will use this property to further self-configure, discover the authorization server’s public keys, and subsequently validate incoming JWTs. + +| |To use the `issuer-uri` property, it must also be true that one of `[https://idp.example.com/issuer/.well-known/openid-configuration](https://idp.example.com/issuer/.well-known/openid-configuration)`, `[https://idp.example.com/.well-known/openid-configuration/issuer](https://idp.example.com/.well-known/openid-configuration/issuer)`, or `[https://idp.example.com/.well-known/oauth-authorization-server/issuer](https://idp.example.com/.well-known/oauth-authorization-server/issuer)` is a supported endpoint for the authorization server.
This endpoint is referred to as a [Provider Configuration](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) endpoint or a [Authorization Server Metadata](https://tools.ietf.org/html/rfc8414#section-3) endpoint.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +And that’s it! + +### Startup Expectations + +When this property and these dependencies are used, Resource Server will automatically configure itself to validate JWT-encoded Bearer Tokens. + +It achieves this through a deterministic startup process: + +1. Hit the Provider Configuration or Authorization Server Metadata endpoint, processing the response for the `jwks_url` property + +2. Configure the validation strategy to query `jwks_url` for valid public keys + +3. Configure the validation strategy to validate each JWTs `iss` claim against `[https://idp.example.com](https://idp.example.com)`. + +A consequence of this process is that the authorization server must be up and receiving requests in order for Resource Server to successfully start up. + +| |If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup will fail.| +|---|-------------------------------------------------------------------------------------------------------------------------| + +### Runtime Expectations + +Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header: + +``` +GET / HTTP/1.1 +Authorization: Bearer some-token-value # Resource Server will process this +``` + +So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification. + +Given a well-formed JWT, Resource Server will: + +1. Validate its signature against a public key obtained from the `jwks_url` endpoint during startup and matched against the JWTs header + +2. Validate the JWTs `exp` and `nbf` timestamps and the JWTs `iss` claim, and + +3. Map each scope to an authority with the prefix `SCOPE_`. + +| |As the authorization server makes available new keys, Spring Security will automatically rotate the keys used to validate the JWT tokens.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------| + +The resulting `Authentication#getPrincipal`, by default, is a Spring Security `Jwt` object, and `Authentication#getName` maps to the JWT’s `sub` property, if one is present. + +From here, consider jumping to: + +[How to Configure without Tying Resource Server startup to an authorization server’s availability](#webflux-oauth2resourceserver-jwt-jwkseturi) + +[How to Configure without Spring Boot](#webflux-oauth2resourceserver-jwt-sansboot) + +### Specifying the Authorization Server JWK Set Uri Directly + +If the authorization server doesn’t support any configuration endpoints, or if Resource Server must be able to start up independently from the authorization server, then the `jwk-set-uri` can be supplied as well: + +``` +spring: + security: + oauth2: + resourceserver: + jwt: + issuer-uri: https://idp.example.com + jwk-set-uri: https://idp.example.com/.well-known/jwks.json +``` + +| |The JWK Set uri is not standardized, but can typically be found in the authorization server’s documentation| +|---|-----------------------------------------------------------------------------------------------------------| + +Consequently, Resource Server will not ping the authorization server at startup. +We still specify the `issuer-uri` so that Resource Server still validates the `iss` claim on incoming JWTs. + +| |This property can also be supplied directly on the [DSL](#webflux-oauth2resourceserver-jwt-jwkseturi-dsl).| +|---|----------------------------------------------------------------------------------------------------------| + +### Overriding or Replacing Boot Auto Configuration + +There are two `@Bean`s that Spring Boot generates on Resource Server’s behalf. + +The first is a `SecurityWebFilterChain` that configures the app as a resource server. When including `spring-security-oauth2-jose`, this `SecurityWebFilterChain` looks like: + +Example 1. Resource Server SecurityWebFilterChain + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt) + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + jwt { } + } + } +} +``` + +If the application doesn’t expose a `SecurityWebFilterChain` bean, then Spring Boot will expose the above default one. + +Replacing this is as simple as exposing the bean within the application: + +Example 2. Replacing SecurityWebFilterChain + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .pathMatchers("/message/**").hasAuthority("SCOPE_message:read") + .anyExchange().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2 + .jwt(withDefaults()) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize("/message/**", hasAuthority("SCOPE_message:read")) + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + jwt { } + } + } +} +``` + +The above requires the scope of `message:read` for any URL that starts with `/messages/`. + +Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration. + +For example, the second `@Bean` Spring Boot creates is a `ReactiveJwtDecoder`, which decodes `String` tokens into validated instances of `Jwt`: + +Example 3. ReactiveJwtDecoder + +Java + +``` +@Bean +public ReactiveJwtDecoder jwtDecoder() { + return ReactiveJwtDecoders.fromIssuerLocation(issuerUri); +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + return ReactiveJwtDecoders.fromIssuerLocation(issuerUri) +} +``` + +| |Calling `[ReactiveJwtDecoders#fromIssuerLocation](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.html#fromIssuerLocation-java.lang.String-)` is what invokes the Provider Configuration or Authorization Server Metadata endpoint in order to derive the JWK Set Uri.
If the application doesn’t expose a `ReactiveJwtDecoder` bean, then Spring Boot will expose the above default one.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +And its configuration can be overridden using `jwkSetUri()` or replaced using `decoder()`. + +#### ` + +An authorization server’s JWK Set Uri can be configured [as a configuration property](#webflux-oauth2resourceserver-jwt-jwkseturi) or it can be supplied in the DSL: + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2 + .jwt(jwt -> jwt + .jwkSetUri("https://idp.example.com/.well-known/jwks.json") + ) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + jwt { + jwkSetUri = "https://idp.example.com/.well-known/jwks.json" + } + } + } +} +``` + +Using `jwkSetUri()` takes precedence over any configuration property. + +#### ` + +More powerful than `jwkSetUri()` is `decoder()`, which will completely replace any Boot auto configuration of `JwtDecoder`: + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2 + .jwt(jwt -> jwt + .decoder(myCustomDecoder()) + ) + ); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + jwt { + jwtDecoder = myCustomDecoder() + } + } + } +} +``` + +This is handy when deeper configuration, like [validation](#webflux-oauth2resourceserver-jwt-validation), is necessary. + +#### Exposing a `ReactiveJwtDecoder` `@Bean` + +Or, exposing a `ReactiveJwtDecoder` `@Bean` has the same effect as `decoder()`: + +Java + +``` +@Bean +public ReactiveJwtDecoder jwtDecoder() { + return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).build(); +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + return ReactiveJwtDecoders.fromIssuerLocation(issuerUri) +} +``` + +## Configuring Trusted Algorithms + +By default, `NimbusReactiveJwtDecoder`, and hence Resource Server, will only trust and verify tokens using `RS256`. + +You can customize this via [Spring Boot](#webflux-oauth2resourceserver-jwt-boot-algorithm) or [the NimbusJwtDecoder builder](#webflux-oauth2resourceserver-jwt-decoder-builder). + +### Via Spring Boot + +The simplest way to set the algorithm is as a property: + +``` +spring: + security: + oauth2: + resourceserver: + jwt: + jws-algorithm: RS512 + jwk-set-uri: https://idp.example.org/.well-known/jwks.json +``` + +### Using a Builder + +For greater power, though, we can use a builder that ships with `NimbusReactiveJwtDecoder`: + +Java + +``` +@Bean +ReactiveJwtDecoder jwtDecoder() { + return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri) + .jwsAlgorithm(RS512).build(); +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri) + .jwsAlgorithm(RS512).build() +} +``` + +Calling `jwsAlgorithm` more than once will configure `NimbusReactiveJwtDecoder` to trust more than one algorithm, like so: + +Java + +``` +@Bean +ReactiveJwtDecoder jwtDecoder() { + return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri) + .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build(); +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri) + .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build() +} +``` + +Or, you can call `jwsAlgorithms`: + +Java + +``` +@Bean +ReactiveJwtDecoder jwtDecoder() { + return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri) + .jwsAlgorithms(algorithms -> { + algorithms.add(RS512); + algorithms.add(ES512); + }).build(); +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri) + .jwsAlgorithms { + it.add(RS512) + it.add(ES512) + } + .build() +} +``` + +### Trusting a Single Asymmetric Key + +Simpler than backing a Resource Server with a JWK Set endpoint is to hard-code an RSA public key. +The public key can be provided via [Spring Boot](#webflux-oauth2resourceserver-jwt-decoder-public-key-boot) or by [Using a Builder](#webflux-oauth2resourceserver-jwt-decoder-public-key-builder). + +#### Via Spring Boot + +Specifying a key via Spring Boot is quite simple. +The key’s location can be specified like so: + +``` +spring: + security: + oauth2: + resourceserver: + jwt: + public-key-location: classpath:my-key.pub +``` + +Or, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`: + +Example 4. BeanFactoryPostProcessor + +Java + +``` +@Bean +BeanFactoryPostProcessor conversionServiceCustomizer() { + return beanFactory -> + beanFactory.getBean(RsaKeyConversionServicePostProcessor.class) + .setResourceLoader(new CustomResourceLoader()); +} +``` + +Kotlin + +``` +@Bean +fun conversionServiceCustomizer(): BeanFactoryPostProcessor { + return BeanFactoryPostProcessor { beanFactory: ConfigurableListableBeanFactory -> + beanFactory.getBean() + .setResourceLoader(CustomResourceLoader()) + } +} +``` + +Specify your key’s location: + +``` +key.location: hfds://my-key.pub +``` + +And then autowire the value: + +Java + +``` +@Value("${key.location}") +RSAPublicKey key; +``` + +Kotlin + +``` +@Value("\${key.location}") +val key: RSAPublicKey? = null +``` + +#### Using a Builder + +To wire an `RSAPublicKey` directly, you can simply use the appropriate `NimbusReactiveJwtDecoder` builder, like so: + +Java + +``` +@Bean +public ReactiveJwtDecoder jwtDecoder() { + return NimbusReactiveJwtDecoder.withPublicKey(this.key).build(); +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + return NimbusReactiveJwtDecoder.withPublicKey(key).build() +} +``` + +### Trusting a Single Symmetric Key + +Using a single symmetric key is also simple. +You can simply load in your `SecretKey` and use the appropriate `NimbusReactiveJwtDecoder` builder, like so: + +Java + +``` +@Bean +public ReactiveJwtDecoder jwtDecoder() { + return NimbusReactiveJwtDecoder.withSecretKey(this.key).build(); +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + return NimbusReactiveJwtDecoder.withSecretKey(this.key).build() +} +``` + +### Configuring Authorization + +A JWT that is issued from an OAuth 2.0 Authorization Server will typically either have a `scope` or `scp` attribute, indicating the scopes (or authorities) it’s been granted, for example: + +`{ …​, "scope" : "messages contacts"}` + +When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string "SCOPE\_". + +This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix: + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts") + .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages") + .anyExchange().authenticated() + ) + .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt); + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize("/contacts/**", hasAuthority("SCOPE_contacts")) + authorize("/messages/**", hasAuthority("SCOPE_messages")) + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + jwt { } + } + } +} +``` + +Or similarly with method security: + +Java + +``` +@PreAuthorize("hasAuthority('SCOPE_messages')") +public Flux getMessages(...) {} +``` + +Kotlin + +``` +@PreAuthorize("hasAuthority('SCOPE_messages')") +fun getMessages(): Flux { } +``` + +#### Extracting Authorities Manually + +However, there are a number of circumstances where this default is insufficient. +For example, some authorization servers don’t use the `scope` attribute, but instead have their own custom attribute. +Or, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities. + +To this end, the DSL exposes `jwtAuthenticationConverter()`: + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2 + .jwt(jwt -> jwt + .jwtAuthenticationConverter(grantedAuthoritiesExtractor()) + ) + ); + return http.build(); +} + +Converter> grantedAuthoritiesExtractor() { + JwtAuthenticationConverter jwtAuthenticationConverter = + new JwtAuthenticationConverter(); + jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter + (new GrantedAuthoritiesExtractor()); + return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + jwt { + jwtAuthenticationConverter = grantedAuthoritiesExtractor() + } + } + } +} + +fun grantedAuthoritiesExtractor(): Converter> { + val jwtAuthenticationConverter = JwtAuthenticationConverter() + jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(GrantedAuthoritiesExtractor()) + return ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter) +} +``` + +which is responsible for converting a `Jwt` into an `Authentication`. +As part of its configuration, we can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities. + +That final converter might be something like `GrantedAuthoritiesExtractor` below: + +Java + +``` +static class GrantedAuthoritiesExtractor + implements Converter> { + + public Collection convert(Jwt jwt) { + Collection authorities = (Collection) + jwt.getClaims().getOrDefault("mycustomclaim", Collections.emptyList()); + + return authorities.stream() + .map(Object::toString) + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + } +} +``` + +Kotlin + +``` +internal class GrantedAuthoritiesExtractor : Converter> { + override fun convert(jwt: Jwt): Collection { + val authorities: List = jwt.claims + .getOrDefault("mycustomclaim", emptyList()) as List + return authorities + .map { it.toString() } + .map { SimpleGrantedAuthority(it) } + } +} +``` + +For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter>`: + +Java + +``` +static class CustomAuthenticationConverter implements Converter> { + public AbstractAuthenticationToken convert(Jwt jwt) { + return Mono.just(jwt).map(this::doConversion); + } +} +``` + +Kotlin + +``` +internal class CustomAuthenticationConverter : Converter> { + override fun convert(jwt: Jwt): Mono { + return Mono.just(jwt).map(this::doConversion) + } +} +``` + +### Configuring Validation + +Using [minimal Spring Boot configuration](#webflux-oauth2resourceserver-jwt-minimalconfiguration), indicating the authorization server’s issuer uri, Resource Server will default to verifying the `iss` claim as well as the `exp` and `nbf` timestamp claims. + +In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances. + +#### Customizing Timestamp Validation + +JWT’s typically have a window of validity, with the start of the window indicated in the `nbf` claim and the end indicated in the `exp` claim. + +However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another. +This can cause some implementation heartburn as the number of collaborating servers increases in a distributed system. + +Resource Server uses `JwtTimestampValidator` to verify a token’s validity window, and it can be configured with a `clockSkew` to alleviate the above problem: + +Java + +``` +@Bean +ReactiveJwtDecoder jwtDecoder() { + NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder) + ReactiveJwtDecoders.fromIssuerLocation(issuerUri); + + OAuth2TokenValidator withClockSkew = new DelegatingOAuth2TokenValidator<>( + new JwtTimestampValidator(Duration.ofSeconds(60)), + new IssuerValidator(issuerUri)); + + jwtDecoder.setJwtValidator(withClockSkew); + + return jwtDecoder; +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder + val withClockSkew: OAuth2TokenValidator = DelegatingOAuth2TokenValidator( + JwtTimestampValidator(Duration.ofSeconds(60)), + JwtIssuerValidator(issuerUri)) + jwtDecoder.setJwtValidator(withClockSkew) + return jwtDecoder +} +``` + +| |By default, Resource Server configures a clock skew of 60 seconds.| +|---|------------------------------------------------------------------| + +#### Configuring a Custom Validator + +Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API: + +Java + +``` +public class AudienceValidator implements OAuth2TokenValidator { + OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null); + + public OAuth2TokenValidatorResult validate(Jwt jwt) { + if (jwt.getAudience().contains("messaging")) { + return OAuth2TokenValidatorResult.success(); + } else { + return OAuth2TokenValidatorResult.failure(error); + } + } +} +``` + +Kotlin + +``` +class AudienceValidator : OAuth2TokenValidator { + var error: OAuth2Error = OAuth2Error("invalid_token", "The required audience is missing", null) + override fun validate(jwt: Jwt): OAuth2TokenValidatorResult { + return if (jwt.audience.contains("messaging")) { + OAuth2TokenValidatorResult.success() + } else { + OAuth2TokenValidatorResult.failure(error) + } + } +} +``` + +Then, to add into a resource server, it’s a matter of specifying the `ReactiveJwtDecoder` instance: + +Java + +``` +@Bean +ReactiveJwtDecoder jwtDecoder() { + NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder) + ReactiveJwtDecoders.fromIssuerLocation(issuerUri); + + OAuth2TokenValidator audienceValidator = new AudienceValidator(); + OAuth2TokenValidator withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri); + OAuth2TokenValidator withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator); + + jwtDecoder.setJwtValidator(withAudience); + + return jwtDecoder; +} +``` + +Kotlin + +``` +@Bean +fun jwtDecoder(): ReactiveJwtDecoder { + val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder + val audienceValidator: OAuth2TokenValidator = AudienceValidator() + val withIssuer: OAuth2TokenValidator = JwtValidators.createDefaultWithIssuer(issuerUri) + val withAudience: OAuth2TokenValidator = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator) + jwtDecoder.setJwtValidator(withAudience) + return jwtDecoder +} +``` + +[OAuth2 Resource Server](index.html)[Opaque Token](opaque-token.html) + diff --git a/docs/en/spring-security/reactive-oauth2-resource-server-multitenancy.md b/docs/en/spring-security/reactive-oauth2-resource-server-multitenancy.md new file mode 100644 index 0000000000000000000000000000000000000000..21a5133ffd747f3ce62e20bb6d049b1758284ac0 --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-resource-server-multitenancy.md @@ -0,0 +1,116 @@ +# OAuth 2.0 Resource Server Multitenancy + +## Multi-tenancy + +A resource server is considered multi-tenant when there are multiple strategies for verifying a bearer token, keyed by some tenant identifier. + +For example, your resource server may accept bearer tokens from two different authorization servers. +Or, your authorization server may represent a multiplicity of issuers. + +In each case, there are two things that need to be done and trade-offs associated with how you choose to do them: + +1. Resolve the tenant + +2. Propagate the tenant + +### Resolving the Tenant By Claim + +One way to differentiate tenants is by the issuer claim. Since the issuer claim accompanies signed JWTs, this can be done with the `JwtIssuerReactiveAuthenticationManagerResolver`, like so: + +Java + +``` +JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver + ("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo"); + +http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2 + .authenticationManagerResolver(authenticationManagerResolver) + ); +``` + +Kotlin + +``` +val customAuthenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo") + +return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + authenticationManagerResolver = customAuthenticationManagerResolver + } +} +``` + +This is nice because the issuer endpoints are loaded lazily. +In fact, the corresponding `JwtReactiveAuthenticationManager` is instantiated only when the first request with the corresponding issuer is sent. +This allows for an application startup that is independent from those authorization servers being up and available. + +#### Dynamic Tenants + +Of course, you may not want to restart the application each time a new tenant is added. +In this case, you can configure the `JwtIssuerReactiveAuthenticationManagerResolver` with a repository of `ReactiveAuthenticationManager` instances, which you can edit at runtime, like so: + +Java + +``` +private Mono addManager( + Map authenticationManagers, String issuer) { + + return Mono.fromCallable(() -> ReactiveJwtDecoders.fromIssuerLocation(issuer)) + .subscribeOn(Schedulers.boundedElastic()) + .map(JwtReactiveAuthenticationManager::new) + .doOnNext(authenticationManager -> authenticationManagers.put(issuer, authenticationManager)); +} + +// ... + +JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = + new JwtIssuerReactiveAuthenticationManagerResolver(authenticationManagers::get); + +http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2 + .authenticationManagerResolver(authenticationManagerResolver) + ); +``` + +Kotlin + +``` +private fun addManager( + authenticationManagers: MutableMap, issuer: String): Mono { + return Mono.fromCallable { ReactiveJwtDecoders.fromIssuerLocation(issuer) } + .subscribeOn(Schedulers.boundedElastic()) + .map { jwtDecoder: ReactiveJwtDecoder -> JwtReactiveAuthenticationManager(jwtDecoder) } + .doOnNext { authenticationManager: JwtReactiveAuthenticationManager -> authenticationManagers[issuer] = authenticationManager } +} + +// ... + +var customAuthenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver(authenticationManagers::get) +return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + authenticationManagerResolver = customAuthenticationManagerResolver + } +} +``` + +In this case, you construct `JwtIssuerReactiveAuthenticationManagerResolver` with a strategy for obtaining the `ReactiveAuthenticationManager` given the issuer. +This approach allows us to add and remove elements from the repository (shown as a `Map` in the snippet) at runtime. + +| |It would be unsafe to simply take any issuer and construct an `ReactiveAuthenticationManager` from it.
The issuer should be one that the code can verify from a trusted source like an allowed list of issuers.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Opaque Token](opaque-token.html)[Bearer Tokens](bearer-tokens.html) + diff --git a/docs/en/spring-security/reactive-oauth2-resource-server-opaque-token.md b/docs/en/spring-security/reactive-oauth2-resource-server-opaque-token.md new file mode 100644 index 0000000000000000000000000000000000000000..2f7274bde520a177e5d3df4001e4cfbdad9bf650 --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-resource-server-opaque-token.md @@ -0,0 +1,733 @@ +# OAuth 2.0 Resource Server Opaque Token + +## Minimal Dependencies for Introspection + +As described in [Minimal Dependencies for JWT](../../../servlet/oauth2/resource-server/jwt.html#oauth2resourceserver-jwt-minimaldependencies) most of Resource Server support is collected in `spring-security-oauth2-resource-server`. +However unless a custom [`ReactiveOpaqueTokenIntrospector`](#webflux-oauth2resourceserver-opaque-introspector-bean) is provided, the Resource Server will fallback to ReactiveOpaqueTokenIntrospector. +Meaning that both `spring-security-oauth2-resource-server` and `oauth2-oidc-sdk` are necessary in order to have a working minimal Resource Server that supports opaque Bearer Tokens. +Please refer to `spring-security-oauth2-resource-server` in order to determin the correct version for `oauth2-oidc-sdk`. + +## Minimal Configuration for Introspection + +Typically, an opaque token can be verified via an [OAuth 2.0 Introspection Endpoint](https://tools.ietf.org/html/rfc7662), hosted by the authorization server. +This can be handy when revocation is a requirement. + +When using [Spring Boot](https://spring.io/projects/spring-boot), configuring an application as a resource server that uses introspection consists of two basic steps. +First, include the needed dependencies and second, indicate the introspection endpoint details. + +### Specifying the Authorization Server + +To specify where the introspection endpoint is, simply do: + +``` +security: + oauth2: + resourceserver: + opaque-token: + introspection-uri: https://idp.example.com/introspect + client-id: client + client-secret: secret +``` + +Where `[https://idp.example.com/introspect](https://idp.example.com/introspect)` is the introspection endpoint hosted by your authorization server and `client-id` and `client-secret` are the credentials needed to hit that endpoint. + +Resource Server will use these properties to further self-configure and subsequently validate incoming JWTs. + +| |When using introspection, the authorization server’s word is the law.
If the authorization server responses that the token is valid, then it is.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------| + +And that’s it! + +### Startup Expectations + +When this property and these dependencies are used, Resource Server will automatically configure itself to validate Opaque Bearer Tokens. + +This startup process is quite a bit simpler than for JWTs since no endpoints need to be discovered and no additional validation rules get added. + +### Runtime Expectations + +Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header: + +``` +GET / HTTP/1.1 +Authorization: Bearer some-token-value # Resource Server will process this +``` + +So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification. + +Given an Opaque Token, Resource Server will + +1. Query the provided introspection endpoint using the provided credentials and the token + +2. Inspect the response for an `{ 'active' : true }` attribute + +3. Map each scope to an authority with the prefix `SCOPE_` + +The resulting `Authentication#getPrincipal`, by default, is a Spring Security `[OAuth2AuthenticatedPrincipal](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.html)` object, and `Authentication#getName` maps to the token’s `sub` property, if one is present. + +From here, you may want to jump to: + +* [Looking Up Attributes Post-Authentication](#webflux-oauth2resourceserver-opaque-attributes) + +* [Extracting Authorities Manually](#webflux-oauth2resourceserver-opaque-authorization-extraction) + +* [Using Introspection with JWTs](#webflux-oauth2resourceserver-opaque-jwt-introspector) + +## Looking Up Attributes Post-Authentication + +Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`. + +This means that it’s available in `@Controller` methods when using `@EnableWebFlux` in your configuration: + +Java + +``` +@GetMapping("/foo") +public Mono foo(BearerTokenAuthentication authentication) { + return Mono.just(authentication.getTokenAttributes().get("sub") + " is the subject"); +} +``` + +Kotlin + +``` +@GetMapping("/foo") +fun foo(authentication: BearerTokenAuthentication): Mono { + return Mono.just(authentication.tokenAttributes["sub"].toString() + " is the subject") +} +``` + +Since `BearerTokenAuthentication` holds an `OAuth2AuthenticatedPrincipal`, that also means that it’s available to controller methods, too: + +Java + +``` +@GetMapping("/foo") +public Mono foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) { + return Mono.just(principal.getAttribute("sub") + " is the subject"); +} +``` + +Kotlin + +``` +@GetMapping("/foo") +fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): Mono { + return Mono.just(principal.getAttribute("sub").toString() + " is the subject") +} +``` + +### Looking Up Attributes Via SpEL + +Of course, this also means that attributes can be accessed via SpEL. + +For example, if using `@EnableReactiveMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do: + +Java + +``` +@PreAuthorize("principal?.attributes['sub'] = 'foo'") +public Mono forFoosEyesOnly() { + return Mono.just("foo"); +} +``` + +Kotlin + +``` +@PreAuthorize("principal.attributes['sub'] = 'foo'") +fun forFoosEyesOnly(): Mono { + return Mono.just("foo") +} +``` + +## Overriding or Replacing Boot Auto Configuration + +There are two `@Bean`s that Spring Boot generates on Resource Server’s behalf. + +The first is a `SecurityWebFilterChain` that configures the app as a resource server. +When use Opaque Token, this `SecurityWebFilterChain` looks like: + +Java + +``` +@Bean +SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken) + return http.build(); +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + opaqueToken { } + } + } +} +``` + +If the application doesn’t expose a `SecurityWebFilterChain` bean, then Spring Boot will expose the above default one. + +Replacing this is as simple as exposing the bean within the application: + +Example 1. Replacing SecurityWebFilterChain + +Java + +``` +@EnableWebFluxSecurity +public class MyCustomSecurityConfiguration { + @Bean + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .pathMatchers("/messages/**").hasAuthority("SCOPE_message:read") + .anyExchange().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2 + .opaqueToken(opaqueToken -> opaqueToken + .introspector(myIntrospector()) + ) + ); + return http.build(); + } +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize("/messages/**", hasAuthority("SCOPE_message:read")) + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + opaqueToken { + introspector = myIntrospector() + } + } + } +} +``` + +The above requires the scope of `message:read` for any URL that starts with `/messages/`. + +Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration. + +For example, the second `@Bean` Spring Boot creates is a `ReactiveOpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`: + +Java + +``` +@Bean +public ReactiveOpaqueTokenIntrospector introspector() { + return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret); +} +``` + +Kotlin + +``` +@Bean +fun introspector(): ReactiveOpaqueTokenIntrospector { + return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret) +} +``` + +If the application doesn’t expose a `ReactiveOpaqueTokenIntrospector` bean, then Spring Boot will expose the above default one. + +And its configuration can be overridden using `introspectionUri()` and `introspectionClientCredentials()` or replaced using `introspector()`. + +### ` + +An authorization server’s Introspection Uri can be configured [as a configuration property](#webflux-oauth2resourceserver-opaque-introspectionuri) or it can be supplied in the DSL: + +Java + +``` +@EnableWebFluxSecurity +public class DirectlyConfiguredIntrospectionUri { + @Bean + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2 + .opaqueToken(opaqueToken -> opaqueToken + .introspectionUri("https://idp.example.com/introspect") + .introspectionClientCredentials("client", "secret") + ) + ); + return http.build(); + } +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + opaqueToken { + introspectionUri = "https://idp.example.com/introspect" + introspectionClientCredentials("client", "secret") + } + } + } +} +``` + +Using `introspectionUri()` takes precedence over any configuration property. + +### ` + +More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of `ReactiveOpaqueTokenIntrospector`: + +Java + +``` +@EnableWebFluxSecurity +public class DirectlyConfiguredIntrospector { + @Bean + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .anyExchange().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2 + .opaqueToken(opaqueToken -> opaqueToken + .introspector(myCustomIntrospector()) + ) + ); + return http.build(); + } +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + opaqueToken { + introspector = myCustomIntrospector() + } + } + } +} +``` + +This is handy when deeper configuration, like [authority mapping](#webflux-oauth2resourceserver-opaque-authorization-extraction)or [JWT revocation](#webflux-oauth2resourceserver-opaque-jwt-introspector) is necessary. + +### Exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` + +Or, exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` has the same effect as `introspector()`: + +Java + +``` +@Bean +public ReactiveOpaqueTokenIntrospector introspector() { + return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret); +} +``` + +Kotlin + +``` +@Bean +fun introspector(): ReactiveOpaqueTokenIntrospector { + return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret) +} +``` + +## Configuring Authorization + +An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it’s been granted, for example: + +`{ …​, "scope" : "messages contacts"}` + +When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string "SCOPE\_". + +This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix: + +Java + +``` +@EnableWebFluxSecurity +public class MappedAuthorities { + @Bean + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchange -> exchange + .pathMatchers("/contacts/**").hasAuthority("SCOPE_contacts") + .pathMatchers("/messages/**").hasAuthority("SCOPE_messages") + .anyExchange().authenticated() + ) + .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken); + return http.build(); + } +} +``` + +Kotlin + +``` +@Bean +fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + return http { + authorizeExchange { + authorize("/contacts/**", hasAuthority("SCOPE_contacts")) + authorize("/messages/**", hasAuthority("SCOPE_messages")) + authorize(anyExchange, authenticated) + } + oauth2ResourceServer { + opaqueToken { } + } + } +} +``` + +Or similarly with method security: + +Java + +``` +@PreAuthorize("hasAuthority('SCOPE_messages')") +public Flux getMessages(...) {} +``` + +Kotlin + +``` +@PreAuthorize("hasAuthority('SCOPE_messages')") +fun getMessages(): Flux { } +``` + +### Extracting Authorities Manually + +By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances. + +For example, if the introspection response were: + +``` +{ + "active" : true, + "scope" : "message:read message:write" +} +``` + +Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`. + +This can, of course, be customized using a custom `ReactiveOpaqueTokenIntrospector` that takes a look at the attribute set and converts in its own way: + +Java + +``` +public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector { + private ReactiveOpaqueTokenIntrospector delegate = + new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret"); + + public Mono introspect(String token) { + return this.delegate.introspect(token) + .map(principal -> new DefaultOAuth2AuthenticatedPrincipal( + principal.getName(), principal.getAttributes(), extractAuthorities(principal))); + } + + private Collection extractAuthorities(OAuth2AuthenticatedPrincipal principal) { + List scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE); + return scopes.stream() + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + } +} +``` + +Kotlin + +``` +class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector { + private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret") + override fun introspect(token: String): Mono { + return delegate.introspect(token) + .map { principal: OAuth2AuthenticatedPrincipal -> + DefaultOAuth2AuthenticatedPrincipal( + principal.name, principal.attributes, extractAuthorities(principal)) + } + } + + private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection { + val scopes = principal.getAttribute>(OAuth2IntrospectionClaimNames.SCOPE) + return scopes + .map { SimpleGrantedAuthority(it) } + } +} +``` + +Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`: + +Java + +``` +@Bean +public ReactiveOpaqueTokenIntrospector introspector() { + return new CustomAuthoritiesOpaqueTokenIntrospector(); +} +``` + +Kotlin + +``` +@Bean +fun introspector(): ReactiveOpaqueTokenIntrospector { + return CustomAuthoritiesOpaqueTokenIntrospector() +} +``` + +## Using Introspection with JWTs + +A common question is whether or not introspection is compatible with JWTs. +Spring Security’s Opaque Token support has been designed to not care about the format of the token — it will gladly pass any token to the introspection endpoint provided. + +So, let’s say that you’ve got a requirement that requires you to check with the authorization server on each request, in case the JWT has been revoked. + +Even though you are using the JWT format for the token, your validation method is introspection, meaning you’d want to do: + +``` +spring: + security: + oauth2: + resourceserver: + opaque-token: + introspection-uri: https://idp.example.org/introspection + client-id: client + client-secret: secret +``` + +In this case, the resulting `Authentication` would be `BearerTokenAuthentication`. +Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint. + +But, let’s say that, oddly enough, the introspection endpoint only returns whether or not the token is active. +Now what? + +In this case, you can create a custom `ReactiveOpaqueTokenIntrospector` that still hits the endpoint, but then updates the returned principal to have the JWTs claims as the attributes: + +Java + +``` +public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector { + private ReactiveOpaqueTokenIntrospector delegate = + new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret"); + private ReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder(new ParseOnlyJWTProcessor()); + + public Mono introspect(String token) { + return this.delegate.introspect(token) + .flatMap(principal -> this.jwtDecoder.decode(token)) + .map(jwt -> new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES)); + } + + private static class ParseOnlyJWTProcessor implements Converter> { + public Mono convert(JWT jwt) { + try { + return Mono.just(jwt.getJWTClaimsSet()); + } catch (Exception ex) { + return Mono.error(ex); + } + } + } +} +``` + +Kotlin + +``` +class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector { + private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret") + private val jwtDecoder: ReactiveJwtDecoder = NimbusReactiveJwtDecoder(ParseOnlyJWTProcessor()) + override fun introspect(token: String): Mono { + return delegate.introspect(token) + .flatMap { jwtDecoder.decode(token) } + .map { jwt: Jwt -> DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES) } + } + + private class ParseOnlyJWTProcessor : Converter> { + override fun convert(jwt: JWT): Mono { + return try { + Mono.just(jwt.jwtClaimsSet) + } catch (e: Exception) { + Mono.error(e) + } + } + } +} +``` + +Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`: + +Java + +``` +@Bean +public ReactiveOpaqueTokenIntrospector introspector() { + return new JwtOpaqueTokenIntropsector(); +} +``` + +Kotlin + +``` +@Bean +fun introspector(): ReactiveOpaqueTokenIntrospector { + return JwtOpaqueTokenIntrospector() +} +``` + +## Calling a `/userinfo` Endpoint + +Generally speaking, a Resource Server doesn’t care about the underlying user, but instead about the authorities that have been granted. + +That said, at times it can be valuable to tie the authorization statement back to a user. + +If an application is also using `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, then this is quite simple with a custom `OpaqueTokenIntrospector`. +This implementation below does three things: + +* Delegates to the introspection endpoint, to affirm the token’s validity + +* Looks up the appropriate client registration associated with the `/userinfo` endpoint + +* Invokes and returns the response from the `/userinfo` endpoint + +Java + +``` +public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector { + private final ReactiveOpaqueTokenIntrospector delegate = + new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret"); + private final ReactiveOAuth2UserService oauth2UserService = + new DefaultReactiveOAuth2UserService(); + + private final ReactiveClientRegistrationRepository repository; + + // ... constructor + + @Override + public Mono introspect(String token) { + return Mono.zip(this.delegate.introspect(token), this.repository.findByRegistrationId("registration-id")) + .map(t -> { + OAuth2AuthenticatedPrincipal authorized = t.getT1(); + ClientRegistration clientRegistration = t.getT2(); + Instant issuedAt = authorized.getAttribute(ISSUED_AT); + Instant expiresAt = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT); + OAuth2AccessToken accessToken = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt); + return new OAuth2UserRequest(clientRegistration, accessToken); + }) + .flatMap(this.oauth2UserService::loadUser); + } +} +``` + +Kotlin + +``` +class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector { + private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret") + private val oauth2UserService: ReactiveOAuth2UserService = DefaultReactiveOAuth2UserService() + private val repository: ReactiveClientRegistrationRepository? = null + + // ... constructor + override fun introspect(token: String?): Mono { + return Mono.zip(delegate.introspect(token), repository!!.findByRegistrationId("registration-id")) + .map { t: Tuple2 -> + val authorized = t.t1 + val clientRegistration = t.t2 + val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT) + val expiresAt: Instant? = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT) + val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt) + OAuth2UserRequest(clientRegistration, accessToken) + } + .flatMap { userRequest: OAuth2UserRequest -> oauth2UserService.loadUser(userRequest) } + } +} +``` + +If you aren’t using `spring-security-oauth2-client`, it’s still quite simple. +You will simply need to invoke the `/userinfo` with your own instance of `WebClient`: + +Java + +``` +public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector { + private final ReactiveOpaqueTokenIntrospector delegate = + new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret"); + private final WebClient rest = WebClient.create(); + + @Override + public Mono introspect(String token) { + return this.delegate.introspect(token) + .map(this::makeUserInfoRequest); + } +} +``` + +Kotlin + +``` +class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector { + private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret") + private val rest: WebClient = WebClient.create() + + override fun introspect(token: String): Mono { + return delegate.introspect(token) + .map(this::makeUserInfoRequest) + } +} +``` + +Either way, having created your `ReactiveOpaqueTokenIntrospector`, you should publish it as a `@Bean` to override the defaults: + +Java + +``` +@Bean +ReactiveOpaqueTokenIntrospector introspector() { + return new UserInfoOpaqueTokenIntrospector(); +} +``` + +Kotlin + +``` +@Bean +fun introspector(): ReactiveOpaqueTokenIntrospector { + return UserInfoOpaqueTokenIntrospector() +} +``` + +[JWT](jwt.html)[Multitenancy](multitenancy.html) + diff --git a/docs/en/spring-security/reactive-oauth2-resource-server.md b/docs/en/spring-security/reactive-oauth2-resource-server.md new file mode 100644 index 0000000000000000000000000000000000000000..def335925b6443995cfe3d4dbf8a0ba53c1bce0b --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2-resource-server.md @@ -0,0 +1,16 @@ +# OAuth 2.0 Resource Server + +Spring Security supports protecting endpoints using two forms of OAuth 2.0 [Bearer Tokens](https://tools.ietf.org/html/rfc6750.html): + +* [JWT](https://tools.ietf.org/html/rfc7519) + +* Opaque Tokens + +This is handy in circumstances where an application has delegated its authority management to an [authorization server](https://tools.ietf.org/html/rfc6749) (for example, Okta or Ping Identity). +This authorization server can be consulted by resource servers to authorize requests. + +| |A complete working example for [**JWTs**](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/reactive/webflux/java/oauth2/resource-server) is available in the [Spring Security repository](https://github.com/spring-projects/spring-security-samples/tree/5.6.x).| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[OAuth2 Authorized Clients](../client/authorized-clients.html)[JWT](jwt.html) + diff --git a/docs/en/spring-security/reactive-oauth2.md b/docs/en/spring-security/reactive-oauth2.md new file mode 100644 index 0000000000000000000000000000000000000000..e553530d3ff3ae13ebd7cf2146153ecb6fc74b3b --- /dev/null +++ b/docs/en/spring-security/reactive-oauth2.md @@ -0,0 +1,12 @@ +# OAuth2 WebFlux + +Spring Security provides OAuth2 and WebFlux integration for reactive applications. + +* [OAuth2 Log In](login/index.html) - Authenticating with an OAuth2 or OpenID Connect 1.0 Provider + +* [OAuth2 Client](client/index.html) - Making requests to an OAuth2 Resource Server + +* [OAuth2 Resource Server](resource-server/index.html) - Protecting a REST endpoint using OAuth2 + +[EnableReactiveMethodSecurity](../authorization/method.html)[OAuth2 Log In](login/index.html) + diff --git a/docs/en/spring-security/reactive-test-method.md b/docs/en/spring-security/reactive-test-method.md new file mode 100644 index 0000000000000000000000000000000000000000..d223484e1aad62a3ff3ad55fa9e644856d09f089 --- /dev/null +++ b/docs/en/spring-security/reactive-test-method.md @@ -0,0 +1,75 @@ +# Testing Method Security + +For example, we can test our example from [EnableReactiveMethodSecurity](../authorization/method.html#jc-erms) using the same setup and annotations we did in [Testing Method Security](../../servlet/test/method.html#test-method). +Here is a minimal sample of what we can do: + +Java + +``` +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = HelloWebfluxMethodApplication.class) +public class HelloWorldMessageServiceTests { + @Autowired + HelloWorldMessageService messages; + + @Test + public void messagesWhenNotAuthenticatedThenDenied() { + StepVerifier.create(this.messages.findMessage()) + .expectError(AccessDeniedException.class) + .verify(); + } + + @Test + @WithMockUser + public void messagesWhenUserThenDenied() { + StepVerifier.create(this.messages.findMessage()) + .expectError(AccessDeniedException.class) + .verify(); + } + + @Test + @WithMockUser(roles = "ADMIN") + public void messagesWhenAdminThenOk() { + StepVerifier.create(this.messages.findMessage()) + .expectNext("Hello World!") + .verifyComplete(); + } +} +``` + +Kotlin + +``` +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [HelloWebfluxMethodApplication::class]) +class HelloWorldMessageServiceTests { + @Autowired + lateinit var messages: HelloWorldMessageService + + @Test + fun messagesWhenNotAuthenticatedThenDenied() { + StepVerifier.create(messages.findMessage()) + .expectError(AccessDeniedException::class.java) + .verify() + } + + @Test + @WithMockUser + fun messagesWhenUserThenDenied() { + StepVerifier.create(messages.findMessage()) + .expectError(AccessDeniedException::class.java) + .verify() + } + + @Test + @WithMockUser(roles = ["ADMIN"]) + fun messagesWhenAdminThenOk() { + StepVerifier.create(messages.findMessage()) + .expectNext("Hello World!") + .verifyComplete() + } +} +``` + +[Testing](index.html)[Testing Web Security](web/index.html) + diff --git a/docs/en/spring-security/reactive-test-web-authentication.md b/docs/en/spring-security/reactive-test-web-authentication.md new file mode 100644 index 0000000000000000000000000000000000000000..ce15ecfd3c701b55a3da1937336e94b6ce90ee16 --- /dev/null +++ b/docs/en/spring-security/reactive-test-web-authentication.md @@ -0,0 +1,115 @@ +# Testing Authentication + +After [applying the Spring Security support to `WebTestClient`](setup.html) we can use either annotations or `mutateWith` support. +For example: + +Java + +``` +@Test +public void messageWhenNotAuthenticated() throws Exception { + this.rest + .get() + .uri("/message") + .exchange() + .expectStatus().isUnauthorized(); +} + +// --- WithMockUser --- + +@Test +@WithMockUser +public void messageWhenWithMockUserThenForbidden() throws Exception { + this.rest + .get() + .uri("/message") + .exchange() + .expectStatus().isEqualTo(HttpStatus.FORBIDDEN); +} + +@Test +@WithMockUser(roles = "ADMIN") +public void messageWhenWithMockAdminThenOk() throws Exception { + this.rest + .get() + .uri("/message") + .exchange() + .expectStatus().isOk() + .expectBody(String.class).isEqualTo("Hello World!"); +} + +// --- mutateWith mockUser --- + +@Test +public void messageWhenMutateWithMockUserThenForbidden() throws Exception { + this.rest + .mutateWith(mockUser()) + .get() + .uri("/message") + .exchange() + .expectStatus().isEqualTo(HttpStatus.FORBIDDEN); +} + +@Test +public void messageWhenMutateWithMockAdminThenOk() throws Exception { + this.rest + .mutateWith(mockUser().roles("ADMIN")) + .get() + .uri("/message") + .exchange() + .expectStatus().isOk() + .expectBody(String.class).isEqualTo("Hello World!"); +} +``` + +Kotlin + +``` +import org.springframework.test.web.reactive.server.expectBody + +//... + +@Test +@WithMockUser +fun messageWhenWithMockUserThenForbidden() { + this.rest.get().uri("/message") + .exchange() + .expectStatus().isEqualTo(HttpStatus.FORBIDDEN) +} + +@Test +@WithMockUser(roles = ["ADMIN"]) +fun messageWhenWithMockAdminThenOk() { + this.rest.get().uri("/message") + .exchange() + .expectStatus().isOk + .expectBody().isEqualTo("Hello World!") + +} + +// --- mutateWith mockUser --- + +@Test +fun messageWhenMutateWithMockUserThenForbidden() { + this.rest + .mutateWith(mockUser()) + .get().uri("/message") + .exchange() + .expectStatus().isEqualTo(HttpStatus.FORBIDDEN) +} + +@Test +fun messageWhenMutateWithMockAdminThenOk() { + this.rest + .mutateWith(mockUser().roles("ADMIN")) + .get().uri("/message") + .exchange() + .expectStatus().isOk + .expectBody().isEqualTo("Hello World!") +} +``` + +In addition to `mockUser()`, Spring Security ships with several other convenience mutators for things like [CSRF](csrf.html) and [OAuth 2.0](oauth2.html). + +[WebTestClient Setup](setup.html)[Testing CSRF](csrf.html) + diff --git a/docs/en/spring-security/reactive-test-web-csrf.md b/docs/en/spring-security/reactive-test-web-csrf.md new file mode 100644 index 0000000000000000000000000000000000000000..5db18abb59309910f3ae41076f449ce4903555b5 --- /dev/null +++ b/docs/en/spring-security/reactive-test-web-csrf.md @@ -0,0 +1,29 @@ +# Testing with CSRF + +Spring Security also provides support for CSRF testing with `WebTestClient`. +For example: + +Java + +``` +this.rest + // provide a valid CSRF token + .mutateWith(csrf()) + .post() + .uri("/login") + ... +``` + +Kotlin + +``` +this.rest + // provide a valid CSRF token + .mutateWith(csrf()) + .post() + .uri("/login") + ... +``` + +[Testing Authentication](authentication.html)[Testing OAuth 2.0](oauth2.html) + diff --git a/docs/en/spring-security/reactive-test-web-oauth2.md b/docs/en/spring-security/reactive-test-web-oauth2.md new file mode 100644 index 0000000000000000000000000000000000000000..8f44ba9b68fd7288cec2a9b8ed0a1bf6285dc1d6 --- /dev/null +++ b/docs/en/spring-security/reactive-test-web-oauth2.md @@ -0,0 +1,1054 @@ +# Testing OAuth 2.0 + +When it comes to OAuth 2.0, [the same principles covered earlier still apply](../method.html#test-erms): Ultimately, it depends on what your method under test is expecting to be in the `SecurityContextHolder`. + +For example, for a controller that looks like this: + +Java + +``` +@GetMapping("/endpoint") +public Mono foo(Principal user) { + return Mono.just(user.getName()); +} +``` + +Kotlin + +``` +@GetMapping("/endpoint") +fun foo(user: Principal): Mono { + return Mono.just(user.name) +} +``` + +There’s nothing OAuth2-specific about it, so you will likely be able to simply [use `@WithMockUser`](../method.html#test-erms) and be fine. + +But, in cases where your controllers are bound to some aspect of Spring Security’s OAuth 2.0 support, like the following: + +Java + +``` +@GetMapping("/endpoint") +public Mono foo(@AuthenticationPrincipal OidcUser user) { + return Mono.just(user.getIdToken().getSubject()); +} +``` + +Kotlin + +``` +@GetMapping("/endpoint") +fun foo(@AuthenticationPrincipal user: OidcUser): Mono { + return Mono.just(user.idToken.subject) +} +``` + +then Spring Security’s test support can come in handy. + +## Testing OIDC Login + +Testing the method above with `WebTestClient` would require simulating some kind of grant flow with an authorization server. +Certainly this would be a daunting task, which is why Spring Security ships with support for removing this boilerplate. + +For example, we can tell Spring Security to include a default `OidcUser` using the `SecurityMockServerConfigurers#mockOidcLogin` method, like so: + +Java + +``` +client + .mutateWith(mockOidcLogin()).get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOidcLogin()) + .get().uri("/endpoint") + .exchange() +``` + +What this will do is configure the associated `MockServerRequest` with an `OidcUser` that includes a simple `OidcIdToken`, `OidcUserInfo`, and `Collection` of granted authorities. + +Specifically, it will include an `OidcIdToken` with a `sub` claim set to `user`: + +Java + +``` +assertThat(user.getIdToken().getClaim("sub")).isEqualTo("user"); +``` + +Kotlin + +``` +assertThat(user.idToken.getClaim("sub")).isEqualTo("user") +``` + +an `OidcUserInfo` with no claims set: + +Java + +``` +assertThat(user.getUserInfo().getClaims()).isEmpty(); +``` + +Kotlin + +``` +assertThat(user.userInfo.claims).isEmpty() +``` + +and a `Collection` of authorities with just one authority, `SCOPE_read`: + +Java + +``` +assertThat(user.getAuthorities()).hasSize(1); +assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read")); +``` + +Kotlin + +``` +assertThat(user.authorities).hasSize(1) +assertThat(user.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read")) +``` + +Spring Security does the necessary work to make sure that the `OidcUser` instance is available for [the `@AuthenticationPrincipal` annotation](../../../servlet/integrations/mvc.html#mvc-authentication-principal). + +Further, it also links that `OidcUser` to a simple instance of `OAuth2AuthorizedClient` that it deposits into a mock `ServerOAuth2AuthorizedClientRepository`. +This can be handy if your tests [use the `@RegisteredOAuth2AuthorizedClient` annotation](#webflux-testing-oauth2-client).. + +### Configuring Authorities + +In many circumstances, your method is protected by filter or method security and needs your `Authentication` to have certain granted authorities to allow the request. + +In this case, you can supply what granted authorities you need using the `authorities()` method: + +Java + +``` +client + .mutateWith(mockOidcLogin() + .authorities(new SimpleGrantedAuthority("SCOPE_message:read")) + ) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOidcLogin() + .authorities(SimpleGrantedAuthority("SCOPE_message:read")) + ) + .get().uri("/endpoint").exchange() +``` + +### Configuring Claims + +And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0. + +Let’s say, for example, that you’ve got a `user_id` claim that indicates the user’s id in your system. +You might access it like so in a controller: + +Java + +``` +@GetMapping("/endpoint") +public Mono foo(@AuthenticationPrincipal OidcUser oidcUser) { + String userId = oidcUser.getIdToken().getClaim("user_id"); + // ... +} +``` + +Kotlin + +``` +@GetMapping("/endpoint") +fun foo(@AuthenticationPrincipal oidcUser: OidcUser): Mono { + val userId = oidcUser.idToken.getClaim("user_id") + // ... +} +``` + +In that case, you’d want to specify that claim with the `idToken()` method: + +Java + +``` +client + .mutateWith(mockOidcLogin() + .idToken(token -> token.claim("user_id", "1234")) + ) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOidcLogin() + .idToken { token -> token.claim("user_id", "1234") } + ) + .get().uri("/endpoint").exchange() +``` + +since `OidcUser` collects its claims from `OidcIdToken`. + +### Additional Configurations + +There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects: + +* `userInfo(OidcUserInfo.Builder)` - For configuring the `OidcUserInfo` instance + +* `clientRegistration(ClientRegistration)` - For configuring the associated `OAuth2AuthorizedClient` with a given `ClientRegistration` + +* `oidcUser(OidcUser)` - For configuring the complete `OidcUser` instance + +That last one is handy if you: +1. Have your own implementation of `OidcUser`, or +2. Need to change the name attribute + +For example, let’s say that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim. +In that case, you can configure an `OidcUser` by hand: + +Java + +``` +OidcUser oidcUser = new DefaultOidcUser( + AuthorityUtils.createAuthorityList("SCOPE_message:read"), + OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(), + "user_name"); + +client + .mutateWith(mockOidcLogin().oidcUser(oidcUser)) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +val oidcUser: OidcUser = DefaultOidcUser( + AuthorityUtils.createAuthorityList("SCOPE_message:read"), + OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(), + "user_name" +) + +client + .mutateWith(mockOidcLogin().oidcUser(oidcUser)) + .get().uri("/endpoint").exchange() +``` + +## Testing OAuth 2.0 Login + +As with [testing OIDC login](#webflux-testing-oidc-login), testing OAuth 2.0 Login presents a similar challenge of mocking a grant flow. +And because of that, Spring Security also has test support for non-OIDC use cases. + +Let’s say that we’ve got a controller that gets the logged-in user as an `OAuth2User`: + +Java + +``` +@GetMapping("/endpoint") +public Mono foo(@AuthenticationPrincipal OAuth2User oauth2User) { + return Mono.just(oauth2User.getAttribute("sub")); +} +``` + +Kotlin + +``` +@GetMapping("/endpoint") +fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): Mono { + return Mono.just(oauth2User.getAttribute("sub")) +} +``` + +In that case, we can tell Spring Security to include a default `OAuth2User` using the `SecurityMockServerConfigurers#mockOAuth2Login` method, like so: + +Java + +``` +client + .mutateWith(mockOAuth2Login()) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOAuth2Login()) + .get().uri("/endpoint").exchange() +``` + +What this will do is configure the associated `MockServerRequest` with an `OAuth2User` that includes a simple `Map` of attributes and `Collection` of granted authorities. + +Specifically, it will include a `Map` with a key/value pair of `sub`/`user`: + +Java + +``` +assertThat((String) user.getAttribute("sub")).isEqualTo("user"); +``` + +Kotlin + +``` +assertThat(user.getAttribute("sub")).isEqualTo("user") +``` + +and a `Collection` of authorities with just one authority, `SCOPE_read`: + +Java + +``` +assertThat(user.getAuthorities()).hasSize(1); +assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read")); +``` + +Kotlin + +``` +assertThat(user.authorities).hasSize(1) +assertThat(user.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read")) +``` + +Spring Security does the necessary work to make sure that the `OAuth2User` instance is available for [the `@AuthenticationPrincipal` annotation](../../../servlet/integrations/mvc.html#mvc-authentication-principal). + +Further, it also links that `OAuth2User` to a simple instance of `OAuth2AuthorizedClient` that it deposits in a mock `ServerOAuth2AuthorizedClientRepository`. +This can be handy if your tests [use the `@RegisteredOAuth2AuthorizedClient` annotation](#webflux-testing-oauth2-client). + +### Configuring Authorities + +In many circumstances, your method is protected by filter or method security and needs your `Authentication` to have certain granted authorities to allow the request. + +In this case, you can supply what granted authorities you need using the `authorities()` method: + +Java + +``` +client + .mutateWith(mockOAuth2Login() + .authorities(new SimpleGrantedAuthority("SCOPE_message:read")) + ) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOAuth2Login() + .authorities(SimpleGrantedAuthority("SCOPE_message:read")) + ) + .get().uri("/endpoint").exchange() +``` + +### Configuring Claims + +And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0. + +Let’s say, for example, that you’ve got a `user_id` attribute that indicates the user’s id in your system. +You might access it like so in a controller: + +Java + +``` +@GetMapping("/endpoint") +public Mono foo(@AuthenticationPrincipal OAuth2User oauth2User) { + String userId = oauth2User.getAttribute("user_id"); + // ... +} +``` + +Kotlin + +``` +@GetMapping("/endpoint") +fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): Mono { + val userId = oauth2User.getAttribute("user_id") + // ... +} +``` + +In that case, you’d want to specify that attribute with the `attributes()` method: + +Java + +``` +client + .mutateWith(mockOAuth2Login() + .attributes(attrs -> attrs.put("user_id", "1234")) + ) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOAuth2Login() + .attributes { attrs -> attrs["user_id"] = "1234" } + ) + .get().uri("/endpoint").exchange() +``` + +### Additional Configurations + +There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects: + +* `clientRegistration(ClientRegistration)` - For configuring the associated `OAuth2AuthorizedClient` with a given `ClientRegistration` + +* `oauth2User(OAuth2User)` - For configuring the complete `OAuth2User` instance + +That last one is handy if you: +1. Have your own implementation of `OAuth2User`, or +2. Need to change the name attribute + +For example, let’s say that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim. +In that case, you can configure an `OAuth2User` by hand: + +Java + +``` +OAuth2User oauth2User = new DefaultOAuth2User( + AuthorityUtils.createAuthorityList("SCOPE_message:read"), + Collections.singletonMap("user_name", "foo_user"), + "user_name"); + +client + .mutateWith(mockOAuth2Login().oauth2User(oauth2User)) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +val oauth2User: OAuth2User = DefaultOAuth2User( + AuthorityUtils.createAuthorityList("SCOPE_message:read"), + mapOf(Pair("user_name", "foo_user")), + "user_name" +) + +client + .mutateWith(mockOAuth2Login().oauth2User(oauth2User)) + .get().uri("/endpoint").exchange() +``` + +## Testing OAuth 2.0 Clients + +Independent of how your user authenticates, you may have other tokens and client registrations that are in play for the request you are testing. +For example, your controller may be relying on the client credentials grant to get a token that isn’t associated with the user at all: + +Java + +``` +@GetMapping("/endpoint") +public Mono foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) { + return this.webClient.get() + .attributes(oauth2AuthorizedClient(authorizedClient)) + .retrieve() + .bodyToMono(String.class); +} +``` + +Kotlin + +``` +import org.springframework.web.reactive.function.client.bodyToMono + +// ... + +@GetMapping("/endpoint") +fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient?): Mono { + return this.webClient.get() + .attributes(oauth2AuthorizedClient(authorizedClient)) + .retrieve() + .bodyToMono() +} +``` + +Simulating this handshake with the authorization server could be cumbersome. +Instead, you can use `SecurityMockServerConfigurers#mockOAuth2Client` to add a `OAuth2AuthorizedClient` into a mock `ServerOAuth2AuthorizedClientRepository`: + +Java + +``` +client + .mutateWith(mockOAuth2Client("my-app")) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOAuth2Client("my-app")) + .get().uri("/endpoint").exchange() +``` + +What this will do is create an `OAuth2AuthorizedClient` that has a simple `ClientRegistration`, `OAuth2AccessToken`, and resource owner name. + +Specifically, it will include a `ClientRegistration` with a client id of "test-client" and client secret of "test-secret": + +Java + +``` +assertThat(authorizedClient.getClientRegistration().getClientId()).isEqualTo("test-client"); +assertThat(authorizedClient.getClientRegistration().getClientSecret()).isEqualTo("test-secret"); +``` + +Kotlin + +``` +assertThat(authorizedClient.clientRegistration.clientId).isEqualTo("test-client") +assertThat(authorizedClient.clientRegistration.clientSecret).isEqualTo("test-secret") +``` + +a resource owner name of "user": + +Java + +``` +assertThat(authorizedClient.getPrincipalName()).isEqualTo("user"); +``` + +Kotlin + +``` +assertThat(authorizedClient.principalName).isEqualTo("user") +``` + +and an `OAuth2AccessToken` with just one scope, `read`: + +Java + +``` +assertThat(authorizedClient.getAccessToken().getScopes()).hasSize(1); +assertThat(authorizedClient.getAccessToken().getScopes()).containsExactly("read"); +``` + +Kotlin + +``` +assertThat(authorizedClient.accessToken.scopes).hasSize(1) +assertThat(authorizedClient.accessToken.scopes).containsExactly("read") +``` + +The client can then be retrieved as normal using `@RegisteredOAuth2AuthorizedClient` in a controller method. + +### Configuring Scopes + +In many circumstances, the OAuth 2.0 access token comes with a set of scopes. +If your controller inspects these, say like so: + +Java + +``` +@GetMapping("/endpoint") +public Mono foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) { + Set scopes = authorizedClient.getAccessToken().getScopes(); + if (scopes.contains("message:read")) { + return this.webClient.get() + .attributes(oauth2AuthorizedClient(authorizedClient)) + .retrieve() + .bodyToMono(String.class); + } + // ... +} +``` + +Kotlin + +``` +import org.springframework.web.reactive.function.client.bodyToMono + +// ... + +@GetMapping("/endpoint") +fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient): Mono { + val scopes = authorizedClient.accessToken.scopes + if (scopes.contains("message:read")) { + return webClient.get() + .attributes(oauth2AuthorizedClient(authorizedClient)) + .retrieve() + .bodyToMono() + } + // ... +} +``` + +then you can configure the scope using the `accessToken()` method: + +Java + +``` +client + .mutateWith(mockOAuth2Client("my-app") + .accessToken(new OAuth2AccessToken(BEARER, "token", null, null, Collections.singleton("message:read"))) + ) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOAuth2Client("my-app") + .accessToken(OAuth2AccessToken(BEARER, "token", null, null, setOf("message:read"))) +) +.get().uri("/endpoint").exchange() +``` + +### Additional Configurations + +There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects: + +* `principalName(String)` - For configuring the resource owner name + +* `clientRegistration(Consumer)` - For configuring the associated `ClientRegistration` + +* `clientRegistration(ClientRegistration)` - For configuring the complete `ClientRegistration` + +That last one is handy if you want to use a real `ClientRegistration` + +For example, let’s say that you are wanting to use one of your app’s `ClientRegistration` definitions, as specified in your `application.yml`. + +In that case, your test can autowire the `ReactiveClientRegistrationRepository` and look up the one your test needs: + +Java + +``` +@Autowired +ReactiveClientRegistrationRepository clientRegistrationRepository; + +// ... + +client + .mutateWith(mockOAuth2Client() + .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block()) + ) + .get().uri("/exchange").exchange(); +``` + +Kotlin + +``` +@Autowired +lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository + +// ... + +client + .mutateWith(mockOAuth2Client() + .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block()) + ) + .get().uri("/exchange").exchange() +``` + +## Testing JWT Authentication + +In order to make an authorized request on a resource server, you need a bearer token. +If your resource server is configured for JWTs, then this would mean that the bearer token needs to be signed and then encoded according to the JWT specification. +All of this can be quite daunting, especially when this isn’t the focus of your test. + +Fortunately, there are a number of simple ways that you can overcome this difficulty and allow your tests to focus on authorization and not on representing bearer tokens. +We’ll look at two of them now: + +### WebTestClientConfigurer` + +The first way is via a `WebTestClientConfigurer`. +The simplest of these would be to use the `SecurityMockServerConfigurers#mockJwt` method like the following: + +Java + +``` +client + .mutateWith(mockJwt()).get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockJwt()).get().uri("/endpoint").exchange() +``` + +What this will do is create a mock `Jwt`, passing it correctly through any authentication APIs so that it’s available for your authorization mechanisms to verify. + +By default, the `JWT` that it creates has the following characteristics: + +``` +{ + "headers" : { "alg" : "none" }, + "claims" : { + "sub" : "user", + "scope" : "read" + } +} +``` + +And the resulting `Jwt`, were it tested, would pass in the following way: + +Java + +``` +assertThat(jwt.getTokenValue()).isEqualTo("token"); +assertThat(jwt.getHeaders().get("alg")).isEqualTo("none"); +assertThat(jwt.getSubject()).isEqualTo("sub"); +``` + +Kotlin + +``` +assertThat(jwt.tokenValue).isEqualTo("token") +assertThat(jwt.headers["alg"]).isEqualTo("none") +assertThat(jwt.subject).isEqualTo("sub") +``` + +These values can, of course be configured. + +Any headers or claims can be configured with their corresponding methods: + +Java + +``` +client + .mutateWith(mockJwt().jwt(jwt -> jwt.header("kid", "one") + .claim("iss", "https://idp.example.org"))) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockJwt().jwt { jwt -> jwt.header("kid", "one") + .claim("iss", "https://idp.example.org") + }) + .get().uri("/endpoint").exchange() +``` + +Java + +``` +client + .mutateWith(mockJwt().jwt(jwt -> jwt.claims(claims -> claims.remove("scope")))) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockJwt().jwt { jwt -> + jwt.claims { claims -> claims.remove("scope") } + }) + .get().uri("/endpoint").exchange() +``` + +The `scope` and `scp` claims are processed the same way here as they are in a normal bearer token request. +However, this can be overridden simply by providing the list of `GrantedAuthority` instances that you need for your test: + +Java + +``` +client + .mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("SCOPE_messages"))) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockJwt().authorities(SimpleGrantedAuthority("SCOPE_messages"))) + .get().uri("/endpoint").exchange() +``` + +Or, if you have a custom `Jwt` to `Collection` converter, you can also use that to derive the authorities: + +Java + +``` +client + .mutateWith(mockJwt().authorities(new MyConverter())) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockJwt().authorities(MyConverter())) + .get().uri("/endpoint").exchange() +``` + +You can also specify a complete `Jwt`, for which `[Jwt.Builder](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/jwt/Jwt.Builder.html)` comes quite handy: + +Java + +``` +Jwt jwt = Jwt.withTokenValue("token") + .header("alg", "none") + .claim("sub", "user") + .claim("scope", "read") + .build(); + +client + .mutateWith(mockJwt().jwt(jwt)) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +val jwt: Jwt = Jwt.withTokenValue("token") + .header("alg", "none") + .claim("sub", "user") + .claim("scope", "read") + .build() + +client + .mutateWith(mockJwt().jwt(jwt)) + .get().uri("/endpoint").exchange() +``` + +### ` `WebTestClientConfigurer` + +The second way is by using the `authentication()` `Mutator`. +Essentially, you can instantiate your own `JwtAuthenticationToken` and provide it in your test, like so: + +Java + +``` +Jwt jwt = Jwt.withTokenValue("token") + .header("alg", "none") + .claim("sub", "user") + .build(); +Collection authorities = AuthorityUtils.createAuthorityList("SCOPE_read"); +JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities); + +client + .mutateWith(mockAuthentication(token)) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +val jwt = Jwt.withTokenValue("token") + .header("alg", "none") + .claim("sub", "user") + .build() +val authorities: Collection = AuthorityUtils.createAuthorityList("SCOPE_read") +val token = JwtAuthenticationToken(jwt, authorities) + +client + .mutateWith(mockAuthentication(token)) + .get().uri("/endpoint").exchange() +``` + +Note that as an alternative to these, you can also mock the `ReactiveJwtDecoder` bean itself with a `@MockBean` annotation. + +## Testing Opaque Token Authentication + +Similar to [JWTs](#webflux-testing-jwt), opaque tokens require an authorization server in order to verify their validity, which can make testing more difficult. +To help with that, Spring Security has test support for opaque tokens. + +Let’s say that we’ve got a controller that retrieves the authentication as a `BearerTokenAuthentication`: + +Java + +``` +@GetMapping("/endpoint") +public Mono foo(BearerTokenAuthentication authentication) { + return Mono.just((String) authentication.getTokenAttributes().get("sub")); +} +``` + +Kotlin + +``` +@GetMapping("/endpoint") +fun foo(authentication: BearerTokenAuthentication): Mono { + return Mono.just(authentication.tokenAttributes["sub"] as String?) +} +``` + +In that case, we can tell Spring Security to include a default `BearerTokenAuthentication` using the `SecurityMockServerConfigurers#mockOpaqueToken` method, like so: + +Java + +``` +client + .mutateWith(mockOpaqueToken()) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOpaqueToken()) + .get().uri("/endpoint").exchange() +``` + +What this will do is configure the associated `MockHttpServletRequest` with a `BearerTokenAuthentication` that includes a simple `OAuth2AuthenticatedPrincipal`, `Map` of attributes, and `Collection` of granted authorities. + +Specifically, it will include a `Map` with a key/value pair of `sub`/`user`: + +Java + +``` +assertThat((String) token.getTokenAttributes().get("sub")).isEqualTo("user"); +``` + +Kotlin + +``` +assertThat(token.tokenAttributes["sub"] as String?).isEqualTo("user") +``` + +and a `Collection` of authorities with just one authority, `SCOPE_read`: + +Java + +``` +assertThat(token.getAuthorities()).hasSize(1); +assertThat(token.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read")); +``` + +Kotlin + +``` +assertThat(token.authorities).hasSize(1) +assertThat(token.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read")) +``` + +Spring Security does the necessary work to make sure that the `BearerTokenAuthentication` instance is available for your controller methods. + +### Configuring Authorities + +In many circumstances, your method is protected by filter or method security and needs your `Authentication` to have certain granted authorities to allow the request. + +In this case, you can supply what granted authorities you need using the `authorities()` method: + +Java + +``` +client + .mutateWith(mockOpaqueToken() + .authorities(new SimpleGrantedAuthority("SCOPE_message:read")) + ) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOpaqueToken() + .authorities(SimpleGrantedAuthority("SCOPE_message:read")) + ) + .get().uri("/endpoint").exchange() +``` + +### Configuring Claims + +And while granted authorities are quite common across all of Spring Security, we also have attributes in the case of OAuth 2.0. + +Let’s say, for example, that you’ve got a `user_id` attribute that indicates the user’s id in your system. +You might access it like so in a controller: + +Java + +``` +@GetMapping("/endpoint") +public Mono foo(BearerTokenAuthentication authentication) { + String userId = (String) authentication.getTokenAttributes().get("user_id"); + // ... +} +``` + +Kotlin + +``` +@GetMapping("/endpoint") +fun foo(authentication: BearerTokenAuthentication): Mono { + val userId = authentication.tokenAttributes["user_id"] as String? + // ... +} +``` + +In that case, you’d want to specify that attribute with the `attributes()` method: + +Java + +``` +client + .mutateWith(mockOpaqueToken() + .attributes(attrs -> attrs.put("user_id", "1234")) + ) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +client + .mutateWith(mockOpaqueToken() + .attributes { attrs -> attrs["user_id"] = "1234" } + ) + .get().uri("/endpoint").exchange() +``` + +### Additional Configurations + +There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects. + +One such is `principal(OAuth2AuthenticatedPrincipal)`, which you can use to configure the complete `OAuth2AuthenticatedPrincipal` instance that underlies the `BearerTokenAuthentication` + +It’s handy if you: +1. Have your own implementation of `OAuth2AuthenticatedPrincipal`, or +2. Want to specify a different principal name + +For example, let’s say that your authorization server sends the principal name in the `user_name` attribute instead of the `sub` attribute. +In that case, you can configure an `OAuth2AuthenticatedPrincipal` by hand: + +Java + +``` +Map attributes = Collections.singletonMap("user_name", "foo_user"); +OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal( + (String) attributes.get("user_name"), + attributes, + AuthorityUtils.createAuthorityList("SCOPE_message:read")); + +client + .mutateWith(mockOpaqueToken().principal(principal)) + .get().uri("/endpoint").exchange(); +``` + +Kotlin + +``` +val attributes: Map = mapOf(Pair("user_name", "foo_user")) +val principal: OAuth2AuthenticatedPrincipal = DefaultOAuth2AuthenticatedPrincipal( + attributes["user_name"] as String?, + attributes, + AuthorityUtils.createAuthorityList("SCOPE_message:read") +) + +client + .mutateWith(mockOpaqueToken().principal(principal)) + .get().uri("/endpoint").exchange() +``` + +Note that as an alternative to using `mockOpaqueToken()` test support, you can also mock the `OpaqueTokenIntrospector` bean itself with a `@MockBean` annotation. + +[Testing CSRF](csrf.html)[WebFlux Security](../../configuration/webflux.html) + diff --git a/docs/en/spring-security/reactive-test-web-setup.md b/docs/en/spring-security/reactive-test-web-setup.md new file mode 100644 index 0000000000000000000000000000000000000000..577eac931b988407f7a080cf31a3ae44554918ab --- /dev/null +++ b/docs/en/spring-security/reactive-test-web-setup.md @@ -0,0 +1,29 @@ +# WebTestClient Security Setup + +The basic setup looks like this: + +``` +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = HelloWebfluxMethodApplication.class) +public class HelloWebfluxMethodApplicationTests { + @Autowired + ApplicationContext context; + + WebTestClient rest; + + @Before + public void setup() { + this.rest = WebTestClient + .bindToApplicationContext(this.context) + // add Spring Security test Support + .apply(springSecurity()) + .configureClient() + .filter(basicAuthentication()) + .build(); + } + // ... +} +``` + +[Testing Web Security](index.html)[Testing Authentication](authentication.html) + diff --git a/docs/en/spring-security/reactive-test-web.md b/docs/en/spring-security/reactive-test-web.md new file mode 100644 index 0000000000000000000000000000000000000000..203c2a6bc2ff81f70cf78f06bcc3848c66938f1c --- /dev/null +++ b/docs/en/spring-security/reactive-test-web.md @@ -0,0 +1,13 @@ +# Testing Web Security + +In this section, we’ll talk about testing web application endpoints. + +## Section Summary + +* [WebTestClient Setup](setup.html) +* [Testing Authentication](authentication.html) +* [Testing CSRF](csrf.html) +* [Testing OAuth 2.0](oauth2.html) + +[Testing Method Security](../method.html)[WebTestClient Setup](setup.html) + diff --git a/docs/en/spring-security/reactive-test.md b/docs/en/spring-security/reactive-test.md new file mode 100644 index 0000000000000000000000000000000000000000..2d19d50dcc0659429040d031f6d76d0d8b6ad7c4 --- /dev/null +++ b/docs/en/spring-security/reactive-test.md @@ -0,0 +1,11 @@ +# Reactive Test Support + +Spring Security supports two basic modes for testing reactive applications. + +## Section Summary + +* [Testing Method Security](method.html) +* [Testing Web Security](web/index.html) + +[RSocket](../integrations/rsocket.html)[Testing Method Security](method.html) + diff --git a/docs/en/spring-security/reactive.md b/docs/en/spring-security/reactive.md new file mode 100644 index 0000000000000000000000000000000000000000..883c93aeeb0e7bebad1adcb965414a71cdb2b413 --- /dev/null +++ b/docs/en/spring-security/reactive.md @@ -0,0 +1,7 @@ +# Reactive Applications + +Reactive applications work very differently than [Servlet Applications](../servlet/index.html#servlet-applications). +This section discusses how Spring Security works with reactive applications which are typically written using Spring’s WebFlux. + +[FAQ](../servlet/appendix/faq.html)[Getting Started](getting-started.html) + diff --git a/docs/en/spring-security/samples.md b/docs/en/spring-security/samples.md new file mode 100644 index 0000000000000000000000000000000000000000..3d243e493f21539f682933f95e4dc9e690fea68b --- /dev/null +++ b/docs/en/spring-security/samples.md @@ -0,0 +1,9 @@ +# Samples + +Spring Security includes many [samples](https://github.com/spring-projects/spring-security-samples/tree/5.6.x) applications. + +| |These samples are being migrated to a separate project, however, you can still find
the not migrated samples in an older branch of the [Spring Security repository](https://github.com/spring-projects/spring-security/tree/5.4.x/samples).| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Project Modules](modules.html)[Servlet Applications](servlet/index.html) + diff --git a/docs/en/spring-security/servlet-appendix-database-schema.md b/docs/en/spring-security/servlet-appendix-database-schema.md new file mode 100644 index 0000000000000000000000000000000000000000..3ee6cf216ba407233645db663e2d567e9acc63b2 --- /dev/null +++ b/docs/en/spring-security/servlet-appendix-database-schema.md @@ -0,0 +1,379 @@ +# Security Database Schema + +DDL statements are given for the HSQLDB database. +You can use these as a guideline for defining the schema for the database you are using. + +## User Schema + +The standard JDBC implementation of the `UserDetailsService` (`JdbcDaoImpl`) requires tables to load the password, account status (enabled or disabled) and a list of authorities (roles) for the user. +You will need to adjust this schema to match the database dialect you are using. + +``` +create table users( + username varchar_ignorecase(50) not null primary key, + password varchar_ignorecase(50) not null, + enabled boolean not null +); + +create table authorities ( + username varchar_ignorecase(50) not null, + authority varchar_ignorecase(50) not null, + constraint fk_authorities_users foreign key(username) references users(username) +); +create unique index ix_auth_username on authorities (username,authority); +``` + +### For Oracle database + +``` +CREATE TABLE USERS ( + USERNAME NVARCHAR2(128) PRIMARY KEY, + PASSWORD NVARCHAR2(128) NOT NULL, + ENABLED CHAR(1) CHECK (ENABLED IN ('Y','N') ) NOT NULL +); + +CREATE TABLE AUTHORITIES ( + USERNAME NVARCHAR2(128) NOT NULL, + AUTHORITY NVARCHAR2(128) NOT NULL +); +ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_UNIQUE UNIQUE (USERNAME, AUTHORITY); +ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME) REFERENCES USERS (USERNAME) ENABLE; +``` + +### Group Authorities + +Spring Security 2.0 introduced support for group authorities in `JdbcDaoImpl`. +The table structure if groups are enabled is as follows. +You will need to adjust this schema to match the database dialect you are using. + +``` +create table groups ( + id bigint generated by default as identity(start with 0) primary key, + group_name varchar_ignorecase(50) not null +); + +create table group_authorities ( + group_id bigint not null, + authority varchar(50) not null, + constraint fk_group_authorities_group foreign key(group_id) references groups(id) +); + +create table group_members ( + id bigint generated by default as identity(start with 0) primary key, + username varchar(50) not null, + group_id bigint not null, + constraint fk_group_members_group foreign key(group_id) references groups(id) +); +``` + +Remember that these tables are only required if you are using the provided JDBC `UserDetailsService` implementation. +If you write your own or choose to implement `AuthenticationProvider` without a `UserDetailsService`, then you have complete freedom over how you store the data, as long as the interface contract is satisfied. + +## Schema + +This table is used to store data used by the more secure [persistent token](../authentication/rememberme.html#remember-me-persistent-token) remember-me implementation. +If you are using `JdbcTokenRepositoryImpl` either directly or through the namespace, then you will need this table. +Remember to adjust this schema to match the database dialect you are using. + +``` +create table persistent_logins ( + username varchar(64) not null, + series varchar(64) primary key, + token varchar(64) not null, + last_used timestamp not null +); +``` + +## ACL Schema + +There are four tables used by the Spring Security [ACL](../authorization/acls.html#domain-acls) implementation. + +1. `acl_sid` stores the security identities recognised by the ACL system. + These can be unique principals or authorities which may apply to multiple principals. + +2. `acl_class` defines the domain object types to which ACLs apply. + The `class` column stores the Java class name of the object. + +3. `acl_object_identity` stores the object identity definitions of specific domain objects. + +4. `acl_entry` stores the ACL permissions which apply to a specific object identity and security identity. + +It is assumed that the database will auto-generate the primary keys for each of the identities. +The `JdbcMutableAclService` has to be able to retrieve these when it has created a new row in the `acl_sid` or `acl_class` tables. +It has two properties which define the SQL needed to retrieve these values `classIdentityQuery` and `sidIdentityQuery`. +Both of these default to `call identity()` + +The ACL artifact JAR contains files for creating the ACL schema in HyperSQL (HSQLDB), PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, and Oracle Database. +These schemas are also demonstrated in the following sections. + +### HyperSQL + +The default schema works with the embedded HSQLDB database that is used in unit tests within the framework. + +``` +create table acl_sid( + id bigint generated by default as identity(start with 100) not null primary key, + principal boolean not null, + sid varchar_ignorecase(100) not null, + constraint unique_uk_1 unique(sid,principal) +); + +create table acl_class( + id bigint generated by default as identity(start with 100) not null primary key, + class varchar_ignorecase(100) not null, + constraint unique_uk_2 unique(class) +); + +create table acl_object_identity( + id bigint generated by default as identity(start with 100) not null primary key, + object_id_class bigint not null, + object_id_identity varchar_ignorecase(36) not null, + parent_object bigint, + owner_sid bigint, + entries_inheriting boolean not null, + constraint unique_uk_3 unique(object_id_class,object_id_identity), + constraint foreign_fk_1 foreign key(parent_object)references acl_object_identity(id), + constraint foreign_fk_2 foreign key(object_id_class)references acl_class(id), + constraint foreign_fk_3 foreign key(owner_sid)references acl_sid(id) +); + +create table acl_entry( + id bigint generated by default as identity(start with 100) not null primary key, + acl_object_identity bigint not null, + ace_order int not null, + sid bigint not null, + mask integer not null, + granting boolean not null, + audit_success boolean not null, + audit_failure boolean not null, + constraint unique_uk_4 unique(acl_object_identity,ace_order), + constraint foreign_fk_4 foreign key(acl_object_identity) references acl_object_identity(id), + constraint foreign_fk_5 foreign key(sid) references acl_sid(id) +); +``` + +### PostgreSQL + +``` +create table acl_sid( + id bigserial not null primary key, + principal boolean not null, + sid varchar(100) not null, + constraint unique_uk_1 unique(sid,principal) +); + +create table acl_class( + id bigserial not null primary key, + class varchar(100) not null, + constraint unique_uk_2 unique(class) +); + +create table acl_object_identity( + id bigserial primary key, + object_id_class bigint not null, + object_id_identity varchar(36) not null, + parent_object bigint, + owner_sid bigint, + entries_inheriting boolean not null, + constraint unique_uk_3 unique(object_id_class,object_id_identity), + constraint foreign_fk_1 foreign key(parent_object)references acl_object_identity(id), + constraint foreign_fk_2 foreign key(object_id_class)references acl_class(id), + constraint foreign_fk_3 foreign key(owner_sid)references acl_sid(id) +); + +create table acl_entry( + id bigserial primary key, + acl_object_identity bigint not null, + ace_order int not null, + sid bigint not null, + mask integer not null, + granting boolean not null, + audit_success boolean not null, + audit_failure boolean not null, + constraint unique_uk_4 unique(acl_object_identity,ace_order), + constraint foreign_fk_4 foreign key(acl_object_identity) references acl_object_identity(id), + constraint foreign_fk_5 foreign key(sid) references acl_sid(id) +); +``` + +You will have to set the `classIdentityQuery` and `sidIdentityQuery` properties of `JdbcMutableAclService` to the following values, respectively: + +* `select currval(pg_get_serial_sequence('acl_class', 'id'))` + +* `select currval(pg_get_serial_sequence('acl_sid', 'id'))` + +### MySQL and MariaDB + +``` +CREATE TABLE acl_sid ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + principal BOOLEAN NOT NULL, + sid VARCHAR(100) NOT NULL, + UNIQUE KEY unique_acl_sid (sid, principal) +) ENGINE=InnoDB; + +CREATE TABLE acl_class ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + class VARCHAR(100) NOT NULL, + UNIQUE KEY uk_acl_class (class) +) ENGINE=InnoDB; + +CREATE TABLE acl_object_identity ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + object_id_class BIGINT UNSIGNED NOT NULL, + object_id_identity VARCHAR(36) NOT NULL, + parent_object BIGINT UNSIGNED, + owner_sid BIGINT UNSIGNED, + entries_inheriting BOOLEAN NOT NULL, + UNIQUE KEY uk_acl_object_identity (object_id_class, object_id_identity), + CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id), + CONSTRAINT fk_acl_object_identity_class FOREIGN KEY (object_id_class) REFERENCES acl_class (id), + CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY (owner_sid) REFERENCES acl_sid (id) +) ENGINE=InnoDB; + +CREATE TABLE acl_entry ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + acl_object_identity BIGINT UNSIGNED NOT NULL, + ace_order INTEGER NOT NULL, + sid BIGINT UNSIGNED NOT NULL, + mask INTEGER UNSIGNED NOT NULL, + granting BOOLEAN NOT NULL, + audit_success BOOLEAN NOT NULL, + audit_failure BOOLEAN NOT NULL, + UNIQUE KEY unique_acl_entry (acl_object_identity, ace_order), + CONSTRAINT fk_acl_entry_object FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity (id), + CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id) +) ENGINE=InnoDB; +``` + +### Microsoft SQL Server + +``` +CREATE TABLE acl_sid ( + id BIGINT NOT NULL IDENTITY PRIMARY KEY, + principal BIT NOT NULL, + sid VARCHAR(100) NOT NULL, + CONSTRAINT unique_acl_sid UNIQUE (sid, principal) +); + +CREATE TABLE acl_class ( + id BIGINT NOT NULL IDENTITY PRIMARY KEY, + class VARCHAR(100) NOT NULL, + CONSTRAINT uk_acl_class UNIQUE (class) +); + +CREATE TABLE acl_object_identity ( + id BIGINT NOT NULL IDENTITY PRIMARY KEY, + object_id_class BIGINT NOT NULL, + object_id_identity VARCHAR(36) NOT NULL, + parent_object BIGINT, + owner_sid BIGINT, + entries_inheriting BIT NOT NULL, + CONSTRAINT uk_acl_object_identity UNIQUE (object_id_class, object_id_identity), + CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id), + CONSTRAINT fk_acl_object_identity_class FOREIGN KEY (object_id_class) REFERENCES acl_class (id), + CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY (owner_sid) REFERENCES acl_sid (id) +); + +CREATE TABLE acl_entry ( + id BIGINT NOT NULL IDENTITY PRIMARY KEY, + acl_object_identity BIGINT NOT NULL, + ace_order INTEGER NOT NULL, + sid BIGINT NOT NULL, + mask INTEGER NOT NULL, + granting BIT NOT NULL, + audit_success BIT NOT NULL, + audit_failure BIT NOT NULL, + CONSTRAINT unique_acl_entry UNIQUE (acl_object_identity, ace_order), + CONSTRAINT fk_acl_entry_object FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity (id), + CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id) +); +``` + +### Oracle Database + +``` +CREATE TABLE ACL_SID ( + ID NUMBER(18) PRIMARY KEY, + PRINCIPAL NUMBER(1) NOT NULL CHECK (PRINCIPAL IN (0, 1 )), + SID NVARCHAR2(128) NOT NULL, + CONSTRAINT ACL_SID_UNIQUE UNIQUE (SID, PRINCIPAL) +); +CREATE SEQUENCE ACL_SID_SQ START WITH 1 INCREMENT BY 1 NOMAXVALUE; +CREATE OR REPLACE TRIGGER ACL_SID_SQ_TR BEFORE INSERT ON ACL_SID FOR EACH ROW +BEGIN + SELECT ACL_SID_SQ.NEXTVAL INTO :NEW.ID FROM DUAL; +END; + +CREATE TABLE ACL_CLASS ( + ID NUMBER(18) PRIMARY KEY, + CLASS NVARCHAR2(128) NOT NULL, + CONSTRAINT ACL_CLASS_UNIQUE UNIQUE (CLASS) +); +CREATE SEQUENCE ACL_CLASS_SQ START WITH 1 INCREMENT BY 1 NOMAXVALUE; +CREATE OR REPLACE TRIGGER ACL_CLASS_ID_TR BEFORE INSERT ON ACL_CLASS FOR EACH ROW +BEGIN + SELECT ACL_CLASS_SQ.NEXTVAL INTO :NEW.ID FROM DUAL; +END; + +CREATE TABLE ACL_OBJECT_IDENTITY( + ID NUMBER(18) PRIMARY KEY, + OBJECT_ID_CLASS NUMBER(18) NOT NULL, + OBJECT_ID_IDENTITY NVARCHAR2(64) NOT NULL, + PARENT_OBJECT NUMBER(18), + OWNER_SID NUMBER(18), + ENTRIES_INHERITING NUMBER(1) NOT NULL CHECK (ENTRIES_INHERITING IN (0, 1)), + CONSTRAINT ACL_OBJECT_IDENTITY_UNIQUE UNIQUE (OBJECT_ID_CLASS, OBJECT_ID_IDENTITY), + CONSTRAINT ACL_OBJECT_IDENTITY_PARENT_FK FOREIGN KEY (PARENT_OBJECT) REFERENCES ACL_OBJECT_IDENTITY(ID), + CONSTRAINT ACL_OBJECT_IDENTITY_CLASS_FK FOREIGN KEY (OBJECT_ID_CLASS) REFERENCES ACL_CLASS(ID), + CONSTRAINT ACL_OBJECT_IDENTITY_OWNER_FK FOREIGN KEY (OWNER_SID) REFERENCES ACL_SID(ID) +); +CREATE SEQUENCE ACL_OBJECT_IDENTITY_SQ START WITH 1 INCREMENT BY 1 NOMAXVALUE; +CREATE OR REPLACE TRIGGER ACL_OBJECT_IDENTITY_ID_TR BEFORE INSERT ON ACL_OBJECT_IDENTITY FOR EACH ROW +BEGIN + SELECT ACL_OBJECT_IDENTITY_SQ.NEXTVAL INTO :NEW.ID FROM DUAL; +END; + +CREATE TABLE ACL_ENTRY ( + ID NUMBER(18) NOT NULL PRIMARY KEY, + ACL_OBJECT_IDENTITY NUMBER(18) NOT NULL, + ACE_ORDER INTEGER NOT NULL, + SID NUMBER(18) NOT NULL, + MASK INTEGER NOT NULL, + GRANTING NUMBER(1) NOT NULL CHECK (GRANTING IN (0, 1)), + AUDIT_SUCCESS NUMBER(1) NOT NULL CHECK (AUDIT_SUCCESS IN (0, 1)), + AUDIT_FAILURE NUMBER(1) NOT NULL CHECK (AUDIT_FAILURE IN (0, 1)), + CONSTRAINT ACL_ENTRY_UNIQUE UNIQUE (ACL_OBJECT_IDENTITY, ACE_ORDER), + CONSTRAINT ACL_ENTRY_OBJECT_FK FOREIGN KEY (ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY (ID), + CONSTRAINT ACL_ENTRY_ACL_FK FOREIGN KEY (SID) REFERENCES ACL_SID(ID) +); +CREATE SEQUENCE ACL_ENTRY_SQ START WITH 1 INCREMENT BY 1 NOMAXVALUE; +CREATE OR REPLACE TRIGGER ACL_ENTRY_ID_TRIGGER BEFORE INSERT ON ACL_ENTRY FOR EACH ROW +BEGIN + SELECT ACL_ENTRY_SQ.NEXTVAL INTO :NEW.ID FROM DUAL; +END; +``` + +## OAuth 2.0 Client Schema + +The JDBC implementation of [ OAuth2AuthorizedClientService](../oauth2/client/core.html#oauth2Client-authorized-repo-service) (`JdbcOAuth2AuthorizedClientService`) requires a table for persisting `OAuth2AuthorizedClient`(s). +You will need to adjust this schema to match the database dialect you are using. + +``` +CREATE TABLE oauth2_authorized_client ( + client_registration_id varchar(100) NOT NULL, + principal_name varchar(200) NOT NULL, + access_token_type varchar(100) NOT NULL, + access_token_value blob NOT NULL, + access_token_issued_at timestamp NOT NULL, + access_token_expires_at timestamp NOT NULL, + access_token_scopes varchar(1000) DEFAULT NULL, + refresh_token_value blob DEFAULT NULL, + refresh_token_issued_at timestamp DEFAULT NULL, + created_at timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL, + PRIMARY KEY (client_registration_id, principal_name) +); +``` + +[Appendix](index.html)[XML Namespace](namespace/index.html) + diff --git a/docs/en/spring-security/servlet-appendix-faq.md b/docs/en/spring-security/servlet-appendix-faq.md new file mode 100644 index 0000000000000000000000000000000000000000..221bb0a4dba6ca0ba8be38ea3cacb2e1346e505b --- /dev/null +++ b/docs/en/spring-security/servlet-appendix-faq.md @@ -0,0 +1,657 @@ +# Spring Security FAQ + +* [General Questions](#appendix-faq-general-questions) + +* [Common Problems](#appendix-faq-common-problems) + +* [Spring Security Architecture Questions](#appendix-faq-architecture) + +* [Common "Howto" Requests](#appendix-faq-howto) + +## General Questions + +1. [Will Spring Security take care of all my application security requirements?](#appendix-faq-other-concerns) + +2. [Why not just use web.xml security?](#appendix-faq-web-xml) + +3. [What Java and Spring Framework versions are required?](#appendix-faq-requirements) + +4. [I’m new to Spring Security and I need to build an application that supports CAS single sign-on over HTTPS, while allowing Basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). I’ve copied some configuration files I found but it doesn’t work.](#appendix-faq-start-simple) + +### Will Spring Security take care of all my application security requirements? + +Spring Security provides you with a very flexible framework for your authentication and authorization requirements, but there are many other considerations for building a secure application that are outside its scope. +Web applications are vulnerable to all kinds of attacks which you should be familiar with, preferably before you start development so you can design and code with them in mind from the beginning. +Check out the [OWASP web site](https://www.owasp.org/) for information on the major issues facing web application developers and the countermeasures you can use against them. + +### Why not just use web.xml security? + +Let’s assume you’re developing an enterprise application based on Spring. +There are four security concerns you typically need to address: authentication, web request security, service layer security (i.e. your methods that implement business logic), and domain object instance security (i.e. different domain objects have different permissions). With these typical requirements in mind: + +1. *Authentication*: The servlet specification provides an approach to authentication. + However, you will need to configure the container to perform authentication which typically requires editing of container-specific "realm" settings. + This makes a non-portable configuration, and if you need to write an actual Java class to implement the container’s authentication interface, it becomes even more non-portable. + With Spring Security you achieve complete portability - right down to the WAR level. + Also, Spring Security offers a choice of production-proven authentication providers and mechanisms, meaning you can switch your authentication approaches at deployment time. + This is particularly valuable for software vendors writing products that need to work in an unknown target environment. + +2. *Web request security:* The servlet specification provides an approach to secure your request URIs. + However, these URIs can only be expressed in the servlet specification’s own limited URI path format. + Spring Security provides a far more comprehensive approach. + For instance, you can use Ant paths or regular expressions, you can consider parts of the URI other than simply the requested page (e.g. + you can consider HTTP GET parameters) and you can implement your own runtime source of configuration data. + This means your web request security can be dynamically changed during the actual execution of your webapp. + +3. *Service layer and domain object security:* The absence of support in the servlet specification for services layer security or domain object instance security represent serious limitations for multi-tiered applications. + Typically developers either ignore these requirements, or implement security logic within their MVC controller code (or even worse, inside the views). There are serious disadvantages with this approach: + + 1. *Separation of concerns:* Authorization is a crosscutting concern and should be implemented as such. + MVC controllers or views implementing authorization code makes it more difficult to test both the controller and authorization logic, more difficult to debug, and will often lead to code duplication. + + 2. *Support for rich clients and web services:* If an additional client type must ultimately be supported, any authorization code embedded within the web layer is non-reusable. + It should be considered that Spring remoting exporters only export service layer beans (not MVC controllers). As such authorization logic needs to be located in the services layer to support a multitude of client types. + + 3. *Layering issues:* An MVC controller or view is simply the incorrect architectural layer to implement authorization decisions concerning services layer methods or domain object instances. + Whilst the Principal may be passed to the services layer to enable it to make the authorization decision, doing so would introduce an additional argument on every services layer method. + A more elegant approach is to use a ThreadLocal to hold the Principal, although this would likely increase development time to a point where it would become more economical (on a cost-benefit basis) to simply use a dedicated security framework. + + 4. *Authorisation code quality:* It is often said of web frameworks that they "make it easier to do the right things, and harder to do the wrong things". Security frameworks are the same, because they are designed in an abstract manner for a wide range of purposes. + Writing your own authorization code from scratch does not provide the "design check" a framework would offer, and in-house authorization code will typically lack the improvements that emerge from widespread deployment, peer review and new versions. + +For simple applications, servlet specification security may just be enough. +Although when considered within the context of web container portability, configuration requirements, limited web request security flexibility, and non-existent services layer and domain object instance security, it becomes clear why developers often look to alternative solutions. + +### What Java and Spring Framework versions are required? + +Spring Security 3.0 and 3.1 require at least JDK 1.5 and also require Spring 3.0.3 as a minimum. +Ideally you should be using the latest release versions to avoid problems. + +Spring Security 2.0.x requires a minimum JDK version of 1.4 and is built against Spring 2.0.x. +It should also be compatible with applications using Spring 2.5.x. + +### . I’ve copied some configuration files I found but it doesn’t work. + +What could be wrong? + +Or substitute an alternative complex scenario…​ + +Realistically, you need an understanding of the technologies you are intending to use before you can successfully build applications with them. +Security is complicated. +Setting up a simple configuration using a login form and some hard-coded users using Spring Security’s namespace is reasonably straightforward. +Moving to using a backed JDBC database is also easy enough. +But if you try and jump straight to a complicated deployment scenario like this you will almost certainly be frustrated. +There is a big jump in the learning curve required to set up systems like CAS, configure LDAP servers and install SSL certificates properly. +So you need to take things one step at a time. + +From a Spring Security perspective, the first thing you should do is follow the "Getting Started" guide on the web site. +This will take you through a series of steps to get up and running and get some idea of how the framework operates. +If you are using other technologies which you aren’t familiar with then you should do some research and try to make sure you can use them in isolation before combining them in a complex system. + +## Common Problems + +1. Authentication + + 1. [When I try to log in, I get an error message that says "Bad Credentials". What’s wrong?](#appendix-faq-bad-credentials) + + 2. [My application goes into an "endless loop" when I try to login, what’s going on?](#appendix-faq-login-loop) + + 3. [I get an exception with the message "Access is denied (user is anonymous);". What’s wrong?](#appendix-faq-anon-access-denied) + + 4. [Why can I still see a secured page even after I’ve logged out of my application?](#appendix-faq-cached-secure-page) + + 5. [I get an exception with the message "An Authentication object was not found in the SecurityContext". What’s wrong?](#auth-exception-credentials-not-found) + + 6. [I can’t get LDAP authentication to work.](#appendix-faq-ldap-authentication) + +2. Session Management + + 1. [I’m using Spring Security’s concurrent session control to prevent users from logging in more than once at a time.](#appendix-faq-concurrent-session-same-browser) + + 2. [Why does the session Id change when I authenticate through Spring Security?](#appendix-faq-new-session-on-authentication) + + 3. [I’m using Tomcat (or some other servlet container) and have enabled HTTPS for my login page, switching back to HTTP afterwards.](#appendix-faq-tomcat-https-session) + + 4. [I’m trying to use the concurrent session-control support but it won’t let me log back in, even if I’m sure I’ve logged out and haven’t exceeded the allowed sessions.](#appendix-faq-session-listener-missing) + + 5. [Spring Security is creating a session somewhere, even though I’ve configured it not to, by setting the create-session attribute to never.](#appendix-faq-unwanted-session-creation) + +3. Miscellaneous + + 1. [I get a 403 Forbidden when performing a POST](#appendix-faq-forbidden-csrf) + + 2. [I’m forwarding a request to another URL using the RequestDispatcher, but my security constraints aren’t being applied.](#appendix-faq-no-security-on-forward) + + 3. [I have added Spring Security’s \ element to my application context but if I add security annotations to my Spring MVC controller beans (Struts actions etc.) then they don’t seem to have an effect.](#appendix-faq-method-security-in-web-context) + + 4. [I have a user who has definitely been authenticated, but when I try to access the SecurityContextHolder during some requests, the Authentication is null.](#appendix-faq-no-filters-no-context) + + 5. [The authorize JSP Tag doesn’t respect my method security annotations when using the URL attribute.](#appendix-faq-method-security-with-taglib) + +### When I try to log in, I get an error message that says "Bad Credentials". What’s wrong? + +This means that authentication has failed. +It doesn’t say why, as it is good practice to avoid giving details which might help an attacker guess account names or passwords. + +This also means that if you ask this question in the forum, you will not get an answer unless you provide additional information. +As with any issue you should check the output from the debug log, note any exception stacktraces and related messages. +Step through the code in a debugger to see where the authentication fails and why. +Write a test case which exercises your authentication configuration outside of the application. +More often than not, the failure is due to a difference in the password data stored in a database and that entered by the user. +If you are using hashed passwords, make sure the value stored in your database is *exactly* the same as the value produced by the `PasswordEncoder` configured in your application. + +### My application goes into an "endless loop" when I try to login, what’s going on? + +A common user problem with infinite loop and redirecting to the login page is caused by accidentally configuring the login page as a "secured" resource. +Make sure your configuration allows anonymous access to the login page, either by excluding it from the security filter chain or marking it as requiring ROLE\_ANONYMOUS. + +If your AccessDecisionManager includes an AuthenticatedVoter, you can use the attribute "IS\_AUTHENTICATED\_ANONYMOUSLY". This is automatically available if you are using the standard namespace configuration setup. + +From Spring Security 2.0.1 onwards, when you are using namespace-based configuration, a check will be made on loading the application context and a warning message logged if your login page appears to be protected. + +### ;". What’s wrong? + +This is a debug level message which occurs the first time an anonymous user attempts to access a protected resource. + +``` +DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point +org.springframework.security.AccessDeniedException: Access is denied +at org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68) +at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262) +``` + +It is normal and shouldn’t be anything to worry about. + +### Why can I still see a secured page even after I’ve logged out of my application? + +The most common reason for this is that your browser has cached the page and you are seeing a copy which is being retrieved from the browsers cache. +Verify this by checking whether the browser is actually sending the request (check your server access logs, the debug log or use a suitable browser debugging plugin such as "Tamper Data" for Firefox). This has nothing to do with Spring Security and you should configure your application or server to set the appropriate `Cache-Control` response headers. +Note that SSL requests are never cached. + +### I get an exception with the message "An Authentication object was not found in the SecurityContext". What’s wrong? + +This is a another debug level message which occurs the first time an anonymous user attempts to access a protected resource, but when you do not have an `AnonymousAuthenticationFilter` in your filter chain configuration. + +``` +DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point +org.springframework.security.AuthenticationCredentialsNotFoundException: + An Authentication object was not found in the SecurityContext +at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342) +at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254) +``` + +It is normal and shouldn’t be anything to worry about. + +### I can’t get LDAP authentication to work. + +What’s wrong with my configuration? + +Note that the permissions for an LDAP directory often do not allow you to read the password for a user. +Hence it is often not possible to use the [What is a UserDetailsService and do I need one?](#appendix-faq-what-is-userdetailservice) where Spring Security compares the stored password with the one submitted by the user. +The most common approach is to use LDAP "bind", which is one of the operations supported by [the LDAP protocol](https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol). With this approach, Spring Security validates the password by attempting to authenticate to the directory as the user. + +The most common problem with LDAP authentication is a lack of knowledge of the directory server tree structure and configuration. +This will be different in different companies, so you have to find it out yourself. +Before adding a Spring Security LDAP configuration to an application, it’s a good idea to write a simple test using standard Java LDAP code (without Spring Security involved), and make sure you can get that to work first. +For example, to authenticate a user, you could use the following code: + +Java + +``` +@Test +public void ldapAuthenticationIsSuccessful() throws Exception { + Hashtable env = new Hashtable(); + env.put(Context.SECURITY_AUTHENTICATION, "simple"); + env.put(Context.SECURITY_PRINCIPAL, "cn=joe,ou=users,dc=mycompany,dc=com"); + env.put(Context.PROVIDER_URL, "ldap://mycompany.com:389/dc=mycompany,dc=com"); + env.put(Context.SECURITY_CREDENTIALS, "joespassword"); + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + + InitialLdapContext ctx = new InitialLdapContext(env, null); + +} +``` + +Kotlin + +``` +@Test +fun ldapAuthenticationIsSuccessful() { + val env = Hashtable() + env[Context.SECURITY_AUTHENTICATION] = "simple" + env[Context.SECURITY_PRINCIPAL] = "cn=joe,ou=users,dc=mycompany,dc=com" + env[Context.PROVIDER_URL] = "ldap://mycompany.com:389/dc=mycompany,dc=com" + env[Context.SECURITY_CREDENTIALS] = "joespassword" + env[Context.INITIAL_CONTEXT_FACTORY] = "com.sun.jndi.ldap.LdapCtxFactory" + val ctx = InitialLdapContext(env, null) +} +``` + +### Session Management + +Session management issues are a common source of forum questions. +If you are developing Java web applications, you should understand how the session is maintained between the servlet container and the user’s browser. +You should also understand the difference between secure and non-secure cookies and the implications of using HTTP/HTTPS and switching between the two. +Spring Security has nothing to do with maintaining the session or providing session identifiers. +This is entirely handled by the servlet container. + +### I’m using Spring Security’s concurrent session control to prevent users from logging in more than once at a time. + +When I open another browser window after logging in, it doesn’t stop me from logging in again. +Why can I log in more than once? + +Browsers generally maintain a single session per browser instance. +You cannot have two separate sessions at once. +So if you log in again in another window or tab you are just reauthenticating in the same session. +The server doesn’t know anything about tabs, windows or browser instances. +All it sees are HTTP requests and it ties those to a particular session according to the value of the JSESSIONID cookie that they contain. +When a user authenticates during a session, Spring Security’s concurrent session control checks the number of *other authenticated sessions* that they have. +If they are already authenticated with the same session, then re-authenticating will have no effect. + +### Why does the session Id change when I authenticate through Spring Security? + +With the default configuration, Spring Security changes the session ID when the user authenticates. +If you’re using a Servlet 3.1 or newer container, the session ID is simply changed. +If you’re using an older container, Spring Security invalidates the existing session, creates a new session, and transfers the session data to the new session. +Changing the session identifier in this manner prevents"session-fixation" attacks. +You can find more about this online and in the reference manual. + +### and have enabled HTTPS for my login page, switching back to HTTP afterwards. + +It doesn’t work - I just end up back at the login page after authenticating. + +This happens because sessions created under HTTPS, for which the session cookie is marked as "secure", cannot subsequently be used under HTTP. The browser will not send the cookie back to the server and any session state will be lost (including the security context information). Starting a session in HTTP first should work as the session cookie won’t be marked as secure. +However, Spring Security’s [Session Fixation Protection](https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-session-fixation) can interfere with this because it results in a new session ID cookie being sent back to the user’s browser, usually with the secure flag. +To get around this, you can disable session fixation protection, but in newer Servlet containers you can also configure session cookies to never use the secure flag. +Note that switching between HTTP and HTTPS is not a good idea in general, as any application which uses HTTP at all is vulnerable to man-in-the-middle attacks. +To be truly secure, the user should begin accessing your site in HTTPS and continue using it until they log out. +Even clicking on an HTTPS link from a page accessed over HTTP is potentially risky. +If you need more convincing, check out a tool like [sslstrip](https://github.com/moxie0/sslstrip/). + +### I’m not switching between HTTP and HTTPS but my session is still getting lost + +Sessions are maintained either by exchanging a session cookie or by adding a `jsessionid` parameter to URLs (this happens automatically if you are using JSTL to output URLs, or if you call `HttpServletResponse.encodeUrl` on URLs (before a redirect, for example). If clients have cookies disabled, and you are not rewriting URLs to include the `jsessionid`, then the session will be lost. +Note that the use of cookies is preferred for security reasons, as it does not expose the session information in the URL. + +### I’m trying to use the concurrent session-control support but it won’t let me log back in, even if I’m sure I’ve logged out and haven’t exceeded the allowed sessions. + +Make sure you have added the listener to your web.xml file. +It is essential to make sure that the Spring Security session registry is notified when a session is destroyed. +Without it, the session information will not be removed from the registry. + +``` + + org.springframework.security.web.session.HttpSessionEventPublisher + +``` + +### Spring Security is creating a session somewhere, even though I’ve configured it not to, by setting the create-session attribute to never. + +This usually means that the user’s application is creating a session somewhere, but that they aren’t aware of it. +The most common culprit is a JSP. Many people aren’t aware that JSPs create sessions by default. +To prevent a JSP from creating a session, add the directive `<%@ page session="false" %>` to the top of the page. + +If you are having trouble working out where a session is being created, you can add some debugging code to track down the location(s). One way to do this would be to add a `javax.servlet.http.HttpSessionListener` to your application, which calls `Thread.dumpStack()` in the `sessionCreated` method. + +### I get a 403 Forbidden when performing a POST + +If an HTTP 403 Forbidden is returned for HTTP POST, but works for HTTP GET then the issue is most likely related to [CSRF](https://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#csrf). Either provide the CSRF Token or disable CSRF protection (not recommended). + +### I’m forwarding a request to another URL using the RequestDispatcher, but my security constraints aren’t being applied. + +Filters are not applied by default to forwards or includes. +If you really want the security filters to be applied to forwards and/or includes, then you have to configure these explicitly in your web.xml using the \ element, a child element of \. + +### then they don’t seem to have an effect. + +In a Spring web application, the application context which holds the Spring MVC beans for the dispatcher servlet is often separate from the main application context. +It is often defined in a file called `myapp-servlet.xml`, where "myapp" is the name assigned to the Spring `DispatcherServlet` in `web.xml`. An application can have multiple `DispatcherServlet`s, each with its own isolated application context. +The beans in these "child" contexts are not visible to the rest of the application. +The"parent" application context is loaded by the `ContextLoaderListener` you define in your `web.xml` and is visible to all the child contexts. +This parent context is usually where you define your security configuration, including the `` element). As a result any security constraints applied to methods in these web beans will not be enforced, since the beans cannot be seen from the `DispatcherServlet` context. +You need to either move the `` declaration to the web context or moved the beans you want secured into the main application context. + +Generally we would recommend applying method security at the service layer rather than on individual web controllers. + +### I have a user who has definitely been authenticated, but when I try to access the SecurityContextHolder during some requests, the Authentication is null. + +Why can’t I see the user information? + +If you have excluded the request from the security filter chain using the attribute `filters='none'` in the `` element that matches the URL pattern, then the `SecurityContextHolder` will not be populated for that request. +Check the debug log to see whether the request is passing through the filter chain. +(You are reading the debug log, right?). + +### The authorize JSP Tag doesn’t respect my method security annotations when using the URL attribute. + +Method security will not hide links when using the `url` attribute in `` because we cannot readily reverse engineer what URL is mapped to what controller endpoint as controllers can rely on headers, current user, etc to determine what method to invoke. + +## Spring Security Architecture Questions + +1. [How do I know which package class X is in?](#appendix-faq-where-is-class-x) + +2. [How do the namespace elements map to conventional bean configurations?](#appendix-faq-namespace-to-bean-mapping) + +3. [What does "ROLE\_" mean and why do I need it on my role names?](#appendix-faq-role-prefix) + +4. [How do I know which dependencies to add to my application to work with Spring Security?](#appendix-faq-what-dependencies) + +5. [What dependencies are needed to run an embedded ApacheDS LDAP server?](#appendix-faq-apacheds-deps) + +6. [What is a UserDetailsService and do I need one?](#appendix-faq-what-is-userdetailservice) + +### How do I know which package class X is in? + +The best way of locating classes is by installing the Spring Security source in your IDE. The distribution includes source jars for each of the modules the project is divided up into. +Add these to your project source path and you can navigate directly to Spring Security classes (`Ctrl-Shift-T` in Eclipse). This also makes debugging easier and allows you to troubleshoot exceptions by looking directly at the code where they occur to see what’s going on there. + +### How do the namespace elements map to conventional bean configurations? + +There is a general overview of what beans are created by the namespace in the namespace appendix of the reference guide. +There is also a detailed blog article called "Behind the Spring Security Namespace" on [blog.springsource.com](https://spring.io/blog/2010/03/06/behind-the-spring-security-namespace/). If want to know the full details then the code is in the `spring-security-config` module within the Spring Security 3.0 distribution. +You should probably read the chapters on namespace parsing in the standard Spring Framework reference documentation first. + +### What does "ROLE\_" mean and why do I need it on my role names? + +Spring Security has a voter-based architecture which means that an access decision is made by a series of `AccessDecisionVoter`s. +The voters act on the "configuration attributes" which are specified for a secured resource (such as a method invocation). With this approach, not all attributes may be relevant to all voters and a voter needs to know when it should ignore an attribute (abstain) and when it should vote to grant or deny access based on the attribute value. +The most common voter is the `RoleVoter` which by default votes whenever it finds an attribute with the "ROLE\_" prefix. +It makes a simple comparison of the attribute (such as "ROLE\_USER") with the names of the authorities which the current user has been assigned. +If it finds a match (they have an authority called "ROLE\_USER"), it votes to grant access, otherwise it votes to deny access. + +The prefix can be changed by setting the `rolePrefix` property of `RoleVoter`. If you only need to use roles in your application and have no need for other custom voters, then you can set the prefix to a blank string, in which case the `RoleVoter` will treat all attributes as roles. + +### How do I know which dependencies to add to my application to work with Spring Security? + +It will depend on what features you are using and what type of application you are developing. +With Spring Security 3.0, the project jars are divided into clearly distinct areas of functionality, so it is straightforward to work out which Spring Security jars you need from your application requirements. +All applications will need the `spring-security-core` jar. +If you’re developing a web application, you need the `spring-security-web` jar. +If you’re using security namespace configuration you need the `spring-security-config` jar, for LDAP support you need the `spring-security-ldap` jar and so on. + +For third-party jars the situation isn’t always quite so obvious. +A good starting point is to copy those from one of the pre-built sample applications WEB-INF/lib directories. +For a basic application, you can start with the tutorial sample. +If you want to use LDAP, with an embedded test server, then use the LDAP sample as a starting point. +The reference manual also includes [an appendix](https://docs.spring.io/spring-security/site/docs/5.6.2/reference/html5/#modules) listing the first-level dependencies for each Spring Security module with some information on whether they are optional and what they are required for. + +If you are building your project with maven, then adding the appropriate Spring Security modules as dependencies to your pom.xml will automatically pull in the core jars that the framework requires. +Any which are marked as "optional" in the Spring Security POM files will have to be added to your own pom.xml file if you need them. + +### What dependencies are needed to run an embedded ApacheDS LDAP server? + +If you are using Maven, you need to add the following to your pom dependencies: + +``` + + org.apache.directory.server + apacheds-core + 1.5.5 + runtime + + + org.apache.directory.server + apacheds-server-jndi + 1.5.5 + runtime + +``` + +The other required jars should be pulled in transitively. + +### What is a UserDetailsService and do I need one? + +`UserDetailsService` is a DAO interface for loading data that is specific to a user account. +It has no other function other to load that data for use by other components within the framework. +It is not responsible for authenticating the user. +Authenticating a user with a username/password combination is most commonly performed by the `DaoAuthenticationProvider`, which is injected with a `UserDetailsService` to allow it to load the password (and other data) for a user in order to compare it with the submitted value. +Note that if you are using LDAP, [this approach may not work](#appendix-faq-ldap-authentication). + +If you want to customize the authentication process then you should implement `AuthenticationProvider` yourself. +See this [ blog article](https://spring.io/blog/2010/08/02/spring-security-in-google-app-engine/) for an example integrating Spring Security authentication with Google App Engine. + +## Common "Howto" Requests + +1. [I need to login in with more information than just the username.](#appendix-faq-extra-login-fields) + +2. [How do I apply different intercept-url constraints where only the fragment value of the requested URLs differs (e.g./foo#bar and /foo#blah?](#appendix-faq-matching-url-fragments) + +3. [How do I access the user’s IP Address (or other web-request data) in a UserDetailsService?](#appendix-faq-request-details-in-user-service) + +4. [How do I access the HttpSession from a UserDetailsService?](#appendix-faq-access-session-from-user-service) + +5. [How do I access the user’s password in a UserDetailsService?](#appendix-faq-password-in-user-service) + +6. [How do I define the secured URLs within an application dynamically?](#appendix-faq-dynamic-url-metadata) + +7. [How do I authenticate against LDAP but load user roles from a database?](#appendix-faq-ldap-authorities) + +8. [I want to modify the property of a bean that is created by the namespace, but there is nothing in the schema to support it.](#appendix-faq-namespace-post-processor) + +### I need to login in with more information than just the username. + +How do I add support for extra login fields (e.g. +a company name)? + +This question comes up repeatedly in the Spring Security forum so you will find more information there by searching the archives (or through google). + +The submitted login information is processed by an instance of `UsernamePasswordAuthenticationFilter`. You will need to customize this class to handle the extra data field(s). One option is to use your own customized authentication token class (rather than the standard `UsernamePasswordAuthenticationToken`), another is simply to concatenate the extra fields with the username (for example, using a ":" as the separator) and pass them in the username property of `UsernamePasswordAuthenticationToken`. + +You will also need to customize the actual authentication process. +If you are using a custom authentication token class, for example, you will have to write an `AuthenticationProvider` to handle it (or extend the standard `DaoAuthenticationProvider`). If you have concatenated the fields, you can implement your own `UserDetailsService` which splits them up and loads the appropriate user data for authentication. + +### How do I apply different intercept-url constraints where only the fragment value of the requested URLs differs (e.g./foo#bar and /foo#blah? + +You can’t do this, since the fragment is not transmitted from the browser to the server. +The URLs above are identical from the server’s perspective. +This is a common question from GWT users. + +### in a UserDetailsService? + +Obviously you can’t (without resorting to something like thread-local variables) since the only information supplied to the interface is the username. +Instead of implementing `UserDetailsService`, you should implement `AuthenticationProvider` directly and extract the information from the supplied `Authentication` token. + +In a standard web setup, the `getDetails()` method on the `Authentication` object will return an instance of `WebAuthenticationDetails`. If you need additional information, you can inject a custom `AuthenticationDetailsSource` into the authentication filter you are using. +If you are using the namespace, for example with the `` element, then you should remove this element and replace it with a `` declaration pointing to an explicitly configured `UsernamePasswordAuthenticationFilter`. + +### How do I access the HttpSession from a UserDetailsService? + +You can’t, since the `UserDetailsService` has no awareness of the servlet API. If you want to store custom user data, then you should customize the `UserDetails` object which is returned. +This can then be accessed at any point, via the thread-local `SecurityContextHolder`. A call to `SecurityContextHolder.getContext().getAuthentication().getPrincipal()` will return this custom object. + +If you really need to access the session, then it must be done by customizing the web tier. + +### How do I access the user’s password in a UserDetailsService? + +You can’t (and shouldn’t). You are probably misunderstanding its purpose. +See "[What is a UserDetailsService?](#appendix-faq-what-is-userdetailservice)" above. + +### How do I define the secured URLs within an application dynamically? + +People often ask about how to store the mapping between secured URLs and security metadata attributes in a database, rather than in the application context. + +The first thing you should ask yourself is if you really need to do this. +If an application requires securing, then it also requires that the security be tested thoroughly based on a defined policy. +It may require auditing and acceptance testing before being rolled out into a production environment. +A security-conscious organization should be aware that the benefits of their diligent testing process could be wiped out instantly by allowing the security settings to be modified at runtime by changing a row or two in a configuration database. +If you have taken this into account (perhaps using multiple layers of security within your application) then Spring Security allows you to fully customize the source of security metadata. +You can make it fully dynamic if you choose. + +Both method and web security are protected by subclasses of `AbstractSecurityInterceptor` which is configured with a `SecurityMetadataSource` from which it obtains the metadata for a particular method or filter invocation. +For web security, the interceptor class is `FilterSecurityInterceptor` and it uses the marker interface `FilterInvocationSecurityMetadataSource`. The "secured object" type it operates on is a `FilterInvocation`. The default implementation which is used (both in the namespace `` and when configuring the interceptor explicitly, stores the list of URL patterns and their corresponding list of "configuration attributes" (instances of `ConfigAttribute`) in an in-memory map. + +To load the data from an alternative source, you must be using an explicitly declared security filter chain (typically Spring Security’s `FilterChainProxy`) in order to customize the `FilterSecurityInterceptor` bean. +You can’t use the namespace. +You would then implement `FilterInvocationSecurityMetadataSource` to load the data as you please for a particular `FilterInvocation` [1]. A very basic outline would look something like this: + +Java + +``` + public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { + + public List getAttributes(Object object) { + FilterInvocation fi = (FilterInvocation) object; + String url = fi.getRequestUrl(); + String httpMethod = fi.getRequest().getMethod(); + List attributes = new ArrayList(); + + // Lookup your database (or other source) using this information and populate the + // list of attributes + + return attributes; + } + + public Collection getAllConfigAttributes() { + return null; + } + + public boolean supports(Class clazz) { + return FilterInvocation.class.isAssignableFrom(clazz); + } + } +``` + +Kotlin + +``` +class MyFilterSecurityMetadataSource : FilterInvocationSecurityMetadataSource { + override fun getAttributes(securedObject: Any): List { + val fi = securedObject as FilterInvocation + val url = fi.requestUrl + val httpMethod = fi.request.method + + // Lookup your database (or other source) using this information and populate the + // list of attributes + return ArrayList() + } + + override fun getAllConfigAttributes(): Collection? { + return null + } + + override fun supports(clazz: Class<*>): Boolean { + return FilterInvocation::class.java.isAssignableFrom(clazz) + } +} +``` + +For more information, look at the code for `DefaultFilterInvocationSecurityMetadataSource`. + +### How do I authenticate against LDAP but load user roles from a database? + +The `LdapAuthenticationProvider` bean (which handles normal LDAP authentication in Spring Security) is configured with two separate strategy interfaces, one which performs the authentication and one which loads the user authorities, called `LdapAuthenticator` and `LdapAuthoritiesPopulator` respectively. +The `DefaultLdapAuthoritiesPopulator` loads the user authorities from the LDAP directory and has various configuration parameters to allow you to specify how these should be retrieved. + +To use JDBC instead, you can implement the interface yourself, using whatever SQL is appropriate for your schema: + +Java + +``` + public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator { + @Autowired + JdbcTemplate template; + + List getGrantedAuthorities(DirContextOperations userData, String username) { + return template.query("select role from roles where username = ?", + new String[] {username}, + new RowMapper() { + /** + * We're assuming here that you're using the standard convention of using the role + * prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter. + */ + @Override + public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException { + return new SimpleGrantedAuthority("ROLE_" + rs.getString(1)); + } + }); + } + } +``` + +Kotlin + +``` +class MyAuthoritiesPopulator : LdapAuthoritiesPopulator { + @Autowired + lateinit var template: JdbcTemplate + + override fun getGrantedAuthorities(userData: DirContextOperations, username: String): MutableList { + return template.query("select role from roles where username = ?", + arrayOf(username) + ) { rs, _ -> + /** + * We're assuming here that you're using the standard convention of using the role + * prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter. + */ + SimpleGrantedAuthority("ROLE_" + rs.getString(1)) + } + } +} +``` + +You would then add a bean of this type to your application context and inject it into the `LdapAuthenticationProvider`. This is covered in the section on configuring LDAP using explicit Spring beans in the LDAP chapter of the reference manual. +Note that you can’t use the namespace for configuration in this case. +You should also consult the Javadoc for the relevant classes and interfaces. + +### I want to modify the property of a bean that is created by the namespace, but there is nothing in the schema to support it. + +What can I do short of abandoning namespace use? + +The namespace functionality is intentionally limited, so it doesn’t cover everything that you can do with plain beans. +If you want to do something simple, like modify a bean, or inject a different dependency, you can do this by adding a `BeanPostProcessor` to your configuration. +More information can be found in the [Spring Reference Manual](https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#beans-factory-extension-bpp). In order to do this, you need to know a bit about which beans are created, so you should also read the blog article in the above question on [how the namespace maps to Spring beans](#appendix-faq-namespace-to-bean-mapping). + +Normally, you would add the functionality you require to the `postProcessBeforeInitialization` method of `BeanPostProcessor`. Let’s say that you want to customize the `AuthenticationDetailsSource` used by the `UsernamePasswordAuthenticationFilter`, (created by the `form-login` element). You want to extract a particular header called `CUSTOM_HEADER` from the request and make use of it while authenticating the user. +The processor class would look like this: + +Java + +``` +public class CustomBeanPostProcessor implements BeanPostProcessor { + + public Object postProcessAfterInitialization(Object bean, String name) { + if (bean instanceof UsernamePasswordAuthenticationFilter) { + System.out.println("********* Post-processing " + name); + ((UsernamePasswordAuthenticationFilter)bean).setAuthenticationDetailsSource( + new AuthenticationDetailsSource() { + public Object buildDetails(Object context) { + return ((HttpServletRequest)context).getHeader("CUSTOM_HEADER"); + } + }); + } + return bean; + } + + public Object postProcessBeforeInitialization(Object bean, String name) { + return bean; + } +} +``` + +Kotlin + +``` +class CustomBeanPostProcessor : BeanPostProcessor { + override fun postProcessAfterInitialization(bean: Any, name: String): Any { + if (bean is UsernamePasswordAuthenticationFilter) { + println("********* Post-processing $name") + bean.setAuthenticationDetailsSource( + AuthenticationDetailsSource { context -> context.getHeader("CUSTOM_HEADER") }) + } + return bean + } + + override fun postProcessBeforeInitialization(bean: Any, name: String?): Any { + return bean + } +} +``` + +You would then register this bean in your application context. +Spring will automatically invoke it on the beans defined in the application context. + +--- + +[1](#_footnoteref_1). The `FilterInvocation` object contains the `HttpServletRequest`, so you can obtain the URL or any other relevant information on which to base your decision on what the list of returned attributes will contain. + +[WebSocket Security](namespace/websocket.html)[Reactive Applications](../../reactive/index.html) + diff --git a/docs/en/spring-security/servlet-appendix-namespace-authentication-manager.md b/docs/en/spring-security/servlet-appendix-namespace-authentication-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..502056ad6a0455676c063dec46aa7097c5133c59 --- /dev/null +++ b/docs/en/spring-security/servlet-appendix-namespace-authentication-manager.md @@ -0,0 +1,168 @@ +# Authentication Services + +This creates an instance of Spring Security’s `ProviderManager` class, which needs to be configured with a list of one or more `AuthenticationProvider` instances. +These can either be created using syntax elements provided by the namespace, or they can be standard bean definitions, marked for addition to the list using the `authentication-provider` element. + +## \ + +Every Spring Security application which uses the namespace must have include this element somewhere. +It is responsible for registering the `AuthenticationManager` which provides authentication services to the application. +All elements which create `AuthenticationProvider` instances should be children of this element. + +### \ Attributes + +* **alias**This attribute allows you to define an alias name for the internal instance for use in your own configuration. + +* **erase-credentials**If set to true, the AuthenticationManager will attempt to clear any credentials data in the returned Authentication object, once the user has been authenticated. + Literally it maps to the `eraseCredentialsAfterAuthentication` property of the [`ProviderManager`](../../authentication/architecture.html#servlet-authentication-providermanager). + +* **id**This attribute allows you to define an id for the internal instance for use in your own configuration. + It is the same as the alias element, but provides a more consistent experience with elements that use the id attribute. + +### Child Elements of \ + +* [authentication-provider](#nsa-authentication-provider) + +* [ldap-authentication-provider](ldap.html#nsa-ldap-authentication-provider) + +## \ + +Unless used with a `ref` attribute, this element is shorthand for configuring a `DaoAuthenticationProvider`.`DaoAuthenticationProvider` loads user information from a `UserDetailsService` and compares the username/password combination with the values supplied at login. +The `UserDetailsService` instance can be defined either by using an available namespace element (`jdbc-user-service` or by using the `user-service-ref` attribute to point to a bean defined elsewhere in the application context). + +### Parent Elements of \ + +* [authentication-manager](#nsa-authentication-manager) + +### \ Attributes + +* **ref**Defines a reference to a Spring bean that implements `AuthenticationProvider`. + +If you have written your own `AuthenticationProvider` implementation (or want to configure one of Spring Security’s own implementations as a traditional bean for some reason, then you can use the following syntax to add it to the internal list of `ProviderManager`: + +``` + + + + +``` + +* **user-service-ref**A reference to a bean that implements UserDetailsService that may be created using the standard bean element or the custom user-service element. + +### Child Elements of \ + +* [jdbc-user-service](#nsa-jdbc-user-service) + +* [ldap-user-service](ldap.html#nsa-ldap-user-service) + +* [password-encoder](#nsa-password-encoder) + +* [user-service](#nsa-user-service) + +## \ + +Causes creation of a JDBC-based UserDetailsService. + +### \ Attributes + +* **authorities-by-username-query**An SQL statement to query for a user’s granted authorities given a username. + +The default is + +``` +select username, authority from authorities where username = ? +``` + +* **cache-ref**Defines a reference to a cache for use with a UserDetailsService. + +* **data-source-ref**The bean ID of the DataSource which provides the required tables. + +* **group-authorities-by-username-query**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 + ``` + +* **id**A bean identifier, used for referring to the bean elsewhere in the context. + +* **role-prefix**A non-empty string prefix that will be added to role strings loaded from persistent storage (default is "ROLE\_"). + Use the value "none" for no prefix in cases where the default is non-empty. + +* **users-by-username-query**An SQL statement to query a username, password, and enabled status given a username. + The default is + + ``` + select username, password, enabled from users where username = ? + ``` + +## \ + +Authentication providers can optionally be configured to use a password encoder as described in the [Password Storage](../../../features/authentication/password-storage.html#authentication-password-storage). +This will result in the bean being injected with the appropriate `PasswordEncoder` instance. + +### Parent Elements of \ + +* [authentication-provider](#nsa-authentication-provider) + +* [password-compare](#nsa-password-compare) + +### \ Attributes + +* **hash**Defines the hashing algorithm used on user passwords. + We recommend strongly against using MD4, as it is a very weak hashing algorithm. + +* **ref**Defines a reference to a Spring bean that implements `PasswordEncoder`. + +## \ + +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. + +### \ Attributes + +* **id**A bean identifier, used for referring to the bean elsewhere in the context. + +* **properties**The location of a Properties file where each line is in the format of + + ``` + username=password,grantedAuthority[,grantedAuthority][,enabled|disabled] + ``` + +### Child Elements of \ + +* [user](#nsa-user) + +## \ + +Represents a user in the application. + +### Parent Elements of \ + +* [user-service](#nsa-user-service) + +### \ Attributes + +* **authorities**One of more authorities granted to the user. + Separate authorities with a comma (but no space). + For example, "ROLE\_USER,ROLE\_ADMINISTRATOR" + +* **disabled**Can be set to "true" to mark an account as disabled and unusable. + +* **locked**Can be set to "true" to mark an account as locked and unusable. + +* **name**The username assigned to the user. + +* **password**The password assigned to the user. + This may be hashed if the corresponding authentication provider supports hashing (remember to set the "hash" attribute of the "user-service" element). + This attribute be omitted in the case where the data will not be used for authentication, but only for accessing authorities. + If omitted, the namespace will generate a random value, preventing its accidental use for authentication. + Cannot be empty. + +[XML Namespace](index.html)[Web Security](http.html) + diff --git a/docs/en/spring-security/servlet-appendix-namespace-http.md b/docs/en/spring-security/servlet-appendix-namespace-http.md new file mode 100644 index 0000000000000000000000000000000000000000..34dd7735e6e7d289e71ae8c559a0c4fdb3c93ea8 --- /dev/null +++ b/docs/en/spring-security/servlet-appendix-namespace-http.md @@ -0,0 +1,1251 @@ +# Web Application Security + +## \ + +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. + +## \ + +If you use an `` element within your application, a `FilterChainProxy` bean named "springSecurityFilterChain" is created and the configuration within the element is used to build a filter chain within`FilterChainProxy`. +As of Spring Security 3.1, additional `http` elements can be used to add extra filter chains [1] for how to set up the mapping from your `web.xml` ]. +Some core filters are always created in a filter chain and others will be added to the stack depending on the attributes and child elements which are present. +The positions of the standard filters are fixed (see[the filter order table](../../configuration/xml-namespace.html#filter-stack) in the namespace introduction), removing a common source of errors with previous versions of the framework when users had to configure the filter chain explicitly in the`FilterChainProxy` bean. +You can, of course, still do this if you need full control of the configuration. + +All filters which require a reference to the [`AuthenticationManager`](../../authentication/architecture.html#servlet-authentication-authenticationmanager) will be automatically injected with the internal instance created by the namespace configuration. + +Each `` namespace block always creates an `SecurityContextPersistenceFilter`, an `ExceptionTranslationFilter` and a `FilterSecurityInterceptor`. +These are fixed and cannot be replaced with alternatives. + +### \ Attributes + +The attributes on the `` element control some of the properties on the core filters. + +* **access-decision-manager-ref**Optional attribute specifying the ID of the `AccessDecisionManager` implementation which should be used for authorizing HTTP requests. + By default an `AffirmativeBased` implementation is used for with a `RoleVoter` and an `AuthenticatedVoter`. + +* **authentication-manager-ref**A reference to the `AuthenticationManager` used for the `FilterChain` created by this http element. + +* **auto-config**Automatically registers a login form, BASIC authentication, logout services. + If set to "true", all of these capabilities are added (although you can still customize the configuration of each by providing the respective element). + If unspecified, defaults to "false". + Use of this attribute is not recommended. + Use explicit configuration elements instead to avoid confusion. + +* **create-session**Controls the eagerness with which an HTTP session is created by Spring Security classes. + Options include: + + * `always` - Spring Security will proactively create a session if one does not exist. + + * `ifRequired` - Spring Security will only create a session only if one is required (default value). + + * `never` - Spring Security will never create a session, but will make use of one if the application does. + + * `stateless` - Spring Security will not create a session and ignore the session for obtaining a Spring `Authentication`. + +* **disable-url-rewriting**Prevents session IDs from being appended to URLs in the application. + Clients must use cookies if this attribute is set to `true`. + The default is `true`. + +* **entry-point-ref**Normally the `AuthenticationEntryPoint` used will be set depending on which authentication mechanisms have been configured. + This attribute allows this behaviour to be overridden by defining a customized `AuthenticationEntryPoint` bean which will start the authentication process. + +* **jaas-api-provision**If available, runs the request as the `Subject` acquired from the `JaasAuthenticationToken` which is implemented by adding a `JaasApiIntegrationFilter` bean to the stack. + Defaults to `false`. + +* **name**A bean identifier, used for referring to the bean elsewhere in the context. + +* **once-per-request**Corresponds to the `observeOncePerRequest` property of `FilterSecurityInterceptor`. + Defaults to `true`. + +* **pattern**Defining a pattern for the [http](#nsa-http) element controls the requests which will be filtered through the list of filters which it defines. + The interpretation is dependent on the configured [request-matcher](#nsa-http-request-matcher). + If no pattern is defined, all requests will be matched, so the most specific patterns should be declared first. + +* **realm**Sets the realm name used for basic authentication (if enabled). + Corresponds to the `realmName` property on `BasicAuthenticationEntryPoint`. + +* **request-matcher**Defines the `RequestMatcher` strategy used in the `FilterChainProxy` and the beans created by the `intercept-url` to match incoming requests. + Options are currently `mvc`, `ant`, `regex` and `ciRegex`, for Spring MVC, ant, regular-expression and case-insensitive regular-expression respectively. + A separate instance is created for each [intercept-url](#nsa-intercept-url) element using its [pattern](#nsa-intercept-url-pattern), [method](#nsa-intercept-url-method) and [servlet-path](#nsa-intercept-url-servlet-path) attributes. + Ant paths are matched using an `AntPathRequestMatcher`, regular expressions are matched using a `RegexRequestMatcher` and for Spring MVC path matching the `MvcRequestMatcher` is used. + See the Javadoc for these classes for more details on exactly how the matching is performed. + Ant paths are the default strategy. + +* **request-matcher-ref**A reference to a bean that implements `RequestMatcher` that will determine if this `FilterChain` should be used. + This is a more powerful alternative to [pattern](#nsa-http-pattern). + +* **security**A request pattern can be mapped to an empty filter chain, by setting this attribute to `none`. + No security will be applied and none of Spring Security’s features will be available. + +* **security-context-repository-ref**Allows injection of a custom `SecurityContextRepository` into the `SecurityContextPersistenceFilter`. + +* **servlet-api-provision**Provides versions of `HttpServletRequest` security methods such as `isUserInRole()` and `getPrincipal()` which are implemented by adding a `SecurityContextHolderAwareRequestFilter` bean to the stack. + Defaults to `true`. + +* **use-expressions**Enables EL-expressions in the `access` attribute, as described in the chapter on [expression-based access-control](../../authorization/expression-based.html#el-access-web). + The default value is true. + +### Child Elements of \ + +* [access-denied-handler](#nsa-access-denied-handler) + +* [anonymous](#nsa-anonymous) + +* [cors](#nsa-cors) + +* [csrf](#nsa-csrf) + +* [custom-filter](#nsa-custom-filter) + +* [expression-handler](#nsa-expression-handler) + +* [form-login](#nsa-form-login) + +* [headers](#nsa-headers) + +* [http-basic](#nsa-http-basic) + +* [intercept-url](#nsa-intercept-url) + +* [jee](#nsa-jee) + +* [logout](#nsa-logout) + +* [oauth2-client](#nsa-oauth2-client) + +* [oauth2-login](#nsa-oauth2-login) + +* [oauth2-resource-server](#nsa-oauth2-resource-server) + +* [openid-login](#nsa-openid-login) + +* [password-management](#nsa-password-management) + +* [port-mappings](#nsa-port-mappings) + +* [remember-me](#nsa-remember-me) + +* [request-cache](#nsa-request-cache) + +* [session-management](#nsa-session-management) + +* [x509](#nsa-x509) + +## \ + +This element allows you to set the `errorPage` property for the default `AccessDeniedHandler` used by the `ExceptionTranslationFilter`, using the [error-page](#nsa-access-denied-handler-error-page) attribute, or to supply your own implementation using the [ref](#nsa-access-denied-handler-ref) attribute. +This is discussed in more detail in the section on the [ExceptionTranslationFilter](../../architecture.html#servlet-exceptiontranslationfilter). + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **error-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. + +* **ref**Defines a reference to a Spring bean of type `AccessDeniedHandler`. + +## \ + +This element allows for configuring a `CorsFilter`. +If no `CorsFilter` or `CorsConfigurationSource` is specified and Spring MVC is on the classpath, a `HandlerMappingIntrospector` is used as the `CorsConfigurationSource`. + +### \ Attributes + +The attributes on the `` element control the headers element. + +* **ref**Optional attribute that specifies the bean name of a `CorsFilter`. + +* **cors-configuration-source-ref**Optional attribute that specifies the bean name of a `CorsConfigurationSource` to be injected into a `CorsFilter` created by the XML namespace. + +### Parent Elements of \ + +* [http](#nsa-http) + +## \ + +This element allows for configuring additional (security) headers to be send with the response. +It enables easy configuration for several headers and also allows for setting custom headers through the [header](#nsa-header) element. +Additional information, can be found in the [Security Headers](../../../features/exploits/headers.html#headers) section of the reference. + +* `Cache-Control`, `Pragma`, and `Expires` - Can be set using the [cache-control](#nsa-cache-control) element. + This ensures that the browser does not cache your secured pages. + +* `Strict-Transport-Security` - Can be set using the [hsts](#nsa-hsts) element. + This ensures that the browser automatically requests HTTPS for future requests. + +* `X-Frame-Options` - Can be set using the [frame-options](#nsa-frame-options) element. + The [X-Frame-Options](https://en.wikipedia.org/wiki/Clickjacking#X-Frame-Options) header can be used to prevent clickjacking attacks. + +* `X-XSS-Protection` - Can be set using the [xss-protection](#nsa-xss-protection) element. + The [X-XSS-Protection ](https://en.wikipedia.org/wiki/Cross-site_scripting) header can be used by browser to do basic control. + +* `X-Content-Type-Options` - Can be set using the [content-type-options](#nsa-content-type-options) element. + The [X-Content-Type-Options](https://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx) header prevents Internet Explorer from MIME-sniffing a response away from the declared content-type. + This also applies to Google Chrome, when downloading extensions. + +* `Public-Key-Pinning` or `Public-Key-Pinning-Report-Only` - Can be set using the [hpkp](#nsa-hpkp) element. + This allows HTTPS websites to resist impersonation by attackers using mis-issued or otherwise fraudulent certificates. + +* `Content-Security-Policy` or `Content-Security-Policy-Report-Only` - Can be set using the [content-security-policy](#nsa-content-security-policy) element.[Content Security Policy (CSP)](https://www.w3.org/TR/CSP2/) is a mechanism that web applications can leverage to mitigate content injection vulnerabilities, such as cross-site scripting (XSS). + +* `Referrer-Policy` - Can be set using the [referrer-policy](#nsa-referrer-policy) element, [Referrer-Policy](https://www.w3.org/TR/referrer-policy/) is a mechanism that web applications can leverage to manage the referrer field, which contains the last page the user was on. + +* `Feature-Policy` - Can be set using the [feature-policy](#nsa-feature-policy) element, [Feature-Policy](https://wicg.github.io/feature-policy/) is a mechanism that allows web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser. + +### \ Attributes + +The attributes on the `` element control the headers element. + +* **defaults-disabled**Optional attribute that specifies to disable the default Spring Security’s HTTP response headers. + The default is false (the default headers are included). + +* **disabled**Optional attribute that specifies to disable Spring Security’s HTTP response headers. + The default is false (the headers are enabled). + +### Parent Elements of \ + +* [http](#nsa-http) + +### Child Elements of \ + +* [cache-control](#nsa-cache-control) + +* [content-security-policy](#nsa-content-security-policy) + +* [content-type-options](#nsa-content-type-options) + +* [feature-policy](#nsa-feature-policy) + +* [frame-options](#nsa-frame-options) + +* [header](#nsa-header) + +* [hpkp](#nsa-hpkp) + +* [hsts](#nsa-hsts) + +* [permission-policy](#nsa-permissions-policy) + +* [referrer-policy](#nsa-referrer-policy) + +* [xss-protection](#nsa-xss-protection) + +## \ + +Adds `Cache-Control`, `Pragma`, and `Expires` headers to ensure that the browser does not cache your secured pages. + +### \ Attributes + +* **disabled**Specifies if Cache Control should be disabled. + Default false. + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +When enabled adds the [Strict-Transport-Security](https://tools.ietf.org/html/rfc6797) header to the response for any secure request. +This allows the server to instruct browsers to automatically use HTTPS for future requests. + +### \ Attributes + +* **disabled**Specifies if Strict-Transport-Security should be disabled. + Default false. + +* **include-sub-domains**Specifies if subdomains should be included. + Default true. + +* **max-age-seconds**Specifies the maximum amount of time the host should be considered a Known HSTS Host. + Default one year. + +* **request-matcher-ref**The RequestMatcher instance to be used to determine if the header should be set. + Default is if HttpServletRequest.isSecure() is true. + +* **preload**Specifies if preload should be included. + Default false. + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +When enabled adds the [Public Key Pinning Extension for HTTP](https://tools.ietf.org/html/rfc7469) header to the response for any secure request. +This allows HTTPS websites to resist impersonation by attackers using mis-issued or otherwise fraudulent certificates. + +### \ Attributes + +* **disabled**Specifies if HTTP Public Key Pinning (HPKP) should be disabled. + Default true. + +* **include-sub-domains**Specifies if subdomains should be included. + Default false. + +* **max-age-seconds**Sets the value for the max-age directive of the Public-Key-Pins header. + Default 60 days. + +* **report-only**Specifies if the browser should only report pin validation failures. + Default true. + +* **report-uri**Specifies the URI to which the browser should report pin validation failures. + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +The list of pins + +### Child Elements of \ + +* [pin](#nsa-pin) + +## \ + +A pin is specified using the base64-encoded SPKI fingerprint as value and the cryptographic hash algorithm as attribute + +### \ Attributes + +* **algorithm**The cryptographic hash algorithm. + Default is SHA256. + +### Parent Elements of \ + +* [pins](#nsa-pins) + +## \ + +When enabled adds the [Content Security Policy (CSP)](https://www.w3.org/TR/CSP2/) header to the response. +CSP is a mechanism that web applications can leverage to mitigate content injection vulnerabilities, such as cross-site scripting (XSS). + +### \ Attributes + +* **policy-directives**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. + +* **report-only**Set to true, to enable the Content-Security-Policy-Report-Only header for reporting policy violations only. + Defaults to false. + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +When enabled adds the [Referrer Policy](https://www.w3.org/TR/referrer-policy/) header to the response. + +### \ Attributes + +* **policy**The policy for the Referrer-Policy header. + Default "no-referrer". + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +When enabled adds the [Feature Policy](https://wicg.github.io/feature-policy/) header to the response. + +### \ Attributes + +* **policy-directives**The security policy directive(s) for the Feature-Policy header. + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +When enabled adds the [X-Frame-Options header](https://tools.ietf.org/html/draft-ietf-websec-x-frame-options) to the response, this allows newer browsers to do some security checks and prevent [clickjacking](https://en.wikipedia.org/wiki/Clickjacking) attacks. + +### \ Attributes + +* **disabled**If disabled, the X-Frame-Options header will not be included. + Default false. + +* **policy** + + * `DENY` The page cannot be displayed in a frame, regardless of the site attempting to do so. + This is the default when frame-options-policy is specified. + + * `SAMEORIGIN` The page can only be displayed in a frame on the same origin as the page itself + + In other words, if you specify DENY, not only will attempts to load the page in a frame fail when loaded from other sites, attempts to do so will fail when loaded from the same site. + On the other hand, if you specify SAMEORIGIN, you can still use the page in a frame as long as the site including it in a frame it is the same as the one serving the page. + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +Adds the [Permissions-Policy header](https://w3c.github.io/webappsec-permissions-policy/) to the response. + +### \ Attributes + +* **policy**The policy value to write for the `Permissions-Policy` header + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +Adds the [X-XSS-Protection header](https://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx) to the response to assist in protecting against [reflected / Type-1 Cross-Site Scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent) attacks. +This is in no-way a full protection to XSS attacks! + +### \ Attributes + +* **xss-protection-disabled**Do not include the header for [reflected / Type-1 Cross-Site Scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent) protection. + +* **xss-protection-enabled**Explicitly enable or disable [reflected / Type-1 Cross-Site Scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent) protection. + +* **xss-protection-block**When true and xss-protection-enabled is true, adds mode=block to the header. + This indicates to the browser that the page should not be loaded at all. + When false and xss-protection-enabled is true, the page will still be rendered when an reflected attack is detected but the response will be modified to protect against the attack. + Note that there are sometimes ways of bypassing this mode which can often times make blocking the page more desirable. + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +Add the X-Content-Type-Options header with the value of nosniff to the response. +This [disables MIME-sniffing](https://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx) for IE8+ and Chrome extensions. + +### \ Attributes + +* **disabled**Specifies if Content Type Options should be disabled. + Default false. + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +Add additional headers to the response, both the name and value need to be specified. + +### \ Attributes + +* **header-name**The `name` of the header. + +* **value**The `value` of the header to add. + +* **ref**Reference to a custom implementation of the `HeaderWriter` interface. + +### Parent Elements of \ + +* [headers](#nsa-headers) + +## \ + +Adds an `AnonymousAuthenticationFilter` to the stack and an `AnonymousAuthenticationProvider`. +Required if you are using the `IS_AUTHENTICATED_ANONYMOUSLY` attribute. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **enabled**With the default namespace setup, the anonymous "authentication" facility is automatically enabled. + You can disable it using this property. + +* **granted-authority**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`. + +* **key**The key shared between the provider and filter. + This generally does not need to be set. + If unset, it will default to a secure randomly generated value. + This means setting this value can improve startup time when using the anonymous functionality since secure random values can take a while to be generated. + +* **username**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`. + +## \ + +This element will add [Cross Site Request Forger (CSRF)](https://en.wikipedia.org/wiki/Cross-site_request_forgery) protection to the application. +It also updates the default RequestCache to only replay "GET" requests upon successful authentication. +Additional information can be found in the [Cross Site Request Forgery (CSRF)](../../../features/exploits/csrf.html#csrf) section of the reference. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **disabled**Optional attribute that specifies to disable Spring Security’s CSRF protection. + The default is false (CSRF protection is enabled). + It is highly recommended to leave CSRF protection enabled. + +* **token-repository-ref**The CsrfTokenRepository to use. + The default is `HttpSessionCsrfTokenRepository`. + +* **request-matcher-ref**The RequestMatcher instance to be used to determine if CSRF should be applied. + Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS". + +## \ + +This element is used to add a filter to the filter chain. +It doesn’t create any additional beans but is used to select a bean of type `javax.servlet.Filter` which is already defined in the application context and add that at a particular position in the filter chain maintained by Spring Security. +Full details can be found in the [ namespace chapter](../../configuration/xml-namespace.html#ns-custom-filters). + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **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. + +* **before**The filter immediately before which the custom-filter should be placed in the chain + +* **position**The explicit position at which the custom-filter should be placed in the chain. + Use if you are replacing a standard filter. + +* **ref**Defines a reference to a Spring bean that implements `Filter`. + +## \ + +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. + +### Parent Elements of \ + +* [global-method-security](method-security.html#nsa-global-method-security) + +* [http](#nsa-http) + +* [method-security](method-security.html#nsa-method-security) + +* [websocket-message-broker](websocket.html#nsa-websocket-message-broker) + +### \ Attributes + +* **ref**Defines a reference to a Spring bean that implements `SecurityExpressionHandler`. + +## \ + +Used to add an `UsernamePasswordAuthenticationFilter` to the filter stack and an `LoginUrlAuthenticationEntryPoint` to the application context to provide authentication on demand. +This will always take precedence over other namespace-created entry points. +If no attributes are supplied, a login page will be generated automatically at the URL "/login" [2] The behaviour can be customized using the [`` Attributes](#nsa-form-login-attributes). + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **always-use-default-target**If set to `true`, the user will always start at the value given by [default-target-url](#nsa-form-login-default-target-url), regardless of how they arrived at the login page. + Maps to the `alwaysUseDefaultTargetUrl` property of `UsernamePasswordAuthenticationFilter`. + Default value is `false`. + +* **authentication-details-source-ref**Reference to an `AuthenticationDetailsSource` which will be used by the authentication filter + +* **authentication-failure-handler-ref**Can be used as an alternative to [authentication-failure-url](#nsa-form-login-authentication-failure-url), giving you full control over the navigation flow after an authentication failure. + The value should be the name of an `AuthenticationFailureHandler` bean in the application context. + +* **authentication-failure-url**Maps to the `authenticationFailureUrl` property of `UsernamePasswordAuthenticationFilter`. + Defines the URL the browser will be redirected to on login failure. + Defaults to `/login?error`, which will be automatically handled by the automatic login page generator, re-rendering the login page with an error message. + +* **authentication-success-handler-ref**This can be used as an alternative to [default-target-url](#nsa-form-login-default-target-url) and [always-use-default-target](#nsa-form-login-always-use-default-target), giving you full control over the navigation flow after a successful authentication. + The value should be the name of an `AuthenticationSuccessHandler` bean in the application context. + By default, an implementation of `SavedRequestAwareAuthenticationSuccessHandler` is used and injected with the [default-target-url ](#nsa-form-login-default-target-url). + +* **default-target-url**Maps to the `defaultTargetUrl` property of `UsernamePasswordAuthenticationFilter`. + If not set, the default value is "/" (the application root). + A user will be taken to this URL after logging in, provided they were not asked to login while attempting to access a secured resource, when they will be taken to the originally requested URL. + +* **login-page**The URL that should be used to render the login page. + Maps to the `loginFormUrl` property of the `LoginUrlAuthenticationEntryPoint`. + Defaults to "/login". + +* **login-processing-url**Maps to the `filterProcessesUrl` property of `UsernamePasswordAuthenticationFilter`. + The default value is "/login". + +* **password-parameter**The name of the request parameter which contains the password. + Defaults to "password". + +* **username-parameter**The name of the request parameter which contains the username. + Defaults to "username". + +* **authentication-success-forward-url**Maps a `ForwardAuthenticationSuccessHandler` to `authenticationSuccessHandler` property of `UsernamePasswordAuthenticationFilter`. + +* **authentication-failure-forward-url**Maps a `ForwardAuthenticationFailureHandler` to `authenticationFailureHandler` property of `UsernamePasswordAuthenticationFilter`. + +## \ + +The [OAuth 2.0 Login](../../oauth2/login/index.html#oauth2login) feature configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **client-registration-repository-ref**Reference to the `ClientRegistrationRepository`. + +* **authorized-client-repository-ref**Reference to the `OAuth2AuthorizedClientRepository`. + +* **authorized-client-service-ref**Reference to the `OAuth2AuthorizedClientService`. + +* **authorization-request-repository-ref**Reference to the `AuthorizationRequestRepository`. + +* **authorization-request-resolver-ref**Reference to the `OAuth2AuthorizationRequestResolver`. + +* **access-token-response-client-ref**Reference to the `OAuth2AccessTokenResponseClient`. + +* **user-authorities-mapper-ref**Reference to the `GrantedAuthoritiesMapper`. + +* **user-service-ref**Reference to the `OAuth2UserService`. + +* **oidc-user-service-ref**Reference to the OpenID Connect `OAuth2UserService`. + +* **login-processing-url**The URI where the filter processes authentication requests. + +* **login-page**The URI to send users to login. + +* **authentication-success-handler-ref**Reference to the `AuthenticationSuccessHandler`. + +* **authentication-failure-handler-ref**Reference to the `AuthenticationFailureHandler`. + +* **jwt-decoder-factory-ref**Reference to the `JwtDecoderFactory` used by `OidcAuthorizationCodeAuthenticationProvider`. + +## \ + +Configures [OAuth 2.0 Client](../../oauth2/client/index.html#oauth2client) support. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **client-registration-repository-ref**Reference to the `ClientRegistrationRepository`. + +* **authorized-client-repository-ref**Reference to the `OAuth2AuthorizedClientRepository`. + +* **authorized-client-service-ref**Reference to the `OAuth2AuthorizedClientService`. + +### Child Elements of \ + +* [authorization-code-grant](#nsa-authorization-code-grant) + +## \ + +Configures [OAuth 2.0 Authorization Code Grant](../../oauth2/client/authorization-grants.html#oauth2Client-auth-grant-support). + +### Parent Elements of \ + +* [oauth2-client](#nsa-oauth2-client) + +### \ Attributes + +* **authorization-request-repository-ref**Reference to the `AuthorizationRequestRepository`. + +* **authorization-request-resolver-ref**Reference to the `OAuth2AuthorizationRequestResolver`. + +* **access-token-response-client-ref**Reference to the `OAuth2AccessTokenResponseClient`. + +## \ + +A container element for client(s) registered ([ClientRegistration](../../oauth2/client/index.html#oauth2Client-client-registration)) with an OAuth 2.0 or OpenID Connect 1.0 Provider. + +### Child Elements of \ + +* [client-registration](#nsa-client-registration) + +* [provider](#nsa-provider) + +## \ + +Represents a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. + +### Parent Elements of \ + +* [client-registrations](#nsa-client-registrations) + +### \ Attributes + +* **registration-id**The ID that uniquely identifies the `ClientRegistration`. + +* **client-id**The client identifier. + +* **client-secret**The client secret. + +* **client-authentication-method**The method used to authenticate the Client with the Provider. + The supported values are **client\_secret\_basic**, **client\_secret\_post**, **private\_key\_jwt**, **client\_secret\_jwt** and **none** [(public clients)](https://tools.ietf.org/html/rfc6749#section-2.1). + +* **authorization-grant-type**The OAuth 2.0 Authorization Framework defines four [Authorization Grant](https://tools.ietf.org/html/rfc6749#section-1.3) types. + The supported values are `authorization_code`, `client_credentials`, `password`, as well as, extension grant type `urn:ietf:params:oauth:grant-type:jwt-bearer`. + +* **redirect-uri**The client’s registered redirect URI that the *Authorization Server* redirects the end-user’s user-agent to after the end-user has authenticated and authorized access to the client. + +* **scope**The scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile. + +* **client-name**A descriptive name used for the client. + The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page. + +* **provider-id**A reference to the associated provider. May reference a `` element or use one of the common providers (google, github, facebook, okta). + +## \ + +The configuration information for an OAuth 2.0 or OpenID Connect 1.0 Provider. + +### Parent Elements of \ + +* [client-registrations](#nsa-client-registrations) + +### \ Attributes + +* **provider-id**The ID that uniquely identifies the provider. + +* **authorization-uri**The Authorization Endpoint URI for the Authorization Server. + +* **token-uri**The Token Endpoint URI for the Authorization Server. + +* **user-info-uri**The UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user. + +* **user-info-authentication-method**The authentication method used when sending the access token to the UserInfo Endpoint. + The supported values are **header**, **form** and **query**. + +* **user-info-user-name-attribute**The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user. + +* **jwk-set-uri**The URI used to retrieve the [JSON Web Key (JWK)](https://tools.ietf.org/html/rfc7517) Set from the Authorization Server, which contains the cryptographic key(s) used to verify the [JSON Web Signature (JWS)](https://tools.ietf.org/html/rfc7515) of the ID Token and optionally the UserInfo Response. + +* **issuer-uri**The URI used to initially configure a `ClientRegistration` using discovery of an OpenID Connect Provider’s [Configuration endpoint](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) or an Authorization Server’s [Metadata endpoint](https://tools.ietf.org/html/rfc8414#section-3). + +## \ + +Adds a `BearerTokenAuthenticationFilter`, `BearerTokenAuthenticationEntryPoint`, and `BearerTokenAccessDeniedHandler` to the configuration. +In addition, either `` or `` must be specified. + +### Parents Elements of \ + +* [http](#nsa-http) + +### Child Elements of \ + +* [jwt](#nsa-jwt) + +* [opaque-token](#nsa-opaque-token) + +### \ Attributes + +* **authentication-manager-resolver-ref**Reference to an `AuthenticationManagerResolver` which will resolve the `AuthenticationManager` at request time + +* **bearer-token-resolver-ref**Reference to a `BearerTokenResolver` which will retrieve the bearer token from the request + +* **entry-point-ref**Reference to a `AuthenticationEntryPoint` which will handle unauthorized requests + +## \ + +Represents an OAuth 2.0 Resource Server that will authorize JWTs + +### Parent Elements of \ + +* [oauth2-resource-server](#nsa-oauth2-resource-server) + +### \ Attributes + +* **jwt-authentication-converter-ref**Reference to a `Converter` + +* **jwt-decoder-ref**Reference to a `JwtDecoder`. This is a larger component that overrides `jwk-set-uri` + +* **jwk-set-uri**The JWK Set Uri used to load signing verification keys from an OAuth 2.0 Authorization Server + +## \ + +Represents an OAuth 2.0 Resource Server that will authorize opaque tokens + +### Parent Elements of \ + +* [oauth2-resource-server](#nsa-oauth2-resource-server) + +### \ Attributes + +* **introspector-ref**Reference to an `OpaqueTokenIntrospector`. This is a larger component that overrides `introspection-uri`, `client-id`, and `client-secret`. + +* **introspection-uri**The Introspection Uri used to introspect the details of an opaque token. Should be accompanied with a `client-id` and `client-secret`. + +* **client-id**The Client Id to use for client authentication against the provided `introspection-uri`. + +* **client-secret**The Client Secret to use for client authentication against the provided `introspection-uri`. + +## \ + +Adds a `BasicAuthenticationFilter` and `BasicAuthenticationEntryPoint` to the configuration. +The latter will only be used as the configuration entry point if form-based login is not enabled. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **authentication-details-source-ref**Reference to an `AuthenticationDetailsSource` which will be used by the authentication filter + +* **entry-point-ref**Sets the `AuthenticationEntryPoint` which is used by the `BasicAuthenticationFilter`. + +## \ Element + +This is a top-level element which can be used to inject a custom implementation of `HttpFirewall` into the `FilterChainProxy` created by the namespace. +The default implementation should be suitable for most applications. + +### \ Attributes + +* **ref**Defines a reference to a Spring bean that implements `HttpFirewall`. + +## \ + +This element is used to define the set of URL patterns that the application is interested in and to configure how they should be handled. +It is used to construct the `FilterInvocationSecurityMetadataSource` used by the `FilterSecurityInterceptor`. +It is also responsible for configuring a `ChannelProcessingFilter` if particular URLs need to be accessed by HTTPS, for example. +When matching the specified patterns against an incoming request, the matching is done in the order in which the elements are declared. +So the most specific patterns should come first and the most general should come last. + +### Parent Elements of \ + +* [filter-security-metadata-source](#nsa-filter-security-metadata-source) + +* [http](#nsa-http) + +### \ Attributes + +* **access**Lists the access attributes which will be stored in the `FilterInvocationSecurityMetadataSource` for the defined URL pattern/method combination. + This should be a comma-separated list of the security configuration attributes (such as role names). + +* **method**The HTTP Method which will be used in combination with the pattern and servlet path (optional) to match an incoming request. + If omitted, any method will match. + If an identical pattern is specified with and without a method, the method-specific match will take precedence. + +* **pattern**The pattern which defines the URL path. + The content will depend on the `request-matcher` attribute from the containing http element, so will default to ant path syntax. + +* **request-matcher-ref**A reference to a `RequestMatcher` that will be used to determine if this `` is used. + +* **requires-channel**Can be "http" or "https" depending on whether a particular URL pattern should be accessed over HTTP or HTTPS respectively. + Alternatively the value "any" can be used when there is no preference. + If this attribute is present on any `` element, then a `ChannelProcessingFilter` will be added to the filter stack and its additional dependencies added to the application context. + +If a `` configuration is added, this will be used to by the `SecureChannelProcessor` and `InsecureChannelProcessor` beans to determine the ports used for redirecting to HTTP/HTTPS. + +| |This property is invalid for [filter-security-metadata-source](#nsa-filter-security-metadata-source)| +|---|----------------------------------------------------------------------------------------------------| + +* **servlet-path**The servlet path which will be used in combination with the pattern and HTTP method to match an incoming request. + This attribute is only applicable when [request-matcher](#nsa-http-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` `'/'`. + +| |This property is invalid for [filter-security-metadata-source](#nsa-filter-security-metadata-source)| +|---|----------------------------------------------------------------------------------------------------| + +## \ + +Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **mappable-roles**A comma-separate list of roles to look for in the incoming HttpServletRequest. + +* **user-service-ref**A reference to a user-service (or UserDetailsService bean) Id + +## \ + +Adds a `LogoutFilter` to the filter stack. +This is configured with a `SecurityContextLogoutHandler`. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **delete-cookies**A comma-separated list of the names of cookies which should be deleted when the user logs out. + +* **invalidate-session**Maps to the `invalidateHttpSession` of the `SecurityContextLogoutHandler`. + Defaults to "true", so the session will be invalidated on logout. + +* **logout-success-url**The destination URL which the user will be taken to after logging out. + Defaults to \/?logout (i.e. /login?logout) + + Setting this attribute will inject the `SessionManagementFilter` with a `SimpleRedirectInvalidSessionStrategy` configured with the attribute value. + When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL. + +* **logout-url**The URL which will cause a logout (i.e. which will be processed by the filter). + Defaults to "/logout". + +* **success-handler-ref**May be used to supply an instance of `LogoutSuccessHandler` which will be invoked to control the navigation after logging out. + +## \ + +Similar to `` and has the same attributes. +The default value for `login-processing-url` is "/login/openid". +An `OpenIDAuthenticationFilter` and `OpenIDAuthenticationProvider` will be registered. +The latter requires a reference to a `UserDetailsService`. +Again, this can be specified by `id`, using the `user-service-ref` attribute, or will be located automatically in the application context. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **always-use-default-target**Whether the user should always be redirected to the default-target-url after login. + +* **authentication-details-source-ref**Reference to an AuthenticationDetailsSource which will be used by the authentication filter + +* **authentication-failure-handler-ref**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 + +* **authentication-failure-url**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?login\_error and a corresponding filter to render that login failure URL when requested. + +* **authentication-success-forward-url**Maps a `ForwardAuthenticationSuccessHandler` to `authenticationSuccessHandler` property of `UsernamePasswordAuthenticationFilter`. + +* **authentication-failure-forward-url**Maps a `ForwardAuthenticationFailureHandler` to `authenticationFailureHandler` property of `UsernamePasswordAuthenticationFilter`. + +* **authentication-success-handler-ref**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](#nsa-openid-login-default-target-url) (or [always-use-default-target](#nsa-openid-login-always-use-default-target)) as the implementation should always deal with navigation to the subsequent destination + +* **default-target-url**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. + +* **login-page**The URL for the login page. + If no login URL is specified, Spring Security will automatically create a login URL at /login and a corresponding filter to render that login URL when requested. + +* **login-processing-url**The URL that the login form is posted to. + If unspecified, it defaults to /login. + +* **password-parameter**The name of the request parameter which contains the password. + Defaults to "password". + +* **user-service-ref**A reference to a user-service (or UserDetailsService bean) Id + +* **username-parameter**The name of the request parameter which contains the username. + Defaults to "username". + +### Child Elements of \ + +* [attribute-exchange](#nsa-attribute-exchange) + +## \ + +The `attribute-exchange` element defines the list of attributes which should be requested from the identity provider. +An example can be found in the [OpenID Support](../../authentication/openid.html#servlet-openid) section of the namespace configuration chapter. +More than one can be used, in which case each must have an `identifier-match` attribute, containing a regular expression which is matched against the supplied OpenID identifier. +This allows different attribute lists to be fetched from different providers (Google, Yahoo etc). + +### Parent Elements of \ + +* [openid-login](#nsa-openid-login) + +### \ Attributes + +* **identifier-match**A regular expression which will be compared against the claimed identity, when deciding which attribute-exchange configuration to use during authentication. + +### Child Elements of \ + +* [openid-attribute](#nsa-openid-attribute) + +## \ + +Attributes used when making an OpenID AX [ Fetch Request](https://openid.net/specs/openid-attribute-exchange-1_0.html#fetch_request) + +### Parent Elements of \ + +* [attribute-exchange](#nsa-attribute-exchange) + +### \ Attributes + +* **count**Specifies the number of attributes that you wish to get back. + For example, return 3 emails. + The default value is 1. + +* **name**Specifies the name of the attribute that you wish to get back. + For example, email. + +* **required**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. + +* **type**Specifies the attribute type. + For example, [https://axschema.org/contact/email](https://axschema.org/contact/email). + See your OP’s documentation for valid attribute types. + +## \ + +This element configures password management. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **change-password-page**The change password page. Defaults to "/change-password". + +## \ + +By default, an instance of `PortMapperImpl` will be added to the configuration for use in redirecting to secure and insecure URLs. +This element can optionally be used to override the default mappings which that class defines. +Each child `` element defines a pair of HTTP:HTTPS ports. +The default mappings are 80:443 and 8080:8443. +An example of overriding these can be found in [Redirect to HTTPS](../../exploits/http.html#servlet-http-redirect). + +### Parent Elements of \ + +* [http](#nsa-http) + +### Child Elements of \ + +* [port-mapping](#nsa-port-mapping) + +## \ + +Provides a method to map http ports to https ports when forcing a redirect. + +### Parent Elements of \ + +* [port-mappings](#nsa-port-mappings) + +### \ Attributes + +* **http**The http port to use. + +* **https**The https port to use. + +## \ + +Adds the `RememberMeAuthenticationFilter` to the stack. +This in turn will be configured with either a `TokenBasedRememberMeServices`, a `PersistentTokenBasedRememberMeServices` or a user-specified bean implementing `RememberMeServices` depending on the attribute settings. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **authentication-success-handler-ref**Sets the `authenticationSuccessHandler` property on the `RememberMeAuthenticationFilter` if custom navigation is required. + The value should be the name of a `AuthenticationSuccessHandler` bean in the application context. + +* **data-source-ref**A reference to a `DataSource` bean. + If this is set, `PersistentTokenBasedRememberMeServices` will be used and configured with a `JdbcTokenRepositoryImpl` instance. + +* **remember-me-parameter**The name of the request parameter which toggles remember-me authentication. + Defaults to "remember-me". + Maps to the "parameter" property of `AbstractRememberMeServices`. + +* **remember-me-cookie**The name of cookie which store the token for remember-me authentication. + Defaults to "remember-me". + Maps to the "cookieName" property of `AbstractRememberMeServices`. + +* **key**Maps to the "key" property of `AbstractRememberMeServices`. + Should be set to a unique value to ensure that remember-me cookies are only valid within the one application [3]. + If this is not set a secure random value will be generated. + Since generating secure random values can take a while, setting this value explicitly can help improve startup times when using the remember-me functionality. + +* **services-alias**Exports the internally defined `RememberMeServices` as a bean alias, allowing it to be used by other beans in the application context. + +* **services-ref**Allows complete control of the `RememberMeServices` implementation that will be used by the filter. + The value should be the `id` of a bean in the application context which implements this interface. + Should also implement `LogoutHandler` if a logout filter is in use. + +* **token-repository-ref**Configures a `PersistentTokenBasedRememberMeServices` but allows the use of a custom `PersistentTokenRepository` bean. + +* **token-validity-seconds**Maps to the `tokenValiditySeconds` property of `AbstractRememberMeServices`. + Specifies the period in seconds for which the remember-me cookie should be valid. + By default it will be valid for 14 days. + +* **use-secure-cookie**It is recommended that remember-me cookies are only submitted over HTTPS and thus should be flagged as "secure". + By default, a secure cookie will be used if the connection over which the login request is made is secure (as it should be). + If you set this property to `false`, secure cookies will not be used. + Setting it to `true` will always set the secure flag on the cookie. + This attribute maps to the `useSecureCookie` property of `AbstractRememberMeServices`. + +* **user-service-ref**The remember-me services implementations require access to a `UserDetailsService`, so there has to be one defined in the application context. + If there is only one, it will be selected and used automatically by the namespace configuration. + If there are multiple instances, you can specify a bean `id` explicitly using this attribute. + +## \ Element + +Sets the `RequestCache` instance which will be used by the `ExceptionTranslationFilter` to store request information before invoking an `AuthenticationEntryPoint`. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **ref**Defines a reference to a Spring bean that is a `RequestCache`. + +## \ + +Session-management related functionality is implemented by the addition of a `SessionManagementFilter` to the filter stack. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **invalid-session-url**Setting this attribute will inject the `SessionManagementFilter` with a `SimpleRedirectInvalidSessionStrategy` configured with the attribute value. + When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL. + +* **invalid-session-url**Allows injection of the InvalidSessionStrategy instance used by the SessionManagementFilter. + Use either this or the `invalid-session-url` attribute but not both. + +* **session-authentication-error-url**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. + +* **session-authentication-strategy-ref**Allows injection of the SessionAuthenticationStrategy instance used by the SessionManagementFilter + +* **session-fixation-protection**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. + + If session fixation protection is enabled, the `SessionManagementFilter` is injected with an appropriately configured `DefaultSessionAuthenticationStrategy`. + See the Javadoc for this class for more details. + +### Child Elements of \ + +* [concurrency-control](#nsa-concurrency-control) + +## \ + +Adds support for concurrent session control, allowing limits to be placed on the number of active sessions a user can have. +A `ConcurrentSessionFilter` will be created, and a `ConcurrentSessionControlAuthenticationStrategy` will be used with the `SessionManagementFilter`. +If a `form-login` element has been declared, the strategy object will also be injected into the created authentication filter. +An instance of `SessionRegistry` (a `SessionRegistryImpl` instance unless the user wishes to use a custom bean) will be created for use by the strategy. + +### Parent Elements of \ + +* [session-management](#nsa-session-management) + +### \ Attributes + +* **error-if-maximum-exceeded**If set to "true" a `SessionAuthenticationException` will be raised when a user attempts to exceed the maximum allowed number of sessions. + The default behaviour is to expire the original session. + +* **expired-url**The URL a user will be redirected to if they attempt to use a session which has been "expired" by the concurrent session controller because the user has exceeded the number of allowed sessions and has logged in again elsewhere. + Should be set unless `exception-if-maximum-exceeded` is set. + If no value is supplied, an expiry message will just be written directly back to the response. + +* **expired-url**Allows injection of the ExpiredSessionStrategy instance used by the ConcurrentSessionFilter + +* **max-sessions**Maps to the `maximumSessions` property of `ConcurrentSessionControlAuthenticationStrategy`. + Specify `-1` as the value to support unlimited sessions. + +* **session-registry-alias**It can also be useful to have a reference to the internal session registry for use in your own beans or an admin interface. + You can expose the internal bean using the `session-registry-alias` attribute, giving it a name that you can use elsewhere in your configuration. + +* **session-registry-ref**The user can supply their own `SessionRegistry` implementation using the `session-registry-ref` attribute. + The other concurrent session control beans will be wired up to use it. + +## \ + +Adds support for X.509 authentication. +An `X509AuthenticationFilter` will be added to the stack and an `Http403ForbiddenEntryPoint` bean will be created. +The latter will only be used if no other authentication mechanisms are in use (its only functionality is to return an HTTP 403 error code). +A `PreAuthenticatedAuthenticationProvider` will also be created which delegates the loading of user authorities to a `UserDetailsService`. + +### Parent Elements of \ + +* [http](#nsa-http) + +### \ Attributes + +* **authentication-details-source-ref**A reference to an `AuthenticationDetailsSource` + +* **subject-principal-regex**Defines a regular expression which will be used to extract the username from the certificate (for use with the `UserDetailsService`). + +* **user-service-ref**Allows a specific `UserDetailsService` to be used with X.509 in the case where multiple instances are configured. + If not set, an attempt will be made to locate a suitable instance automatically and use that. + +## \ + +Used to explicitly configure a FilterChainProxy instance with a FilterChainMap + +### \ Attributes + +* **request-matcher**Defines the strategy to use for matching incoming requests. + Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions. + +### Child Elements of \ + +* [filter-chain](#nsa-filter-chain) + +## \ + +Used within to define a specific URL pattern and the list of filters which apply to the URLs matching that pattern. +When multiple filter-chain elements are assembled in a list in order to configure a FilterChainProxy, the most specific patterns must be placed at the top of the list, with most general ones at the bottom. + +### Parent Elements of \ + +* [filter-chain-map](#nsa-filter-chain-map) + +### \ Attributes + +* **filters**A comma separated list of references to Spring beans that implement `Filter`. + The value "none" means that no `Filter` should be used for this `FilterChain`. + +* **pattern**A pattern that creates RequestMatcher in combination with the [request-matcher](#nsa-filter-chain-map-request-matcher) + +* **request-matcher-ref**A reference to a `RequestMatcher` that will be used to determine if any `Filter` from the `filters` attribute should be invoked. + +## \ + +Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. +Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the\ element. +The intercept-url elements used should only contain pattern, method and access attributes. +Any others will result in a configuration error. + +### \ Attributes + +* **id**A bean identifier, used for referring to the bean elsewhere in the context. + +* **request-matcher**Defines the strategy use for matching incoming requests. + Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions. + +* **use-expressions**Enables the use of expressions in the 'access' attributes in \ elements rather than the traditional list of configuration attributes. + Defaults to 'true'. + If enabled, each attribute should contain a single Boolean expression. + If the expression evaluates to 'true', access will be granted. + +### Child Elements of \ + +* [intercept-url](#nsa-intercept-url) + +--- + +[1](#_footnoteref_1). See the xref:servlet/configuration/xml-namespace.adoc#ns-web-xml[introductory chapter + +[2](#_footnoteref_2). This feature is really just provided for convenience and is not intended for production (where a view technology will have been chosen and can be used to render a customized login page). The class `DefaultLoginPageGeneratingFilter` is responsible for rendering the login page and will provide login forms for both normal form login and/or OpenID if required. + +[3](#_footnoteref_3). This doesn’t affect the use of `PersistentTokenBasedRememberMeServices`, where the tokens are stored on the server side. + +[Authentication Services](authentication-manager.html)[Method Security](method-security.html) + diff --git a/docs/en/spring-security/servlet-appendix-namespace-ldap.md b/docs/en/spring-security/servlet-appendix-namespace-ldap.md new file mode 100644 index 0000000000000000000000000000000000000000..32fe528fb532ee761e895ac87c1e67dea2ee3d71 --- /dev/null +++ b/docs/en/spring-security/servlet-appendix-namespace-ldap.md @@ -0,0 +1,169 @@ +# LDAP Namespace Options + +The LDAP implementation uses Spring LDAP extensively, so some familiarity with that project’s API may be useful. + +## Defining the LDAP Server using the + +`` Element +This element sets up a Spring LDAP `ContextSource` for use by the other LDAP beans, defining the location of the LDAP server and other information (such as a username and password, if it doesn’t allow anonymous access) for connecting to it. +It can also be used to create an embedded server for testing. +Details of the syntax for both options are covered in the [LDAP chapter](../../authentication/passwords/ldap.html#servlet-authentication-ldap). +The actual `ContextSource` implementation is `DefaultSpringSecurityContextSource` which extends Spring LDAP’s `LdapContextSource` class. +The `manager-dn` and `manager-password` attributes map to the latter’s `userDn` and `password` properties respectively. + +If you only have one server defined in your application context, the other LDAP namespace-defined beans will use it automatically. +Otherwise, you can give the element an "id" attribute and refer to it from other namespace beans using the `server-ref` attribute. +This is actually the bean `id` of the `ContextSource` instance, if you want to use it in other traditional Spring beans. + +### \ Attributes + +* **mode**Explicitly specifies which embedded ldap server should use. Values are `apacheds` and `unboundid`. By default, it will depends if the library is available in the classpath. + +* **id**A bean identifier, used for referring to the bean elsewhere in the context. + +* **ldif**Explicitly specifies an ldif file resource to load into an embedded LDAP server. + The ldif should be a Spring resource pattern (i.e. classpath:init.ldif). + The default is classpath\*:\*.ldif + +* **manager-dn**Username (DN) of the "manager" user identity which will be used to authenticate to a (non-embedded) LDAP server. + If omitted, anonymous access will be used. + +* **manager-password**The password for the manager DN. + This is required if the manager-dn is specified. + +* **port**Specifies an IP port number. + Used to configure an embedded LDAP server, for example. + The default value is 33389. + +* **root**Optional root suffix for the embedded LDAP server. + Default is "dc=springframework,dc=org" + +* **url**Specifies the ldap server URL when not using the embedded LDAP server. + +## \ + +This element is shorthand for the creation of an `LdapAuthenticationProvider` instance. +By default this will be configured with a `BindAuthenticator` instance and a `DefaultAuthoritiesPopulator`. +As with all namespace authentication providers, it must be included as a child of the `authentication-provider` element. + +### Parent Elements of \ + +* [authentication-manager](authentication-manager.html#nsa-authentication-manager) + +### \ Attributes + +* **group-role-attribute**The LDAP attribute name which contains the role name which will be used within Spring Security. + Maps to the `DefaultLdapAuthoritiesPopulator`'s `groupRoleAttribute` property. + Defaults to "cn". + +* **group-search-base**Search base for group membership searches. + Maps to the `DefaultLdapAuthoritiesPopulator`'s `groupSearchBase` constructor argument. + Defaults to "" (searching from the root). + +* **group-search-filter**Group search filter. + Maps to the `DefaultLdapAuthoritiesPopulator`'s `groupSearchFilter` property. + Defaults to `(uniqueMember={0})`. + The substituted parameter is the DN of the user. + +* **role-prefix**A non-empty string prefix that will be added to role strings loaded from persistent. + Maps to the `DefaultLdapAuthoritiesPopulator`'s `rolePrefix` property. + Defaults to "ROLE\_". + Use the value "none" for no prefix in cases where the default is non-empty. + +* **server-ref**The optional server to use. + If omitted, and a default LDAP server is registered (using \ with no Id), that server will be used. + +* **user-context-mapper-ref**Allows explicit customization of the loaded user object by specifying a UserDetailsContextMapper bean which will be called with the context information from the user’s directory entry + +* **user-details-class**Allows the objectClass of the user entry to be specified. + If set, the framework will attempt to load standard attributes for the defined class into the returned UserDetails object + +* **user-dn-pattern**If your users are at a fixed location in the directory (i.e. you can work out the DN directly from the username without doing a directory search), you can use this attribute to map directly to the DN. + It maps directly to the `userDnPatterns` property of `AbstractLdapAuthenticator`. + The value is a specific pattern used to build the user’s DN, for example `uid={0},ou=people`. + The key `{0}` must be present and will be substituted with the username. + +* **user-search-base**Search base for user searches. + Defaults to "". + Only used with a 'user-search-filter'. + + If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. + The `BindAuthenticator` will be configured with a `FilterBasedLdapUserSearch` and the attribute values map directly to the first two arguments of that bean’s constructor. + If these attributes aren’t set and no `user-dn-pattern` has been supplied as an alternative, then the default search values of `user-search-filter="(uid={0})"` and `user-search-base=""` will be used. + +* **user-search-filter**The LDAP filter used to search for users (optional). + For example `(uid={0})`. + The substituted parameter is the user’s login name. + + If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. + The `BindAuthenticator` will be configured with a `FilterBasedLdapUserSearch` and the attribute values map directly to the first two arguments of that bean’s constructor. + If these attributes aren’t set and no `user-dn-pattern` has been supplied as an alternative, then the default search values of `user-search-filter="(uid={0})"` and `user-search-base=""` will be used. + +### Child Elements of \ + +* [password-compare](#nsa-password-compare) + +## \ + +This is used as child element to `` and switches the authentication strategy from `BindAuthenticator` to `PasswordComparisonAuthenticator`. + +### Parent Elements of \ + +* [ldap-authentication-provider](#nsa-ldap-authentication-provider) + +### \ Attributes + +* **hash**Defines the hashing algorithm used on user passwords. + We recommend strongly against using MD4, as it is a very weak hashing algorithm. + +* **password-attribute**The attribute in the directory which contains the user password. + Defaults to "userPassword". + +### Child Elements of \ + +* [password-encoder](authentication-manager.html#nsa-password-encoder) + +## \ + +This element configures an LDAP `UserDetailsService`. +The class used is `LdapUserDetailsService` which is a combination of a `FilterBasedLdapUserSearch` and a `DefaultLdapAuthoritiesPopulator`. +The attributes it supports have the same usage as in ``. + +### \ Attributes + +* **cache-ref**Defines a reference to a cache for use with a UserDetailsService. + +* **group-role-attribute**The LDAP attribute name which contains the role name which will be used within Spring Security. + Defaults to "cn". + +* **group-search-base**Search base for group membership searches. + Defaults to "" (searching from the root). + +* **group-search-filter**Group search filter. + Defaults to `(uniqueMember={0})`. + The substituted parameter is the DN of the user. + +* **id**A bean identifier, used for referring to the bean elsewhere in the context. + +* **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. + +* **server-ref**The optional server to use. + If omitted, and a default LDAP server is registered (using \ with no Id), that server will be used. + +* **user-context-mapper-ref**Allows explicit customization of the loaded user object by specifying a UserDetailsContextMapper bean which will be called with the context information from the user’s directory entry + +* **user-details-class**Allows the objectClass of the user entry to be specified. + If set, the framework will attempt to load standard attributes for the defined class into the returned UserDetails object + +* **user-search-base**Search base for user searches. + Defaults to "". + Only used with a 'user-search-filter'. + +* **user-search-filter**The LDAP filter used to search for users (optional). + For example `(uid={0})`. + The substituted parameter is the user’s login name. + +[Method Security](method-security.html)[WebSocket Security](websocket.html) + diff --git a/docs/en/spring-security/servlet-appendix-namespace-method-security.md b/docs/en/spring-security/servlet-appendix-namespace-method-security.md new file mode 100644 index 0000000000000000000000000000000000000000..4e20d47f9f959b92bd2b8f0b8210c347823fff1c --- /dev/null +++ b/docs/en/spring-security/servlet-appendix-namespace-method-security.md @@ -0,0 +1,204 @@ +# Method Security + +## \ + +This element is the primary means of adding support for securing methods on Spring Security beans. +Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts. + +### \ attributes + +* **pre-post-enabled**Enables Spring Security’s pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) for this application context. + Defaults to "true". + +* **secured-enabled**Enables Spring Security’s @Secured annotation for this application context. + Defaults to "false". + +* **jsr250-enabled**Enables JSR-250 authorization annotations (@RolesAllowed, @PermitAll, @DenyAll) for this application context. + Defaults to "false". + +* **proxy-target-class**If true, class based proxying will be used instead of interface based proxying. + Defaults to "false". + +### Child Elements of \ + +* [expression-handler](http.html#nsa-expression-handler) + +## \ + +This element is the primary means of adding support for securing methods on Spring Security beans. +Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts as child elements, using AspectJ syntax. + +### \ Attributes + +* **access-decision-manager-ref**Method security uses the same `AccessDecisionManager` configuration as web security, but this can be overridden using this attribute. + By default an AffirmativeBased implementation is used for with a RoleVoter and an AuthenticatedVoter. + +* **authentication-manager-ref**A reference to an `AuthenticationManager` that should be used for method security. + +* **jsr250-annotations**Specifies whether JSR-250 style attributes are to be used (for example "RolesAllowed"). + This will require the javax.annotation.security classes on the classpath. + Setting this to true also adds a `Jsr250Voter` to the `AccessDecisionManager`, so you need to make sure you do this if you are using a custom implementation and want to use these annotations. + +* **metadata-source-ref**An external `MethodSecurityMetadataSource` instance can be supplied which will take priority over other sources (such as the default annotations). + +* **mode**This attribute can be set to "aspectj" to specify that AspectJ should be used instead of the default Spring AOP. + Secured methods must be woven with the `AnnotationSecurityAspect` from the `spring-security-aspects` module. + +It is important to note that AspectJ follows Java’s rule that annotations on interfaces are not inherited. +This means that methods that define the Security annotations on the interface will not be secured. +Instead, you must place the Security annotation on the class when using AspectJ. + +* **order**Allows the advice "order" to be set for the method security interceptor. + +* **pre-post-annotations**Specifies whether the use of Spring Security’s pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) should be enabled for this application context. + Defaults to "disabled". + +* **proxy-target-class**If true, class based proxying will be used instead of interface based proxying. + +* **run-as-manager-ref**A reference to an optional `RunAsManager` implementation which will be used by the configured `MethodSecurityInterceptor` + +* **secured-annotations**Specifies whether the use of Spring Security’s @Secured annotations should be enabled for this application context. + Defaults to "disabled". + +### Child Elements of \ + +* [after-invocation-provider](#nsa-after-invocation-provider) + +* [expression-handler](http.html#nsa-expression-handler) + +* [pre-post-annotation-handling](#nsa-pre-post-annotation-handling) + +* [protect-pointcut](#nsa-protect-pointcut) + +## \ + +This element can be used to decorate an `AfterInvocationProvider` for use by the security interceptor maintained by the `` namespace. +You can define zero or more of these within the `global-method-security` element, each with a `ref` attribute pointing to an `AfterInvocationProvider` bean instance within your application context. + +### Parent Elements of \ + +* [global-method-security](#nsa-global-method-security) + +### \ Attributes + +* **ref**Defines a reference to a Spring bean that implements `AfterInvocationProvider`. + +## \ + +Allows the default expression-based mechanism for handling Spring Security’s pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) to be replaced entirely. +Only applies if these annotations are enabled. + +### Parent Elements of \ + +* [global-method-security](#nsa-global-method-security) + +### Child Elements of \ + +* [invocation-attribute-factory](#nsa-invocation-attribute-factory) + +* [post-invocation-advice](#nsa-post-invocation-advice) + +* [pre-invocation-advice](#nsa-pre-invocation-advice) + +## \ + +Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods. + +### Parent Elements of \ + +* [pre-post-annotation-handling](#nsa-pre-post-annotation-handling) + +### \ Attributes + +* **ref**Defines a reference to a Spring bean Id. + +## \ + +Customizes the `PostInvocationAdviceProvider` with the ref as the `PostInvocationAuthorizationAdvice` for the \ element. + +### Parent Elements of \ + +* [pre-post-annotation-handling](#nsa-pre-post-annotation-handling) + +### \ Attributes + +* **ref**Defines a reference to a Spring bean Id. + +## \ + +Customizes the `PreInvocationAuthorizationAdviceVoter` with the ref as the `PreInvocationAuthorizationAdviceVoter` for the \ element. + +### Parent Elements of \ + +* [pre-post-annotation-handling](#nsa-pre-post-annotation-handling) + +### \ Attributes + +* **ref**Defines a reference to a Spring bean Id. + +## Securing Methods using + +``Rather than defining security attributes on an individual method or class basis using the `@Secured` annotation, you can define cross-cutting security constraints across whole sets of methods and interfaces in your service layer using the `` element. +You can find an example in the [namespace introduction](../../authorization/method-security.html#ns-protect-pointcut). + +### Parent Elements of \ + +* [global-method-security](#nsa-global-method-security) + +### \ Attributes + +* **access**Access configuration attributes list that applies to all methods matching the pointcut, e.g. + "ROLE\_A,ROLE\_B" + +* **expression**An AspectJ expression, including the `execution` keyword. + For example, `execution(int com.foo.TargetObject.countLength(String))`. + +## \ + +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 + +### \ Attributes + +* **access-decision-manager-ref**Optional AccessDecisionManager bean ID to be used by the created method security interceptor. + +### Child Elements of \ + +* [protect](#nsa-protect) + +## \ + +Creates a MethodSecurityMetadataSource instance + +### \ Attributes + +* **id**A bean identifier, used for referring to the bean elsewhere in the context. + +* **use-expressions**Enables the use of expressions in the 'access' attributes in \ elements rather than the traditional list of configuration attributes. + Defaults to 'false'. + If enabled, each attribute should contain a single Boolean expression. + If the expression evaluates to 'true', access will be granted. + +### Child Elements of \ + +* [protect](#nsa-protect) + +## \ + +Defines a protected method and the access control configuration attributes that apply to it. +We strongly advise you NOT to mix "protect" declarations with any services provided "global-method-security". + +### Parent Elements of \ + +* [intercept-methods](#nsa-intercept-methods) + +* [method-security-metadata-source](#nsa-method-security-metadata-source) + +### \ Attributes + +* **access**Access configuration attributes list that applies to the method, e.g. + "ROLE\_A,ROLE\_B". + +* **method**A method name + +[Web Security](http.html)[LDAP Security](ldap.html) + diff --git a/docs/en/spring-security/servlet-appendix-namespace-websocket.md b/docs/en/spring-security/servlet-appendix-namespace-websocket.md new file mode 100644 index 0000000000000000000000000000000000000000..b5e8a9d84b1afc5b85a6c0fe4cb86ca965dc5800 --- /dev/null +++ b/docs/en/spring-security/servlet-appendix-namespace-websocket.md @@ -0,0 +1,65 @@ +# WebSocket Security + +Spring Security 4.0+ provides support for authorizing messages. +One concrete example of where this is useful is to provide authorization in WebSocket based applications. + +## \ + +The websocket-message-broker element has two different modes. +If the [[email protected]](#nsa-websocket-message-broker-id) is not specified, then it will do the following things: + +* Ensure that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver. + This allows the use of `@AuthenticationPrincipal` to resolve the principal of the current `Authentication` + +* Ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel. + This populates the SecurityContextHolder with the user that is found in the Message + +* Ensures that a ChannelSecurityInterceptor is registered with the clientInboundChannel. + This allows authorization rules to be specified for a message. + +* Ensures that a CsrfChannelInterceptor is registered with the clientInboundChannel. + This ensures that only requests from the original domain are enabled. + +* Ensures that a CsrfTokenHandshakeInterceptor is registered with WebSocketHttpRequestHandler, TransportHandlingSockJsService, or DefaultSockJsService. + This ensures that the expected CsrfToken from the HttpServletRequest is copied into the WebSocket Session attributes. + +If additional control is necessary, the id can be specified and a ChannelSecurityInterceptor will be assigned to the specified id. +All the wiring with Spring’s messaging infrastructure can then be done manually. +This is more cumbersome, but provides greater control over the configuration. + +### \ Attributes + +* **id** A bean identifier, used for referring to the ChannelSecurityInterceptor bean elsewhere in the context. + If specified, Spring Security requires explicit configuration within Spring Messaging. + If not specified, Spring Security will automatically integrate with the messaging infrastructure as described in [\](#nsa-websocket-message-broker) + +* **same-origin-disabled** 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. + +### Child Elements of \ + +* [expression-handler](http.html#nsa-expression-handler) + +* [intercept-message](#nsa-intercept-message) + +## \ + +Defines an authorization rule for a message. + +### Parent Elements of \ + +* [websocket-message-broker](#nsa-websocket-message-broker) + +### \ Attributes + +* **pattern** An ant based pattern that matches on the Message destination. + For example, "/**" matches any Message with a destination; "/admin/**" matches any Message that has a destination that starts with "/admin/\*\*". + +* **type** The type of message to match on. + Valid values are defined in SimpMessageType (i.e. CONNECT, CONNECT\_ACK, HEARTBEAT, MESSAGE, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, DISCONNECT\_ACK, OTHER). + +* **access** The expression used to secure the Message. + For example, "denyAll" will deny access to all of the matching Messages; "permitAll" will grant access to all of the matching Messages; "hasRole('ADMIN') requires the current user to have the role 'ROLE\_ADMIN' for the matching Messages. + +[LDAP Security](ldap.html)[FAQ](../faq.html) + diff --git a/docs/en/spring-security/servlet-appendix-namespace.md b/docs/en/spring-security/servlet-appendix-namespace.md new file mode 100644 index 0000000000000000000000000000000000000000..212633ca6f7cb612956ed0f861cac209bf946a4d --- /dev/null +++ b/docs/en/spring-security/servlet-appendix-namespace.md @@ -0,0 +1,18 @@ +# The Security Namespace + +This appendix provides a reference to the elements available in the security namespace and information on the underlying beans they create (a knowledge of the individual classes and how they work together is assumed - you can find more information in the project Javadoc and elsewhere in this document). +If you haven’t used the namespace before, please read the [introductory chapter](../../configuration/xml-namespace.html#ns-config) on namespace configuration, as this is intended as a supplement to the information there. +Using a good quality XML editor while editing a configuration based on the schema is recommended as this will provide contextual information on which elements and attributes are available as well as comments explaining their purpose. +The namespace is written in [RELAX NG](https://relaxng.org/) Compact format and later converted into an XSD schema. +If you are familiar with this format, you may wish to examine the [schema file](https://raw.githubusercontent.com/spring-projects/spring-security/main/config/src/main/resources/org/springframework/security/config/spring-security-5.6.rnc) directly. + +## Section Summary + +* [Authentication Services](authentication-manager.html) +* [Web Security](http.html) +* [Method Security](method-security.html) +* [LDAP Security](ldap.html) +* [WebSocket Security](websocket.html) + +[Database Schemas](../database-schema.html)[Authentication Services](authentication-manager.html) + diff --git a/docs/en/spring-security/servlet-appendix.md b/docs/en/spring-security/servlet-appendix.md new file mode 100644 index 0000000000000000000000000000000000000000..10e29864a8d253f678b7c845ad63cf341f6781c7 --- /dev/null +++ b/docs/en/spring-security/servlet-appendix.md @@ -0,0 +1,13 @@ +# Appendix + +This is an appendix for Servlet based Spring Security. +It has the following sections: + +* [Database Schemas](database-schema.html) + +* [XML Namespace](namespace/index.html) + +* [FAQ](faq.html) + +[Security ResultHandlers](../test/mockmvc/result-handlers.html)[Database Schemas](database-schema.html) + diff --git a/docs/en/spring-security/servlet-architecture.md b/docs/en/spring-security/servlet-architecture.md new file mode 100644 index 0000000000000000000000000000000000000000..59d8d8c28877b1061a2160c90992e268bef552b3 --- /dev/null +++ b/docs/en/spring-security/servlet-architecture.md @@ -0,0 +1,263 @@ +# Architecture + +This section discusses Spring Security’s high level architecture within Servlet based applications. +We build on this high level understanding within [Authentication](authentication/index.html#servlet-authentication), [Authorization](authorization/index.html#servlet-authorization), [Protection Against Exploits](exploits/index.html#servlet-exploits) sections of the reference. + +## A Review of `Filter`s + +Spring Security’s Servlet support is based on Servlet `Filter`s, so it is helpful to look at the role of `Filter`s generally first. +The picture below shows the typical layering of the handlers for a single HTTP request. + +![filterchain](../_images/servlet/architecture/filterchain.png) + +Figure 1. FilterChain + +The client sends a request to the application, and the container creates a `FilterChain` which contains the `Filter`s and `Servlet` that should process the `HttpServletRequest` based on the path of the request URI. +In a Spring MVC application the `Servlet` is an instance of [`DispatcherServlet`](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#mvc-servlet). +At most one `Servlet` can handle a single `HttpServletRequest` and `HttpServletResponse`. +However, more than one `Filter` can be used to: + +* Prevent downstream `Filter`s or the `Servlet` from being invoked. + In this instance the `Filter` will typically write the `HttpServletResponse`. + +* Modify the `HttpServletRequest` or `HttpServletResponse` used by the downstream `Filter`s and `Servlet` + +The power of the `Filter` comes from the `FilterChain` that is passed into it. + +Example 1. `FilterChain` Usage Example + +Java + +``` +public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { + // do something before the rest of the application + chain.doFilter(request, response); // invoke the rest of the application + // do something after the rest of the application +} +``` + +Kotlin + +``` +fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) { + // do something before the rest of the application + chain.doFilter(request, response) // invoke the rest of the application + // do something after the rest of the application +} +``` + +Since a `Filter` only impacts downstream `Filter`s and the `Servlet`, the order each `Filter` is invoked is extremely important. + +## DelegatingFilterProxy + +Spring provides a `Filter` implementation named [`DelegatingFilterProxy`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/filter/DelegatingFilterProxy.html) that allows bridging between the Servlet container’s lifecycle and Spring’s `ApplicationContext`. +The Servlet container allows registering `Filter`s using its own standards, but it is not aware of Spring defined Beans.`DelegatingFilterProxy` can be registered via standard Servlet container mechanisms, but delegate all the work to a Spring Bean that implements `Filter`. + +Here is a picture of how `DelegatingFilterProxy` fits into the [`Filter`s and the `FilterChain`](#servlet-filters-review). + +![delegatingfilterproxy](../_images/servlet/architecture/delegatingfilterproxy.png) + +Figure 2. DelegatingFilterProxy + +`DelegatingFilterProxy` looks up *Bean Filter0* from the `ApplicationContext` and then invokes *Bean Filter0*. +The pseudo code of `DelegatingFilterProxy` can be seen below. + +Example 2. `DelegatingFilterProxy` Pseudo Code + +Java + +``` +public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { + // Lazily get Filter that was registered as a Spring Bean + // For the example in DelegatingFilterProxy delegate is an instance of Bean Filter0 + Filter delegate = getFilterBean(someBeanName); + // delegate work to the Spring Bean + delegate.doFilter(request, response); +} +``` + +Kotlin + +``` +fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) { + // Lazily get Filter that was registered as a Spring Bean + // For the example in DelegatingFilterProxy delegate is an instance of Bean Filter0 + val delegate: Filter = getFilterBean(someBeanName) + // delegate work to the Spring Bean + delegate.doFilter(request, response) +} +``` + +Another benefit of `DelegatingFilterProxy` is that it allows delaying looking `Filter` bean instances. +This is important because the container needs to register the `Filter` instances before the container can startup. +However, Spring typically uses a `ContextLoaderListener` to load the Spring Beans which will not be done until after the `Filter` instances need to be registered. + +## FilterChainProxy + +Spring Security’s Servlet support is contained within `FilterChainProxy`.`FilterChainProxy` is a special `Filter` provided by Spring Security that allows delegating to many `Filter` instances through [`SecurityFilterChain`](#servlet-securityfilterchain). +Since `FilterChainProxy` is a Bean, it is typically wrapped in a [DelegatingFilterProxy](#servlet-delegatingfilterproxy). + +![filterchainproxy](../_images/servlet/architecture/filterchainproxy.png) + +Figure 3. FilterChainProxy + +## SecurityFilterChain + +[`SecurityFilterChain`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/SecurityFilterChain.html) is used by [FilterChainProxy](#servlet-filterchainproxy) to determine which Spring Security `Filter`s should be invoked for this request. + +![securityfilterchain](../_images/servlet/architecture/securityfilterchain.png) + +Figure 4. SecurityFilterChain + +The [Security Filters](#servlet-security-filters) in `SecurityFilterChain` are typically Beans, but they are registered with `FilterChainProxy` instead of [DelegatingFilterProxy](#servlet-delegatingfilterproxy).`FilterChainProxy` provides a number of advantages to registering directly with the Servlet container or [DelegatingFilterProxy](#servlet-delegatingfilterproxy). +First, it provides a starting point for all of Spring Security’s Servlet support. +For that reason, if you are attempting to troubleshoot Spring Security’s Servlet support, adding a debug point in `FilterChainProxy` is a great place to start. + +Second, since `FilterChainProxy` is central to Spring Security usage it can perform tasks that are not viewed as optional. +For example, it clears out the `SecurityContext` to avoid memory leaks. +It also applies Spring Security’s [`HttpFirewall`](exploits/firewall.html#servlet-httpfirewall) to protect applications against certain types of attacks. + +In addition, it provides more flexibility in determining when a `SecurityFilterChain` should be invoked. +In a Servlet container, `Filter`s are invoked based upon the URL alone. +However, `FilterChainProxy` can determine invocation based upon anything in the `HttpServletRequest` by leveraging the `RequestMatcher` interface. + +In fact, `FilterChainProxy` can be used to determine which `SecurityFilterChain` should be used. +This allows providing a totally separate configuration for different *slices* of your application. + +![multi securityfilterchain](../_images/servlet/architecture/multi-securityfilterchain.png) + +Figure 5. Multiple SecurityFilterChain + +In the [Multiple SecurityFilterChain](#servlet-multi-securityfilterchain-figure) Figure `FilterChainProxy` decides which `SecurityFilterChain` should be used. +Only the first `SecurityFilterChain` that matches will be invoked. +If a URL of `/api/messages/` is requested, it will first match on `SecurityFilterChain0`'s pattern of `/api/**`, so only `SecurityFilterChain0` will be invoked even though it also matches on `SecurityFilterChainn`. +If a URL of `/messages/` is requested, it will not match on `SecurityFilterChain0`'s pattern of `/api/**`, so `FilterChainProxy` will continue trying each `SecurityFilterChain`. +Assuming that no other, `SecurityFilterChain` instances match `SecurityFilterChainn` will be invoked. + +Notice that `SecurityFilterChain0` has only three security `Filter`s instances configured. +However, `SecurityFilterChainn` has four security `Filter`s configured. +It is important to note that each `SecurityFilterChain` can be unique and configured in isolation. +In fact, a `SecurityFilterChain` might have zero security `Filter`s if the application wants Spring Security to ignore certain requests. + +## Security Filters + +The Security Filters are inserted into the [FilterChainProxy](#servlet-filterchainproxy) with the [SecurityFilterChain](#servlet-securityfilterchain) API. +The [order of `Filter`](#servlet-filters-review)s matters. +It is typically not necessary to know the ordering of Spring Security’s `Filter`s. +However, there are times that it is beneficial to know the ordering + +Below is a comprehensive list of Spring Security Filter ordering: + +* ChannelProcessingFilter + +* WebAsyncManagerIntegrationFilter + +* SecurityContextPersistenceFilter + +* HeaderWriterFilter + +* CorsFilter + +* CsrfFilter + +* LogoutFilter + +* OAuth2AuthorizationRequestRedirectFilter + +* Saml2WebSsoAuthenticationRequestFilter + +* X509AuthenticationFilter + +* AbstractPreAuthenticatedProcessingFilter + +* CasAuthenticationFilter + +* OAuth2LoginAuthenticationFilter + +* Saml2WebSsoAuthenticationFilter + +* [`UsernamePasswordAuthenticationFilter`](authentication/passwords/form.html#servlet-authentication-usernamepasswordauthenticationfilter) + +* OpenIDAuthenticationFilter + +* DefaultLoginPageGeneratingFilter + +* DefaultLogoutPageGeneratingFilter + +* ConcurrentSessionFilter + +* [`DigestAuthenticationFilter`](authentication/passwords/digest.html#servlet-authentication-digest) + +* BearerTokenAuthenticationFilter + +* [`BasicAuthenticationFilter`](authentication/passwords/basic.html#servlet-authentication-basic) + +* RequestCacheAwareFilter + +* SecurityContextHolderAwareRequestFilter + +* JaasApiIntegrationFilter + +* RememberMeAuthenticationFilter + +* AnonymousAuthenticationFilter + +* OAuth2AuthorizationCodeGrantFilter + +* SessionManagementFilter + +* [`ExceptionTranslationFilter`](#servlet-exceptiontranslationfilter) + +* [`FilterSecurityInterceptor`](authorization/authorize-requests.html#servlet-authorization-filtersecurityinterceptor) + +* SwitchUserFilter + +## Handling Security Exceptions + +The [`ExceptionTranslationFilter`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/access/ExceptionTranslationFilter.html) allows translation of [`AccessDeniedException`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/access/AccessDeniedException.html) and [`AuthenticationException`](https://docs.spring.io/spring-security/site/docs/5.6.2/api//org/springframework/security/core/AuthenticationException.html) into HTTP responses. + +`ExceptionTranslationFilter` is inserted into the [FilterChainProxy](#servlet-filterchainproxy) as one of the [Security Filters](#servlet-security-filters). + +![exceptiontranslationfilter](../_images/servlet/architecture/exceptiontranslationfilter.png) + +* ![number 1](../_images/icons/number_1.png) First, the `ExceptionTranslationFilter` invokes `FilterChain.doFilter(request, response)` to invoke the rest of the application. + +* ![number 2](../_images/icons/number_2.png) If the user is not authenticated or it is an `AuthenticationException`, then *Start Authentication*. + + * The [SecurityContextHolder](authentication/architecture.html#servlet-authentication-securitycontextholder) is cleared out + + * The `HttpServletRequest` is saved in the [`RequestCache`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/savedrequest/RequestCache.html). + When the user successfully authenticates, the `RequestCache` is used to replay the original request. + + * The `AuthenticationEntryPoint` is used to request credentials from the client. + For example, it might redirect to a log in page or send a `WWW-Authenticate` header. + +* ![number 3](../_images/icons/number_3.png) Otherwise if it is an `AccessDeniedException`, then *Access Denied*. + The `AccessDeniedHandler` is invoked to handle access denied. + +| |If the application does not throw an `AccessDeniedException` or an `AuthenticationException`, then `ExceptionTranslationFilter` does not do anything.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------| + +The pseudocode for `ExceptionTranslationFilter` looks something like this: + +ExceptionTranslationFilter pseudocode + +``` +try { + filterChain.doFilter(request, response); (1) +} catch (AccessDeniedException | AuthenticationException ex) { + if (!authenticated || ex instanceof AuthenticationException) { + startAuthentication(); (2) + } else { + accessDenied(); (3) + } +} +``` + +|**1**|You will recall from [A Review of `Filter`s](#servlet-filters-review) that invoking `FilterChain.doFilter(request, response)` is the equivalent of invoking the rest of the application.
This means that if another part of the application, (i.e. [`FilterSecurityInterceptor`](authorization/authorize-requests.html#servlet-authorization-filtersecurityinterceptor) or method security) throws an `AuthenticationException` or `AccessDeniedException` it will be caught and handled here.| +|-----|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**| If the user is not authenticated or it is an `AuthenticationException`, then *Start Authentication*. | +|**3**| Otherwise, *Access Denied* | + +[Getting Started](getting-started.html)[Authentication](authentication/index.html) + diff --git a/docs/en/spring-security/servlet-authentication-anonymous.md b/docs/en/spring-security/servlet-authentication-anonymous.md new file mode 100644 index 0000000000000000000000000000000000000000..e4a113be290e7c7e50379255447117a761a6febd --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-anonymous.md @@ -0,0 +1,142 @@ +# Anonymous Authentication + +## Overview + +It’s generally considered good security practice to adopt a "deny-by-default" where you explicitly specify what is allowed and disallow everything else. +Defining what is accessible to unauthenticated users is a similar situation, particularly for web applications. +Many sites require that users must be authenticated for anything other than a few URLs (for example the home and login pages). +In this case it is easiest to define access configuration attributes for these specific URLs rather than have for every secured resource. +Put differently, sometimes it is nice to say `ROLE_SOMETHING` is required by default and only allow certain exceptions to this rule, such as for login, logout and home pages of an application. +You could also omit these pages from the filter chain entirely, thus bypassing the access control checks, but this may be undesirable for other reasons, particularly if the pages behave differently for authenticated users. + +This is what we mean by anonymous authentication. +Note that there is no real conceptual difference between a user who is "anonymously authenticated" and an unauthenticated user. +Spring Security’s anonymous authentication just gives you a more convenient way to configure your access-control attributes. +Calls to servlet API such as `getCallerPrincipal`, for example, will still return null even though there is actually an anonymous authentication object in the `SecurityContextHolder`. + +There are other situations where anonymous authentication is useful, such as when an auditing interceptor queries the `SecurityContextHolder` to identify which principal was responsible for a given operation. +Classes can be authored more robustly if they know the `SecurityContextHolder` always contains an `Authentication` object, and never `null`. + +## Configuration + +Anonymous authentication support is provided automatically when using the HTTP configuration Spring Security 3.0 and can be customized (or disabled) using the `` element. +You don’t need to configure the beans described here unless you are using traditional bean configuration. + +Three classes that together provide the anonymous authentication feature.`AnonymousAuthenticationToken` is an implementation of `Authentication`, and stores the `GrantedAuthority`s which apply to the anonymous principal. +There is a corresponding `AnonymousAuthenticationProvider`, which is chained into the `ProviderManager` so that `AnonymousAuthenticationToken`s are accepted. +Finally, there is an `AnonymousAuthenticationFilter`, which is chained after the normal authentication mechanisms and automatically adds an `AnonymousAuthenticationToken` to the `SecurityContextHolder` if there is no existing `Authentication` held there. +The definition of the filter and authentication provider appears as follows: + +``` + + + + + + + + +``` + +The `key` is shared between the filter and authentication provider, so that tokens created by the former are accepted by the latter [1]. +The `userAttribute` is expressed in the form of `usernameInTheAuthenticationToken,grantedAuthority[,grantedAuthority]`. +This is the same syntax as used after the equals sign for the `userMap` property of `InMemoryDaoImpl`. + +As explained earlier, the benefit of anonymous authentication is that all URI patterns can have security applied to them. +For example: + +``` + + + + + + + + + + + " + + + +``` + +## AuthenticationTrustResolver + +Rounding out the anonymous authentication discussion is the `AuthenticationTrustResolver` interface, with its corresponding `AuthenticationTrustResolverImpl` implementation. +This interface provides an `isAnonymous(Authentication)` method, which allows interested classes to take into account this special type of authentication status. +The `ExceptionTranslationFilter` uses this interface in processing `AccessDeniedException`s. +If an `AccessDeniedException` is thrown, and the authentication is of an anonymous type, instead of throwing a 403 (forbidden) response, the filter will instead commence the `AuthenticationEntryPoint` so the principal can authenticate properly. +This is a necessary distinction, otherwise principals would always be deemed "authenticated" and never be given an opportunity to login via form, basic, digest or some other normal authentication mechanism. + +You will often see the `ROLE_ANONYMOUS` attribute in the above interceptor configuration replaced with `IS_AUTHENTICATED_ANONYMOUSLY`, which is effectively the same thing when defining access controls. +This is an example of the use of the `AuthenticatedVoter` which we will see in the [authorization chapter](../authorization/architecture.html#authz-authenticated-voter). +It uses an `AuthenticationTrustResolver` to process this particular configuration attribute and grant access to anonymous users. +The `AuthenticatedVoter` approach is more powerful, since it allows you to differentiate between anonymous, remember-me and fully-authenticated users. +If you don’t need this functionality though, then you can stick with `ROLE_ANONYMOUS`, which will be processed by Spring Security’s standard `RoleVoter`. + +## Getting Anonymous Authentications with Spring MVC + +[Spring MVC resolves parameters of type `Principal`](https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-arguments) using its own argument resolver. + +This means that a construct like this one: + +Java + +``` +@GetMapping("/") +public String method(Authentication authentication) { + if (authentication instanceof AnonymousAuthenticationToken) { + return "anonymous"; + } else { + return "not anonymous"; + } +} +``` + +Kotlin + +``` +@GetMapping("/") +fun method(authentication: Authentication?): String { + return if (authentication is AnonymousAuthenticationToken) { + "anonymous" + } else { + "not anonymous" + } +} +``` + +will always return "not anonymous", even for anonymous requests. +The reason is that Spring MVC resolves the parameter using `HttpServletRequest#getPrincipal`, which is `null` when the request is anonymous. + +If you’d like to obtain the `Authentication` in anonymous requests, use `@CurrentSecurityContext` instead: + +Example 1. Use CurrentSecurityContext for Anonymous requests + +Java + +``` +@GetMapping("/") +public String method(@CurrentSecurityContext SecurityContext context) { + return context.getAuthentication().getName(); +} +``` + +Kotlin + +``` +@GetMapping("/") +fun method(@CurrentSecurityContext context : SecurityContext) : String = + context!!.authentication!!.name +``` + +--- + +[1](#_footnoteref_1). The use of the `key` property should not be regarded as providing any real security here. It is merely a book-keeping exercise. If you are sharing a `ProviderManager` which contains an `AnonymousAuthenticationProvider` in a scenario where it is possible for an authenticating client to construct the `Authentication` object (such as with RMI invocations), then a malicious client could submit an `AnonymousAuthenticationToken` which it had created itself (with chosen username and authority list). If the `key` is guessable or can be found out, then the token would be accepted by the anonymous provider. This isn’t a problem with normal usage but if you are using RMI you would be best to use a customized `ProviderManager` which omits the anonymous provider rather than sharing the one you use for your HTTP authentication mechanisms. + +[OpenID](openid.html)[Pre-Authentication](preauth.html) + diff --git a/docs/en/spring-security/servlet-authentication-architecture.md b/docs/en/spring-security/servlet-authentication-architecture.md new file mode 100644 index 0000000000000000000000000000000000000000..cf520d98f0caa4f06da8d70cff8ad2387199d275 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-architecture.md @@ -0,0 +1,244 @@ +# Servlet Authentication Architecture + +This discussion expands on [Servlet Security: The Big Picture](../architecture.html#servlet-architecture) to describe the main architectural components of Spring Security’s used in Servlet authentication. +If you need concrete flows that explain how these pieces fit together, look at the [Authentication Mechanism](index.html#servlet-authentication-mechanisms) specific sections. + +* [SecurityContextHolder](#servlet-authentication-securitycontextholder) - The `SecurityContextHolder` is where Spring Security stores the details of who is [authenticated](../../features/authentication/index.html#authentication). + +* [SecurityContext](#servlet-authentication-securitycontext) - is obtained from the `SecurityContextHolder` and contains the `Authentication` of the currently authenticated user. + +* [Authentication](#servlet-authentication-authentication) - Can be the input to `AuthenticationManager` to provide the credentials a user has provided to authenticate or the current user from the `SecurityContext`. + +* [GrantedAuthority](#servlet-authentication-granted-authority) - An authority that is granted to the principal on the `Authentication` (i.e. roles, scopes, etc.) + +* [AuthenticationManager](#servlet-authentication-authenticationmanager) - the API that defines how Spring Security’s Filters perform [authentication](../../features/authentication/index.html#authentication). + +* [ProviderManager](#servlet-authentication-providermanager) - the most common implementation of `AuthenticationManager`. + +* [AuthenticationProvider](#servlet-authentication-authenticationprovider) - used by `ProviderManager` to perform a specific type of authentication. + +* [Request Credentials with `AuthenticationEntryPoint`](#servlet-authentication-authenticationentrypoint) - used for requesting credentials from a client (i.e. redirecting to a log in page, sending a `WWW-Authenticate` response, etc.) + +* [AbstractAuthenticationProcessingFilter](#servlet-authentication-abstractprocessingfilter) - a base `Filter` used for authentication. + This also gives a good idea of the high level flow of authentication and how pieces work together. + +## SecurityContextHolder + +Hi servlet/authentication/architecture there + +At the heart of Spring Security’s authentication model is the `SecurityContextHolder`. +It contains the [SecurityContext](#servlet-authentication-securitycontext). + +![securitycontextholder](../../_images/servlet/authentication/architecture/securitycontextholder.png) + +The `SecurityContextHolder` is where Spring Security stores the details of who is [authenticated](../../features/authentication/index.html#authentication). +Spring Security does not care how the `SecurityContextHolder` is populated. +If it contains a value, then it is used as the currently authenticated user. + +The simplest way to indicate a user is authenticated is to set the `SecurityContextHolder` directly. + +Example 1. Setting `SecurityContextHolder` + +Java + +``` +SecurityContext context = SecurityContextHolder.createEmptyContext(); (1) +Authentication authentication = + new TestingAuthenticationToken("username", "password", "ROLE_USER"); (2) +context.setAuthentication(authentication); + +SecurityContextHolder.setContext(context); (3) +``` + +Kotlin + +``` +val context: SecurityContext = SecurityContextHolder.createEmptyContext() (1) +val authentication: Authentication = TestingAuthenticationToken("username", "password", "ROLE_USER") (2) +context.authentication = authentication + +SecurityContextHolder.setContext(context) (3) +``` + +|**1**| We start by creating an empty `SecurityContext`.
It is important to create a new `SecurityContext` instance instead of using `SecurityContextHolder.getContext().setAuthentication(authentication)` to avoid race conditions across multiple threads. | +|-----|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**|Next we create a new [`Authentication`](#servlet-authentication-authentication) object.
Spring Security does not care what type of `Authentication` implementation is set on the `SecurityContext`.
Here we use `TestingAuthenticationToken` because it is very simple.
A more common production scenario is `UsernamePasswordAuthenticationToken(userDetails, password, authorities)`.| +|**3**| Finally, we set the `SecurityContext` on the `SecurityContextHolder`.
Spring Security will use this information for [authorization](../authorization/index.html#servlet-authorization). | + +If you wish to obtain information about the authenticated principal, you can do so by accessing the `SecurityContextHolder`. + +Example 2. Access Currently Authenticated User + +Java + +``` +SecurityContext context = SecurityContextHolder.getContext(); +Authentication authentication = context.getAuthentication(); +String username = authentication.getName(); +Object principal = authentication.getPrincipal(); +Collection authorities = authentication.getAuthorities(); +``` + +Kotlin + +``` +val context = SecurityContextHolder.getContext() +val authentication = context.authentication +val username = authentication.name +val principal = authentication.principal +val authorities = authentication.authorities +``` + +By default the `SecurityContextHolder` uses a `ThreadLocal` to store these details, which means that the `SecurityContext` is always available to methods in the same thread, even if the `SecurityContext` is not explicitly passed around as an argument to those methods. +Using a `ThreadLocal` in this way is quite safe if care is taken to clear the thread after the present principal’s request is processed. +Spring Security’s [FilterChainProxy](../architecture.html#servlet-filterchainproxy) ensures that the `SecurityContext` is always cleared. + +Some applications aren’t entirely suitable for using a `ThreadLocal`, because of the specific way they work with threads. +For example, a Swing client might want all threads in a Java Virtual Machine to use the same security context.`SecurityContextHolder` can be configured with a strategy on startup to specify how you would like the context to be stored. +For a standalone application you would use the `SecurityContextHolder.MODE_GLOBAL` strategy. +Other applications might want to have threads spawned by the secure thread also assume the same security identity. +This is achieved by using `SecurityContextHolder.MODE_INHERITABLETHREADLOCAL`. +You can change the mode from the default `SecurityContextHolder.MODE_THREADLOCAL` in two ways. +The first is to set a system property, the second is to call a static method on `SecurityContextHolder`. +Most applications won’t need to change from the default, but if you do, take a look at the Javadoc for `SecurityContextHolder` to learn more. + +## SecurityContext + +The [`SecurityContext`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/core/context/SecurityContext.html) is obtained from the [SecurityContextHolder](#servlet-authentication-securitycontextholder). +The `SecurityContext` contains an [Authentication](#servlet-authentication-authentication) object. + +## Authentication + +The [`Authentication`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/core/Authentication.html) serves two main purposes within Spring Security: + +* An input to [`AuthenticationManager`](#servlet-authentication-authenticationmanager) to provide the credentials a user has provided to authenticate. + When used in this scenario, `isAuthenticated()` returns `false`. + +* Represents the currently authenticated user. + The current `Authentication` can be obtained from the [SecurityContext](#servlet-authentication-securitycontext). + +The `Authentication` contains: + +* `principal` - identifies the user. + When authenticating with a username/password this is often an instance of [`UserDetails`](passwords/user-details.html#servlet-authentication-userdetails). + +* `credentials` - often a password. + In many cases this will be cleared after the user is authenticated to ensure it is not leaked. + +* `authorities` - the [`GrantedAuthority`s](#servlet-authentication-granted-authority) are high level permissions the user is granted. + A few examples are roles or scopes. + +## GrantedAuthority + +[`GrantedAuthority`s](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/core/GrantedAuthority.html) are high level permissions the user is granted. A few examples are roles or scopes. + +`GrantedAuthority`s can be obtained from the [`Authentication.getAuthorities()`](#servlet-authentication-authentication) method. +This method provides a `Collection` of `GrantedAuthority` objects. +A `GrantedAuthority` is, not surprisingly, an authority that is granted to the principal. +Such authorities are usually "roles", such as `ROLE_ADMINISTRATOR` or `ROLE_HR_SUPERVISOR`. +These roles are later on configured for web authorization, method authorization and domain object authorization. +Other parts of Spring Security are capable of interpreting these authorities, and expect them to be present. +When using username/password based authentication `GrantedAuthority`s are usually loaded by the [`UserDetailsService`](passwords/user-details-service.html#servlet-authentication-userdetailsservice). + +Usually the `GrantedAuthority` objects are application-wide permissions. +They are not specific to a given domain object. +Thus, you wouldn’t likely have a `GrantedAuthority` to represent a permission to `Employee` object number 54, because if there are thousands of such authorities you would quickly run out of memory (or, at the very least, cause the application to take a long time to authenticate a user). +Of course, Spring Security is expressly designed to handle this common requirement, but you’d instead use the project’s domain object security capabilities for this purpose. + +## AuthenticationManager + +[`AuthenticationManager`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/authentication/AuthenticationManager.html) is the API that defines how Spring Security’s Filters perform [authentication](../../features/authentication/index.html#authentication). +The [`Authentication`](#servlet-authentication-authentication) that is returned is then set on the [SecurityContextHolder](#servlet-authentication-securitycontextholder) by the controller (i.e. [Spring Security’s `Filters`s](../architecture.html#servlet-security-filters)) that invoked the `AuthenticationManager`. +If you are not integrating with *Spring Security’s `Filters`s* you can set the `SecurityContextHolder` directly and are not required to use an `AuthenticationManager`. + +While the implementation of `AuthenticationManager` could be anything, the most common implementation is [`ProviderManager`](#servlet-authentication-providermanager). + +## ProviderManager + +[`ProviderManager`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/authentication/ProviderManager.html) is the most commonly used implementation of [`AuthenticationManager`](#servlet-authentication-authenticationmanager).`ProviderManager` delegates to a `List` of [`AuthenticationProvider`s](#servlet-authentication-authenticationprovider). +Each `AuthenticationProvider` has an opportunity to indicate that authentication should be successful, fail, or indicate it cannot make a decision and allow a downstream `AuthenticationProvider` to decide. +If none of the configured `AuthenticationProvider`s can authenticate, then authentication will fail with a `ProviderNotFoundException` which is a special `AuthenticationException` that indicates the `ProviderManager` was not configured to support the type of `Authentication` that was passed into it. + +![providermanager](../../_images/servlet/authentication/architecture/providermanager.png) + +In practice each `AuthenticationProvider` knows how to perform a specific type of authentication. +For example, one `AuthenticationProvider` might be able to validate a username/password, while another might be able to authenticate a SAML assertion. +This allows each `AuthenticationProvider` to do a very specific type of authentication, while supporting multiple types of authentication and only exposing a single `AuthenticationManager` bean. + +`ProviderManager` also allows configuring an optional parent `AuthenticationManager` which is consulted in the event that no `AuthenticationProvider` can perform authentication. +The parent can be any type of `AuthenticationManager`, but it is often an instance of `ProviderManager`. + +![providermanager parent](../../_images/servlet/authentication/architecture/providermanager-parent.png) + +In fact, multiple `ProviderManager` instances might share the same parent `AuthenticationManager`. +This is somewhat common in scenarios where there are multiple [`SecurityFilterChain`](../architecture.html#servlet-securityfilterchain) instances that have some authentication in common (the shared parent `AuthenticationManager`), but also different authentication mechanisms (the different `ProviderManager` instances). + +![providermanagers parent](../../_images/servlet/authentication/architecture/providermanagers-parent.png) + +By default `ProviderManager` will attempt to clear any sensitive credentials information from the `Authentication` object which is returned by a successful authentication request. +This prevents information like passwords being retained longer than necessary in the `HttpSession`. + +This may cause issues when you are using a cache of user objects, for example, to improve performance in a stateless application. +If the `Authentication` contains a reference to an object in the cache (such as a `UserDetails` instance) and this has its credentials removed, then it will no longer be possible to authenticate against the cached value. +You need to take this into account if you are using a cache. +An obvious solution is to make a copy of the object first, either in the cache implementation or in the `AuthenticationProvider` which creates the returned `Authentication` object. +Alternatively, you can disable the `eraseCredentialsAfterAuthentication` property on `ProviderManager`. +See the [Javadoc](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/authentication/ProviderManager.html) for more information. + +## AuthenticationProvider + +Multiple [`AuthenticationProvider`s](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/authentication/AuthenticationProvider.html) can be injected into [`ProviderManager`](#servlet-authentication-providermanager). +Each `AuthenticationProvider` performs a specific type of authentication. +For example, [`DaoAuthenticationProvider`](passwords/dao-authentication-provider.html#servlet-authentication-daoauthenticationprovider) supports username/password based authentication while `JwtAuthenticationProvider` supports authenticating a JWT token. + +## Request Credentials with `AuthenticationEntryPoint` + +[`AuthenticationEntryPoint`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/AuthenticationEntryPoint.html) is used to send an HTTP response that requests credentials from a client. + +Sometimes a client will proactively include credentials such as a username/password to request a resource. +In these cases, Spring Security does not need to provide an HTTP response that requests credentials from the client since they are already included. + +In other cases, a client will make an unauthenticated request to a resource that they are not authorized to access. +In this case, an implementation of `AuthenticationEntryPoint` is used to request credentials from the client. +The `AuthenticationEntryPoint` implementation might perform a [redirect to a log in page](passwords/form.html#servlet-authentication-form), respond with an [WWW-Authenticate](passwords/basic.html#servlet-authentication-basic) header, etc. + +## AbstractAuthenticationProcessingFilter + +[`AbstractAuthenticationProcessingFilter`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.html) is used as a base `Filter` for authenticating a user’s credentials. +Before the credentials can be authenticated, Spring Security typically requests the credentials using [`AuthenticationEntryPoint`](#servlet-authentication-authenticationentrypoint). + +Next, the `AbstractAuthenticationProcessingFilter` can authenticate any authentication requests that are submitted to it. + +![abstractauthenticationprocessingfilter](../../_images/servlet/authentication/architecture/abstractauthenticationprocessingfilter.png) + +![number 1](../../_images/icons/number_1.png) When the user submits their credentials, the `AbstractAuthenticationProcessingFilter` creates an [`Authentication`](#servlet-authentication-authentication) from the `HttpServletRequest` to be authenticated. +The type of `Authentication` created depends on the subclass of `AbstractAuthenticationProcessingFilter`. +For example, [`UsernamePasswordAuthenticationFilter`](passwords/form.html#servlet-authentication-usernamepasswordauthenticationfilter) creates a `UsernamePasswordAuthenticationToken` from a *username* and *password* that are submitted in the `HttpServletRequest`. + +![number 2](../../_images/icons/number_2.png) Next, the [`Authentication`](#servlet-authentication-authentication) is passed into the [`AuthenticationManager`](#servlet-authentication-authenticationmanager) to be authenticated. + +![number 3](../../_images/icons/number_3.png) If authentication fails, then *Failure* + +* The [SecurityContextHolder](#servlet-authentication-securitycontextholder) is cleared out. + +* `RememberMeServices.loginFail` is invoked. + If remember me is not configured, this is a no-op. + +* `AuthenticationFailureHandler` is invoked. + +![number 4](../../_images/icons/number_4.png) If authentication is successful, then *Success*. + +* `SessionAuthenticationStrategy` is notified of a new log in. + +* The [Authentication](#servlet-authentication-authentication) is set on the [SecurityContextHolder](#servlet-authentication-securitycontextholder). + Later the `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession`. + +* `RememberMeServices.loginSuccess` is invoked. + If remember me is not configured, this is a no-op. + +* `ApplicationEventPublisher` publishes an `InteractiveAuthenticationSuccessEvent`. + +* `AuthenticationSuccessHandler` is invoked. + +[Authentication](index.html)[Username/Password](passwords/index.html) + diff --git a/docs/en/spring-security/servlet-authentication-cas.md b/docs/en/spring-security/servlet-authentication-cas.md new file mode 100644 index 0000000000000000000000000000000000000000..087503a5c8e7cccd678039371250351797161091 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-cas.md @@ -0,0 +1,461 @@ +# CAS Authentication + +## Overview + +JA-SIG produces an enterprise-wide single sign on system known as CAS. +Unlike other initiatives, JA-SIG’s Central Authentication Service is open source, widely used, simple to understand, platform independent, and supports proxy capabilities. +Spring Security fully supports CAS, and provides an easy migration path from single-application deployments of Spring Security through to multiple-application deployments secured by an enterprise-wide CAS server. + +You can learn more about CAS at [https://www.apereo.org](https://www.apereo.org). +You will also need to visit this site to download the CAS Server files. + +## How CAS Works + +Whilst the CAS web site contains documents that detail the architecture of CAS, we present the general overview again here within the context of Spring Security. +Spring Security 3.x supports CAS 3. +At the time of writing, the CAS server was at version 3.4. + +Somewhere in your enterprise you will need to setup a CAS server. +The CAS server is simply a standard WAR file, so there isn’t anything difficult about setting up your server. +Inside the WAR file you will customise the login and other single sign on pages displayed to users. + +When deploying a CAS 3.4 server, you will also need to specify an `AuthenticationHandler` in the `deployerConfigContext.xml` included with CAS. +The `AuthenticationHandler` has a simple method that returns a boolean as to whether a given set of Credentials is valid. +Your `AuthenticationHandler` implementation will need to link into some type of backend authentication repository, such as an LDAP server or database. +CAS itself includes numerous `AuthenticationHandler`s out of the box to assist with this. +When you download and deploy the server war file, it is set up to successfully authenticate users who enter a password matching their username, which is useful for testing. + +Apart from the CAS server itself, the other key players are of course the secure web applications deployed throughout your enterprise. +These web applications are known as "services". +There are three types of services. +Those that authenticate service tickets, those that can obtain proxy tickets, and those that authenticate proxy tickets. +Authenticating a proxy ticket differs because the list of proxies must be validated and often times a proxy ticket can be reused. + +### Spring Security and CAS Interaction Sequence + +The basic interaction between a web browser, CAS server and a Spring Security-secured service is as follows: + +* The web user is browsing the service’s public pages. + CAS or Spring Security is not involved. + +* The user eventually requests a page that is either secure or one of the beans it uses is secure. + Spring Security’s `ExceptionTranslationFilter` will detect the `AccessDeniedException` or `AuthenticationException`. + +* Because the user’s `Authentication` object (or lack thereof) caused an `AuthenticationException`, the `ExceptionTranslationFilter` will call the configured `AuthenticationEntryPoint`. + If using CAS, this will be the `CasAuthenticationEntryPoint` class. + +* The `CasAuthenticationEntryPoint` will redirect the user’s browser to the CAS server. + It will also indicate a `service` parameter, which is the callback URL for the Spring Security service (your application). + For example, the URL to which the browser is redirected might be [https://my.company.com/cas/login?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Flogin/cas](https://my.company.com/cas/login?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Flogin/cas). + +* After the user’s browser redirects to CAS, they will be prompted for their username and password. + If the user presents a session cookie which indicates they’ve previously logged on, they will not be prompted to login again (there is an exception to this procedure, which we’ll cover later). + CAS will use the `PasswordHandler` (or `AuthenticationHandler` if using CAS 3.0) discussed above to decide whether the username and password is valid. + +* Upon successful login, CAS will redirect the user’s browser back to the original service. + It will also include a `ticket` parameter, which is an opaque string representing the "service ticket". + Continuing our earlier example, the URL the browser is redirected to might be [https://server3.company.com/webapp/login/cas?ticket=ST-0-ER94xMJmn6pha35CQRoZ](https://server3.company.com/webapp/login/cas?ticket=ST-0-ER94xMJmn6pha35CQRoZ). + +* Back in the service web application, the `CasAuthenticationFilter` is always listening for requests to `/login/cas` (this is configurable, but we’ll use the defaults in this introduction). + The processing filter will construct a `UsernamePasswordAuthenticationToken` representing the service ticket. + The principal will be equal to `CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER`, whilst the credentials will be the service ticket opaque value. + This authentication request will then be handed to the configured `AuthenticationManager`. + +* The `AuthenticationManager` implementation will be the `ProviderManager`, which is in turn configured with the `CasAuthenticationProvider`. + The `CasAuthenticationProvider` only responds to `UsernamePasswordAuthenticationToken`s containing the CAS-specific principal (such as `CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER`) and `CasAuthenticationToken`s (discussed later). + +* `CasAuthenticationProvider` will validate the service ticket using a `TicketValidator` implementation. + This will typically be a `Cas20ServiceTicketValidator` which is one of the classes included in the CAS client library. + In the event the application needs to validate proxy tickets, the `Cas20ProxyTicketValidator` is used. + The `TicketValidator` makes an HTTPS request to the CAS server in order to validate the service ticket. + It may also include a proxy callback URL, which is included in this example: [https://my.company.com/cas/proxyValidate?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Flogin/cas&ticket=ST-0-ER94xMJmn6pha35CQRoZ&pgtUrl=https://server3.company.com/webapp/login/cas/proxyreceptor](https://my.company.com/cas/proxyValidate?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Flogin/cas&ticket=ST-0-ER94xMJmn6pha35CQRoZ&pgtUrl=https://server3.company.com/webapp/login/cas/proxyreceptor). + +* Back on the CAS server, the validation request will be received. + If the presented service ticket matches the service URL the ticket was issued to, CAS will provide an affirmative response in XML indicating the username. + If any proxy was involved in the authentication (discussed below), the list of proxies is also included in the XML response. + +* [OPTIONAL] If the request to the CAS validation service included the proxy callback URL (in the `pgtUrl` parameter), CAS will include a `pgtIou` string in the XML response. + This `pgtIou` represents a proxy-granting ticket IOU. + The CAS server will then create its own HTTPS connection back to the `pgtUrl`. + This is to mutually authenticate the CAS server and the claimed service URL. + The HTTPS connection will be used to send a proxy granting ticket to the original web application. + For example, [https://server3.company.com/webapp/login/cas/proxyreceptor?pgtIou=PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt&pgtId=PGT-1-si9YkkHLrtACBo64rmsi3v2nf7cpCResXg5MpESZFArbaZiOKH](https://server3.company.com/webapp/login/cas/proxyreceptor?pgtIou=PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt&pgtId=PGT-1-si9YkkHLrtACBo64rmsi3v2nf7cpCResXg5MpESZFArbaZiOKH). + +* The `Cas20TicketValidator` will parse the XML received from the CAS server. + It will return to the `CasAuthenticationProvider` a `TicketResponse`, which includes the username (mandatory), proxy list (if any were involved), and proxy-granting ticket IOU (if the proxy callback was requested). + +* Next `CasAuthenticationProvider` will call a configured `CasProxyDecider`. + The `CasProxyDecider` indicates whether the proxy list in the `TicketResponse` is acceptable to the service. + Several implementations are provided with Spring Security: `RejectProxyTickets`, `AcceptAnyCasProxy` and `NamedCasProxyDecider`. + These names are largely self-explanatory, except `NamedCasProxyDecider` which allows a `List` of trusted proxies to be provided. + +* `CasAuthenticationProvider` will next request a `AuthenticationUserDetailsService` to load the `GrantedAuthority` objects that apply to the user contained in the `Assertion`. + +* If there were no problems, `CasAuthenticationProvider` constructs a `CasAuthenticationToken` including the details contained in the `TicketResponse` and the `GrantedAuthority`s. + +* Control then returns to `CasAuthenticationFilter`, which places the created `CasAuthenticationToken` in the security context. + +* The user’s browser is redirected to the original page that caused the `AuthenticationException` (or a custom destination depending on the configuration). + +It’s good that you’re still here! +Let’s now look at how this is configured + +## Configuration of CAS Client + +The web application side of CAS is made easy due to Spring Security. +It is assumed you already know the basics of using Spring Security, so these are not covered again below. +We’ll assume a namespace based configuration is being used and add in the CAS beans as required. +Each section builds upon the previous section. +A full CAS sample application can be found in the Spring Security [Samples](../../samples.html#samples). + +### Service Ticket Authentication + +This section describes how to setup Spring Security to authenticate Service Tickets. +Often times this is all a web application requires. +You will need to add a `ServiceProperties` bean to your application context. +This represents your CAS service: + +``` + + + + +``` + +The `service` must equal a URL that will be monitored by the `CasAuthenticationFilter`. +The `sendRenew` defaults to false, but should be set to true if your application is particularly sensitive. +What this parameter does is tell the CAS login service that a single sign on login is unacceptable. +Instead, the user will need to re-enter their username and password in order to gain access to the service. + +The following beans should be configured to commence the CAS authentication process (assuming you’re using a namespace configuration): + +``` + +... + + + + + + + + + + + +``` + +For CAS to operate, the `ExceptionTranslationFilter` must have its `authenticationEntryPoint` property set to the `CasAuthenticationEntryPoint` bean. +This can easily be done using [entry-point-ref](../appendix/namespace/http.html#nsa-http-entry-point-ref) as is done in the example above. +The `CasAuthenticationEntryPoint` must refer to the `ServiceProperties` bean (discussed above), which provides the URL to the enterprise’s CAS login server. +This is where the user’s browser will be redirected. + +The `CasAuthenticationFilter` has very similar properties to the `UsernamePasswordAuthenticationFilter` (used for form-based logins). +You can use these properties to customize things like behavior for authentication success and failure. + +Next you need to add a `CasAuthenticationProvider` and its collaborators: + +``` + + + + + + + + + + + + + + + + + + + + + + +... + +``` + +The `CasAuthenticationProvider` uses a `UserDetailsService` instance to load the authorities for a user, once they have been authenticated by CAS. +We’ve shown a simple in-memory setup here. +Note that the `CasAuthenticationProvider` does not actually use the password for authentication, but it does use the authorities. + +The beans are all reasonably self-explanatory if you refer back to the [How CAS Works](#cas-how-it-works) section. + +This completes the most basic configuration for CAS. +If you haven’t made any mistakes, your web application should happily work within the framework of CAS single sign on. +No other parts of Spring Security need to be concerned about the fact CAS handled authentication. +In the following sections we will discuss some (optional) more advanced configurations. + +### Single Logout + +The CAS protocol supports Single Logout and can be easily added to your Spring Security configuration. +Below are updates to the Spring Security configuration that handle Single Logout + +``` + +... + + + + + + + + + + + + + + + + +``` + +The `logout` element logs the user out of the local application, but does not end the session with the CAS server or any other applications that have been logged into. +The `requestSingleLogoutFilter` filter will allow the URL of `/spring_security_cas_logout` to be requested to redirect the application to the configured CAS Server logout URL. +Then the CAS Server will send a Single Logout request to all the services that were signed into. +The `singleLogoutFilter` handles the Single Logout request by looking up the `HttpSession` in a static `Map` and then invalidating it. + +It might be confusing why both the `logout` element and the `singleLogoutFilter` are needed. +It is considered best practice to logout locally first since the `SingleSignOutFilter` just stores the `HttpSession` in a static `Map` in order to call invalidate on it. +With the configuration above, the flow of logout would be: + +* The user requests `/logout` which would log the user out of the local application and send the user to the logout success page. + +* The logout success page, `/cas-logout.jsp`, should instruct the user to click a link pointing to `/logout/cas` in order to logout out of all applications. + +* When the user clicks the link, the user is redirected to the CAS single logout URL ([https://localhost:9443/cas/logout](https://localhost:9443/cas/logout)). + +* On the CAS Server side, the CAS single logout URL then submits single logout requests to all the CAS Services. + On the CAS Service side, JASIG’s `SingleSignOutFilter` processes the logout request by invalidating the original session. + +The next step is to add the following to your web.xml + +``` + +characterEncodingFilter + + org.springframework.web.filter.CharacterEncodingFilter + + + encoding + UTF-8 + + + +characterEncodingFilter +/* + + + + org.jasig.cas.client.session.SingleSignOutHttpSessionListener + + +``` + +When using the SingleSignOutFilter you might encounter some encoding issues. +Therefore it is recommended to add the `CharacterEncodingFilter` to ensure that the character encoding is correct when using the `SingleSignOutFilter`. +Again, refer to JASIG’s documentation for details. +The `SingleSignOutHttpSessionListener` ensures that when an `HttpSession` expires, the mapping used for single logout is removed. + +### Authenticating to a Stateless Service with CAS + +This section describes how to authenticate to a service using CAS. +In other words, this section discusses how to setup a client that uses a service that authenticates with CAS. +The next section describes how to setup a stateless service to Authenticate using CAS. + +#### Configuring CAS to Obtain Proxy Granting Tickets + +In order to authenticate to a stateless service, the application needs to obtain a proxy granting ticket (PGT). +This section describes how to configure Spring Security to obtain a PGT building upon thencas-st[Service Ticket Authentication] configuration. + +The first step is to include a `ProxyGrantingTicketStorage` in your Spring Security configuration. +This is used to store PGT’s that are obtained by the `CasAuthenticationFilter` so that they can be used to obtain proxy tickets. +An example configuration is shown below + +``` + + +``` + +The next step is to update the `CasAuthenticationProvider` to be able to obtain proxy tickets. +To do this replace the `Cas20ServiceTicketValidator` with a `Cas20ProxyTicketValidator`. +The `proxyCallbackUrl` should be set to a URL that the application will receive PGT’s at. +Last, the configuration should also reference the `ProxyGrantingTicketStorage` so it can use a PGT to obtain proxy tickets. +You can find an example of the configuration changes that should be made below. + +``` + +... + + + + + + + + +``` + +The last step is to update the `CasAuthenticationFilter` to accept PGT and to store them in the `ProxyGrantingTicketStorage`. +It is important the `proxyReceptorUrl` matches the `proxyCallbackUrl` of the `Cas20ProxyTicketValidator`. +An example configuration is shown below. + +``` + + ... + + + +``` + +#### Calling a Stateless Service Using a Proxy Ticket + +Now that Spring Security obtains PGTs, you can use them to create proxy tickets which can be used to authenticate to a stateless service. +The CAS [sample application](../../samples.html#samples) contains a working example in the `ProxyTicketSampleServlet`. +Example code can be found below: + +Java + +``` +protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { +// NOTE: The CasAuthenticationToken can also be obtained using +// SecurityContextHolder.getContext().getAuthentication() +final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal(); +// proxyTicket could be reused to make calls to the CAS service even if the +// target url differs +final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl); + +// Make a remote call using the proxy ticket +final String serviceUrl = targetUrl+"?ticket="+URLEncoder.encode(proxyTicket, "UTF-8"); +String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8"); +... +} +``` + +Kotlin + +``` +protected fun doGet(request: HttpServletRequest, response: HttpServletResponse?) { + // NOTE: The CasAuthenticationToken can also be obtained using + // SecurityContextHolder.getContext().getAuthentication() + val token = request.userPrincipal as CasAuthenticationToken + // proxyTicket could be reused to make calls to the CAS service even if the + // target url differs + val proxyTicket = token.assertion.principal.getProxyTicketFor(targetUrl) + + // Make a remote call using the proxy ticket + val serviceUrl: String = targetUrl + "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8") + val proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8") +} +``` + +### Proxy Ticket Authentication + +The `CasAuthenticationProvider` distinguishes between stateful and stateless clients. +A stateful client is considered any that submits to the `filterProcessUrl` of the `CasAuthenticationFilter`. +A stateless client is any that presents an authentication request to `CasAuthenticationFilter` on a URL other than the `filterProcessUrl`. + +Because remoting protocols have no way of presenting themselves within the context of an `HttpSession`, it isn’t possible to rely on the default practice of storing the security context in the session between requests. +Furthermore, because the CAS server invalidates a ticket after it has been validated by the `TicketValidator`, presenting the same proxy ticket on subsequent requests will not work. + +One obvious option is to not use CAS at all for remoting protocol clients. +However, this would eliminate many of the desirable features of CAS. +As a middle-ground, the `CasAuthenticationProvider` uses a `StatelessTicketCache`. +This is used solely for stateless clients which use a principal equal to `CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER`. +What happens is the `CasAuthenticationProvider` will store the resulting `CasAuthenticationToken` in the `StatelessTicketCache`, keyed on the proxy ticket. +Accordingly, remoting protocol clients can present the same proxy ticket and the `CasAuthenticationProvider` will not need to contact the CAS server for validation (aside from the first request). +Once authenticated, the proxy ticket could be used for URLs other than the original target service. + +This section builds upon the previous sections to accommodate proxy ticket authentication. +The first step is to specify to authenticate all artifacts as shown below. + +``` + +... + + +``` + +The next step is to specify `serviceProperties` and the `authenticationDetailsSource` for the `CasAuthenticationFilter`. +The `serviceProperties` property instructs the `CasAuthenticationFilter` to attempt to authenticate all artifacts instead of only ones present on the `filterProcessUrl`. +The `ServiceAuthenticationDetailsSource` creates a `ServiceAuthenticationDetails` that ensures the current URL, based upon the `HttpServletRequest`, is used as the service URL when validating the ticket. +The method for generating the service URL can be customized by injecting a custom `AuthenticationDetailsSource` that returns a custom `ServiceAuthenticationDetails`. + +``` + +... + + + + + + + +``` + +You will also need to update the `CasAuthenticationProvider` to handle proxy tickets. +To do this replace the `Cas20ServiceTicketValidator` with a `Cas20ProxyTicketValidator`. +You will need to configure the `statelessTicketCache` and which proxies you want to accept. +You can find an example of the updates required to accept all proxies below. + +``` + +... + + + + + + + + + + + + + + + + + + + + + +``` + +[JAAS](jaas.html)[X509](x509.html) + diff --git a/docs/en/spring-security/servlet-authentication-events.md b/docs/en/spring-security/servlet-authentication-events.md new file mode 100644 index 0000000000000000000000000000000000000000..90040c25aa9e3e70360b24d556c3ae211a728d8b --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-events.md @@ -0,0 +1,147 @@ +# Authentication Events + +For each authentication that succeeds or fails, a `AuthenticationSuccessEvent` or `AbstractAuthenticationFailureEvent` is fired, respectively. + +To listen for these events, you must first publish an `AuthenticationEventPublisher`. +Spring Security’s `DefaultAuthenticationEventPublisher` will probably do fine: + +Java + +``` +@Bean +public AuthenticationEventPublisher authenticationEventPublisher + (ApplicationEventPublisher applicationEventPublisher) { + return new DefaultAuthenticationEventPublisher(applicationEventPublisher); +} +``` + +Kotlin + +``` +@Bean +fun authenticationEventPublisher + (applicationEventPublisher: ApplicationEventPublisher?): AuthenticationEventPublisher { + return DefaultAuthenticationEventPublisher(applicationEventPublisher) +} +``` + +Then, you can use Spring’s `@EventListener` support: + +Java + +``` +@Component +public class AuthenticationEvents { + @EventListener + public void onSuccess(AuthenticationSuccessEvent success) { + // ... + } + + @EventListener + public void onFailure(AbstractAuthenticationFailureEvent failures) { + // ... + } +} +``` + +Kotlin + +``` +@Component +class AuthenticationEvents { + @EventListener + fun onSuccess(success: AuthenticationSuccessEvent?) { + // ... + } + + @EventListener + fun onFailure(failures: AbstractAuthenticationFailureEvent?) { + // ... + } +} +``` + +While similar to `AuthenticationSuccessHandler` and `AuthenticationFailureHandler`, these are nice in that they can be used independently from the servlet API. + +## Adding Exception Mappings + +`DefaultAuthenticationEventPublisher` by default will publish an `AbstractAuthenticationFailureEvent` for the following events: + +| Exception | Event | +|--------------------------------|----------------------------------------------| +| `BadCredentialsException` | `AuthenticationFailureBadCredentialsEvent` | +| `UsernameNotFoundException` | `AuthenticationFailureBadCredentialsEvent` | +| `AccountExpiredException` | `AuthenticationFailureExpiredEvent` | +| `ProviderNotFoundException` | `AuthenticationFailureProviderNotFoundEvent` | +| `DisabledException` | `AuthenticationFailureDisabledEvent` | +| `LockedException` | `AuthenticationFailureLockedEvent` | +|`AuthenticationServiceException`| `AuthenticationFailureServiceExceptionEvent` | +| `CredentialsExpiredException` |`AuthenticationFailureCredentialsExpiredEvent`| +| `InvalidBearerTokenException` | `AuthenticationFailureBadCredentialsEvent` | + +The publisher does an exact `Exception` match, which means that sub-classes of these exceptions won’t also produce events. + +To that end, you may want to supply additional mappings to the publisher via the `setAdditionalExceptionMappings` method: + +Java + +``` +@Bean +public AuthenticationEventPublisher authenticationEventPublisher + (ApplicationEventPublisher applicationEventPublisher) { + Map, + Class> mapping = + Collections.singletonMap(FooException.class, FooEvent.class); + AuthenticationEventPublisher authenticationEventPublisher = + new DefaultAuthenticationEventPublisher(applicationEventPublisher); + authenticationEventPublisher.setAdditionalExceptionMappings(mapping); + return authenticationEventPublisher; +} +``` + +Kotlin + +``` +@Bean +fun authenticationEventPublisher + (applicationEventPublisher: ApplicationEventPublisher?): AuthenticationEventPublisher { + val mapping: Map, Class> = + mapOf(Pair(FooException::class.java, FooEvent::class.java)) + val authenticationEventPublisher = DefaultAuthenticationEventPublisher(applicationEventPublisher) + authenticationEventPublisher.setAdditionalExceptionMappings(mapping) + return authenticationEventPublisher +} +``` + +## Default Event + +And, you can supply a catch-all event to fire in the case of any `AuthenticationException`: + +Java + +``` +@Bean +public AuthenticationEventPublisher authenticationEventPublisher + (ApplicationEventPublisher applicationEventPublisher) { + AuthenticationEventPublisher authenticationEventPublisher = + new DefaultAuthenticationEventPublisher(applicationEventPublisher); + authenticationEventPublisher.setDefaultAuthenticationFailureEvent + (GenericAuthenticationFailureEvent.class); + return authenticationEventPublisher; +} +``` + +Kotlin + +``` +@Bean +fun authenticationEventPublisher + (applicationEventPublisher: ApplicationEventPublisher?): AuthenticationEventPublisher { + val authenticationEventPublisher = DefaultAuthenticationEventPublisher(applicationEventPublisher) + authenticationEventPublisher.setDefaultAuthenticationFailureEvent(GenericAuthenticationFailureEvent::class.java) + return authenticationEventPublisher +} +``` + +[Logout](logout.html)[Authorization](../authorization/index.html) + diff --git a/docs/en/spring-security/servlet-authentication-jaas.md b/docs/en/spring-security/servlet-authentication-jaas.md new file mode 100644 index 0000000000000000000000000000000000000000..4a99141c6407f7f187475f1d5f55945eef5b5df4 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-jaas.md @@ -0,0 +1,155 @@ +# Java Authentication and Authorization Service (JAAS) Provider + +## Overview + +Spring Security provides a package able to delegate authentication requests to the Java Authentication and Authorization Service (JAAS). +This package is discussed in detail below. + +## AbstractJaasAuthenticationProvider + +The `AbstractJaasAuthenticationProvider` is the basis for the provided JAAS `AuthenticationProvider` implementations. +Subclasses must implement a method that creates the `LoginContext`. +The `AbstractJaasAuthenticationProvider` has a number of dependencies that can be injected into it that are discussed below. + +### JAAS CallbackHandler + +Most JAAS `LoginModule`s require a callback of some sort. +These callbacks are usually used to obtain the username and password from the user. + +In a Spring Security deployment, Spring Security is responsible for this user interaction (via the authentication mechanism). +Thus, by the time the authentication request is delegated through to JAAS, Spring Security’s authentication mechanism will already have fully-populated an `Authentication` object containing all the information required by the JAAS `LoginModule`. + +Therefore, the JAAS package for Spring Security provides two default callback handlers, `JaasNameCallbackHandler` and `JaasPasswordCallbackHandler`. +Each of these callback handlers implement `JaasAuthenticationCallbackHandler`. +In most cases these callback handlers can simply be used without understanding the internal mechanics. + +For those needing full control over the callback behavior, internally `AbstractJaasAuthenticationProvider` wraps these `JaasAuthenticationCallbackHandler`s with an `InternalCallbackHandler`. +The `InternalCallbackHandler` is the class that actually implements JAAS normal `CallbackHandler` interface. +Any time that the JAAS `LoginModule` is used, it is passed a list of application context configured `InternalCallbackHandler`s. +If the `LoginModule` requests a callback against the `InternalCallbackHandler`s, the callback is in-turn passed to the `JaasAuthenticationCallbackHandler`s being wrapped. + +### JAAS AuthorityGranter + +JAAS works with principals. +Even "roles" are represented as principals in JAAS. +Spring Security, on the other hand, works with `Authentication` objects. +Each `Authentication` object contains a single principal, and multiple `GrantedAuthority`s. +To facilitate mapping between these different concepts, Spring Security’s JAAS package includes an `AuthorityGranter` interface. + +An `AuthorityGranter` is responsible for inspecting a JAAS principal and returning a set of `String`s, representing the authorities assigned to the principal. +For each returned authority string, the `AbstractJaasAuthenticationProvider` creates a `JaasGrantedAuthority` (which implements Spring Security’s `GrantedAuthority` interface) containing the authority string and the JAAS principal that the `AuthorityGranter` was passed. +The `AbstractJaasAuthenticationProvider` obtains the JAAS principals by firstly successfully authenticating the user’s credentials using the JAAS `LoginModule`, and then accessing the `LoginContext` it returns. +A call to `LoginContext.getSubject().getPrincipals()` is made, with each resulting principal passed to each `AuthorityGranter` defined against the `AbstractJaasAuthenticationProvider.setAuthorityGranters(List)` property. + +Spring Security does not include any production `AuthorityGranter`s given that every JAAS principal has an implementation-specific meaning. +However, there is a `TestAuthorityGranter` in the unit tests that demonstrates a simple `AuthorityGranter` implementation. + +## DefaultJaasAuthenticationProvider + +The `DefaultJaasAuthenticationProvider` allows a JAAS `Configuration` object to be injected into it as a dependency. +It then creates a `LoginContext` using the injected JAAS `Configuration`. +This means that `DefaultJaasAuthenticationProvider` is not bound any particular implementation of `Configuration` as `JaasAuthenticationProvider` is. + +### InMemoryConfiguration + +In order to make it easy to inject a `Configuration` into `DefaultJaasAuthenticationProvider`, a default in-memory implementation named `InMemoryConfiguration` is provided. +The implementation constructor accepts a `Map` where each key represents a login configuration name and the value represents an `Array` of `AppConfigurationEntry`s.`InMemoryConfiguration` also supports a default `Array` of `AppConfigurationEntry` objects that will be used if no mapping is found within the provided `Map`. +For details, refer to the class level javadoc of `InMemoryConfiguration`. + +### DefaultJaasAuthenticationProvider Example Configuration + +While the Spring configuration for `InMemoryConfiguration` can be more verbose than the standard JAAS configuration files, using it in conjunction with `DefaultJaasAuthenticationProvider` is more flexible than `JaasAuthenticationProvider` since it not dependant on the default `Configuration` implementation. + +An example configuration of `DefaultJaasAuthenticationProvider` using `InMemoryConfiguration` is provided below. +Note that custom implementations of `Configuration` can easily be injected into `DefaultJaasAuthenticationProvider` as well. + +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +## JaasAuthenticationProvider + +The `JaasAuthenticationProvider` assumes the default `Configuration` is an instance of [ ConfigFile](https://docs.oracle.com/javase/8/docs/jre/api/security/jaas/spec/com/sun/security/auth/login/ConfigFile.html). +This assumption is made in order to attempt to update the `Configuration`. +The `JaasAuthenticationProvider` then uses the default `Configuration` to create the `LoginContext`. + +Let’s assume we have a JAAS login configuration file, `/WEB-INF/login.conf`, with the following contents: + +``` +JAASTest { + sample.SampleLoginModule required; +}; +``` + +Like all Spring Security beans, the `JaasAuthenticationProvider` is configured via the application context. +The following definitions would correspond to the above JAAS login configuration file: + +``` + + + + + + + + + + + + + + + +``` + +## Running as a Subject + +If configured, the `JaasApiIntegrationFilter` will attempt to run as the `Subject` on the `JaasAuthenticationToken`. +This means that the `Subject` can be accessed using: + +``` +Subject subject = Subject.getSubject(AccessController.getContext()); +``` + +This integration can easily be configured using the [jaas-api-provision](../appendix/namespace/http.html#nsa-http-jaas-api-provision) attribute. +This feature is useful when integrating with legacy or external API’s that rely on the JAAS Subject being populated. + +[Pre-Authentication](preauth.html)[CAS](cas.html) + diff --git a/docs/en/spring-security/servlet-authentication-logout.md b/docs/en/spring-security/servlet-authentication-logout.md new file mode 100644 index 0000000000000000000000000000000000000000..3201c28b8b02859188eb481b14cce16013832728 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-logout.md @@ -0,0 +1,141 @@ +# Handling Logouts + +## Logout Java/Kotlin Configuration + +When using the `[WebSecurityConfigurerAdapter](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html)`, logout capabilities are automatically applied. +The default is that accessing the URL `/logout` will log the user out by: + +* Invalidating the HTTP Session + +* Cleaning up any RememberMe authentication that was configured + +* Clearing the `SecurityContextHolder` + +* Redirect to `/login?logout` + +Similar to configuring login capabilities, however, you also have various options to further customize your logout requirements: + +Example 1. Logout Configuration + +Java + +``` +protected void configure(HttpSecurity http) throws Exception { + http + .logout(logout -> logout (1) + .logoutUrl("/my/logout") (2) + .logoutSuccessUrl("/my/index") (3) + .logoutSuccessHandler(logoutSuccessHandler) (4) + .invalidateHttpSession(true) (5) + .addLogoutHandler(logoutHandler) (6) + .deleteCookies(cookieNamesToClear) (7) + ) + ... +} +``` + +Kotlin + +``` +override fun configure(http: HttpSecurity) { + http { + logout { + logoutUrl = "/my/logout" (1) + logoutSuccessUrl = "/my/index" (2) + logoutSuccessHandler = customLogoutSuccessHandler (3) + invalidateHttpSession = true (4) + addLogoutHandler(logoutHandler) (5) + deleteCookies(cookieNamesToClear) (6) + } + } +} +``` + +|**1**| Provides logout support.
This is automatically applied when using `WebSecurityConfigurerAdapter`. | +|-----|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**| The URL that triggers log out to occur (default is `/logout`).
If CSRF protection is enabled (default), then the request must also be a POST.
For more information, please consult the [Javadoc](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutUrl-java.lang.String-). | +|**3**| The URL to redirect to after logout has occurred.
The default is `/login?logout`.
For more information, please consult the [Javadoc](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessUrl-java.lang.String-). | +|**4**|Let’s you specify a custom `LogoutSuccessHandler`.
If this is specified, `logoutSuccessUrl()` is ignored.
For more information, please consult the [Javadoc](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessHandler-org.springframework.security.web.authentication.logout.LogoutSuccessHandler-).| +|**5**| Specify whether to invalidate the `HttpSession` at the time of logout.
This is **true** by default.
Configures the `SecurityContextLogoutHandler` under the covers.
For more information, please consult the [Javadoc](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#invalidateHttpSession-boolean-). | +|**6**| Adds a `LogoutHandler`.`SecurityContextLogoutHandler` is added as the last `LogoutHandler` by default. | +|**7**| Allows specifying the names of cookies to be removed on logout success.
This is a shortcut for adding a `CookieClearingLogoutHandler` explicitly. | + +| |Logouts can of course also be configured using the XML Namespace notation.
Please see the documentation for the [ logout element](../appendix/namespace/http.html#nsa-logout) in the Spring Security XML Namespace section for further details.| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Generally, in order to customize logout functionality, you can add`[LogoutHandler](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/logout/LogoutHandler.html)`and/or`[LogoutSuccessHandler](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/logout/LogoutSuccessHandler.html)`implementations. +For many common scenarios, these handlers are applied under the +covers when using the fluent API. + +## Logout XML Configuration + +The `logout` element adds support for logging out by navigating to a particular URL. +The default logout URL is `/logout`, but you can set it to something else using the `logout-url` attribute. +More information on other available attributes may be found in the namespace appendix. + +## LogoutHandler + +Generally, `[LogoutHandler](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/logout/LogoutHandler.html)`implementations indicate classes that are able to participate in logout handling. +They are expected to be invoked to perform necessary clean-up. +As such they should +not throw exceptions. +Various implementations are provided: + +* [PersistentTokenBasedRememberMeServices](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.html) + +* [TokenBasedRememberMeServices](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.html) + +* [CookieClearingLogoutHandler](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandler.html) + +* [CsrfLogoutHandler](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/csrf/CsrfLogoutHandler.html) + +* [SecurityContextLogoutHandler](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html) + +* [HeaderWriterLogoutHandler](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/logout/HeaderWriterLogoutHandler.html) + +Please see [Remember-Me Interfaces and Implementations](rememberme.html#remember-me-impls) for details. + +Instead of providing `LogoutHandler` implementations directly, the fluent API also provides shortcuts that provide the respective `LogoutHandler` implementations under the covers. +E.g. `deleteCookies()` allows specifying the names of one or more cookies to be removed on logout success. +This is a shortcut compared to adding a `CookieClearingLogoutHandler`. + +## LogoutSuccessHandler + +The `LogoutSuccessHandler` is called after a successful logout by the `LogoutFilter`, to handle e.g. +redirection or forwarding to the appropriate destination. +Note that the interface is almost the same as the `LogoutHandler` but may raise an exception. + +The following implementations are provided: + +* [SimpleUrlLogoutSuccessHandler](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.html) + +* HttpStatusReturningLogoutSuccessHandler + +As mentioned above, you don’t need to specify the `SimpleUrlLogoutSuccessHandler` directly. +Instead, the fluent API provides a shortcut by setting the `logoutSuccessUrl()`. +This will setup the `SimpleUrlLogoutSuccessHandler` under the covers. +The provided URL will be redirected to after a logout has occurred. +The default is `/login?logout`. + +The `HttpStatusReturningLogoutSuccessHandler` can be interesting in REST API type scenarios. +Instead of redirecting to a URL upon the successful logout, this `LogoutSuccessHandler` allows you to provide a plain HTTP status code to be returned. +If not configured a status code 200 will be returned by default. + +## Further Logout-Related References + +* [Logout Handling](#ns-logout) + +* [ Testing Logout](../test/mockmvc/logout.html#test-logout) + +* [ HttpServletRequest.logout()](../integrations/servlet-api.html#servletapi-logout) + +* [Remember-Me Interfaces and Implementations](rememberme.html#remember-me-impls) + +* [ Logging Out](../exploits/csrf.html#servlet-considerations-csrf-logout) in section CSRF Caveats + +* Section [ Single Logout](cas.html#cas-singlelogout) (CAS protocol) + +* Documentation for the [ logout element](../appendix/namespace/http.html#nsa-logout) in the Spring Security XML Namespace section + +[Run-As](runas.html)[Authentication Events](events.html) + diff --git a/docs/en/spring-security/servlet-authentication-openid.md b/docs/en/spring-security/servlet-authentication-openid.md new file mode 100644 index 0000000000000000000000000000000000000000..abecc7d99fb918bea0069a5281ce1c0da07234cc --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-openid.md @@ -0,0 +1,58 @@ +# OpenID Support + +| |The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported by spring-security-oauth2.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------| + +The namespace supports [OpenID](https://openid.net/) login either instead of, or in addition to normal form-based login, with a simple change: + +``` + + + + +``` + +You should then register yourself with an OpenID provider (such as myopenid.com), and add the user information to your in-memory ``: + +``` + +``` + +You should be able to login using the `myopenid.com` site to authenticate. +It is also possible to select a specific `UserDetailsService` bean for use OpenID by setting the `user-service-ref` attribute on the `openid-login` element. +Note that we have omitted the password attribute from the above user configuration, since this set of user data is only being used to load the authorities for the user. +A random password will be generated internally, preventing you from accidentally using this user data as an authentication source elsewhere in your configuration. + +## Attribute Exchange + +Support for OpenID [attribute exchange](https://openid.net/specs/openid-attribute-exchange-1_0.html). +As an example, the following configuration would attempt to retrieve the email and full name from the OpenID provider, for use by the application: + +``` + + + + + + +``` + +The "type" of each OpenID attribute is a URI, determined by a particular schema, in this case [https://axschema.org/](https://axschema.org/). +If an attribute must be retrieved for successful authentication, the `required` attribute can be set. +The exact schema and attributes supported will depend on your OpenID provider. +The attribute values are returned as part of the authentication process and can be accessed afterwards using the following code: + +``` +OpenIDAuthenticationToken token = + (OpenIDAuthenticationToken)SecurityContextHolder.getContext().getAuthentication(); +List attributes = token.getAttributes(); +``` + +We can obtain the `OpenIDAuthenticationToken` from the [SecurityContextHolder](architecture.html#servlet-authentication-securitycontextholder). +The `OpenIDAttribute` contains the attribute type and the retrieved value (or values in the case of multi-valued attributes). +You can supply multiple `attribute-exchange` elements, using an `identifier-matcher` attribute on each. +This contains a regular expression which will be matched against the OpenID identifier supplied by the user. +See the OpenID sample application in the codebase for an example configuration, providing different attribute lists for the Google, Yahoo and MyOpenID providers. + +[Remember Me](rememberme.html)[Anonymous](anonymous.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-basic.md b/docs/en/spring-security/servlet-authentication-passwords-basic.md new file mode 100644 index 0000000000000000000000000000000000000000..8a87e1df786811f5f7b6f74c8b066d27c4da6c36 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-basic.md @@ -0,0 +1,92 @@ +# Basic Authentication + +This section provides details on how Spring Security provides support for [Basic HTTP Authentication](https://tools.ietf.org/html/rfc7617) for servlet based applications. + +Let’s take a look at how HTTP Basic Authentication works within Spring Security. +First, we see the [WWW-Authenticate](https://tools.ietf.org/html/rfc7235#section-4.1) header is sent back to an unauthenticated client. + +![basicauthenticationentrypoint](../../../_images/servlet/authentication/unpwd/basicauthenticationentrypoint.png) + +Figure 1. Sending WWW-Authenticate Header + +The figure builds off our [`SecurityFilterChain`](../../architecture.html#servlet-securityfilterchain) diagram. + +![number 1](../../../_images/icons/number_1.png) First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized. + +![number 2](../../../_images/icons/number_2.png) Spring Security’s [`FilterSecurityInterceptor`](../../authorization/authorize-requests.html#servlet-authorization-filtersecurityinterceptor) indicates that the unauthenticated request is *Denied* by throwing an `AccessDeniedException`. + +![number 3](../../../_images/icons/number_3.png) Since the user is not authenticated, [`ExceptionTranslationFilter`](../../architecture.html#servlet-exceptiontranslationfilter) initiates *Start Authentication*. +The configured [`AuthenticationEntryPoint`](../architecture.html#servlet-authentication-authenticationentrypoint) is an instance of [`BasicAuthenticationEntryPoint`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.html) which sends a WWW-Authenticate header. +The `RequestCache` is typically a `NullRequestCache` that does not save the request since the client is capable of replaying the requests it originally requested. + +When a client receives the WWW-Authenticate header it knows it should retry with a username and password. +Below is the flow for the username and password being processed. + +![basicauthenticationfilter](../../../_images/servlet/authentication/unpwd/basicauthenticationfilter.png) + +Figure 2. Authenticating Username and Password + +The figure builds off our [`SecurityFilterChain`](../../architecture.html#servlet-securityfilterchain) diagram. + +![number 1](../../../_images/icons/number_1.png) When the user submits their username and password, the `BasicAuthenticationFilter` creates a `UsernamePasswordAuthenticationToken` which is a type of [`Authentication`](../architecture.html#servlet-authentication-authentication) by extracting the username and password from the `HttpServletRequest`. + +![number 2](../../../_images/icons/number_2.png) Next, the `UsernamePasswordAuthenticationToken` is passed into the `AuthenticationManager` to be authenticated. +The details of what `AuthenticationManager` looks like depend on how the [user information is stored](index.html#servlet-authentication-unpwd-storage). + +![number 3](../../../_images/icons/number_3.png) If authentication fails, then *Failure* + +* The [SecurityContextHolder](../architecture.html#servlet-authentication-securitycontextholder) is cleared out. + +* `RememberMeServices.loginFail` is invoked. + If remember me is not configured, this is a no-op. + +* `AuthenticationEntryPoint` is invoked to trigger the WWW-Authenticate to be sent again. + +![number 4](../../../_images/icons/number_4.png) If authentication is successful, then *Success*. + +* The [Authentication](../architecture.html#servlet-authentication-authentication) is set on the [SecurityContextHolder](../architecture.html#servlet-authentication-securitycontextholder). + +* `RememberMeServices.loginSuccess` is invoked. + If remember me is not configured, this is a no-op. + +* The `BasicAuthenticationFilter` invokes `FilterChain.doFilter(request,response)` to continue with the rest of the application logic. + +Spring Security’s HTTP Basic Authentication support in is enabled by default. +However, as soon as any servlet based configuration is provided, HTTP Basic must be explicitly provided. + +A minimal, explicit configuration can be found below: + +Example 1. Explicit HTTP Basic Configuration + +Java + +``` +protected void configure(HttpSecurity http) { + http + // ... + .httpBasic(withDefaults()); +} +``` + +XML + +``` + + + + +``` + +Kotlin + +``` +fun configure(http: HttpSecurity) { + http { + // ... + httpBasic { } + } +} +``` + +[Form](form.html)[Digest](digest.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-digest.md b/docs/en/spring-security/servlet-authentication-passwords-digest.md new file mode 100644 index 0000000000000000000000000000000000000000..5d319535dfb6b7c31d113e297ac8c73d14562b89 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-digest.md @@ -0,0 +1,82 @@ +# Digest Authentication + +This section provides details on how Spring Security provides support for [Digest Authentication](https://tools.ietf.org/html/rfc2617) which is provided `DigestAuthenticationFilter`. + +| |You should not use Digest Authentication in modern applications because it is not considered secure.
The most obvious problem is that you must store your passwords in plaintext, encrypted, or an MD5 format.
All of these storage formats are considered insecure.
Instead, you should store credentials using a one way adaptive password hash (i.e. bCrypt, PBKDF2, SCrypt, etc) which is not supported by Digest Authentication.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Digest Authentication attempts to solve many of the weaknesses of [Basic authentication](basic.html#servlet-authentication-basic), specifically by ensuring credentials are never sent in clear text across the wire. +Many [browsers support Digest Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Digest#Browser_compatibility). + +The standard governing HTTP Digest Authentication is defined by [RFC 2617](https://tools.ietf.org/html/rfc2617), which updates an earlier version of the Digest Authentication standard prescribed by [RFC 2069](https://tools.ietf.org/html/rfc2069). +Most user agents implement RFC 2617. +Spring Security’s Digest Authentication support is compatible with the “auth” quality of protection (`qop`) prescribed by RFC 2617, which also provides backward compatibility with RFC 2069. +Digest Authentication was seen as a more attractive option if you need to use unencrypted HTTP (i.e. no TLS/HTTPS) and wish to maximise security of the authentication process. +However, everyone should use [HTTPS](../../../features/exploits/http.html#http). + +Central to Digest Authentication is a "nonce". +This is a value the server generates. +Spring Security’s nonce adopts the following format: + +Example 1. Digest Syntax + +``` +base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key)) +expirationTime: The date and time when the nonce expires, expressed in milliseconds +key: A private key to prevent modification of the nonce token +``` + +You will need to ensure you [configure](../../../features/authentication/password-storage.html#authentication-password-storage-configuration) insecure plain text [Password Storage](../../../features/authentication/password-storage.html#authentication-password-storage) using `NoOpPasswordEncoder`. +The following provides an example of configuring Digest Authentication with Java Configuration: + +Example 2. Digest Authentication + +Java + +``` +@Autowired +UserDetailsService userDetailsService; + +DigestAuthenticationEntryPoint entryPoint() { + DigestAuthenticationEntryPoint result = new DigestAuthenticationEntryPoint(); + result.setRealmName("My App Relam"); + result.setKey("3028472b-da34-4501-bfd8-a355c42bdf92"); +} + +DigestAuthenticationFilter digestAuthenticationFilter() { + DigestAuthenticationFilter result = new DigestAuthenticationFilter(); + result.setUserDetailsService(userDetailsService); + result.setAuthenticationEntryPoint(entryPoint()); +} + +protected void configure(HttpSecurity http) throws Exception { + http + // ... + .exceptionHandling(e -> e.authenticationEntryPoint(authenticationEntryPoint())) + .addFilterBefore(digestFilter()); +} +``` + +XML + +``` + + + + + + + + +``` + +[Basic](basic.html)[Password Storage](storage.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-form.md b/docs/en/spring-security/servlet-authentication-passwords-form.md new file mode 100644 index 0000000000000000000000000000000000000000..5ce119305a0769f5fbd28cb313a3dfd020911910 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-form.md @@ -0,0 +1,221 @@ +# Form Login + +Spring Security provides support for username and password being provided through an html form. +This section provides details on how form based authentication works within Spring Security. + +Let’s take a look at how form based log in works within Spring Security. +First, we see how the user is redirected to the log in form. + +![loginurlauthenticationentrypoint](../../../_images/servlet/authentication/unpwd/loginurlauthenticationentrypoint.png) + +Figure 1. Redirecting to the Log In Page + +The figure builds off our [`SecurityFilterChain`](../../architecture.html#servlet-securityfilterchain) diagram. + +![number 1](../../../_images/icons/number_1.png) First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized. + +![number 2](../../../_images/icons/number_2.png) Spring Security’s [`FilterSecurityInterceptor`](../../authorization/authorize-requests.html#servlet-authorization-filtersecurityinterceptor) indicates that the unauthenticated request is *Denied* by throwing an `AccessDeniedException`. + +![number 3](../../../_images/icons/number_3.png) Since the user is not authenticated, [`ExceptionTranslationFilter`](../../architecture.html#servlet-exceptiontranslationfilter) initiates *Start Authentication* and sends a redirect to the log in page with the configured [`AuthenticationEntryPoint`](../architecture.html#servlet-authentication-authenticationentrypoint). +In most cases the `AuthenticationEntryPoint` is an instance of [`LoginUrlAuthenticationEntryPoint`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html). + +![number 4](../../../_images/icons/number_4.png) The browser will then request the log in page that it was redirected to. + +![number 5](../../../_images/icons/number_5.png) Something within the application, must [render the log in page](#servlet-authentication-form-custom). + +When the username and password are submitted, the `UsernamePasswordAuthenticationFilter` authenticates the username and password. +The `UsernamePasswordAuthenticationFilter` extends [AbstractAuthenticationProcessingFilter](../architecture.html#servlet-authentication-abstractprocessingfilter), so this diagram should look pretty similar. + +![usernamepasswordauthenticationfilter](../../../_images/servlet/authentication/unpwd/usernamepasswordauthenticationfilter.png) + +Figure 2. Authenticating Username and Password + +The figure builds off our [`SecurityFilterChain`](../../architecture.html#servlet-securityfilterchain) diagram. + +![number 1](../../../_images/icons/number_1.png) When the user submits their username and password, the `UsernamePasswordAuthenticationFilter` creates a `UsernamePasswordAuthenticationToken` which is a type of [`Authentication`](../architecture.html#servlet-authentication-authentication) by extracting the username and password from the `HttpServletRequest`. + +![number 2](../../../_images/icons/number_2.png) Next, the `UsernamePasswordAuthenticationToken` is passed into the `AuthenticationManager` to be authenticated. +The details of what `AuthenticationManager` looks like depend on how the [user information is stored](index.html#servlet-authentication-unpwd-storage). + +![number 3](../../../_images/icons/number_3.png) If authentication fails, then *Failure* + +* The [SecurityContextHolder](../architecture.html#servlet-authentication-securitycontextholder) is cleared out. + +* `RememberMeServices.loginFail` is invoked. + If remember me is not configured, this is a no-op. + +* `AuthenticationFailureHandler` is invoked. + +![number 4](../../../_images/icons/number_4.png) If authentication is successful, then *Success*. + +* `SessionAuthenticationStrategy` is notified of a new log in. + +* The [Authentication](../architecture.html#servlet-authentication-authentication) is set on the [SecurityContextHolder](../architecture.html#servlet-authentication-securitycontextholder). + +* `RememberMeServices.loginSuccess` is invoked. + If remember me is not configured, this is a no-op. + +* `ApplicationEventPublisher` publishes an `InteractiveAuthenticationSuccessEvent`. + +* The `AuthenticationSuccessHandler` is invoked. Typically this is a `SimpleUrlAuthenticationSuccessHandler` which will redirect to a request saved by [`ExceptionTranslationFilter`](../../architecture.html#servlet-exceptiontranslationfilter) when we redirect to the log in page. + +Spring Security form log in is enabled by default. +However, as soon as any servlet based configuration is provided, form based log in must be explicitly provided. +A minimal, explicit Java configuration can be found below: + +Example 1. Form Log In + +Java + +``` +protected void configure(HttpSecurity http) { + http + // ... + .formLogin(withDefaults()); +} +``` + +XML + +``` + + + + +``` + +Kotlin + +``` +fun configure(http: HttpSecurity) { + http { + // ... + formLogin { } + } +} +``` + +In this configuration Spring Security will render a default log in page. +Most production applications will require a custom log in form. + +The configuration below demonstrates how to provide a custom log in form. + +Example 2. Custom Log In Form Configuration + +Java + +``` +protected void configure(HttpSecurity http) throws Exception { + http + // ... + .formLogin(form -> form + .loginPage("/login") + .permitAll() + ); +} +``` + +XML + +``` + + + + + +``` + +Kotlin + +``` +fun configure(http: HttpSecurity) { + http { + // ... + formLogin { + loginPage = "/login" + permitAll() + } + } +} +``` + +When the login page is specified in the Spring Security configuration, you are responsible for rendering the page. +Below is a [Thymeleaf](https://www.thymeleaf.org/) template that produces an HTML login form that complies with a login page of `/login`: + +Example 3. Log In Form + +src/main/resources/templates/login.html + +``` + + + + Please Log In + + +

Please Log In

+
+ Invalid username and password.
+
+ You have been logged out.
+ +
+ +
+
+ +
+ + + + +``` + +There are a few key points about the default HTML form: + +* The form should perform a `post` to `/login` + +* The form will need to include a [CSRF Token](../../exploits/csrf.html#servlet-csrf) which is [automatically included](../../exploits/csrf.html#servlet-csrf-include-form-auto) by Thymeleaf. + +* The form should specify the username in a parameter named `username` + +* The form should specify the password in a parameter named `password` + +* If the HTTP parameter error is found, it indicates the user failed to provide a valid username / password + +* If the HTTP parameter logout is found, it indicates the user has logged out successfully + +Many users will not need much more than to customize the log in page. +However, if needed, everything above can be customized with additional configuration. + +If you are using Spring MVC, you will need a controller that maps `GET /login` to the login template we created. +A minimal sample `LoginController` can be seen below: + +Example 4. LoginController + +Java + +``` +@Controller +class LoginController { + @GetMapping("/login") + String login() { + return "login"; + } +} +``` + +Kotlin + +``` +@Controller +class LoginController { + @GetMapping("/login") + fun login(): String { + return "login" + } +} +``` + +[Reading Username/Password](input.html)[Basic](basic.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-input.md b/docs/en/spring-security/servlet-authentication-passwords-input.md new file mode 100644 index 0000000000000000000000000000000000000000..ccd18bcdbe2da88457d55f91d16ca13e30c97121 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-input.md @@ -0,0 +1,12 @@ +# Reading the Username & Password + +Spring Security provides the following built in mechanisms for reading a username and password from the `HttpServletRequest`: + +## Section Summary + +* [Form](form.html) +* [Basic](basic.html) +* [Digest](digest.html) + +[Username/Password](index.html)[Form](form.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-storage-dao-authentication-provider.md b/docs/en/spring-security/servlet-authentication-passwords-storage-dao-authentication-provider.md new file mode 100644 index 0000000000000000000000000000000000000000..e798dcf36548dfc067db749ce5b40002ae8b8794 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-storage-dao-authentication-provider.md @@ -0,0 +1,24 @@ +# DaoAuthenticationProvider + +[`DaoAuthenticationProvider`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/authentication/dao/DaoAuthenticationProvider.html) is an [`AuthenticationProvider`](../architecture.html#servlet-authentication-authenticationprovider) implementation that leverages a [`UserDetailsService`](user-details-service.html#servlet-authentication-userdetailsservice) and [`PasswordEncoder`](password-encoder.html#servlet-authentication-password-storage) to authenticate a username and password. + +Let’s take a look at how `DaoAuthenticationProvider` works within Spring Security. +The figure explains details of how the [`AuthenticationManager`](../architecture.html#servlet-authentication-authenticationmanager) in figures from [Reading the Username & Password](index.html#servlet-authentication-unpwd-input) works. + +![daoauthenticationprovider](../../../_images/servlet/authentication/unpwd/daoauthenticationprovider.png) + +Figure 1. `DaoAuthenticationProvider` Usage + +![number 1](../../../_images/icons/number_1.png) The authentication `Filter` from [Reading the Username & Password](index.html#servlet-authentication-unpwd-input) passes a `UsernamePasswordAuthenticationToken` to the `AuthenticationManager` which is implemented by [`ProviderManager`](../architecture.html#servlet-authentication-providermanager). + +![number 2](../../../_images/icons/number_2.png) The `ProviderManager` is configured to use an [AuthenticationProvider](../architecture.html#servlet-authentication-authenticationprovider) of type `DaoAuthenticationProvider`. + +![number 3](../../../_images/icons/number_3.png) `DaoAuthenticationProvider` looks up the `UserDetails` from the `UserDetailsService`. + +![number 4](../../../_images/icons/number_4.png) `DaoAuthenticationProvider` then uses the [`PasswordEncoder`](password-encoder.html#servlet-authentication-password-storage) to validate the password on the `UserDetails` returned in the previous step. + +![number 5](../../../_images/icons/number_5.png) When authentication is successful, the [`Authentication`](../architecture.html#servlet-authentication-authentication) that is returned is of type `UsernamePasswordAuthenticationToken` and has a principal that is the `UserDetails` returned by the configured `UserDetailsService`. +Ultimately, the returned `UsernamePasswordAuthenticationToken` will be set on the [`SecurityContextHolder`](../architecture.html#servlet-authentication-securitycontextholder) by the authentication `Filter`. + +[PasswordEncoder](password-encoder.html)[LDAP](ldap.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-storage-in-memory.md b/docs/en/spring-security/servlet-authentication-passwords-storage-in-memory.md new file mode 100644 index 0000000000000000000000000000000000000000..4a2f9d816bee7bba883ed96c56e37539ec3b0fd8 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-storage-in-memory.md @@ -0,0 +1,127 @@ +# In-Memory Authentication + +Spring Security’s `InMemoryUserDetailsManager` implements [UserDetailsService](user-details-service.html#servlet-authentication-userdetailsservice) to provide support for username/password based authentication that is stored in memory.`InMemoryUserDetailsManager` provides management of `UserDetails` by implementing the `UserDetailsManager` interface.`UserDetails` based authentication is used by Spring Security when it is configured to [accept a username/password](index.html#servlet-authentication-unpwd-input) for authentication. + +In this sample we use [Spring Boot CLI](../../../features/authentication/password-storage.html#authentication-password-storage-boot-cli) to encode the password of `password` and get the encoded password of `{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW`. + +Example 1. InMemoryUserDetailsManager Java Configuration + +Java + +``` +@Bean +public UserDetailsService users() { + UserDetails user = User.builder() + .username("user") + .password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW") + .roles("USER") + .build(); + UserDetails admin = User.builder() + .username("admin") + .password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW") + .roles("USER", "ADMIN") + .build(); + return new InMemoryUserDetailsManager(user, admin); +} +``` + +XML + +``` + + + + +``` + +Kotlin + +``` +@Bean +fun users(): UserDetailsService { + val user = User.builder() + .username("user") + .password("{bcrypt}$2a$10\$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW") + .roles("USER") + .build() + val admin = User.builder() + .username("admin") + .password("{bcrypt}$2a$10\$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW") + .roles("USER", "ADMIN") + .build() + return InMemoryUserDetailsManager(user, admin) +} +``` + +The samples above store the passwords in a secure format, but leave a lot to be desired in terms of getting started experience. + +In the sample below we leverage [User.withDefaultPasswordEncoder](../../../features/authentication/password-storage.html#authentication-password-storage-dep-getting-started) to ensure that the password stored in memory is protected. +However, it does not protect against obtaining the password by decompiling the source code. +For this reason, `User.withDefaultPasswordEncoder` should only be used for "getting started" and is not intended for production. + +Example 2. InMemoryUserDetailsManager with User.withDefaultPasswordEncoder + +Java + +``` +@Bean +public UserDetailsService users() { + // The builder will ensure the passwords are encoded before saving in memory + UserBuilder users = User.withDefaultPasswordEncoder(); + UserDetails user = users + .username("user") + .password("password") + .roles("USER") + .build(); + UserDetails admin = users + .username("admin") + .password("password") + .roles("USER", "ADMIN") + .build(); + return new InMemoryUserDetailsManager(user, admin); +} +``` + +Kotlin + +``` +@Bean +fun users(): UserDetailsService { + // The builder will ensure the passwords are encoded before saving in memory + val users = User.withDefaultPasswordEncoder() + val user = users + .username("user") + .password("password") + .roles("USER") + .build() + val admin = users + .username("admin") + .password("password") + .roles("USER", "ADMIN") + .build() + return InMemoryUserDetailsManager(user, admin) +} +``` + +There is no simple way to use `User.withDefaultPasswordEncoder` with XML based configuration. +For demos or just getting started, you can choose to prefix the password with `{noop}` to indicate [no encoding should be used](../../../features/authentication/password-storage.html#authentication-password-storage-dpe-format). + +Example 3. \ `{noop}` XML Configuration + +``` + + + + +``` + +[Password Storage](storage.html)[JDBC](jdbc.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-storage-jdbc.md b/docs/en/spring-security/servlet-authentication-passwords-storage-jdbc.md new file mode 100644 index 0000000000000000000000000000000000000000..c2b936d6afb1700f64c53f8050439819ef6289d7 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-storage-jdbc.md @@ -0,0 +1,197 @@ +# JDBC Authentication + +Spring Security’s `JdbcDaoImpl` implements [UserDetailsService](user-details-service.html#servlet-authentication-userdetailsservice) to provide support for username/password based authentication that is retrieved using JDBC.`JdbcUserDetailsManager` extends `JdbcDaoImpl` to provide management of `UserDetails` through the `UserDetailsManager` interface.`UserDetails` based authentication is used by Spring Security when it is configured to [accept a username/password](index.html#servlet-authentication-unpwd-input) for authentication. + +In the following sections we will discuss: + +* The [Default Schema](#servlet-authentication-jdbc-schema) used by Spring Security JDBC Authentication + +* [Setting up a DataSource](#servlet-authentication-jdbc-datasource) + +* [JdbcUserDetailsManager Bean](#servlet-authentication-jdbc-bean) + +## Default Schema + +Spring Security provides default queries for JDBC based authentication. +This section provides the corresponding default schemas used with the default queries. +You will need to adjust the schema to match any customizations to the queries and the database dialect you are using. + +### User Schema + +`JdbcDaoImpl` requires tables to load the password, account status (enabled or disabled) and a list of authorities (roles) for the user. +The default schema required can be found below. + +| |The default schema is also exposed as a classpath resource named `org/springframework/security/core/userdetails/jdbc/users.ddl`.| +|---|--------------------------------------------------------------------------------------------------------------------------------| + +Example 1. Default User Schema + +``` +create table users( + username varchar_ignorecase(50) not null primary key, + password varchar_ignorecase(500) not null, + enabled boolean not null +); + +create table authorities ( + username varchar_ignorecase(50) not null, + authority varchar_ignorecase(50) not null, + constraint fk_authorities_users foreign key(username) references users(username) +); +create unique index ix_auth_username on authorities (username,authority); +``` + +Oracle is a popular database choice, but requires a slightly different schema. +You can find the default Oracle Schema for users below. + +Example 2. Default User Schema for Oracle Databases + +``` +CREATE TABLE USERS ( + USERNAME NVARCHAR2(128) PRIMARY KEY, + PASSWORD NVARCHAR2(128) NOT NULL, + ENABLED CHAR(1) CHECK (ENABLED IN ('Y','N') ) NOT NULL +); + +CREATE TABLE AUTHORITIES ( + USERNAME NVARCHAR2(128) NOT NULL, + AUTHORITY NVARCHAR2(128) NOT NULL +); +ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_UNIQUE UNIQUE (USERNAME, AUTHORITY); +ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME) REFERENCES USERS (USERNAME) ENABLE; +``` + +### Group Schema + +If your application is leveraging groups, you will need to provide the groups schema. +The default schema for groups can be found below. + +Example 3. Default Group Schema + +``` +create table groups ( + id bigint generated by default as identity(start with 0) primary key, + group_name varchar_ignorecase(50) not null +); + +create table group_authorities ( + group_id bigint not null, + authority varchar(50) not null, + constraint fk_group_authorities_group foreign key(group_id) references groups(id) +); + +create table group_members ( + id bigint generated by default as identity(start with 0) primary key, + username varchar(50) not null, + group_id bigint not null, + constraint fk_group_members_group foreign key(group_id) references groups(id) +); +``` + +## Setting up a DataSource + +Before we configure `JdbcUserDetailsManager`, we must create a `DataSource`. +In our example, we will setup an [embedded DataSource](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#jdbc-embedded-database-support) that is initialized with the [default user schema](#servlet-authentication-jdbc-schema). + +Example 4. Embedded Data Source + +Java + +``` +@Bean +DataSource dataSource() { + return new EmbeddedDatabaseBuilder() + .setType(H2) + .addScript("classpath:org/springframework/security/core/userdetails/jdbc/users.ddl") + .build(); +} +``` + +XML + +``` + + + +``` + +Kotlin + +``` +@Bean +fun dataSource(): DataSource { + return EmbeddedDatabaseBuilder() + .setType(H2) + .addScript("classpath:org/springframework/security/core/userdetails/jdbc/users.ddl") + .build() +} +``` + +In a production environment, you will want to ensure you setup a connection to an external database. + +## JdbcUserDetailsManager Bean + +In this sample we use [Spring Boot CLI](../../../features/authentication/password-storage.html#authentication-password-storage-boot-cli) to encode the password of `password` and get the encoded password of `{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW`. +See the [PasswordEncoder](../../../features/authentication/password-storage.html#authentication-password-storage) section for more details about how to store passwords. + +Example 5. JdbcUserDetailsManager + +Java + +``` +@Bean +UserDetailsManager users(DataSource dataSource) { + UserDetails user = User.builder() + .username("user") + .password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW") + .roles("USER") + .build(); + UserDetails admin = User.builder() + .username("admin") + .password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW") + .roles("USER", "ADMIN") + .build(); + JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource); + users.createUser(user); + users.createUser(admin); + return users; +} +``` + +XML + +``` + + + + +``` + +Kotlin + +``` +@Bean +fun users(dataSource: DataSource): UserDetailsManager { + val user = User.builder() + .username("user") + .password("{bcrypt}$2a$10\$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW") + .roles("USER") + .build(); + val admin = User.builder() + .username("admin") + .password("{bcrypt}$2a$10\$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW") + .roles("USER", "ADMIN") + .build(); + val users = JdbcUserDetailsManager(dataSource) + users.createUser(user) + users.createUser(admin) + return users +} +``` + +[In Memory](in-memory.html)[UserDetails](user-details.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-storage-ldap.md b/docs/en/spring-security/servlet-authentication-passwords-storage-ldap.md new file mode 100644 index 0000000000000000000000000000000000000000..cb1b27a5ed89987a02c7a857cc6bdba0ec4d87da --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-storage-ldap.md @@ -0,0 +1,550 @@ +# LDAP Authentication + +LDAP is often used by organizations as a central repository for user information and as an authentication service. +It can also be used to store the role information for application users. + +Spring Security’s LDAP based authentication is used by Spring Security when it is configured to [accept a username/password](index.html#servlet-authentication-unpwd-input) for authentication. +However, despite leveraging a username/password for authentication it does not integrate using `UserDetailsService` because in [bind authentication](#servlet-authentication-ldap-bind) the LDAP server does not return the password so the application cannot perform validation of the password. + +There are many different scenarios for how an LDAP server may be configured so Spring Security’s LDAP provider is fully configurable. +It uses separate strategy interfaces for authentication and role retrieval and provides default implementations which can be configured to handle a wide range of situations. + +## Prerequisites + +You should be familiar with LDAP before trying to use it with Spring Security. +The following link provides a good introduction to the concepts involved and a guide to setting up a directory using the free LDAP server OpenLDAP: [https://www.zytrax.com/books/ldap/](https://www.zytrax.com/books/ldap/). +Some familiarity with the JNDI APIs used to access LDAP from Java may also be useful. +We don’t use any third-party LDAP libraries (Mozilla, JLDAP etc.) in the LDAP provider, but extensive use is made of Spring LDAP, so some familiarity with that project may be useful if you plan on adding your own customizations. + +When using LDAP authentication, it is important to ensure that you configure LDAP connection pooling properly. +If you are unfamiliar with how to do this, you can refer to the [Java LDAP documentation](https://docs.oracle.com/javase/jndi/tutorial/ldap/connect/config.html). + +## Setting up an Embedded LDAP Server + +The first thing you will need to do is to ensure that you have an LDAP Server to point your configuration to. +For simplicity, it often best to start with an embedded LDAP Server. +Spring Security supports using either: + +* [Embedded UnboundID Server](#servlet-authentication-ldap-unboundid) + +* [Embedded ApacheDS Server](#servlet-authentication-ldap-apacheds) + +In the samples below, we expose the following as `users.ldif` as a classpath resource to initialize the embedded LDAP server with the users `user` and `admin` both of which have a password of `password`. + +users.ldif + +``` +dn: ou=groups,dc=springframework,dc=org +objectclass: top +objectclass: organizationalUnit +ou: groups + +dn: ou=people,dc=springframework,dc=org +objectclass: top +objectclass: organizationalUnit +ou: people + +dn: uid=admin,ou=people,dc=springframework,dc=org +objectclass: top +objectclass: person +objectclass: organizationalPerson +objectclass: inetOrgPerson +cn: Rod Johnson +sn: Johnson +uid: admin +userPassword: password + +dn: uid=user,ou=people,dc=springframework,dc=org +objectclass: top +objectclass: person +objectclass: organizationalPerson +objectclass: inetOrgPerson +cn: Dianne Emu +sn: Emu +uid: user +userPassword: password + +dn: cn=user,ou=groups,dc=springframework,dc=org +objectclass: top +objectclass: groupOfNames +cn: user +uniqueMember: uid=admin,ou=people,dc=springframework,dc=org +uniqueMember: uid=user,ou=people,dc=springframework,dc=org + +dn: cn=admin,ou=groups,dc=springframework,dc=org +objectclass: top +objectclass: groupOfNames +cn: admin +uniqueMember: uid=admin,ou=people,dc=springframework,dc=org +``` + +### Embedded UnboundID Server + +If you wish to use [UnboundID](https://ldap.com/unboundid-ldap-sdk-for-java/), then specify the following dependencies: + +Example 1. UnboundID Dependencies + +Maven + +``` + + com.unboundid + unboundid-ldapsdk + 4.0.14 + runtime + +``` + +Gradle + +``` +depenendencies { + runtimeOnly "com.unboundid:unboundid-ldapsdk:4.0.14" +} +``` + +You can then configure the Embedded LDAP Server + +Example 2. Embedded LDAP Server Configuration + +Java + +``` +@Bean +UnboundIdContainer ldapContainer() { + return new UnboundIdContainer("dc=springframework,dc=org", + "classpath:users.ldif"); +} +``` + +XML + +``` + +``` + +Kotlin + +``` +@Bean +fun ldapContainer(): UnboundIdContainer { + return UnboundIdContainer("dc=springframework,dc=org","classpath:users.ldif") +} +``` + +### Embedded ApacheDS Server + +| |Spring Security uses ApacheDS 1.x which is no longer maintained.
Unfortunately, ApacheDS 2.x has only released milestone versions with no stable release.
Once a stable release of ApacheDS 2.x is available, we will consider updating.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +If you wish to use [Apache DS](https://directory.apache.org/apacheds/), then specify the following dependencies: + +Example 3. ApacheDS Dependencies + +Maven + +``` + + org.apache.directory.server + apacheds-core + 1.5.5 + runtime + + + org.apache.directory.server + apacheds-server-jndi + 1.5.5 + runtime + +``` + +Gradle + +``` +depenendencies { + runtimeOnly "org.apache.directory.server:apacheds-core:1.5.5" + runtimeOnly "org.apache.directory.server:apacheds-server-jndi:1.5.5" +} +``` + +You can then configure the Embedded LDAP Server + +Example 4. Embedded LDAP Server Configuration + +Java + +``` +@Bean +ApacheDSContainer ldapContainer() { + return new ApacheDSContainer("dc=springframework,dc=org", + "classpath:users.ldif"); +} +``` + +XML + +``` + +``` + +Kotlin + +``` +@Bean +fun ldapContainer(): ApacheDSContainer { + return ApacheDSContainer("dc=springframework,dc=org", "classpath:users.ldif") +} +``` + +## LDAP ContextSource + +Once you have an LDAP Server to point your configuration to, you need configure Spring Security to point to an LDAP server that should be used to authenticate users. +This is done by creating an LDAP `ContextSource`, which is the equivalent of a JDBC `DataSource`. + +Example 5. LDAP Context Source + +Java + +``` +ContextSource contextSource(UnboundIdContainer container) { + return new DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org"); +} +``` + +XML + +``` + +``` + +Kotlin + +``` +fun contextSource(container: UnboundIdContainer): ContextSource { + return DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org") +} +``` + +## Authentication + +Spring Security’s LDAP support does not use the [UserDetailsService](user-details-service.html#servlet-authentication-userdetailsservice) because LDAP bind authentication does not allow clients to read the password or even a hashed version of the password. +This means there is no way a password to be read and then authenticated by Spring Security. + +For this reason, LDAP support is implemented using the `LdapAuthenticator` interface. +The `LdapAuthenticator` is also responsible for retrieving any required user attributes. +This is because the permissions on the attributes may depend on the type of authentication being used. +For example, if binding as the user, it may be necessary to read them with the user’s own permissions. + +There are two `LdapAuthenticator` implementations supplied with Spring Security: + +* [Using Bind Authentication](#servlet-authentication-ldap-bind) + +* [Using Password Authentication](#servlet-authentication-ldap-pwd) + +## Using Bind Authentication + +[Bind Authentication](https://ldap.com/the-ldap-bind-operation/) is the most common mechanism for authenticating users with LDAP. +In bind authentication the users credentials (i.e. username/password) are submitted to the LDAP server which authenticates them. +The advantage to using bind authentication is that the user’s secrets (i.e. password) do not need to be exposed to clients which helps to protect them from leaking. + +An example of bind authentication configuration can be found below. + +Example 6. Bind Authentication + +Java + +``` +@Bean +BindAuthenticator authenticator(BaseLdapPathContextSource contextSource) { + BindAuthenticator authenticator = new BindAuthenticator(contextSource); + authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); + return authenticator; +} + +@Bean +LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) { + return new LdapAuthenticationProvider(authenticator); +} +``` + +XML + +``` + +``` + +Kotlin + +``` +@Bean +fun authenticator(contextSource: BaseLdapPathContextSource): BindAuthenticator { + val authenticator = BindAuthenticator(contextSource) + authenticator.setUserDnPatterns(arrayOf("uid={0},ou=people")) + return authenticator +} + +@Bean +fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider { + return LdapAuthenticationProvider(authenticator) +} +``` + +This simple example would obtain the DN for the user by substituting the user login name in the supplied pattern and attempting to bind as that user with the login password. +This is OK if all your users are stored under a single node in the directory. +If instead you wished to configure an LDAP search filter to locate the user, you could use the following: + +Example 7. Bind Authentication with Search Filter + +Java + +``` +@Bean +BindAuthenticator authenticator(BaseLdapPathContextSource contextSource) { + String searchBase = "ou=people"; + String filter = "(uid={0})"; + FilterBasedLdapUserSearch search = + new FilterBasedLdapUserSearch(searchBase, filter, contextSource); + BindAuthenticator authenticator = new BindAuthenticator(contextSource); + authenticator.setUserSearch(search); + return authenticator; +} + +@Bean +LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) { + return new LdapAuthenticationProvider(authenticator); +} +``` + +XML + +``` + +``` + +Kotlin + +``` +@Bean +fun authenticator(contextSource: BaseLdapPathContextSource): BindAuthenticator { + val searchBase = "ou=people" + val filter = "(uid={0})" + val search = FilterBasedLdapUserSearch(searchBase, filter, contextSource) + val authenticator = BindAuthenticator(contextSource) + authenticator.setUserSearch(search) + return authenticator +} + +@Bean +fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider { + return LdapAuthenticationProvider(authenticator) +} +``` + +If used with the `ContextSource` [definition above](#servlet-authentication-ldap-contextsource), this would perform a search under the DN `ou=people,dc=springframework,dc=org` using `(uid={0})` as a filter. +Again the user login name is substituted for the parameter in the filter name, so it will search for an entry with the `uid` attribute equal to the user name. +If a user search base isn’t supplied, the search will be performed from the root. + +## Using Password Authentication + +Password comparison is when the password supplied by the user is compared with the one stored in the repository. +This can either be done by retrieving the value of the password attribute and checking it locally or by performing an LDAP "compare" operation, where the supplied password is passed to the server for comparison and the real password value is never retrieved. +An LDAP compare cannot be done when the password is properly hashed with a random salt. + +Example 8. Minimal Password Compare Configuration + +Java + +``` +@Bean +PasswordComparisonAuthenticator authenticator(BaseLdapPathContextSource contextSource) { + return new PasswordComparisonAuthenticator(contextSource); +} + +@Bean +LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) { + return new LdapAuthenticationProvider(authenticator); +} +``` + +XML + +``` + + + +``` + +Kotlin + +``` +@Bean +fun authenticator(contextSource: BaseLdapPathContextSource): PasswordComparisonAuthenticator { + return PasswordComparisonAuthenticator(contextSource) +} + +@Bean +fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider { + return LdapAuthenticationProvider(authenticator) +} +``` + +A more advanced configuration with some customizations can be found below. + +Example 9. Password Compare Configuration + +Java + +``` +@Bean +PasswordComparisonAuthenticator authenticator(BaseLdapPathContextSource contextSource) { + PasswordComparisonAuthenticator authenticator = + new PasswordComparisonAuthenticator(contextSource); + authenticator.setPasswordAttributeName("pwd"); (1) + authenticator.setPasswordEncoder(new BCryptPasswordEncoder()); (2) + return authenticator; +} + +@Bean +LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) { + return new LdapAuthenticationProvider(authenticator); +} +``` + +XML + +``` + + (1) + (2) + + + +``` + +Kotlin + +``` +@Bean +fun authenticator(contextSource: BaseLdapPathContextSource): PasswordComparisonAuthenticator { + val authenticator = PasswordComparisonAuthenticator(contextSource) + authenticator.setPasswordAttributeName("pwd") (1) + authenticator.setPasswordEncoder(BCryptPasswordEncoder()) (2) + return authenticator +} + +@Bean +fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider { + return LdapAuthenticationProvider(authenticator) +} +``` + +|**1**|Specify the password attribute as `pwd`| +|-----|---------------------------------------| +|**2**| Use `BCryptPasswordEncoder` | + +## LdapAuthoritiesPopulator + +Spring Security’s `LdapAuthoritiesPopulator` is used to determine what authorites are returned for the user. + +Example 10. LdapAuthoritiesPopulator Configuration + +Java + +``` +@Bean +LdapAuthoritiesPopulator authorities(BaseLdapPathContextSource contextSource) { + String groupSearchBase = ""; + DefaultLdapAuthoritiesPopulator authorities = + new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase); + authorities.setGroupSearchFilter("member={0}"); + return authorities; +} + +@Bean +LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator, LdapAuthoritiesPopulator authorities) { + return new LdapAuthenticationProvider(authenticator, authorities); +} +``` + +XML + +``` + +``` + +Kotlin + +``` +@Bean +fun authorities(contextSource: BaseLdapPathContextSource): LdapAuthoritiesPopulator { + val groupSearchBase = "" + val authorities = DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase) + authorities.setGroupSearchFilter("member={0}") + return authorities +} + +@Bean +fun authenticationProvider(authenticator: LdapAuthenticator, authorities: LdapAuthoritiesPopulator): LdapAuthenticationProvider { + return LdapAuthenticationProvider(authenticator, authorities) +} +``` + +## Active Directory + +Active Directory supports its own non-standard authentication options, and the normal usage pattern doesn’t fit too cleanly with the standard `LdapAuthenticationProvider`. +Typically authentication is performed using the domain username (in the form `[[email protected]](/cdn-cgi/l/email-protection)`), rather than using an LDAP distinguished name. +To make this easier, Spring Security has an authentication provider which is customized for a typical Active Directory setup. + +Configuring `ActiveDirectoryLdapAuthenticationProvider` is quite straightforward. +You just need to supply the domain name and an LDAP URL supplying the address of the server [1]. +An example configuration can be seen below: + +Example 11. Example Active Directory Configuration + +Java + +``` +@Bean +ActiveDirectoryLdapAuthenticationProvider authenticationProvider() { + return new ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/"); +} +``` + +XML + +``` + + + + +``` + +Kotlin + +``` +@Bean +fun authenticationProvider(): ActiveDirectoryLdapAuthenticationProvider { + return ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/") +} +``` + +--- + +[1](#_footnoteref_1). It is also possible to obtain the server’s IP address using a DNS lookup. This is not currently supported, but hopefully will be in a future version. + +[DaoAuthenticationProvider](dao-authentication-provider.html)[Session Management](../session-management.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-storage-password-encoder.md b/docs/en/spring-security/servlet-authentication-passwords-storage-password-encoder.md new file mode 100644 index 0000000000000000000000000000000000000000..dad4220003147b617a7f43ff777d97b59069a475 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-storage-password-encoder.md @@ -0,0 +1,7 @@ +# PasswordEncoder + +Spring Security’s servlet support storing passwords securely by integrating with [`PasswordEncoder`](../../../features/authentication/password-storage.html#authentication-password-storage). +Customizing the `PasswordEncoder` implementation used by Spring Security can be done by [exposing a `PasswordEncoder` Bean](../../../features/authentication/password-storage.html#authentication-password-storage-configuration). + +[UserDetailsService](user-details-service.html)[DaoAuthenticationProvider](dao-authentication-provider.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-storage-user-details-service.md b/docs/en/spring-security/servlet-authentication-passwords-storage-user-details-service.md new file mode 100644 index 0000000000000000000000000000000000000000..5b2d009950d5b2157af30406b04e59be9ba08fcf --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-storage-user-details-service.md @@ -0,0 +1,37 @@ +# UserDetailsService + +[`UserDetailsService`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/core/userdetails/UserDetailsService.html) is used by [`DaoAuthenticationProvider`](dao-authentication-provider.html#servlet-authentication-daoauthenticationprovider) for retrieving a username, password, and other attributes for authenticating with a username and password. +Spring Security provides [in-memory](in-memory.html#servlet-authentication-inmemory) and [JDBC](jdbc.html#servlet-authentication-jdbc) implementations of `UserDetailsService`. + +You can define custom authentication by exposing a custom `UserDetailsService` as a bean. +For example, the following will customize authentication assuming that `CustomUserDetailsService` implements `UserDetailsService`: + +| |This is only used if the `AuthenticationManagerBuilder` has not been populated and no `AuthenticationProviderBean` is defined.| +|---|------------------------------------------------------------------------------------------------------------------------------| + +Example 1. Custom UserDetailsService Bean + +Java + +``` +@Bean +CustomUserDetailsService customUserDetailsService() { + return new CustomUserDetailsService(); +} +``` + +XML + +``` + +``` + +Kotlin + +``` +@Bean +fun customUserDetailsService() = CustomUserDetailsService() +``` + +[UserDetails](user-details.html)[PasswordEncoder](password-encoder.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-storage-user-details.md b/docs/en/spring-security/servlet-authentication-passwords-storage-user-details.md new file mode 100644 index 0000000000000000000000000000000000000000..1a8d941c469a000cabdb5107a5578f23bc4ab590 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-storage-user-details.md @@ -0,0 +1,7 @@ +# UserDetails + +[`UserDetails`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/core/userdetails/UserDetails.html) is returned by the [`UserDetailsService`](user-details-service.html#servlet-authentication-userdetailsservice). +The [`DaoAuthenticationProvider`](dao-authentication-provider.html#servlet-authentication-daoauthenticationprovider) validates the `UserDetails` and then returns an [`Authentication`](../architecture.html#servlet-authentication-authentication) that has a principal that is the `UserDetails` returned by the configured `UserDetailsService`. + +[JDBC](jdbc.html)[UserDetailsService](user-details-service.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords-storage.md b/docs/en/spring-security/servlet-authentication-passwords-storage.md new file mode 100644 index 0000000000000000000000000000000000000000..5969790faa0b063028ff31ac8fa885064f67ff2d --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords-storage.md @@ -0,0 +1,24 @@ +# Storage Mechanisms + +Each of the supported mechanisms for reading a username and password can leverage any of the supported storage mechanisms: + +* Simple Storage with [In-Memory Authentication](in-memory.html#servlet-authentication-inmemory) + +* Relational Databases with [JDBC Authentication](jdbc.html#servlet-authentication-jdbc) + +* Custom data stores with [UserDetailsService](user-details-service.html#servlet-authentication-userdetailsservice) + +* LDAP storage with [LDAP Authentication](ldap.html#servlet-authentication-ldap) + +## Section Summary + +* [In Memory](in-memory.html) +* [JDBC](jdbc.html) +* [UserDetails](user-details.html) +* [UserDetailsService](user-details-service.html) +* [PasswordEncoder](password-encoder.html) +* [DaoAuthenticationProvider](dao-authentication-provider.html) +* [LDAP](ldap.html) + +[Digest](digest.html)[In Memory](in-memory.html) + diff --git a/docs/en/spring-security/servlet-authentication-passwords.md b/docs/en/spring-security/servlet-authentication-passwords.md new file mode 100644 index 0000000000000000000000000000000000000000..30fe6f8c92d068ea258b5bae5a5ae1bef0430410 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-passwords.md @@ -0,0 +1,12 @@ +# Username/Password Authentication + +One of the most common ways to authenticate a user is by validating a username and password. +As such, Spring Security provides comprehensive support for authenticating with a username and password. + +## Section Summary + +* [Reading Username/Password](input.html) +* [Password Storage](storage.html) + +[Authentication Architecture](../architecture.html)[Reading Username/Password](input.html) + diff --git a/docs/en/spring-security/servlet-authentication-preauth.md b/docs/en/spring-security/servlet-authentication-preauth.md new file mode 100644 index 0000000000000000000000000000000000000000..ddbef24fbd01217dba2607e8411770477d073a59 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-preauth.md @@ -0,0 +1,144 @@ +# Pre-Authentication Scenarios + +Examples include X.509, Siteminder and authentication by the Java EE container in which the application is running. +When using pre-authentication, Spring Security has to + +* Identify the user making the request. + +* Obtain the authorities for the user. + +The details will depend on the external authentication mechanism. +A user might be identified by their certificate information in the case of X.509, or by an HTTP request header in the case of Siteminder. +If relying on container authentication, the user will be identified by calling the `getUserPrincipal()` method on the incoming HTTP request. +In some cases, the external mechanism may supply role/authority information for the user but in others the authorities must be obtained from a separate source, such as a `UserDetailsService`. + +## Pre-Authentication Framework Classes + +Because most pre-authentication mechanisms follow the same pattern, Spring Security has a set of classes which provide an internal framework for implementing pre-authenticated authentication providers. +This removes duplication and allows new implementations to be added in a structured fashion, without having to write everything from scratch. +You don’t need to know about these classes if you want to use something like [X.509 authentication](x509.html#servlet-x509), as it already has a namespace configuration option which is simpler to use and get started with. +If you need to use explicit bean configuration or are planning on writing your own implementation then an understanding of how the provided implementations work will be useful. +You will find classes under the `org.springframework.security.web.authentication.preauth`. +We just provide an outline here so you should consult the Javadoc and source where appropriate. + +### AbstractPreAuthenticatedProcessingFilter + +This class will check the current contents of the security context and, if empty, it will attempt to extract user information from the HTTP request and submit it to the `AuthenticationManager`. +Subclasses override the following methods to obtain this information: + +Example 1. Override AbstractPreAuthenticatedProcessingFilter + +Java + +``` +protected abstract Object getPreAuthenticatedPrincipal(HttpServletRequest request); + +protected abstract Object getPreAuthenticatedCredentials(HttpServletRequest request); +``` + +Kotlin + +``` +protected abstract fun getPreAuthenticatedPrincipal(request: HttpServletRequest): Any? + +protected abstract fun getPreAuthenticatedCredentials(request: HttpServletRequest): Any? +``` + +After calling these, the filter will create a `PreAuthenticatedAuthenticationToken` containing the returned data and submit it for authentication. +By "authentication" here, we really just mean further processing to perhaps load the user’s authorities, but the standard Spring Security authentication architecture is followed. + +Like other Spring Security authentication filters, the pre-authentication filter has an `authenticationDetailsSource` property which by default will create a `WebAuthenticationDetails` object to store additional information such as the session-identifier and originating IP address in the `details` property of the `Authentication` object. +In cases where user role information can be obtained from the pre-authentication mechanism, the data is also stored in this property, with the details implementing the `GrantedAuthoritiesContainer` interface. +This enables the authentication provider to read the authorities which were externally allocated to the user. +We’ll look at a concrete example next. + +#### J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource + +If the filter is configured with an `authenticationDetailsSource` which is an instance of this class, the authority information is obtained by calling the `isUserInRole(String role)` method for each of a pre-determined set of "mappable roles". +The class gets these from a configured `MappableAttributesRetriever`. +Possible implementations include hard-coding a list in the application context and reading the role information from the `` information in a `web.xml` file. +The pre-authentication sample application uses the latter approach. + +There is an additional stage where the roles (or attributes) are mapped to Spring Security `GrantedAuthority` objects using a configured `Attributes2GrantedAuthoritiesMapper`. +The default will just add the usual `ROLE_` prefix to the names, but it gives you full control over the behaviour. + +### PreAuthenticatedAuthenticationProvider + +The pre-authenticated provider has little more to do than load the `UserDetails` object for the user. +It does this by delegating to an `AuthenticationUserDetailsService`. +The latter is similar to the standard `UserDetailsService` but takes an `Authentication` object rather than just user name: + +``` +public interface AuthenticationUserDetailsService { + UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException; +} +``` + +This interface may have also other uses but with pre-authentication it allows access to the authorities which were packaged in the `Authentication` object, as we saw in the previous section. +The `PreAuthenticatedGrantedAuthoritiesUserDetailsService` class does this. +Alternatively, it may delegate to a standard `UserDetailsService` via the `UserDetailsByNameServiceWrapper` implementation. + +### Http403ForbiddenEntryPoint + +The [`AuthenticationEntryPoint`](architecture.html#servlet-authentication-authenticationentrypoint) is responsible for kick-starting the authentication process for an unauthenticated user (when they try to access a protected resource), but in the pre-authenticated case this doesn’t apply. +You would only configure the `ExceptionTranslationFilter` with an instance of this class if you aren’t using pre-authentication in combination with other authentication mechanisms. +It will be called if the user is rejected by the `AbstractPreAuthenticatedProcessingFilter` resulting in a null authentication. +It always returns a `403`-forbidden response code if called. + +## Concrete Implementations + +X.509 authentication is covered in its [own chapter](x509.html#servlet-x509). +Here we’ll look at some classes which provide support for other pre-authenticated scenarios. + +### + +An external authentication system may supply information to the application by setting specific headers on the HTTP request. +A well-known example of this is Siteminder, which passes the username in a header called `SM_USER`. +This mechanism is supported by the class `RequestHeaderAuthenticationFilter` which simply extracts the username from the header. +It defaults to using the name `SM_USER` as the header name. +See the Javadoc for more details. + +| |Note that when using a system like this, the framework performs no authentication checks at all and it is *extremely* important that the external system is configured properly and protects all access to the application.
If an attacker is able to forge the headers in their original request without this being detected then they could potentially choose any username they wished.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +#### Siteminder Example Configuration + +A typical configuration using this filter would look like this: + +``` + + + + + + + + + + + + + + + + + + + + + +``` + +We’ve assumed here that the [security namespace](../configuration/xml-namespace.html#ns-config) is being used for configuration. +It’s also assumed that you have added a `UserDetailsService` (called "userDetailsService") to your configuration to load the user’s roles. + +### Java EE Container Authentication + +The class `J2eePreAuthenticatedProcessingFilter` will extract the username from the `userPrincipal` property of the `HttpServletRequest`. +Use of this filter would usually be combined with the use of Java EE roles as described above in [J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource](#j2ee-preauth-details). + +There is a [sample application](https://github.com/spring-projects/spring-security/tree/5.4.x/samples/xml/preauth) in the samples project which uses this approach, so get hold of the code from GitHub and have a look at the application context file if you are interested. + +[Anonymous](anonymous.html)[JAAS](jaas.html) + diff --git a/docs/en/spring-security/servlet-authentication-rememberme.md b/docs/en/spring-security/servlet-authentication-rememberme.md new file mode 100644 index 0000000000000000000000000000000000000000..0deedcdf921670d3c0a2ed7d4148059c74105552 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-rememberme.md @@ -0,0 +1,137 @@ +# Remember-Me Authentication + +## Overview + +Remember-me or persistent-login authentication refers to web sites being able to remember the identity of a principal between sessions. +This is typically accomplished by sending a cookie to the browser, with the cookie being detected during future sessions and causing automated login to take place. +Spring Security provides the necessary hooks for these operations to take place, and has two concrete remember-me implementations. +One uses hashing to preserve the security of cookie-based tokens and the other uses a database or other persistent storage mechanism to store the generated tokens. + +Note that both implementations require a `UserDetailsService`. +If you are using an authentication provider which doesn’t use a `UserDetailsService` (for example, the LDAP provider) then it won’t work unless you also have a `UserDetailsService` bean in your application context. + +## Simple Hash-Based Token Approach + +This approach uses hashing to achieve a useful remember-me strategy. +In essence a cookie is sent to the browser upon successful interactive authentication, with the cookie being composed as follows: + +``` +base64(username + ":" + expirationTime + ":" + +md5Hex(username + ":" + expirationTime + ":" password + ":" + key)) + +username: As identifiable to the UserDetailsService +password: That matches the one in the retrieved UserDetails +expirationTime: The date and time when the remember-me token expires, expressed in milliseconds +key: A private key to prevent modification of the remember-me token +``` + +As such the remember-me token is valid only for the period specified, and provided that the username, password and key does not change. +Notably, this has a potential security issue in that a captured remember-me token will be usable from any user agent until such time as the token expires. +This is the same issue as with digest authentication. +If a principal is aware a token has been captured, they can easily change their password and immediately invalidate all remember-me tokens on issue. +If more significant security is needed you should use the approach described in the next section. +Alternatively, remember-me services should simply not be used at all. + +If you are familiar with the topics discussed in the chapter on [namespace configuration](../configuration/xml-namespace.html#ns-config), you can enable remember-me authentication just by adding the `` element: + +``` + +... + + +``` + +The `UserDetailsService` will normally be selected automatically. +If you have more than one in your application context, you need to specify which one should be used with the `user-service-ref` attribute, where the value is the name of your `UserDetailsService` bean. + +## Persistent Token Approach + +This approach is based on the article [http://jaspan.com/improved\_persistent\_login\_cookie\_best\_practice](https://web.archive.org/web/20180819014446/http://jaspan.com/improved_persistent_login_cookie_best_practice) with some minor modifications [1]. +To use the this approach with namespace configuration, you would supply a datasource reference: + +``` + +... + + +``` + +The database should contain a `persistent_logins` table, created using the following SQL (or equivalent): + +``` +create table persistent_logins (username varchar(64) not null, + series varchar(64) primary key, + token varchar(64) not null, + last_used timestamp not null) +``` + +## Remember-Me Interfaces and Implementations + +Remember-me is used with `UsernamePasswordAuthenticationFilter`, and is implemented via hooks in the `AbstractAuthenticationProcessingFilter` superclass. +It is also used within `BasicAuthenticationFilter`. +The hooks will invoke a concrete `RememberMeServices` at the appropriate times. +The interface looks like this: + +``` +Authentication autoLogin(HttpServletRequest request, HttpServletResponse response); + +void loginFail(HttpServletRequest request, HttpServletResponse response); + +void loginSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication successfulAuthentication); +``` + +Please refer to the Javadoc for a fuller discussion on what the methods do, although note at this stage that `AbstractAuthenticationProcessingFilter` only calls the `loginFail()` and `loginSuccess()` methods. +The `autoLogin()` method is called by `RememberMeAuthenticationFilter` whenever the `SecurityContextHolder` does not contain an `Authentication`. +This interface therefore provides the underlying remember-me implementation with sufficient notification of authentication-related events, and delegates to the implementation whenever a candidate web request might contain a cookie and wish to be remembered. +This design allows any number of remember-me implementation strategies. +We’ve seen above that Spring Security provides two implementations. +We’ll look at these in turn. + +### TokenBasedRememberMeServices + +This implementation supports the simpler approach described in [Simple Hash-Based Token Approach](#remember-me-hash-token).`TokenBasedRememberMeServices` generates a `RememberMeAuthenticationToken`, which is processed by `RememberMeAuthenticationProvider`. +A `key` is shared between this authentication provider and the `TokenBasedRememberMeServices`. +In addition, `TokenBasedRememberMeServices` requires A UserDetailsService from which it can retrieve the username and password for signature comparison purposes, and generate the `RememberMeAuthenticationToken` to contain the correct `GrantedAuthority`s. +Some sort of logout command should be provided by the application that invalidates the cookie if the user requests this.`TokenBasedRememberMeServices` also implements Spring Security’s `LogoutHandler` interface so can be used with `LogoutFilter` to have the cookie cleared automatically. + +The beans required in an application context to enable remember-me services are as follows: + +``` + + + + + + + + + + + + + +``` + +Don’t forget to add your `RememberMeServices` implementation to your `UsernamePasswordAuthenticationFilter.setRememberMeServices()` property, include the `RememberMeAuthenticationProvider` in your `AuthenticationManager.setProviders()` list, and add `RememberMeAuthenticationFilter` into your `FilterChainProxy` (typically immediately after your `UsernamePasswordAuthenticationFilter`). + +### PersistentTokenBasedRememberMeServices + +This class can be used in the same way as `TokenBasedRememberMeServices`, but it additionally needs to be configured with a `PersistentTokenRepository` to store the tokens. +There are two standard implementations. + +* `InMemoryTokenRepositoryImpl` which is intended for testing only. + +* `JdbcTokenRepositoryImpl` which stores the tokens in a database. + +The database schema is described above in [Persistent Token Approach](#remember-me-persistent-token). + +--- + +[1](#_footnoteref_1). Essentially, the username is not included in the cookie, to prevent exposing a valid login name unecessarily. There is a discussion on this in the comments section of this article. + +[Session Management](session-management.html)[OpenID](openid.html) + diff --git a/docs/en/spring-security/servlet-authentication-runas.md b/docs/en/spring-security/servlet-authentication-runas.md new file mode 100644 index 0000000000000000000000000000000000000000..a4b629678d36cfc72a907cf82425c73ad2ca67d3 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-runas.md @@ -0,0 +1,61 @@ +# Run-As Authentication Replacement + +## Overview + +The `AbstractSecurityInterceptor` is able to temporarily replace the `Authentication` object in the `SecurityContext` and `SecurityContextHolder` during the secure object callback phase. +This only occurs if the original `Authentication` object was successfully processed by the `AuthenticationManager` and `AccessDecisionManager`. +The `RunAsManager` will indicate the replacement `Authentication` object, if any, that should be used during the `SecurityInterceptorCallback`. + +By temporarily replacing the `Authentication` object during the secure object callback phase, the secured invocation will be able to call other objects which require different authentication and authorization credentials. +It will also be able to perform any internal security checks for specific `GrantedAuthority` objects. +Because Spring Security provides a number of helper classes that automatically configure remoting protocols based on the contents of the `SecurityContextHolder`, these run-as replacements are particularly useful when calling remote web services. + +## Configuration + +A `RunAsManager` interface is provided by Spring Security: + +``` +Authentication buildRunAs(Authentication authentication, Object object, + List config); + +boolean supports(ConfigAttribute attribute); + +boolean supports(Class clazz); +``` + +The first method returns the `Authentication` object that should replace the existing `Authentication` object for the duration of the method invocation. +If the method returns `null`, it indicates no replacement should be made. +The second method is used by the `AbstractSecurityInterceptor` as part of its startup validation of configuration attributes. +The `supports(Class)` method is called by a security interceptor implementation to ensure the configured `RunAsManager` supports the type of secure object that the security interceptor will present. + +One concrete implementation of a `RunAsManager` is provided with Spring Security. +The `RunAsManagerImpl` class returns a replacement `RunAsUserToken` if any `ConfigAttribute` starts with `RUN_AS_`. +If any such `ConfigAttribute` is found, the replacement `RunAsUserToken` will contain the same principal, credentials and granted authorities as the original `Authentication` object, along with a new `SimpleGrantedAuthority` for each `RUN_AS_` `ConfigAttribute`. +Each new `SimpleGrantedAuthority` will be prefixed with `ROLE_`, followed by the `RUN_AS` `ConfigAttribute`. +For example, a `RUN_AS_SERVER` will result in the replacement `RunAsUserToken` containing a `ROLE_RUN_AS_SERVER` granted authority. + +The replacement `RunAsUserToken` is just like any other `Authentication` object. +It needs to be authenticated by the `AuthenticationManager`, probably via delegation to a suitable `AuthenticationProvider`. +The `RunAsImplAuthenticationProvider` performs such authentication. +It simply accepts as valid any `RunAsUserToken` presented. + +To ensure malicious code does not create a `RunAsUserToken` and present it for guaranteed acceptance by the `RunAsImplAuthenticationProvider`, the hash of a key is stored in all generated tokens. +The `RunAsManagerImpl` and `RunAsImplAuthenticationProvider` is created in the bean context with the same key: + +``` + + + + + + + +``` + +By using the same key, each `RunAsUserToken` can be validated it was created by an approved `RunAsManagerImpl`. +The `RunAsUserToken` is immutable after creation for security reasons + +[X509](x509.html)[Logout](logout.html) + diff --git a/docs/en/spring-security/servlet-authentication-session-management.md b/docs/en/spring-security/servlet-authentication-session-management.md new file mode 100644 index 0000000000000000000000000000000000000000..3adc112f1c861bdeaf92ed4e7a026f48c48fe665 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-session-management.md @@ -0,0 +1,298 @@ +# Session Management + +## Detecting Timeouts + +You can configure Spring Security to detect the submission of an invalid session ID and redirect the user to an appropriate URL. +This is achieved through the `session-management` element: + +Java + +``` +@Override +protected void configure(HttpSecurity http) throws Exception{ + http + .sessionManagement(session -> session + .invalidSessionUrl("/invalidSession.htm") + ); +} +``` + +XML + +``` + +... + + +``` + +Note that if you use this mechanism to detect session timeouts, it may falsely report an error if the user logs out and then logs back in without closing the browser. +This is because the session cookie is not cleared when you invalidate the session and will be resubmitted even if the user has logged out. +You may be able to explicitly delete the JSESSIONID cookie on logging out, for example by using the following syntax in the logout handler: + +Java + +``` +@Override +protected void configure(HttpSecurity http) throws Exception{ + http + .logout(logout -> logout + .deleteCookies("JSESSIONID") + ); +} +``` + +XML + +``` + + + +``` + +Unfortunately this can’t be guaranteed to work with every servlet container, so you will need to test it in your environment + +| |If you are running your application behind a proxy, you may also be able to remove the session cookie by configuring the proxy server.
For example, using Apache HTTPD’s mod\_headers, the following directive would delete the `JSESSIONID` cookie by expiring it in the response to a logout request (assuming the application is deployed under the path `/tutorial`):

```

Header always set Set-Cookie "JSESSIONID=;Path=/tutorial;Expires=Thu, 01 Jan 1970 00:00:00 GMT"

```| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## Concurrent Session Control + +If you wish to place constraints on a single user’s ability to log in to your application, Spring Security supports this out of the box with the following simple additions. +First, you need to add the following listener to your configuration to keep Spring Security updated about session lifecycle events: + +Java + +``` +@Bean +public HttpSessionEventPublisher httpSessionEventPublisher() { + return new HttpSessionEventPublisher(); +} +``` + +XML + +``` + + + org.springframework.security.web.session.HttpSessionEventPublisher + + +``` + +Then add the following lines to your application context: + +Java + +``` +@Override +protected void configure(HttpSecurity http) throws Exception { + http + .sessionManagement(session -> session + .maximumSessions(1) + ); +} +``` + +XML + +``` + +... + + + + +``` + +This will prevent a user from logging in multiple times - a second login will cause the first to be invalidated. +Often you would prefer to prevent a second login, in which case you can use + +Java + +``` +@Override +protected void configure(HttpSecurity http) throws Exception { + http + .sessionManagement(session -> session + .maximumSessions(1) + .maxSessionsPreventsLogin(true) + ); +} +``` + +XML + +``` + + + + + +``` + +The second login will then be rejected. +By "rejected", we mean that the user will be sent to the `authentication-failure-url` if form-based login is being used. +If the second authentication takes place through another non-interactive mechanism, such as "remember-me", an "unauthorized" (401) error will be sent to the client. +If instead you want to use an error page, you can add the attribute `session-authentication-error-url` to the `session-management` element. + +If you are using a customized authentication filter for form-based login, then you have to configure concurrent session control support explicitly. +More details can be found in the [Session Management chapter](#session-mgmt). + +## Session Fixation Attack Protection + +[Session fixation](https://en.wikipedia.org/wiki/Session_fixation) attacks are a potential risk where it is possible for a malicious attacker to create a session by accessing a site, then persuade another user to log in with the same session (by sending them a link containing the session identifier as a parameter, for example). +Spring Security protects against this automatically by creating a new session or otherwise changing the session ID when a user logs in. +If you don’t require this protection, or it conflicts with some other requirement, you can control the behavior using the `session-fixation-protection` attribute on ``, which has four options + +* `none` - Don’t do anything. + The original session will be retained. + +* `newSession` - Create a new "clean" session, without copying the existing session data (Spring Security-related attributes will still be copied). + +* `migrateSession` - Create a new session and copy all existing session attributes to the new session. + This is the default in Servlet 3.0 or older containers. + +* `changeSessionId` - Do not create a new session. + Instead, use the session fixation protection provided by the Servlet container (`HttpServletRequest#changeSessionId()`). + This option is only available in Servlet 3.1 (Java EE 7) and newer containers. + Specifying it in older containers will result in an exception. + This is the default in Servlet 3.1 and newer containers. + +When session fixation protection occurs, it results in a `SessionFixationProtectionEvent` being published in the application context. +If you use `changeSessionId`, this protection will *also* result in any `javax.servlet.http.HttpSessionIdListener`s being notified, so use caution if your code listens for both events. +See the [Session Management](#session-mgmt) chapter for additional information. + +## SessionManagementFilter + +The `SessionManagementFilter` checks the contents of the `SecurityContextRepository` against the current contents of the `SecurityContextHolder` to determine whether a user has been authenticated during the current request, typically by a non-interactive authentication mechanism, such as pre-authentication or remember-me [1]. +If the repository contains a security context, the filter does nothing. +If it doesn’t, and the thread-local `SecurityContext` contains a (non-anonymous) `Authentication` object, the filter assumes they have been authenticated by a previous filter in the stack. +It will then invoke the configured `SessionAuthenticationStrategy`. + +If the user is not currently authenticated, the filter will check whether an invalid session ID has been requested (because of a timeout, for example) and will invoke the configured `InvalidSessionStrategy`, if one is set. +The most common behaviour is just to redirect to a fixed URL and this is encapsulated in the standard implementation `SimpleRedirectInvalidSessionStrategy`. +The latter is also used when configuring an invalid session URL through the namespace, [as described earlier](#session-mgmt). + +## SessionAuthenticationStrategy + +`SessionAuthenticationStrategy` is used by both `SessionManagementFilter` and `AbstractAuthenticationProcessingFilter`, so if you are using a customized form-login class, for example, you will need to inject it into both of these. +In this case, a typical configuration, combining the namespace and custom beans might look like this: + +``` + + + + + + + + ... + + + +``` + +Note that the use of the default, `SessionFixationProtectionStrategy` may cause issues if you are storing beans in the session which implement `HttpSessionBindingListener`, including Spring session-scoped beans. +See the Javadoc for this class for more information. + +## Concurrency Control + +Spring Security is able to prevent a principal from concurrently authenticating to the same application more than a specified number of times. +Many ISVs take advantage of this to enforce licensing, whilst network administrators like this feature because it helps prevent people from sharing login names. +You can, for example, stop user "Batman" from logging onto the web application from two different sessions. +You can either expire their previous login or you can report an error when they try to log in again, preventing the second login. +Note that if you are using the second approach, a user who has not explicitly logged out (but who has just closed their browser, for example) will not be able to log in again until their original session expires. + +Concurrency control is supported by the namespace, so please check the earlier namespace chapter for the simplest configuration. +Sometimes you need to customize things though. + +The implementation uses a specialized version of `SessionAuthenticationStrategy`, called `ConcurrentSessionControlAuthenticationStrategy`. + +| |Previously the concurrent authentication check was made by the `ProviderManager`, which could be injected with a `ConcurrentSessionController`.
The latter would check if the user was attempting to exceed the number of permitted sessions.
However, this approach required that an HTTP session be created in advance, which is undesirable.
In Spring Security 3, the user is first authenticated by the `AuthenticationManager` and once they are successfully authenticated, a session is created and the check is made whether they are allowed to have another session open.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +To use concurrent session support, you’ll need to add the following to `web.xml`: + +``` + + + org.springframework.security.web.session.HttpSessionEventPublisher + + +``` + +In addition, you will need to add the `ConcurrentSessionFilter` to your `FilterChainProxy`. +The `ConcurrentSessionFilter` requires two constructor arguments, `sessionRegistry`, which generally points to an instance of `SessionRegistryImpl`, and `sessionInformationExpiredStrategy`, which defines the strategy to apply when a session has expired. +A configuration using the namespace to create the `FilterChainProxy` and other default beans might look like this: + +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +Adding the listener to `web.xml` causes an `ApplicationEvent` to be published to the Spring `ApplicationContext` every time a `HttpSession` commences or ends. +This is critical, as it allows the `SessionRegistryImpl` to be notified when a session ends. +Without it, a user will never be able to log back in again once they have exceeded their session allowance, even if they log out of another session or it times out. + +### Querying the SessionRegistry for currently authenticated users and their sessions + +Setting up concurrency-control, either through the namespace or using plain beans has the useful side effect of providing you with a reference to the `SessionRegistry` which you can use directly within your application, so even if you don’t want to restrict the number of sessions a user may have, it may be worth setting up the infrastructure anyway. +You can set the `maximumSession` property to -1 to allow unlimited sessions. +If you’re using the namespace, you can set an alias for the internally-created `SessionRegistry` using the `session-registry-alias` attribute, providing a reference which you can inject into your own beans. + +The `getAllPrincipals()` method supplies you with a list of the currently authenticated users. +You can list a user’s sessions by calling the `getAllSessions(Object principal, boolean includeExpiredSessions)` method, which returns a list of `SessionInformation` objects. +You can also expire a user’s session by calling `expireNow()` on a `SessionInformation` instance. +When the user returns to the application, they will be prevented from proceeding. +You may find these methods useful in an administration application, for example. +Have a look at the Javadoc for more information. + +--- + +[1](#_footnoteref_1). Authentication by mechanisms which perform a redirect after authenticating (such as form-login) will not be detected by `SessionManagementFilter`, as the filter will not be invoked during the authenticating request. Session-management functionality has to be handled separately in these cases. + +[LDAP](passwords/ldap.html)[Remember Me](rememberme.html) + diff --git a/docs/en/spring-security/servlet-authentication-x509.md b/docs/en/spring-security/servlet-authentication-x509.md new file mode 100644 index 0000000000000000000000000000000000000000..f2374d11784a0c822345e84cecd2c4ae757741a6 --- /dev/null +++ b/docs/en/spring-security/servlet-authentication-x509.md @@ -0,0 +1,75 @@ +# X.509 Authentication + +## Overview + +The most common use of X.509 certificate authentication is in verifying the identity of a server when using SSL, most commonly when using HTTPS from a browser. +The browser will automatically check that the certificate presented by a server has been issued (ie digitally signed) by one of a list of trusted certificate authorities which it maintains. + +You can also use SSL with "mutual authentication"; the server will then request a valid certificate from the client as part of the SSL handshake. +The server will authenticate the client by checking that its certificate is signed by an acceptable authority. +If a valid certificate has been provided, it can be obtained through the servlet API in an application. +Spring Security X.509 module extracts the certificate using a filter. +It maps the certificate to an application user and loads that user’s set of granted authorities for use with the standard Spring Security infrastructure. + +You should be familiar with using certificates and setting up client authentication for your servlet container before attempting to use it with Spring Security. +Most of the work is in creating and installing suitable certificates and keys. +For example, if you’re using Tomcat then read the instructions here [https://tomcat.apache.org/tomcat-9.0-doc/ssl-howto.html](https://tomcat.apache.org/tomcat-9.0-doc/ssl-howto.html). +It’s important that you get this working before trying it out with Spring Security + +## Adding X.509 Authentication to Your Web Application + +Enabling X.509 client authentication is very straightforward. +Just add the `` element to your http security namespace configuration. + +``` + +... + ; + +``` + +The element has two optional attributes: + +* `subject-principal-regex`. + The regular expression used to extract a username from the certificate’s subject name. + The default value is shown above. + This is the username which will be passed to the `UserDetailsService` to load the authorities for the user. + +* `user-service-ref`. + This is the bean Id of the `UserDetailsService` to be used with X.509. + It isn’t needed if there is only one defined in your application context. + +The `subject-principal-regex` should contain a single group. +For example the default expression "CN=(.\*?)," matches the common name field. +So if the subject name in the certificate is "CN=Jimi Hendrix, OU=…​", this will give a user name of "Jimi Hendrix". +The matches are case insensitive. +So "emailAddress=(.\*?)," will match "EMAILADDRESS=[[email protected]](/cdn-cgi/l/email-protection#244e4d494d644c414a40564d5c0a4b5643),CN=…​" giving a user name "[[email protected]](/cdn-cgi/l/email-protection#1a707377735a727f747e6873623475687d)". +If the client presents a certificate and a valid username is successfully extracted, then there should be a valid `Authentication` object in the security context. +If no certificate is found, or no corresponding user could be found then the security context will remain empty. +This means that you can easily use X.509 authentication with other options such as a form-based login. + +## Setting up SSL in Tomcat + +There are some pre-generated certificates in the [Spring Security Samples repository](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/servlet/java-configuration/authentication/x509/server). +You can use these to enable SSL for testing if you don’t want to generate your own. +The file `server.jks` contains the server certificate, private key and the issuing certificate authority certificate. +There are also some client certificate files for the users from the sample applications. +You can install these in your browser to enable SSL client authentication. + +To run tomcat with SSL support, drop the `server.jks` file into the tomcat `conf` directory and add the following connector to the `server.xml` file + +``` + +``` + +`clientAuth` can also be set to `want` if you still want SSL connections to succeed even if the client doesn’t provide a certificate. +Clients which don’t present a certificate won’t be able to access any objects secured by Spring Security unless you use a non-X.509 authentication mechanism, such as form authentication. + +[CAS](cas.html)[Run-As](runas.html) + diff --git a/docs/en/spring-security/servlet-authentication.md b/docs/en/spring-security/servlet-authentication.md new file mode 100644 index 0000000000000000000000000000000000000000..a517d13ff59600490aed65ae5d8743f2300f5f6d --- /dev/null +++ b/docs/en/spring-security/servlet-authentication.md @@ -0,0 +1,31 @@ +# Authentication + +Spring Security provides comprehensive support for [Authentication](../../features/authentication/index.html#authentication). +We start by discussing the overall [Servlet Authentication Architecture](../architecture.html#servlet-architecture). +As you might expect, this section is more abstract describing the architecture without much discussion on how it applies to concrete flows. + +If you prefer, you can refer to [Authentication Mechanisms](#servlet-authentication-mechanisms) for concrete ways in which users can authenticate. +These sections focus on specific ways you may want to authenticate and point back at the architecture sections to describe how the specific flows work. + +## Authentication Mechanisms + +* [Username and Password](passwords/index.html#servlet-authentication-unpwd) - how to authenticate with a username/password + +* [OAuth 2.0 Login](../oauth2/login/index.html#oauth2login) - OAuth 2.0 Log In with OpenID Connect and non-standard OAuth 2.0 Login (i.e. GitHub) + +* [SAML 2.0 Login](../saml2/index.html#servlet-saml2) - SAML 2.0 Log In + +* [Central Authentication Server (CAS)](cas.html#servlet-cas) - Central Authentication Server (CAS) Support + +* [Remember Me](rememberme.html#servlet-rememberme) - how to remember a user past session expiration + +* [JAAS Authentication](jaas.html#servlet-jaas) - authenticate with JAAS + +* [OpenID](openid.html#servlet-openid) - OpenID Authentication (not to be confused with OpenID Connect) + +* [Pre-Authentication Scenarios](preauth.html#servlet-preauth) - authenticate with an external mechanism such as [SiteMinder](https://www.siteminder.com/) or Java EE security but still use Spring Security for authorization and protection against common exploits. + +* [X509 Authentication](x509.html#servlet-x509) - X509 Authentication + +[Architecture](../architecture.html)[Authentication Architecture](architecture.html) + diff --git a/docs/en/spring-security/servlet-authorization-.md b/docs/en/spring-security/servlet-authorization-.md new file mode 100644 index 0000000000000000000000000000000000000000..26c407138104fbf5615916b8488db05e12ced625 --- /dev/null +++ b/docs/en/spring-security/servlet-authorization-.md @@ -0,0 +1,20 @@ +# Authorization + +The advanced authorization capabilities within Spring Security represent one of the most compelling reasons for its popularity. +Irrespective of how you choose to authenticate - whether using a Spring Security-provided mechanism and provider, or integrating with a container or other non-Spring Security authentication authority - you will find the authorization services can be used within your application in a consistent and simple way. + +In this part we’ll explore the different `AbstractSecurityInterceptor` implementations, which were introduced in Part I. +We then move on to explore how to fine-tune authorization through use of domain access control lists. + +## Section Summary + +* [Authorization Architecture](architecture.html) +* [Authorize HTTP Requests](authorize-http-requests.html) +* [Authorize HTTP Requests with FilterSecurityInterceptor](authorize-requests.html) +* [Expression-Based Access Control](expression-based.html) +* [Secure Object Implementations](secure-objects.html) +* [Method Security](method-security.html) +* [Domain Object Security ACLs](acls.html) + +[Authentication Events](../authentication/events.html)[Authorization Architecture](architecture.html) + diff --git a/docs/en/spring-security/servlet-authorization-acls.md b/docs/en/spring-security/servlet-authorization-acls.md new file mode 100644 index 0000000000000000000000000000000000000000..bdbdb6ec45f6291522d64b20ad6b0759b443f46d --- /dev/null +++ b/docs/en/spring-security/servlet-authorization-acls.md @@ -0,0 +1,206 @@ +# Domain Object Security (ACLs) + +## Overview + +Complex applications often will find the need to define access permissions not simply at a web request or method invocation level. +Instead, security decisions need to comprise both who (`Authentication`), where (`MethodInvocation`) and what (`SomeDomainObject`). +In other words, authorization decisions also need to consider the actual domain object instance subject of a method invocation. + +Imagine you’re designing an application for a pet clinic. +There will be two main groups of users of your Spring-based application: staff of the pet clinic, as well as the pet clinic’s customers. +The staff will have access to all of the data, whilst your customers will only be able to see their own customer records. +To make it a little more interesting, your customers can allow other users to see their customer records, such as their "puppy preschool" mentor or president of their local "Pony Club". +Using Spring Security as the foundation, you have several approaches that can be used: + +* Write your business methods to enforce the security. + You could consult a collection within the `Customer` domain object instance to determine which users have access. + By using the `SecurityContextHolder.getContext().getAuthentication()`, you’ll be able to access the `Authentication` object. + +* Write an `AccessDecisionVoter` to enforce the security from the `GrantedAuthority[]`s stored in the `Authentication` object. + This would mean your `AuthenticationManager` would need to populate the `Authentication` with custom `GrantedAuthority[]`s representing each of the `Customer` domain object instances the principal has access to. + +* Write an `AccessDecisionVoter` to enforce the security and open the target `Customer` domain object directly. + This would mean your voter needs access to a DAO that allows it to retrieve the `Customer` object. + It would then access the `Customer` object’s collection of approved users and make the appropriate decision. + +Each one of these approaches is perfectly legitimate. +However, the first couples your authorization checking to your business code. +The main problems with this include the enhanced difficulty of unit testing and the fact it would be more difficult to reuse the `Customer` authorization logic elsewhere. +Obtaining the `GrantedAuthority[]`s from the `Authentication` object is also fine, but will not scale to large numbers of `Customer`s. +If a user might be able to access 5,000 `Customer`s (unlikely in this case, but imagine if it were a popular vet for a large Pony Club!) the amount of memory consumed and time required to construct the `Authentication` object would be undesirable. +The final method, opening the `Customer` directly from external code, is probably the best of the three. +It achieves separation of concerns, and doesn’t misuse memory or CPU cycles, but it is still inefficient in that both the `AccessDecisionVoter` and the eventual business method itself will perform a call to the DAO responsible for retrieving the `Customer` object. +Two accesses per method invocation is clearly undesirable. +In addition, with every approach listed you’ll need to write your own access control list (ACL) persistence and business logic from scratch. + +Fortunately, there is another alternative, which we’ll talk about below. + +## Key Concepts + +Spring Security’s ACL services are shipped in the `spring-security-acl-xxx.jar`. +You will need to add this JAR to your classpath to use Spring Security’s domain object instance security capabilities. + +Spring Security’s domain object instance security capabilities centre on the concept of an access control list (ACL). +Every domain object instance in your system has its own ACL, and the ACL records details of who can and can’t work with that domain object. +With this in mind, Spring Security delivers three main ACL-related capabilities to your application: + +* A way of efficiently retrieving ACL entries for all of your domain objects (and modifying those ACLs) + +* A way of ensuring a given principal is permitted to work with your objects, before methods are called + +* A way of ensuring a given principal is permitted to work with your objects (or something they return), after methods are called + +As indicated by the first bullet point, one of the main capabilities of the Spring Security ACL module is providing a high-performance way of retrieving ACLs. +This ACL repository capability is extremely important, because every domain object instance in your system might have several access control entries, and each ACL might inherit from other ACLs in a tree-like structure (this is supported out-of-the-box by Spring Security, and is very commonly used). +Spring Security’s ACL capability has been carefully designed to provide high performance retrieval of ACLs, together with pluggable caching, deadlock-minimizing database updates, independence from ORM frameworks (we use JDBC directly), proper encapsulation, and transparent database updating. + +Given databases are central to the operation of the ACL module, let’s explore the four main tables used by default in the implementation. +The tables are presented below in order of size in a typical Spring Security ACL deployment, with the table with the most rows listed last: + +* ACL\_SID allows us to uniquely identify any principal or authority in the system ("SID" stands for "security identity"). + The only columns are the ID, a textual representation of the SID, and a flag to indicate whether the textual representation refers to a principal name or a `GrantedAuthority`. + Thus, there is a single row for each unique principal or `GrantedAuthority`. + When used in the context of receiving a permission, a SID is generally called a "recipient". + +* ACL\_CLASS allows us to uniquely identify any domain object class in the system. + The only columns are the ID and the Java class name. + Thus, there is a single row for each unique Class we wish to store ACL permissions for. + +* ACL\_OBJECT\_IDENTITY stores information for each unique domain object instance in the system. + Columns include the ID, a foreign key to the ACL\_CLASS table, a unique identifier so we know which ACL\_CLASS instance we’re providing information for, the parent, a foreign key to the ACL\_SID table to represent the owner of the domain object instance, and whether we allow ACL entries to inherit from any parent ACL. + We have a single row for every domain object instance we’re storing ACL permissions for. + +* Finally, ACL\_ENTRY stores the individual permissions assigned to each recipient. + Columns include a foreign key to the ACL\_OBJECT\_IDENTITY, the recipient (i.e. a foreign key to ACL\_SID), whether we’ll be auditing or not, and the integer bit mask that represents the actual permission being granted or denied. + We have a single row for every recipient that receives a permission to work with a domain object. + +As mentioned in the last paragraph, the ACL system uses integer bit masking. +Don’t worry, you need not be aware of the finer points of bit shifting to use the ACL system, but suffice to say that we have 32 bits we can switch on or off. +Each of these bits represents a permission, and by default the permissions are read (bit 0), write (bit 1), create (bit 2), delete (bit 3) and administer (bit 4). +It’s easy to implement your own `Permission` instance if you wish to use other permissions, and the remainder of the ACL framework will operate without knowledge of your extensions. + +It is important to understand that the number of domain objects in your system has absolutely no bearing on the fact we’ve chosen to use integer bit masking. +Whilst you have 32 bits available for permissions, you could have billions of domain object instances (which will mean billions of rows in ACL\_OBJECT\_IDENTITY and quite probably ACL\_ENTRY). +We make this point because we’ve found sometimes people mistakenly believe they need a bit for each potential domain object, which is not the case. + +Now that we’ve provided a basic overview of what the ACL system does, and what it looks like at a table structure, let’s explore the key interfaces. +The key interfaces are: + +* `Acl`: Every domain object has one and only one `Acl` object, which internally holds the `AccessControlEntry`s as well as knows the owner of the `Acl`. + An Acl does not refer directly to the domain object, but instead to an `ObjectIdentity`. + The `Acl` is stored in the ACL\_OBJECT\_IDENTITY table. + +* `AccessControlEntry`: An `Acl` holds multiple `AccessControlEntry`s, which are often abbreviated as ACEs in the framework. + Each ACE refers to a specific tuple of `Permission`, `Sid` and `Acl`. + An ACE can also be granting or non-granting and contain audit settings. + The ACE is stored in the ACL\_ENTRY table. + +* `Permission`: A permission represents a particular immutable bit mask, and offers convenience functions for bit masking and outputting information. + The basic permissions presented above (bits 0 through 4) are contained in the `BasePermission` class. + +* `Sid`: The ACL module needs to refer to principals and `GrantedAuthority[]`s. + A level of indirection is provided by the `Sid` interface, which is an abbreviation of "security identity". + Common classes include `PrincipalSid` (to represent the principal inside an `Authentication` object) and `GrantedAuthoritySid`. + The security identity information is stored in the ACL\_SID table. + +* `ObjectIdentity`: Each domain object is represented internally within the ACL module by an `ObjectIdentity`. + The default implementation is called `ObjectIdentityImpl`. + +* `AclService`: Retrieves the `Acl` applicable for a given `ObjectIdentity`. + In the included implementation (`JdbcAclService`), retrieval operations are delegated to a `LookupStrategy`. + The `LookupStrategy` provides a highly optimized strategy for retrieving ACL information, using batched retrievals (`BasicLookupStrategy`) and supporting custom implementations that leverage materialized views, hierarchical queries and similar performance-centric, non-ANSI SQL capabilities. + +* `MutableAclService`: Allows a modified `Acl` to be presented for persistence. + It is not essential to use this interface if you do not wish. + +Please note that our out-of-the-box AclService and related database classes all use ANSI SQL. +This should therefore work with all major databases. +At the time of writing, the system had been successfully tested using Hypersonic SQL, PostgreSQL, Microsoft SQL Server and Oracle. + +Two samples ship with Spring Security that demonstrate the ACL module. +The first is the [Contacts Sample](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/servlet/xml/java/contacts), and the other is the [Document Management System (DMS) Sample](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/servlet/xml/java/dms). +We suggest taking a look over these for examples. + +## Getting Started + +To get starting using Spring Security’s ACL capability, you will need to store your ACL information somewhere. +This necessitates the instantiation of a `DataSource` using Spring. +The `DataSource` is then injected into a `JdbcMutableAclService` and `BasicLookupStrategy` instance. +The latter provides high-performance ACL retrieval capabilities, and the former provides mutator capabilities. +Refer to one of the samples that ship with Spring Security for an example configuration. +You’ll also need to populate the database with the four ACL-specific tables listed in the last section (refer to the ACL samples for the appropriate SQL statements). + +Once you’ve created the required schema and instantiated `JdbcMutableAclService`, you’ll next need to ensure your domain model supports interoperability with the Spring Security ACL package. +Hopefully `ObjectIdentityImpl` will prove sufficient, as it provides a large number of ways in which it can be used. +Most people will have domain objects that contain a `public Serializable getId()` method. +If the return type is long, or compatible with long (e.g. an int), you will find you need not give further consideration to `ObjectIdentity` issues. +Many parts of the ACL module rely on long identifiers. +If you’re not using long (or an int, byte etc), there is a very good chance you’ll need to reimplement a number of classes. +We do not intend to support non-long identifiers in Spring Security’s ACL module, as longs are already compatible with all database sequences, the most common identifier data type, and are of sufficient length to accommodate all common usage scenarios. + +The following fragment of code shows how to create an `Acl`, or modify an existing `Acl`: + +Java + +``` +// Prepare the information we'd like in our access control entry (ACE) +ObjectIdentity oi = new ObjectIdentityImpl(Foo.class, new Long(44)); +Sid sid = new PrincipalSid("Samantha"); +Permission p = BasePermission.ADMINISTRATION; + +// Create or update the relevant ACL +MutableAcl acl = null; +try { +acl = (MutableAcl) aclService.readAclById(oi); +} catch (NotFoundException nfe) { +acl = aclService.createAcl(oi); +} + +// Now grant some permissions via an access control entry (ACE) +acl.insertAce(acl.getEntries().length, p, sid, true); +aclService.updateAcl(acl); +``` + +Kotlin + +``` +val oi: ObjectIdentity = ObjectIdentityImpl(Foo::class.java, 44) +val sid: Sid = PrincipalSid("Samantha") +val p: Permission = BasePermission.ADMINISTRATION + +// Create or update the relevant ACL +var acl: MutableAcl? = null +acl = try { +aclService.readAclById(oi) as MutableAcl +} catch (nfe: NotFoundException) { +aclService.createAcl(oi) +} + +// Now grant some permissions via an access control entry (ACE) +acl!!.insertAce(acl.entries.size, p, sid, true) +aclService.updateAcl(acl) +``` + +In the example above, we’re retrieving the ACL associated with the "Foo" domain object with identifier number 44. +We’re then adding an ACE so that a principal named "Samantha" can "administer" the object. +The code fragment is relatively self-explanatory, except the insertAce method. +The first argument to the insertAce method is determining at what position in the Acl the new entry will be inserted. +In the example above, we’re just putting the new ACE at the end of the existing ACEs. +The final argument is a Boolean indicating whether the ACE is granting or denying. +Most of the time it will be granting (true), but if it is denying (false), the permissions are effectively being blocked. + +Spring Security does not provide any special integration to automatically create, update or delete ACLs as part of your DAO or repository operations. +Instead, you will need to write code like shown above for your individual domain objects. +It’s worth considering using AOP on your services layer to automatically integrate the ACL information with your services layer operations. +We’ve found this quite an effective approach in the past. + +Once you’ve used the above techniques to store some ACL information in the database, the next step is to actually use the ACL information as part of authorization decision logic. +You have a number of choices here. +You could write your own `AccessDecisionVoter` or `AfterInvocationProvider` that respectively fires before or after a method invocation. +Such classes would use `AclService` to retrieve the relevant ACL and then call `Acl.isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode)` to decide whether permission is granted or denied. +Alternately, you could use our `AclEntryVoter`, `AclEntryAfterInvocationProvider` or `AclEntryAfterInvocationCollectionFilteringProvider` classes. +All of these classes provide a declarative-based approach to evaluating ACL information at runtime, freeing you from needing to write any code. +Please refer to the sample applications to learn how to use these classes. + +[Method Security](method-security.html)[OAuth2](../oauth2/index.html) + diff --git a/docs/en/spring-security/servlet-authorization-architecture.md b/docs/en/spring-security/servlet-authorization-architecture.md new file mode 100644 index 0000000000000000000000000000000000000000..a677565271fc03504d3e123f640da7959bc1461e --- /dev/null +++ b/docs/en/spring-security/servlet-authorization-architecture.md @@ -0,0 +1,318 @@ +# Authorization Architecture + +## Authorities + +[`Authentication`](../authentication/architecture.html#servlet-authentication-authentication), discusses how all `Authentication` implementations store a list of `GrantedAuthority` objects. +These represent the authorities that have been granted to the principal. +The `GrantedAuthority` objects are inserted into the `Authentication` object by the `AuthenticationManager` and are later read by either the `AuthorizationManager` when making authorization decisions. + +`GrantedAuthority` is an interface with only one method: + +``` +String getAuthority(); +``` + +This method allows `AuthorizationManager`s to obtain a precise `String` representation of the `GrantedAuthority`. +By returning a representation as a `String`, a `GrantedAuthority` can be easily "read" by most `AuthorizationManager`s and `AccessDecisionManager`s. +If a `GrantedAuthority` cannot be precisely represented as a `String`, the `GrantedAuthority` is considered "complex" and `getAuthority()` must return `null`. + +An example of a "complex" `GrantedAuthority` would be an implementation that stores a list of operations and authority thresholds that apply to different customer account numbers. +Representing this complex `GrantedAuthority` as a `String` would be quite difficult, and as a result the `getAuthority()` method should return `null`. +This will indicate to any `AuthorizationManager` that it will need to specifically support the `GrantedAuthority` implementation in order to understand its contents. + +Spring Security includes one concrete `GrantedAuthority` implementation, `SimpleGrantedAuthority`. +This allows any user-specified `String` to be converted into a `GrantedAuthority`. +All `AuthenticationProvider`s included with the security architecture use `SimpleGrantedAuthority` to populate the `Authentication` object. + +## Pre-Invocation Handling + +Spring Security provides interceptors which control access to secure objects such as method invocations or web requests. +A pre-invocation decision on whether the invocation is allowed to proceed is made by the `AccessDecisionManager`. + +### The AuthorizationManager + +`AuthorizationManager` supersedes both [`AccessDecisionManager` and `AccessDecisionVoter`](#authz-legacy-note). + +Applications that customize an `AccessDecisionManager` or `AccessDecisionVoter` are encouraged to [change to using `AuthorizationManager`](#authz-voter-adaptation). + +`AuthorizationManager`s are called by the [`AuthorizationFilter`](authorize-http-requests.html) and are responsible for making final access control decisions. +The `AuthorizationManager` interface contains two methods: + +``` +AuthorizationDecision check(Supplier authentication, Object secureObject); + +default AuthorizationDecision verify(Supplier authentication, Object secureObject) + throws AccessDeniedException { + // ... +} +``` + +The `AuthorizationManager`'s `check` method is passed all the relevant information it needs in order to make an authorization decision. +In particular, passing the secure `Object` enables those arguments contained in the actual secure object invocation to be inspected. +For example, let’s assume the secure object was a `MethodInvocation`. +It would be easy to query the `MethodInvocation` for any `Customer` argument, and then implement some sort of security logic in the `AuthorizationManager` to ensure the principal is permitted to operate on that customer. +Implementations are expected to return a positive `AuthorizationDecision` if access is granted, negative `AuthorizationDecision` if access is denied, and a null `AuthorizationDecision` when abstaining from making a decision. + +`verify` calls `check` and subsequently throws an `AccessDeniedException` in the case of a negative `AuthorizationDecision`. + +### Delegate-based AuthorizationManager Implementations + +Whilst users can implement their own `AuthorizationManager` to control all aspects of authorization, Spring Security ships with a delegating `AuthorizationManager` that can collaborate with individual `AuthorizationManager`s. + +`RequestMatcherDelegatingAuthorizationManager` will match the request with the most appropriate delegate `AuthorizationManager`. +For method security, you can use `AuthorizationManagerBeforeMethodInterceptor` and `AuthorizationManagerAfterMethodInterceptor`. + +[Authorization Manager Implementations](#authz-authorization-manager-implementations) illustrates the relevant classes. + +![authorizationhierarchy](../../_images/servlet/authorization/authorizationhierarchy.png) + +Figure 1. Authorization Manager Implementations + +Using this approach, a composition of `AuthorizationManager` implementations can be polled on an authorization decision. + +#### AuthorityAuthorizationManager + +The most common `AuthorizationManager` provided with Spring Security is `AuthorityAuthorizationManager`. +It is configured with a given set of authorities to look for on the current `Authentication`. +It will return positive `AuthorizationDecision` should the `Authentication` contain any of the configured authorities. +It will return a negative `AuthorizationDecision` otherwise. + +#### AuthenticatedAuthorizationManager + +Another manager is the `AuthenticatedAuthorizationManager`. +It can be used to differentiate between anonymous, fully-authenticated and remember-me authenticated users. +Many sites allow certain limited access under remember-me authentication, but require a user to confirm their identity by logging in for full access. + +#### Custom Authorization Managers + +Obviously, you can also implement a custom `AuthorizationManager` and you can put just about any access-control logic you want in it. +It might be specific to your application (business-logic related) or it might implement some security administration logic. +For example, you can create an implementation that can query Open Policy Agent or your own authorization database. + +| |You’ll find a [blog article](https://spring.io/blog/2009/01/03/spring-security-customization-part-2-adjusting-secured-session-in-real-time) on the Spring web site which describes how to use the legacy `AccessDecisionVoter` to deny access in real-time to users whose accounts have been suspended.
You can achieve the same outcome by implementing `AuthorizationManager` instead.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## Adapting AccessDecisionManager and AccessDecisionVoters + +Previous to `AuthorizationManager`, Spring Security published [`AccessDecisionManager` and `AccessDecisionVoter`](#authz-legacy-note). + +In some cases, like migrating an older application, it may be desirable to introduce an `AuthorizationManager` that invokes an `AccessDecisionManager` or `AccessDecisionVoter`. + +To call an existing `AccessDecisionManager`, you can do: + +Example 1. Adapting an AccessDecisionManager + +Java + +``` +@Component +public class AccessDecisionManagerAuthorizationManagerAdapter implements AuthorizationManager { + private final AccessDecisionManager accessDecisionManager; + private final SecurityMetadataSource securityMetadataSource; + + @Override + public AuthorizationDecision check(Supplier authentication, Object object) { + try { + Collection attributes = this.securityMetadataSource.getAttributes(object); + this.accessDecisionManager.decide(authentication.get(), object, attributes); + return new AuthorizationDecision(true); + } catch (AccessDeniedException ex) { + return new AuthorizationDecision(false); + } + } + + @Override + public void verify(Supplier authentication, Object object) { + Collection attributes = this.securityMetadataSource.getAttributes(object); + this.accessDecisionManager.decide(authentication.get(), object, attributes); + } +} +``` + +And then wire it into your `SecurityFilterChain`. + +Or to only call an `AccessDecisionVoter`, you can do: + +Example 2. Adapting an AccessDecisionVoter + +Java + +``` +@Component +public class AccessDecisionVoterAuthorizationManagerAdapter implements AuthorizationManager { + private final AccessDecisionVoter accessDecisionVoter; + private final SecurityMetadataSource securityMetadataSource; + + @Override + public AuthorizationDecision check(Supplier authentication, Object object) { + Collection attributes = this.securityMetadataSource.getAttributes(object); + int decision = this.accessDecisionVoter.vote(authentication.get(), object, attributes); + switch (decision) { + case ACCESS_GRANTED: + return new AuthorizationDecision(true); + case ACCESS_DENIED: + return new AuthorizationDecision(false); + } + return null; + } +} +``` + +And then wire it into your `SecurityFilterChain`. + +## Hierarchical Roles + +It is a common requirement that a particular role in an application should automatically "include" other roles. +For example, in an application which has the concept of an "admin" and a "user" role, you may want an admin to be able to do everything a normal user can. +To achieve this, you can either make sure that all admin users are also assigned the "user" role. +Alternatively, you can modify every access constraint which requires the "user" role to also include the "admin" role. +This can get quite complicated if you have a lot of different roles in your application. + +The use of a role-hierarchy allows you to configure which roles (or authorities) should include others. +An extended version of Spring Security’s `RoleVoter`, `RoleHierarchyVoter`, is configured with a `RoleHierarchy`, from which it obtains all the "reachable authorities" which the user is assigned. +A typical configuration might look like this: + +Example 3. Hierarchical Roles Configuration + +Java + +``` +@Bean +AccessDecisionVoter hierarchyVoter() { + RoleHierarchy hierarchy = new RoleHierarchyImpl(); + hierarchy.setHierarchy("ROLE_ADMIN > ROLE_STAFF\n" + + "ROLE_STAFF > ROLE_USER\n" + + "ROLE_USER > ROLE_GUEST"); + return new RoleHierarcyVoter(hierarchy); +} +``` + +Xml + +``` + + + + + + + ROLE_ADMIN > ROLE_STAFF + ROLE_STAFF > ROLE_USER + ROLE_USER > ROLE_GUEST + + + +``` + +Here we have four roles in a hierarchy `ROLE_ADMIN ⇒ ROLE_STAFF ⇒ ROLE_USER ⇒ ROLE_GUEST`. +A user who is authenticated with `ROLE_ADMIN`, will behave as if they have all four roles when security constraints are evaluated against an `AuthorizationManager` adapted to call the above `RoleHierarchyVoter`. +The `>` symbol can be thought of as meaning "includes". + +Role hierarchies offer a convenient means of simplifying the access-control configuration data for your application and/or reducing the number of authorities which you need to assign to a user. +For more complex requirements you may wish to define a logical mapping between the specific access-rights your application requires and the roles that are assigned to users, translating between the two when loading the user information. + +## Legacy Authorization Components + +| |Spring Security contains some legacy components.
Since they are not yet removed, documentation is included for historical purposes.
Their recommended replacements are above.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### The AccessDecisionManager + +The `AccessDecisionManager` is called by the `AbstractSecurityInterceptor` and is responsible for making final access control decisions. +The `AccessDecisionManager` interface contains three methods: + +``` +void decide(Authentication authentication, Object secureObject, + Collection attrs) throws AccessDeniedException; + +boolean supports(ConfigAttribute attribute); + +boolean supports(Class clazz); +``` + +The `AccessDecisionManager`'s `decide` method is passed all the relevant information it needs in order to make an authorization decision. +In particular, passing the secure `Object` enables those arguments contained in the actual secure object invocation to be inspected. +For example, let’s assume the secure object was a `MethodInvocation`. +It would be easy to query the `MethodInvocation` for any `Customer` argument, and then implement some sort of security logic in the `AccessDecisionManager` to ensure the principal is permitted to operate on that customer. +Implementations are expected to throw an `AccessDeniedException` if access is denied. + +The `supports(ConfigAttribute)` method is called by the `AbstractSecurityInterceptor` at startup time to determine if the `AccessDecisionManager` can process the passed `ConfigAttribute`. +The `supports(Class)` method is called by a security interceptor implementation to ensure the configured `AccessDecisionManager` supports the type of secure object that the security interceptor will present. + +### Voting-Based AccessDecisionManager Implementations + +Whilst users can implement their own `AccessDecisionManager` to control all aspects of authorization, Spring Security includes several `AccessDecisionManager` implementations that are based on voting.[Voting Decision Manager](#authz-access-voting) illustrates the relevant classes. + +![access decision voting](../../_images/servlet/authorization/access-decision-voting.png) + +Figure 2. Voting Decision Manager + +Using this approach, a series of `AccessDecisionVoter` implementations are polled on an authorization decision. +The `AccessDecisionManager` then decides whether or not to throw an `AccessDeniedException` based on its assessment of the votes. + +The `AccessDecisionVoter` interface has three methods: + +``` +int vote(Authentication authentication, Object object, Collection attrs); + +boolean supports(ConfigAttribute attribute); + +boolean supports(Class clazz); +``` + +Concrete implementations return an `int`, with possible values being reflected in the `AccessDecisionVoter` static fields `ACCESS_ABSTAIN`, `ACCESS_DENIED` and `ACCESS_GRANTED`. +A voting implementation will return `ACCESS_ABSTAIN` if it has no opinion on an authorization decision. +If it does have an opinion, it must return either `ACCESS_DENIED` or `ACCESS_GRANTED`. + +There are three concrete `AccessDecisionManager`s provided with Spring Security that tally the votes. +The `ConsensusBased` implementation will grant or deny access based on the consensus of non-abstain votes. +Properties are provided to control behavior in the event of an equality of votes or if all votes are abstain. +The `AffirmativeBased` implementation will grant access if one or more `ACCESS_GRANTED` votes were received (i.e. a deny vote will be ignored, provided there was at least one grant vote). +Like the `ConsensusBased` implementation, there is a parameter that controls the behavior if all voters abstain. +The `UnanimousBased` provider expects unanimous `ACCESS_GRANTED` votes in order to grant access, ignoring abstains. +It will deny access if there is any `ACCESS_DENIED` vote. +Like the other implementations, there is a parameter that controls the behaviour if all voters abstain. + +It is possible to implement a custom `AccessDecisionManager` that tallies votes differently. +For example, votes from a particular `AccessDecisionVoter` might receive additional weighting, whilst a deny vote from a particular voter may have a veto effect. + +#### RoleVoter + +The most commonly used `AccessDecisionVoter` provided with Spring Security is the simple `RoleVoter`, which treats configuration attributes as simple role names and votes to grant access if the user has been assigned that role. + +It will vote if any `ConfigAttribute` begins with the prefix `ROLE_`. +It will vote to grant access if there is a `GrantedAuthority` which returns a `String` representation (via the `getAuthority()` method) exactly equal to one or more `ConfigAttributes` starting with the prefix `ROLE_`. +If there is no exact match of any `ConfigAttribute` starting with `ROLE_`, the `RoleVoter` will vote to deny access. +If no `ConfigAttribute` begins with `ROLE_`, the voter will abstain. + +#### AuthenticatedVoter + +Another voter which we’ve implicitly seen is the `AuthenticatedVoter`, which can be used to differentiate between anonymous, fully-authenticated and remember-me authenticated users. +Many sites allow certain limited access under remember-me authentication, but require a user to confirm their identity by logging in for full access. + +When we’ve used the attribute `IS_AUTHENTICATED_ANONYMOUSLY` to grant anonymous access, this attribute was being processed by the `AuthenticatedVoter`. +See the Javadoc for this class for more information. + +#### Custom Voters + +Obviously, you can also implement a custom `AccessDecisionVoter` and you can put just about any access-control logic you want in it. +It might be specific to your application (business-logic related) or it might implement some security administration logic. +For example, you’ll find a [blog article](https://spring.io/blog/2009/01/03/spring-security-customization-part-2-adjusting-secured-session-in-real-time) on the Spring web site which describes how to use a voter to deny access in real-time to users whose accounts have been suspended. + +![after invocation](../../_images/servlet/authorization/after-invocation.png) + +Figure 3. After Invocation Implementation + +Like many other parts of Spring Security, `AfterInvocationManager` has a single concrete implementation, `AfterInvocationProviderManager`, which polls a list of `AfterInvocationProvider`s. +Each `AfterInvocationProvider` is allowed to modify the return object or throw an `AccessDeniedException`. +Indeed multiple providers can modify the object, as the result of the previous provider is passed to the next in the list. + +Please be aware that if you’re using `AfterInvocationManager`, you will still need configuration attributes that allow the `MethodSecurityInterceptor`'s `AccessDecisionManager` to allow an operation. +If you’re using the typical Spring Security included `AccessDecisionManager` implementations, having no configuration attributes defined for a particular secure method invocation will cause each `AccessDecisionVoter` to abstain from voting. +In turn, if the `AccessDecisionManager` property “allowIfAllAbstainDecisions” is `false`, an `AccessDeniedException` will be thrown. +You may avoid this potential issue by either (i) setting “allowIfAllAbstainDecisions” to `true` (although this is generally not recommended) or (ii) simply ensure that there is at least one configuration attribute that an `AccessDecisionVoter` will vote to grant access for. +This latter (recommended) approach is usually achieved through a `ROLE_USER` or `ROLE_AUTHENTICATED` configuration attribute. + +[Authorization](index.html)[Authorize HTTP Requests](authorize-http-requests.html) + diff --git a/docs/en/spring-security/servlet-authorization-authorize-http-requests.md b/docs/en/spring-security/servlet-authorization-authorize-http-requests.md new file mode 100644 index 0000000000000000000000000000000000000000..14af279a5b42dd93a387d038e7d70fc80c010c8f --- /dev/null +++ b/docs/en/spring-security/servlet-authorization-authorize-http-requests.md @@ -0,0 +1,168 @@ +# Authorize HttpServletRequests with AuthorizationFilter + +This section builds on [Servlet Architecture and Implementation](../architecture.html#servlet-architecture) by digging deeper into how [authorization](index.html#servlet-authorization) works within Servlet-based applications. + +| |`AuthorizationFilter` supersedes [`FilterSecurityInterceptor`](authorize-requests.html#servlet-authorization-filtersecurityinterceptor).
To remain backward compatible, `FilterSecurityInterceptor` remains the default.
This section discusses how `AuthorizationFilter` works and how to override the default configuration.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The [`AuthorizationFilter`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/access/intercept/AuthorizationFilter.html) provides [authorization](index.html#servlet-authorization) for `HttpServletRequest`s. +It is inserted into the [FilterChainProxy](../architecture.html#servlet-filterchainproxy) as one of the [Security Filters](../architecture.html#servlet-security-filters). + +You can override the default when you declare a `SecurityFilterChain`. +Instead of using [`authorizeRequests`](#servlet-authorize-requests-defaults), use `authorizeHttpRequests`, like so: + +Example 1. Use authorizeHttpRequests + +Java + +``` +@Bean +SecurityFilterChain web(HttpSecurity http) throws AuthenticationException { + http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest().authenticated(); + ) + // ... + + return http.build(); +} +``` + +This improves on `authorizeRequests` in a number of ways: + +1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters. + This simplifies reuse and customization. + +2. Delays `Authentication` lookup. + Instead of the authentication needing to be looked up for every request, it will only look it up in requests where an authorization decision requires authentication. + +3. Bean-based configuration support. + +When `authorizeHttpRequests` is used instead of `authorizeRequests`, then [`AuthorizationFilter`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/access/intercept/AuthorizationFilter.html) is used instead of [`FilterSecurityInterceptor`](authorize-requests.html#servlet-authorization-filtersecurityinterceptor). + +![authorizationfilter](../../_images/servlet/authorization/authorizationfilter.png) + +Figure 1. Authorize HttpServletRequest + +* ![number 1](../../_images/icons/number_1.png) First, the `AuthorizationFilter` obtains an [Authentication](../authentication/architecture.html#servlet-authentication-authentication) from the [SecurityContextHolder](../authentication/architecture.html#servlet-authentication-securitycontextholder). + It wraps this in an `Supplier` in order to delay lookup. + +* ![number 2](../../_images/icons/number_2.png) Second, `AuthorizationFilter` creates a [`FilterInvocation`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/FilterInvocation.html) from the `HttpServletRequest`, `HttpServletResponse`, and `FilterChain`. + +* ![number 3](../../_images/icons/number_3.png) Next, it passes the `Supplier` and `FilterInvocation` to the [`AuthorizationManager`](../architecture.html#authz-authorization-manager). + + * ![number 4](../../_images/icons/number_4.png) If authorization is denied, an `AccessDeniedException` is thrown. + In this case the [`ExceptionTranslationFilter`](../architecture.html#servlet-exceptiontranslationfilter) handles the `AccessDeniedException`. + + * ![number 5](../../_images/icons/number_5.png) If access is granted, `AuthorizationFilter` continues with the [FilterChain](../architecture.html#servlet-filters-review) which allows the application to process normally. + +We can configure Spring Security to have different rules by adding more rules in order of precedence. + +Example 2. Authorize Requests + +Java + +``` +@Bean +SecurityFilterChain web(HttpSecurity http) throws Exception { + http + // ... + .authorizeHttpRequests(authorize -> authorize (1) + .mvcMatchers("/resources/**", "/signup", "/about").permitAll() (2) + .mvcMatchers("/admin/**").hasRole("ADMIN") (3) + .mvcMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") (4) + .anyRequest().denyAll() (5) + ); + + return http.build(); +} +``` + +|**1**| There are multiple authorization rules specified.
Each rule is considered in the order they were declared. | +|-----|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**| We specified multiple URL patterns that any user can access.
Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about". | +|**3**|Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE\_ADMIN".
You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE\_" prefix.| +|**4**|Any URL that starts with "/db/" requires the user to have both "ROLE\_ADMIN" and "ROLE\_DBA".
You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE\_" prefix. | +|**5**| Any URL that has not already been matched on is denied access.
This is a good strategy if you do not want to accidentally forget to update your authorization rules. | + +You can take a bean-based approach by constructing your own [`RequestMatcherDelegatingAuthorizationManager`](architecture.html#authz-delegate-authorization-manager) like so: + +Example 3. Configure RequestMatcherDelegatingAuthorizationManager + +Java + +``` +@Bean +SecurityFilterChain web(HttpSecurity http, AuthorizationManager access) + throws AuthenticationException { + http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest().access(access) + ) + // ... + + return http.build(); +} + +@Bean +AuthorizationManager requestMatcherAuthorizationManager(HandlerMappingIntrospector introspector) { + RequestMatcher permitAll = + new AndRequestMatcher( + new MvcRequestMatcher(introspector, "/resources/**"), + new MvcRequestMatcher(introspector, "/signup"), + new MvcRequestMatcher(introspector, "/about")); + RequestMatcher admin = new MvcRequestMatcher(introspector, "/admin/**"); + RequestMatcher db = new MvcRequestMatcher(introspector, "/db/**"); + RequestMatcher any = AnyRequestMatcher.INSTANCE; + AuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder() + .add(permitAll, (context) -> new AuthorizationDecision(true)) + .add(admin, AuthorityAuthorizationManager.hasRole("ADMIN")) + .add(db, AuthorityAuthorizationManager.hasRole("DBA")) + .add(any, new AuthenticatedAuthorizationManager()) + .build(); + return (context) -> manager.check(context.getRequest()); +} +``` + +You can also wire [your own custom authorization managers](architecture.html#authz-custom-authorization-manager) for any request matcher. + +Here is an example of mapping a custom authorization manager to the `my/authorized/endpoint`: + +Example 4. Custom Authorization Manager + +Java + +``` +@Bean +SecurityFilterChain web(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests((authorize) -> authorize + .mvcMatchers("/my/authorized/endpoint").access(new CustomAuthorizationManager()); + ) + // ... + + return http.build(); +} +``` + +Or you can provide it for all requests as seen below: + +Example 5. Custom Authorization Manager for All Requests + +Java + +``` +@Bean +SecurityFilterChain web(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest.access(new CustomAuthorizationManager()); + ) + // ... + + return http.build(); +} +``` + +[Authorization Architecture](architecture.html)[Authorize HTTP Requests with FilterSecurityInterceptor](authorize-requests.html) + diff --git a/docs/en/spring-security/servlet-authorization-authorize-requests.md b/docs/en/spring-security/servlet-authorization-authorize-requests.md new file mode 100644 index 0000000000000000000000000000000000000000..b9535838920f64b35ea6198d58e5abdf28af4c40 --- /dev/null +++ b/docs/en/spring-security/servlet-authorization-authorize-requests.md @@ -0,0 +1,128 @@ +# Authorize HttpServletRequest with FilterSecurityInterceptor + +| |`FilterSecurityInterceptor` is in the process of being replaced by [`AuthorizationFilter`](authorize-http-requests.html).
Consider using that instead.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------| + +This section builds on [Servlet Architecture and Implementation](../architecture.html#servlet-architecture) by digging deeper into how [authorization](index.html#servlet-authorization) works within Servlet based applications. + +The [`FilterSecurityInterceptor`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html) provides [authorization](index.html#servlet-authorization) for `HttpServletRequest`s. +It is inserted into the [FilterChainProxy](../architecture.html#servlet-filterchainproxy) as one of the [Security Filters](../architecture.html#servlet-security-filters). + +![filtersecurityinterceptor](../../_images/servlet/authorization/filtersecurityinterceptor.png) + +Figure 1. Authorize HttpServletRequest + +* ![number 1](../../_images/icons/number_1.png) First, the `FilterSecurityInterceptor` obtains an [Authentication](../authentication/architecture.html#servlet-authentication-authentication) from the [SecurityContextHolder](../authentication/architecture.html#servlet-authentication-securitycontextholder). + +* ![number 2](../../_images/icons/number_2.png) Second, `FilterSecurityInterceptor` creates a [`FilterInvocation`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/FilterInvocation.html) from the `HttpServletRequest`, `HttpServletResponse`, and `FilterChain` that are passed into the `FilterSecurityInterceptor`. + +* ![number 3](../../_images/icons/number_3.png) Next, it passes the `FilterInvocation` to `SecurityMetadataSource` to get the `ConfigAttribute`s. + +* ![number 4](../../_images/icons/number_4.png) Finally, it passes the `Authentication`, `FilterInvocation`, and `ConfigAttribute`s to the xref:servlet/authorization.adoc#authz-access-decision-manager`AccessDecisionManager`. + + * ![number 5](../../_images/icons/number_5.png) If authorization is denied, an `AccessDeniedException` is thrown. + In this case the [`ExceptionTranslationFilter`](../architecture.html#servlet-exceptiontranslationfilter) handles the `AccessDeniedException`. + + * ![number 6](../../_images/icons/number_6.png) If access is granted, `FilterSecurityInterceptor` continues with the [FilterChain](../architecture.html#servlet-filters-review) which allows the application to process normally. + +By default, Spring Security’s authorization will require all requests to be authenticated. +The explicit configuration looks like: + +Example 1. Every Request Must be Authenticated + +Java + +``` +protected void configure(HttpSecurity http) throws Exception { + http + // ... + .authorizeRequests(authorize -> authorize + .anyRequest().authenticated() + ); +} +``` + +XML + +``` + + + + +``` + +Kotlin + +``` +fun configure(http: HttpSecurity) { + http { + // ... + authorizeRequests { + authorize(anyRequest, authenticated) + } + } +} +``` + +We can configure Spring Security to have different rules by adding more rules in order of precedence. + +Example 2. Authorize Requests + +Java + +``` +protected void configure(HttpSecurity http) throws Exception { + http + // ... + .authorizeRequests(authorize -> authorize (1) + .mvcMatchers("/resources/**", "/signup", "/about").permitAll() (2) + .mvcMatchers("/admin/**").hasRole("ADMIN") (3) + .mvcMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") (4) + .anyRequest().denyAll() (5) + ); +} +``` + +XML + +``` + (1) + + (2) + + + + + (3) + (4) + (5) + +``` + +Kotlin + +``` +fun configure(http: HttpSecurity) { + http { + authorizeRequests { (1) + authorize("/resources/**", permitAll) (2) + authorize("/signup", permitAll) + authorize("/about", permitAll) + + authorize("/admin/**", hasRole("ADMIN")) (3) + authorize("/db/**", "hasRole('ADMIN') and hasRole('DBA')") (4) + authorize(anyRequest, denyAll) (5) + } + } +} +``` + +|**1**| There are multiple authorization rules specified.
Each rule is considered in the order they were declared. | +|-----|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**| We specified multiple URL patterns that any user can access.
Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about". | +|**3**|Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE\_ADMIN".
You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE\_" prefix.| +|**4**|Any URL that starts with "/db/" requires the user to have both "ROLE\_ADMIN" and "ROLE\_DBA".
You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE\_" prefix. | +|**5**| Any URL that has not already been matched on is denied access.
This is a good strategy if you do not want to accidentally forget to update your authorization rules. | + +[Authorize HTTP Requests](authorize-http-requests.html)[Expression-Based Access Control](expression-based.html) + diff --git a/docs/en/spring-security/servlet-authorization-expression-based.md b/docs/en/spring-security/servlet-authorization-expression-based.md new file mode 100644 index 0000000000000000000000000000000000000000..b887685aa290354259653911290820edeffedb66 --- /dev/null +++ b/docs/en/spring-security/servlet-authorization-expression-based.md @@ -0,0 +1,439 @@ +# Expression-Based Access Control + +## Overview + +Spring Security uses Spring EL for expression support and you should look at how that works if you are interested in understanding the topic in more depth. +Expressions are evaluated with a "root object" as part of the evaluation context. +Spring Security uses specific classes for web and method security as the root object, in order to provide built-in expressions and access to values such as the current principal. + +### Common Built-In Expressions + +The base class for expression root objects is `SecurityExpressionRoot`. +This provides some common expressions which are available in both web and method security. + +| Expression | Description | +|----------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `hasRole(String role)` | Returns `true` if the current principal has the specified role.

For example, `hasRole('admin')`

By default if the supplied role does not start with 'ROLE\_' it will be added.
This can be customized by modifying the `defaultRolePrefix` on `DefaultWebSecurityExpressionHandler`. | +| `hasAnyRole(String…​ roles)` |Returns `true` if the current principal has any of the supplied roles (given as a comma-separated list of strings).

For example, `hasAnyRole('admin', 'user')`

By default if the supplied role does not start with 'ROLE\_' it will be added.
This can be customized by modifying the `defaultRolePrefix` on `DefaultWebSecurityExpressionHandler`.| +| `hasAuthority(String authority)` | Returns `true` if the current principal has the specified authority.

For example, `hasAuthority('read')` | +| `hasAnyAuthority(String…​ authorities)` | Returns `true` if the current principal has any of the supplied authorities (given as a comma-separated list of strings)

For example, `hasAnyAuthority('read', 'write')` | +| `principal` | Allows direct access to the principal object representing the current user | +| `authentication` | Allows direct access to the current `Authentication` object obtained from the `SecurityContext` | +| `permitAll` | Always evaluates to `true` | +| `denyAll` | Always evaluates to `false` | +| `isAnonymous()` | Returns `true` if the current principal is an anonymous user | +| `isRememberMe()` | Returns `true` if the current principal is a remember-me user | +| `isAuthenticated()` | Returns `true` if the user is not anonymous | +| `isFullyAuthenticated()` | Returns `true` if the user is not an anonymous or a remember-me user | +| `hasPermission(Object target, Object permission)` | Returns `true` if the user has access to the provided target for the given permission.
For example, `hasPermission(domainObject, 'read')` | +|`hasPermission(Object targetId, String targetType, Object permission)`| Returns `true` if the user has access to the provided target for the given permission.
For example, `hasPermission(1, 'com.example.domain.Message', 'read')` | + +## Web Security Expressions + +To use expressions to secure individual URLs, you would first need to set the `use-expressions` attribute in the `` element to `true`. +Spring Security will then expect the `access` attributes of the `` elements to contain Spring EL expressions. +The expressions should evaluate to a Boolean, defining whether access should be allowed or not. +For example: + +``` + + + ... + +``` + +Here we have defined that the "admin" area of an application (defined by the URL pattern) should only be available to users who have the granted authority "admin" and whose IP address matches a local subnet. +We’ve already seen the built-in `hasRole` expression in the previous section. +The expression `hasIpAddress` is an additional built-in expression which is specific to web security. +It is defined by the `WebSecurityExpressionRoot` class, an instance of which is used as the expression root object when evaluating web-access expressions. +This object also directly exposed the `HttpServletRequest` object under the name `request` so you can invoke the request directly in an expression. +If expressions are being used, a `WebExpressionVoter` will be added to the `AccessDecisionManager` which is used by the namespace. +So if you aren’t using the namespace and want to use expressions, you will have to add one of these to your configuration. + +### Referring to Beans in Web Security Expressions + +If you wish to extend the expressions that are available, you can easily refer to any Spring Bean you expose. +For example, assuming you have a Bean with the name of `webSecurity` that contains the following method signature: + +Java + +``` +public class WebSecurity { + public boolean check(Authentication authentication, HttpServletRequest request) { + ... + } +} +``` + +Kotlin + +``` +class WebSecurity { + fun check(authentication: Authentication?, request: HttpServletRequest?): Boolean { + // ... + } +} +``` + +You could refer to the method using: + +Example 1. Refer to method + +Java + +``` +http + .authorizeHttpRequests(authorize -> authorize + .antMatchers("/user/**").access("@webSecurity.check(authentication,request)") + ... + ) +``` + +XML + +``` + + + ... + +``` + +Kotlin + +``` +http { + authorizeRequests { + authorize("/user/**", "@webSecurity.check(authentication,request)") + } +} +``` + +### Path Variables in Web Security Expressions + +At times it is nice to be able to refer to path variables within a URL. +For example, consider a RESTful application that looks up a user by id from the URL path in the format `/user/{userId}`. + +You can easily refer to the path variable by placing it in the pattern. +For example, if you had a Bean with the name of `webSecurity` that contains the following method signature: + +Java + +``` +public class WebSecurity { + public boolean checkUserId(Authentication authentication, int id) { + ... + } +} +``` + +Kotlin + +``` +class WebSecurity { + fun checkUserId(authentication: Authentication?, id: Int): Boolean { + // ... + } +} +``` + +You could refer to the method using: + +Example 2. Path Variables + +Java + +``` +http + .authorizeHttpRequests(authorize -> authorize + .antMatchers("/user/{userId}/**").access("@webSecurity.checkUserId(authentication,#userId)") + ... + ); +``` + +XML + +``` + + + ... + +``` + +Kotlin + +``` +http { + authorizeRequests { + authorize("/user/{userId}/**", "@webSecurity.checkUserId(authentication,#userId)") + } +} +``` + +In this configuration URLs that match would pass in the path variable (and convert it) into checkUserId method. +For example, if the URL were `/user/123/resource`, then the id passed in would be `123`. + +## Method Security Expressions + +Method security is a bit more complicated than a simple allow or deny rule. +Spring Security 3.0 introduced some new annotations in order to allow comprehensive support for the use of expressions. + +### @Pre and @Post Annotations + +There are four annotations which support expression attributes to allow pre and post-invocation authorization checks and also to support filtering of submitted collection arguments or return values. +They are `@PreAuthorize`, `@PreFilter`, `@PostAuthorize` and `@PostFilter`. +Their use is enabled through the `global-method-security` namespace element: + +``` + +``` + +#### Access Control using @PreAuthorize and @PostAuthorize + +The most obviously useful annotation is `@PreAuthorize` which decides whether a method can actually be invoked or not. +For example (from the [Contacts](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/servlet/xml/java/contacts) sample application) + +Java + +``` +@PreAuthorize("hasRole('USER')") +public void create(Contact contact); +``` + +Kotlin + +``` +@PreAuthorize("hasRole('USER')") +fun create(contact: Contact?) +``` + +which means that access will only be allowed for users with the role "ROLE\_USER". +Obviously the same thing could easily be achieved using a traditional configuration and a simple configuration attribute for the required role. +But what about: + +Java + +``` +@PreAuthorize("hasPermission(#contact, 'admin')") +public void deletePermission(Contact contact, Sid recipient, Permission permission); +``` + +Kotlin + +``` +@PreAuthorize("hasPermission(#contact, 'admin')") +fun deletePermission(contact: Contact?, recipient: Sid?, permission: Permission?) +``` + +Here we’re actually using a method argument as part of the expression to decide whether the current user has the "admin" permission for the given contact. +The built-in `hasPermission()` expression is linked into the Spring Security ACL module through the application context, as we’ll [see below](#el-permission-evaluator). +You can access any of the method arguments by name as expression variables. + +There are a number of ways in which Spring Security can resolve the method arguments. +Spring Security uses `DefaultSecurityParameterNameDiscoverer` to discover the parameter names. +By default, the following options are tried for a method as a whole. + +* If Spring Security’s `@P` annotation is present on a single argument to the method, the value will be used. + This is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names. + For example: + + Java + + ``` + import org.springframework.security.access.method.P; + + ... + + @PreAuthorize("#c.name == authentication.name") + public void doSomething(@P("c") Contact contact); + ``` + + Kotlin + + ``` + import org.springframework.security.access.method.P + + ... + + @PreAuthorize("#c.name == authentication.name") + fun doSomething(@P("c") contact: Contact?) + ``` + + Behind the scenes this is implemented using `AnnotationParameterNameDiscoverer` which can be customized to support the value attribute of any specified annotation. + +* If Spring Data’s `@Param` annotation is present on at least one parameter for the method, the value will be used. + This is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names. + For example: + + Java + + ``` + import org.springframework.data.repository.query.Param; + + ... + + @PreAuthorize("#n == authentication.name") + Contact findContactByName(@Param("n") String name); + ``` + + Kotlin + + ``` + import org.springframework.data.repository.query.Param + + ... + + @PreAuthorize("#n == authentication.name") + fun findContactByName(@Param("n") name: String?): Contact? + ``` + + Behind the scenes this is implemented using `AnnotationParameterNameDiscoverer` which can be customized to support the value attribute of any specified annotation. + +* If JDK 8 was used to compile the source with the -parameters argument and Spring 4+ is being used, then the standard JDK reflection API is used to discover the parameter names. + This works on both classes and interfaces. + +* Last, if the code was compiled with the debug symbols, the parameter names will be discovered using the debug symbols. + This will not work for interfaces since they do not have debug information about the parameter names. + For interfaces, annotations or the JDK 8 approach must be used. + + + +Any Spring-EL functionality is available within the expression, so you can also access properties on the arguments. +For example, if you wanted a particular method to only allow access to a user whose username matched that of the contact, you could write + +Java + +``` +@PreAuthorize("#contact.name == authentication.name") +public void doSomething(Contact contact); +``` + +Kotlin + +``` +@PreAuthorize("#contact.name == authentication.name") +fun doSomething(contact: Contact?) +``` + +Here we are accessing another built-in expression, `authentication`, which is the `Authentication` stored in the security context. +You can also access its "principal" property directly, using the expression `principal`. +The value will often be a `UserDetails` instance, so you might use an expression like `principal.username` or `principal.enabled`. + + + +Less commonly, you may wish to perform an access-control check after the method has been invoked. +This can be achieved using the `@PostAuthorize` annotation. +To access the return value from a method, use the built-in name `returnObject` in the expression. + +#### Filtering using @PreFilter and @PostFilter + +Spring Security supports filtering of collections, arrays, maps and streams using expressions. +This is most commonly performed on the return value of a method. +For example: + +Java + +``` +@PreAuthorize("hasRole('USER')") +@PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')") +public List getAll(); +``` + +Kotlin + +``` +@PreAuthorize("hasRole('USER')") +@PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')") +fun getAll(): List +``` + +When using the `@PostFilter` annotation, Spring Security iterates through the returned collection or map and removes any elements for which the supplied expression is false. +For an array, a new array instance will be returned containing filtered elements. +The name `filterObject` refers to the current object in the collection. +In case when a map is used it will refer to the current `Map.Entry` object which allows one to use `filterObject.key` or `filterObject.value` in the expresion. +You can also filter before the method call, using `@PreFilter`, though this is a less common requirement. +The syntax is just the same, but if there is more than one argument which is a collection type then you have to select one by name using the `filterTarget` property of this annotation. + +Note that filtering is obviously not a substitute for tuning your data retrieval queries. +If you are filtering large collections and removing many of the entries then this is likely to be inefficient. + +### Built-In Expressions + +There are some built-in expressions which are specific to method security, which we have already seen in use above. +The `filterTarget` and `returnValue` values are simple enough, but the use of the `hasPermission()` expression warrants a closer look. + +#### The PermissionEvaluator interface + +`hasPermission()` expressions are delegated to an instance of `PermissionEvaluator`. +It is intended to bridge between the expression system and Spring Security’s ACL system, allowing you to specify authorization constraints on domain objects, based on abstract permissions. +It has no explicit dependencies on the ACL module, so you could swap that out for an alternative implementation if required. +The interface has two methods: + +``` +boolean hasPermission(Authentication authentication, Object targetDomainObject, + Object permission); + +boolean hasPermission(Authentication authentication, Serializable targetId, + String targetType, Object permission); +``` + +which map directly to the available versions of the expression, with the exception that the first argument (the `Authentication` object) is not supplied. +The first is used in situations where the domain object, to which access is being controlled, is already loaded. +Then expression will return true if the current user has the given permission for that object. +The second version is used in cases where the object is not loaded, but its identifier is known. +An abstract "type" specifier for the domain object is also required, allowing the correct ACL permissions to be loaded. +This has traditionally been the Java class of the object, but does not have to be as long as it is consistent with how the permissions are loaded. + +To use `hasPermission()` expressions, you have to explicitly configure a `PermissionEvaluator` in your application context. +This would look something like this: + +``` + + + + + + + +``` + +Where `myPermissionEvaluator` is the bean which implements `PermissionEvaluator`. +Usually this will be the implementation from the ACL module which is called `AclPermissionEvaluator`. +See the [Contacts](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/servlet/xml/java/contacts) sample application configuration for more details. + +#### Method Security Meta Annotations + +You can make use of meta annotations for method security to make your code more readable. +This is especially convenient if you find that you are repeating the same complex expression throughout your code base. +For example, consider the following: + +``` +@PreAuthorize("#contact.name == authentication.name") +``` + +Instead of repeating this everywhere, we can create a meta annotation that can be used instead. + +Java + +``` +@Retention(RetentionPolicy.RUNTIME) +@PreAuthorize("#contact.name == authentication.name") +public @interface ContactPermission {} +``` + +Kotlin + +``` +@Retention(AnnotationRetention.RUNTIME) +@PreAuthorize("#contact.name == authentication.name") +annotation class ContactPermission +``` + +Meta annotations can be used for any of the Spring Security method security annotations. +In order to remain compliant with the specification JSR-250 annotations do not support meta annotations. + +[Authorize HTTP Requests with FilterSecurityInterceptor](authorize-requests.html)[Secure Object Implementations](secure-objects.html) + diff --git a/docs/en/spring-security/servlet-authorization-method-security.md b/docs/en/spring-security/servlet-authorization-method-security.md new file mode 100644 index 0000000000000000000000000000000000000000..331850e43e4e31269b49a083b305f200bf9d4e5f --- /dev/null +++ b/docs/en/spring-security/servlet-authorization-method-security.md @@ -0,0 +1,855 @@ +# Method Security + +From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. +It provides support for JSR-250 annotation security as well as the framework’s original `@Secured` annotation. +From 3.0 you can also make use of new [expression-based annotations](expression-based.html#el-access). +You can apply security to a single bean, using the `intercept-methods` element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts. + +## EnableMethodSecurity + +In Spring Security 5.6, we can enable annotation-based security using the `@EnableMethodSecurity` annotation on any `@Configuration` instance. + +This improves upon `@EnableGlobalMethodSecurity` in a number of ways. `@EnableMethodSecurity`: + +1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters. + This simplifies reuse and customization. + +2. Favors direct bean-based configuration, instead of requiring extending `GlobalMethodSecurityConfiguration` to customize beans + +3. Is built using native Spring AOP, removing abstractions and allowing you to use Spring AOP building blocks to customize + +4. Checks for conflicting annotations to ensure an unambiguous security configuration + +5. Complies with JSR-250 + +6. Enables `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` by default + +| |For earlier versions, please read about similar support with [@EnableGlobalMethodSecurity](#jc-enable-global-method-security).| +|---|------------------------------------------------------------------------------------------------------------------------------| + +For example, the following would enable Spring Security’s `@PreAuthorize` annotation: + +Example 1. Method Security Configuration + +Java + +``` +@EnableMethodSecurity +public class MethodSecurityConfig { + // ... +} +``` + +Kotlin + +``` +@EnableMethodSecurity +class MethodSecurityConfig { + // ... +} +``` + +Xml + +``` + +``` + +Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly. +Spring Security’s native annotation support defines a set of attributes for the method. +These will be passed to the `DefaultAuthorizationMethodInterceptorChain` for it to make the actual decision: + +Example 2. Method Security Annotation Usage + +Java + +``` +public interface BankService { + @PreAuthorize("hasRole('USER')") + Account readAccount(Long id); + + @PreAuthorize("hasRole('USER')") + List findAccounts(); + + @PreAuthorize("hasRole('TELLER')") + Account post(Account account, Double amount); +} +``` + +Kotlin + +``` +interface BankService { + @PreAuthorize("hasRole('USER')") + fun readAccount(id : Long) : Account + + @PreAuthorize("hasRole('USER')") + fun findAccounts() : List + + @PreAuthorize("hasRole('TELLER')") + fun post(account : Account, amount : Double) : Account +} +``` + +You can enable support for Spring Security’s `@Secured` annotation using: + +Example 3. @Secured Configuration + +Java + +``` +@EnableMethodSecurity(securedEnabled = true) +public class MethodSecurityConfig { + // ... +} +``` + +Kotlin + +``` +@EnableMethodSecurity(securedEnabled = true) +class MethodSecurityConfig { + // ... +} +``` + +Xml + +``` + +``` + +or JSR-250 using: + +Example 4. JSR-250 Configuration + +Java + +``` +@EnableMethodSecurity(jsr250Enabled = true) +public class MethodSecurityConfig { + // ... +} +``` + +Kotlin + +``` +@EnableMethodSecurity(jsr250Enabled = true) +class MethodSecurityConfig { + // ... +} +``` + +Xml + +``` + +``` + +### Customizing Authorization + +Spring Security’s `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` ship with rich expression-based support. + +If you need to customize the way that expressions are handled, you can expose a custom `MethodSecurityExpressionHandler`, like so: + +Example 5. Custom MethodSecurityExpressionHandler + +Java + +``` +@Bean +static MethodSecurityExpressionHandler methodSecurityExpressionHandler() { + DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler(); + handler.setTrustResolver(myCustomTrustResolver); + return handler; +} +``` + +Kotlin + +``` +companion object { + @Bean + fun methodSecurityExpressionHandler() : MethodSecurityExpressionHandler { + val handler = DefaultMethodSecurityExpressionHandler(); + handler.setTrustResolver(myCustomTrustResolver); + return handler; + } +} +``` + +Xml + +``` + + + + + + + +``` + +| |We expose `MethodSecurityExpressionHandler` using a `static` method to ensure that Spring publishes it before it initializes Spring Security’s method security `@Configuration` classes| +|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +Also, for role-based authorization, Spring Security adds a default `ROLE_` prefix, which is uses when evaluating expressions like `hasRole`. + +You can configure the authorization rules to use a different prefix by exposing a `GrantedAuthorityDefaults` bean, like so: + +Example 6. Custom MethodSecurityExpressionHandler + +Java + +``` +@Bean +static GrantedAuthorityDefaults grantedAuthorityDefaults() { + return new GrantedAuthorityDefaults("MYPREFIX_"); +} +``` + +Kotlin + +``` +companion object { + @Bean + fun grantedAuthorityDefaults() : GrantedAuthorityDefaults { + return GrantedAuthorityDefaults("MYPREFIX_"); + } +} +``` + +Xml + +``` + + + + + +``` + +| |We expose `GrantedAuthorityDefaults` using a `static` method to ensure that Spring publishes it before it initializes Spring Security’s method security `@Configuration` classes| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +### Custom Authorization Managers + +Method authorization is a combination of before- and after-method authorization. + +| |Before-method authorization is performed before the method is invoked.
If that authorization denies access, the method is not invoked, and an `AccessDeniedException` is thrown
After-method authorization is performed after the method is invoked, but before the method returns to the caller.
If that authorization denies access, the value is not returned, and an `AccessDeniedException` is thrown| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +To recreate what adding `@EnableMethodSecurity` does by default, you would publish the following configuration: + +Example 7. Full Pre-post Method Security Configuration + +Java + +``` +@EnableMethodSecurity(prePostEnabled = false) +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + Advisor preFilterAuthorizationMethodInterceptor() { + return new PreFilterAuthorizationMethodInterceptor(); + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + Advisor preAuthorizeAuthorizationMethodInterceptor() { + return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(); + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + Advisor postAuthorizeAuthorizationMethodInterceptor() { + return AuthorizationManagerAfterMethodInterceptor.postAuthorize(); + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + Advisor postFilterAuthorizationMethodInterceptor() { + return new PostFilterAuthorizationMethodInterceptor(); + } +} +``` + +Kotlin + +``` +@EnableMethodSecurity(prePostEnabled = false) +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun preFilterAuthorizationMethodInterceptor() : Advisor { + return PreFilterAuthorizationMethodInterceptor(); + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun preAuthorizeAuthorizationMethodInterceptor() : Advisor { + return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(); + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun postAuthorizeAuthorizationMethodInterceptor() : Advisor { + return AuthorizationManagerAfterMethodInterceptor.postAuthorize(); + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun postFilterAuthorizationMethodInterceptor() : Advisor { + return PostFilterAuthorizationMethodInterceptor(); + } +} +``` + +Xml + +``` + + + + + + + + +``` + +Notice that Spring Security’s method security is built using Spring AOP. +So, interceptors are invoked based on the order specified. +This can be customized by calling `setOrder` on the interceptor instances like so: + +Example 8. Publish Custom Advisor + +Java + +``` +@Bean +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) +Advisor postFilterAuthorizationMethodInterceptor() { + PostFilterAuthorizationMethodInterceptor interceptor = new PostFilterAuthorizationMethodInterceptor(); + interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1); + return interceptor; +} +``` + +Kotlin + +``` +@Bean +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) +fun postFilterAuthorizationMethodInterceptor() : Advisor { + val interceptor = PostFilterAuthorizationMethodInterceptor(); + interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1); + return interceptor; +} +``` + +Xml + +``` + + + +``` + +You may want to only support `@PreAuthorize` in your application, in which case you can do the following: + +Example 9. Only @PreAuthorize Configuration + +Java + +``` +@EnableMethodSecurity(prePostEnabled = false) +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + Advisor preAuthorize() { + return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(); + } +} +``` + +Kotlin + +``` +@EnableMethodSecurity(prePostEnabled = false) +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun preAuthorize() : Advisor { + return AuthorizationManagerBeforeMethodInterceptor.preAuthorize() + } +} +``` + +Xml + +``` + + + + + +``` + +Or, you may have a custom before-method `AuthorizationManager` that you want to add to the list. + +In this case, you will need to tell Spring Security both the `AuthorizationManager` and to which methods and classes your authorization manager applies. + +Thus, you can configure Spring Security to invoke your `AuthorizationManager` in between `@PreAuthorize` and `@PostAuthorize` like so: + +Example 10. Custom Before Advisor + +Java + +``` +@EnableMethodSecurity +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + public Advisor customAuthorize() { + JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut(); + pattern.setPattern("org.mycompany.myapp.service.*"); + AuthorizationManager rule = AuthorityAuthorizationManager.isAuthenticated(); + AuthorizationManagerBeforeMethodInterceptor interceptor = new AuthorizationManagerBeforeMethodInterceptor(pattern, rule); + interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1); + return interceptor; + } +} +``` + +Kotlin + +``` +@EnableMethodSecurity +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun customAuthorize() : Advisor { + val pattern = JdkRegexpMethodPointcut(); + pattern.setPattern("org.mycompany.myapp.service.*"); + val rule = AuthorityAuthorizationManager.isAuthenticated(); + val interceptor = AuthorizationManagerBeforeMethodInterceptor(pattern, rule); + interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1); + return interceptor; + } +} +``` + +Xml + +``` + + + + + + + + + + + + + + + +``` + +| |You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------| + +The same can be done for after-method authorization. +After-method authorization is generally concerned with analysing the return value to verify access. + +For example, you might have a method that confirms that the account requested actually belongs to the logged-in user like so: + +Example 11. @PostAuthorize example + +Java + +``` +public interface BankService { + + @PreAuthorize("hasRole('USER')") + @PostAuthorize("returnObject.owner == authentication.name") + Account readAccount(Long id); +} +``` + +Kotlin + +``` +interface BankService { + + @PreAuthorize("hasRole('USER')") + @PostAuthorize("returnObject.owner == authentication.name") + fun readAccount(id : Long) : Account +} +``` + +You can supply your own `AuthorizationMethodInterceptor` to customize how access to the return value is evaluated. + +For example, if you have your own custom annotation, you can configure it like so: + +Example 12. Custom After Advisor + +Java + +``` +@EnableMethodSecurity +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + public Advisor customAuthorize(AuthorizationManager rules) { + AnnotationMethodMatcher pattern = new AnnotationMethodMatcher(MySecurityAnnotation.class); + AuthorizationManagerAfterMethodInterceptor interceptor = new AuthorizationManagerAfterMethodInterceptor(pattern, rules); + interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1); + return interceptor; + } +} +``` + +Kotlin + +``` +@EnableMethodSecurity +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun customAuthorize(rules : AuthorizationManager) : Advisor { + val pattern = AnnotationMethodMatcher(MySecurityAnnotation::class.java); + val interceptor = AuthorizationManagerAfterMethodInterceptor(pattern, rules); + interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1); + return interceptor; + } +} +``` + +Xml + +``` + + + + + + + + + + + + + + + +``` + +and it will be invoked after the `@PostAuthorize` interceptor. + +## EnableGlobalMethodSecurity + +We can enable annotation-based security using the `@EnableGlobalMethodSecurity` annotation on any `@Configuration` instance. +For example, the following would enable Spring Security’s `@Secured` annotation. + +Java + +``` +@EnableGlobalMethodSecurity(securedEnabled = true) +public class MethodSecurityConfig { +// ... +} +``` + +Kotlin + +``` +@EnableGlobalMethodSecurity(securedEnabled = true) +open class MethodSecurityConfig { + // ... +} +``` + +Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly. +Spring Security’s native annotation support defines a set of attributes for the method. +These will be passed to the AccessDecisionManager for it to make the actual decision: + +Java + +``` +public interface BankService { + +@Secured("IS_AUTHENTICATED_ANONYMOUSLY") +public Account readAccount(Long id); + +@Secured("IS_AUTHENTICATED_ANONYMOUSLY") +public Account[] findAccounts(); + +@Secured("ROLE_TELLER") +public Account post(Account account, double amount); +} +``` + +Kotlin + +``` +interface BankService { + @Secured("IS_AUTHENTICATED_ANONYMOUSLY") + fun readAccount(id: Long): Account + + @Secured("IS_AUTHENTICATED_ANONYMOUSLY") + fun findAccounts(): Array + + @Secured("ROLE_TELLER") + fun post(account: Account, amount: Double): Account +} +``` + +Support for JSR-250 annotations can be enabled using + +Java + +``` +@EnableGlobalMethodSecurity(jsr250Enabled = true) +public class MethodSecurityConfig { +// ... +} +``` + +Kotlin + +``` +@EnableGlobalMethodSecurity(jsr250Enabled = true) +open class MethodSecurityConfig { + // ... +} +``` + +These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security’s native annotations. +To use the new expression-based syntax, you would use + +Java + +``` +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class MethodSecurityConfig { +// ... +} +``` + +Kotlin + +``` +@EnableGlobalMethodSecurity(prePostEnabled = true) +open class MethodSecurityConfig { + // ... +} +``` + +and the equivalent Java code would be + +Java + +``` +public interface BankService { + +@PreAuthorize("isAnonymous()") +public Account readAccount(Long id); + +@PreAuthorize("isAnonymous()") +public Account[] findAccounts(); + +@PreAuthorize("hasAuthority('ROLE_TELLER')") +public Account post(Account account, double amount); +} +``` + +Kotlin + +``` +interface BankService { + @PreAuthorize("isAnonymous()") + fun readAccount(id: Long): Account + + @PreAuthorize("isAnonymous()") + fun findAccounts(): Array + + @PreAuthorize("hasAuthority('ROLE_TELLER')") + fun post(account: Account, amount: Double): Account +} +``` + +## GlobalMethodSecurityConfiguration + +Sometimes you may need to perform operations that are more complicated than are possible with the `@EnableGlobalMethodSecurity` annotation allow. +For these instances, you can extend the `GlobalMethodSecurityConfiguration` ensuring that the `@EnableGlobalMethodSecurity` annotation is present on your subclass. +For example, if you wanted to provide a custom `MethodSecurityExpressionHandler`, you could use the following configuration: + +Java + +``` +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { + @Override + protected MethodSecurityExpressionHandler createExpressionHandler() { + // ... create and return custom MethodSecurityExpressionHandler ... + return expressionHandler; + } +} +``` + +Kotlin + +``` +@EnableGlobalMethodSecurity(prePostEnabled = true) +open class MethodSecurityConfig : GlobalMethodSecurityConfiguration() { + override fun createExpressionHandler(): MethodSecurityExpressionHandler { + // ... create and return custom MethodSecurityExpressionHandler ... + return expressionHandler + } +} +``` + +For additional information about methods that can be overridden, refer to the `GlobalMethodSecurityConfiguration` Javadoc. + +## The \ Element + +This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element), and also to group together security pointcut declarations which will be applied across your entire application context. +You should only declare one `` element. +The following declaration would enable support for Spring Security’s `@Secured`: + +``` + +``` + +Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly. +Spring Security’s native annotation support defines a set of attributes for the method. +These will be passed to the `AccessDecisionManager` for it to make the actual decision: + +Java + +``` +public interface BankService { + +@Secured("IS_AUTHENTICATED_ANONYMOUSLY") +public Account readAccount(Long id); + +@Secured("IS_AUTHENTICATED_ANONYMOUSLY") +public Account[] findAccounts(); + +@Secured("ROLE_TELLER") +public Account post(Account account, double amount); +} +``` + +Kotlin + +``` +interface BankService { + @Secured("IS_AUTHENTICATED_ANONYMOUSLY") + fun readAccount(id: Long): Account + + @Secured("IS_AUTHENTICATED_ANONYMOUSLY") + fun findAccounts(): Array + + @Secured("ROLE_TELLER") + fun post(account: Account, amount: Double): Account +} +``` + +Support for JSR-250 annotations can be enabled using + +``` + +``` + +These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security’s native annotations. +To use the new expression-based syntax, you would use + +``` + +``` + +and the equivalent Java code would be + +Java + +``` +public interface BankService { + +@PreAuthorize("isAnonymous()") +public Account readAccount(Long id); + +@PreAuthorize("isAnonymous()") +public Account[] findAccounts(); + +@PreAuthorize("hasAuthority('ROLE_TELLER')") +public Account post(Account account, double amount); +} +``` + +Kotlin + +``` +interface BankService { + @PreAuthorize("isAnonymous()") + fun readAccount(id: Long): Account + + @PreAuthorize("isAnonymous()") + fun findAccounts(): Array + + @PreAuthorize("hasAuthority('ROLE_TELLER')") + fun post(account: Account, amount: Double): Account +} +``` + +Expression-based annotations are a good choice if you need to define simple rules that go beyond checking the role names against the user’s list of authorities. + +| |The annotated methods will only be secured for instances which are defined as Spring beans (in the same application context in which method-security is enabled).
If you want to secure instances which are not created by Spring (using the `new` operator, for example) then you need to use AspectJ.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +| |You can enable more than one type of annotation in the same application, but only one type should be used for any interface or class as the behaviour will not be well-defined otherwise.
If two annotations are found which apply to a particular method, then only one of them will be applied.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## Adding Security Pointcuts using protect-pointcut + +The use of `protect-pointcut` is particularly powerful, as it allows you to apply security to many beans with only a simple declaration. +Consider the following example: + +``` + + + +``` + +This will protect all methods on beans declared in the application context whose classes are in the `com.mycompany` package and whose class names end in "Service". +Only users with the `ROLE_USER` role will be able to invoke these methods. +As with URL matching, the most specific matches must come first in the list of pointcuts, as the first matching expression will be used. +Security annotations take precedence over pointcuts. + +[Secure Object Implementations](secure-objects.html)[Domain Object Security ACLs](acls.html) + diff --git a/docs/en/spring-security/servlet-authorization-secure-objects.md b/docs/en/spring-security/servlet-authorization-secure-objects.md new file mode 100644 index 0000000000000000000000000000000000000000..0a30d7fff05babe720782abfc8f654039e2bf652 --- /dev/null +++ b/docs/en/spring-security/servlet-authorization-secure-objects.md @@ -0,0 +1,130 @@ +# Secure Object Implementations + +## Security Interceptor + +Prior to Spring Security 2.0, securing `MethodInvocation`s needed quite a lot of boiler plate configuration. +Now the recommended approach for method security is to use [namespace configuration](../configuration/xml-namespace.html#ns-method-security). +This way the method security infrastructure beans are configured automatically for you so you don’t really need to know about the implementation classes. +We’ll just provide a quick overview of the classes that are involved here. + +Method security is enforced using a `MethodSecurityInterceptor`, which secures `MethodInvocation`s. +Depending on the configuration approach, an interceptor may be specific to a single bean or shared between multiple beans. +The interceptor uses a `MethodSecurityMetadataSource` instance to obtain the configuration attributes that apply to a particular method invocation.`MapBasedMethodSecurityMetadataSource` is used to store configuration attributes keyed by method names (which can be wildcarded) and will be used internally when the attributes are defined in the application context using the `` or `` elements. +Other implementations will be used to handle annotation-based configuration. + +### Explicit MethodSecurityInterceptor Configuration + +You can of course configure a `MethodSecurityInterceptor` directly in your application context for use with one of Spring AOP’s proxying mechanisms: + +``` + + + + + + + + + + + +``` + +## Security Interceptor + +The AspectJ security interceptor is very similar to the AOP Alliance security interceptor discussed in the previous section. +Indeed we will only discuss the differences in this section. + +The AspectJ interceptor is named `AspectJSecurityInterceptor`. +Unlike the AOP Alliance security interceptor, which relies on the Spring application context to weave in the security interceptor via proxying, the `AspectJSecurityInterceptor` is weaved in via the AspectJ compiler. +It would not be uncommon to use both types of security interceptors in the same application, with `AspectJSecurityInterceptor` being used for domain object instance security and the AOP Alliance `MethodSecurityInterceptor` being used for services layer security. + +Let’s first consider how the `AspectJSecurityInterceptor` is configured in the Spring application context: + +``` + + + + + + + + + + + +``` + +As you can see, aside from the class name, the `AspectJSecurityInterceptor` is exactly the same as the AOP Alliance security interceptor. +Indeed the two interceptors can share the same `securityMetadataSource`, as the `SecurityMetadataSource` works with `java.lang.reflect.Method`s rather than an AOP library-specific class. +Of course, your access decisions have access to the relevant AOP library-specific invocation (ie `MethodInvocation` or `JoinPoint`) and as such can consider a range of addition criteria when making access decisions (such as method arguments). + +Next you’ll need to define an AspectJ `aspect`. +For example: + +``` +package org.springframework.security.samples.aspectj; + +import org.springframework.security.access.intercept.aspectj.AspectJSecurityInterceptor; +import org.springframework.security.access.intercept.aspectj.AspectJCallback; +import org.springframework.beans.factory.InitializingBean; + +public aspect DomainObjectInstanceSecurityAspect implements InitializingBean { + + private AspectJSecurityInterceptor securityInterceptor; + + pointcut domainObjectInstanceExecution(): target(PersistableEntity) + && execution(public * *(..)) && !within(DomainObjectInstanceSecurityAspect); + + Object around(): domainObjectInstanceExecution() { + if (this.securityInterceptor == null) { + return proceed(); + } + + AspectJCallback callback = new AspectJCallback() { + public Object proceedWithObject() { + return proceed(); + } + }; + + return this.securityInterceptor.invoke(thisJoinPoint, callback); + } + + public AspectJSecurityInterceptor getSecurityInterceptor() { + return securityInterceptor; + } + + public void setSecurityInterceptor(AspectJSecurityInterceptor securityInterceptor) { + this.securityInterceptor = securityInterceptor; + } + + public void afterPropertiesSet() throws Exception { + if (this.securityInterceptor == null) + throw new IllegalArgumentException("securityInterceptor required"); + } + } +} +``` + +In the above example, the security interceptor will be applied to every instance of `PersistableEntity`, which is an abstract class not shown (you can use any other class or `pointcut` expression you like). +For those curious, `AspectJCallback` is needed because the `proceed();` statement has special meaning only within an `around()` body. +The `AspectJSecurityInterceptor` calls this anonymous `AspectJCallback` class when it wants the target object to continue. + +You will need to configure Spring to load the aspect and wire it with the `AspectJSecurityInterceptor`. +A bean declaration which achieves this is shown below: + +``` + + + +``` + +That’s it! +Now you can create your beans from anywhere within your application, using whatever means you think fit (e.g. `new Person();`) and they will have the security interceptor applied. + +[Expression-Based Access Control](expression-based.html)[Method Security](method-security.html) + diff --git a/docs/en/spring-security/servlet-configuration-java.md b/docs/en/spring-security/servlet-configuration-java.md new file mode 100644 index 0000000000000000000000000000000000000000..67618d29e67ea8757d82d7473885d16b290ea202 --- /dev/null +++ b/docs/en/spring-security/servlet-configuration-java.md @@ -0,0 +1,347 @@ +# Java Configuration + +General support for [Java Configuration](https://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java) was added to Spring Framework in Spring 3.1. +Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML. + +If you are familiar with the [Security Namespace Configuration](xml-namespace.html#ns-config) then you should find quite a few similarities between it and the Security Java Configuration support. + +| |Spring Security provides [lots of sample applications](https://github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration) which demonstrate the use of Spring Security Java Configuration.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## Hello Web Security Java Configuration + +The first step is to create our Spring Security Java Configuration. +The configuration creates a Servlet Filter known as the `springSecurityFilterChain` which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application. +You can find the most basic example of a Spring Security Java Configuration below: + +``` +import org.springframework.beans.factory.annotation.Autowired; + +import org.springframework.context.annotation.*; +import org.springframework.security.config.annotation.authentication.builders.*; +import org.springframework.security.config.annotation.web.configuration.*; + +@EnableWebSecurity +public class WebSecurityConfig { + + @Bean + public UserDetailsService userDetailsService() { + InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); + manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build()); + return manager; + } +} +``` + +There really isn’t much to this configuration, but it does a lot. +You can find a summary of the features below: + +* Require authentication to every URL in your application + +* Generate a login form for you + +* Allow the user with the **Username** *user* and the **Password** *password* to authenticate with form based authentication + +* Allow the user to logout + +* [CSRF attack](https://en.wikipedia.org/wiki/Cross-site_request_forgery) prevention + +* [Session Fixation](https://en.wikipedia.org/wiki/Session_fixation) protection + +* Security Header integration + + * [HTTP Strict Transport Security](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) for secure requests + + * [X-Content-Type-Options](https://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx) integration + + * Cache Control (can be overridden later by your application to allow caching of your static resources) + + * [X-XSS-Protection](https://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx) integration + + * X-Frame-Options integration to help prevent [Clickjacking](https://en.wikipedia.org/wiki/Clickjacking) + +* Integrate with the following Servlet API methods + + * [HttpServletRequest#getRemoteUser()](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()) + + * [HttpServletRequest#getUserPrincipal()](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()) + + * [HttpServletRequest#isUserInRole(java.lang.String)](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)) + + * [HttpServletRequest#login(java.lang.String, java.lang.String)](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)) + + * [HttpServletRequest#logout()](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()) + +### AbstractSecurityWebApplicationInitializer + +The next step is to register the `springSecurityFilterChain` with the war. +This can be done in Java Configuration with [Spring’s WebApplicationInitializer support](https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config) in a Servlet 3.0+ environment. +Not suprisingly, Spring Security provides a base class `AbstractSecurityWebApplicationInitializer` that will ensure the `springSecurityFilterChain` gets registered for you. +The way in which we use `AbstractSecurityWebApplicationInitializer` differs depending on if we are already using Spring or if Spring Security is the only Spring component in our application. + +* [AbstractSecurityWebApplicationInitializer without Existing Spring](#abstractsecuritywebapplicationinitializer-without-existing-spring) - Use these instructions if you are not using Spring already + +* [AbstractSecurityWebApplicationInitializer with Spring MVC](#abstractsecuritywebapplicationinitializer-with-spring-mvc) - Use these instructions if you are already using Spring + +### AbstractSecurityWebApplicationInitializer without Existing Spring + +If you are not using Spring or Spring MVC, you will need to pass in the `WebSecurityConfig` into the superclass to ensure the configuration is picked up. +You can find an example below: + +``` +import org.springframework.security.web.context.*; + +public class SecurityWebApplicationInitializer + extends AbstractSecurityWebApplicationInitializer { + + public SecurityWebApplicationInitializer() { + super(WebSecurityConfig.class); + } +} +``` + +The `SecurityWebApplicationInitializer` will do the following things: + +* Automatically register the springSecurityFilterChain Filter for every URL in your application + +* Add a ContextLoaderListener that loads the [WebSecurityConfig](#jc-hello-wsca). + +### AbstractSecurityWebApplicationInitializer with Spring MVC + +If we were using Spring elsewhere in our application we probably already had a `WebApplicationInitializer` that is loading our Spring Configuration. +If we use the previous configuration we would get an error. +Instead, we should register Spring Security with the existing `ApplicationContext`. +For example, if we were using Spring MVC our `SecurityWebApplicationInitializer` would look something like the following: + +``` +import org.springframework.security.web.context.*; + +public class SecurityWebApplicationInitializer + extends AbstractSecurityWebApplicationInitializer { + +} +``` + +This would simply only register the springSecurityFilterChain Filter for every URL in your application. +After that we would ensure that `WebSecurityConfig` was loaded in our existing ApplicationInitializer. +For example, if we were using Spring MVC it would be added in the `getRootConfigClasses()` + +``` +public class MvcWebApplicationInitializer extends + AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { WebSecurityConfig.class }; + } + + // ... other overrides ... +} +``` + +## HttpSecurity + +Thus far our [WebSecurityConfig](#jc-hello-wsca) only contains information about how to authenticate our users. +How does Spring Security know that we want to require all users to be authenticated? +How does Spring Security know we want to support form based authentication? +Actually, there is a configuration class that is being invoked behind the scenes called `WebSecurityConfigurerAdapter`. +It has a method called `configure` with the following default implementation: + +``` +protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests(authorize -> authorize + .anyRequest().authenticated() + ) + .formLogin(withDefaults()) + .httpBasic(withDefaults()); +} +``` + +The default configuration above: + +* Ensures that any request to our application requires the user to be authenticated + +* Allows users to authenticate with form based login + +* Allows users to authenticate with HTTP Basic authentication + +You will notice that this configuration is quite similar the XML Namespace configuration: + +``` + + + + + +``` + +## Multiple HttpSecurity + +We can configure multiple HttpSecurity instances just as we can have multiple `` blocks. +The key is to extend the `WebSecurityConfigurerAdapter` multiple times. +For example, the following is an example of having a different configuration for URL’s that start with `/api/`. + +``` +@EnableWebSecurity +public class MultiHttpSecurityConfig { + @Bean (1) + public UserDetailsService userDetailsService() throws Exception { + // ensure the passwords are encoded properly + UserBuilder users = User.withDefaultPasswordEncoder(); + InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); + manager.createUser(users.username("user").password("password").roles("USER").build()); + manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build()); + return manager; + } + + @Configuration + @Order(1) (2) + public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { + protected void configure(HttpSecurity http) throws Exception { + http + .antMatcher("/api/**") (3) + .authorizeHttpRequests(authorize -> authorize + .anyRequest().hasRole("ADMIN") + ) + .httpBasic(withDefaults()); + } + } + + @Configuration (4) + public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests(authorize -> authorize + .anyRequest().authenticated() + ) + .formLogin(withDefaults()); + } + } +} +``` + +|**1**| Configure Authentication as normal | +|-----|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**| Create an instance of `WebSecurityConfigurerAdapter` that contains `@Order` to specify which `WebSecurityConfigurerAdapter` should be considered first. | +|**3**| The `http.antMatcher` states that this `HttpSecurity` will only be applicable to URLs that start with `/api/` | +|**4**|Create another instance of `WebSecurityConfigurerAdapter`.
If the URL does not start with `/api/` this configuration will be used.
This configuration is considered after `ApiWebSecurityConfigurationAdapter` since it has an `@Order` value after `1` (no `@Order` defaults to last).| + +## Custom DSLs + +You can provide your own custom DSLs in Spring Security. +For example, you might have something that looks like this: + +``` +public class MyCustomDsl extends AbstractHttpConfigurer { + private boolean flag; + + @Override + public void init(HttpSecurity http) throws Exception { + // any method that adds another configurer + // must be done in the init method + http.csrf().disable(); + } + + @Override + public void configure(HttpSecurity http) throws Exception { + ApplicationContext context = http.getSharedObject(ApplicationContext.class); + + // here we lookup from the ApplicationContext. You can also just create a new instance. + MyFilter myFilter = context.getBean(MyFilter.class); + myFilter.setFlag(flag); + http.addFilterBefore(myFilter, UsernamePasswordAuthenticationFilter.class); + } + + public MyCustomDsl flag(boolean value) { + this.flag = value; + return this; + } + + public static MyCustomDsl customDsl() { + return new MyCustomDsl(); + } +} +``` + +| |This is actually how methods like `HttpSecurity.authorizeRequests()` are implemented.| +|---|-------------------------------------------------------------------------------------| + +The custom DSL can then be used like this: + +``` +@EnableWebSecurity +public class Config extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .apply(customDsl()) + .flag(true) + .and() + ...; + } +} +``` + +The code is invoked in the following order: + +* Code in `Config`s configure method is invoked + +* Code in `MyCustomDsl`s init method is invoked + +* Code in `MyCustomDsl`s configure method is invoked + +If you want, you can have `WebSecurityConfigurerAdapter` add `MyCustomDsl` by default by using `SpringFactories`. +For example, you would create a resource on the classpath named `META-INF/spring.factories` with the following contents: + +META-INF/spring.factories + +``` +org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyCustomDsl +``` + +Users wishing to disable the default can do so explicitly. + +``` +@EnableWebSecurity +public class Config extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .apply(customDsl()).disable() + ...; + } +} +``` + +## Post Processing Configured Objects + +Spring Security’s Java Configuration does not expose every property of every object that it configures. +This simplifies the configuration for a majority of users. +Afterall, if every property was exposed, users could use standard bean configuration. + +While there are good reasons to not directly expose every property, users may still need more advanced configuration options. +To address this Spring Security introduces the concept of an `ObjectPostProcessor` which can be used to modify or replace many of the Object instances created by the Java Configuration. +For example, if you wanted to configure the `filterSecurityPublishAuthorizationSuccess` property on `FilterSecurityInterceptor` you could use the following: + +``` +@Override +protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests(authorize -> authorize + .anyRequest().authenticated() + .withObjectPostProcessor(new ObjectPostProcessor() { + public O postProcess( + O fsi) { + fsi.setPublishAuthorizationSuccess(true); + return fsi; + } + }) + ); +} +``` + +[JSP Taglib](../integrations/jsp-taglibs.html)[Kotlin Configuration](kotlin.html) + diff --git a/docs/en/spring-security/servlet-configuration-kotlin.md b/docs/en/spring-security/servlet-configuration-kotlin.md new file mode 100644 index 0000000000000000000000000000000000000000..a55ff3df3bb0c27f3b1b22feec817f4ac70e6983 --- /dev/null +++ b/docs/en/spring-security/servlet-configuration-kotlin.md @@ -0,0 +1,96 @@ +# Kotlin Configuration + +| |Spring Security provides [a sample application](https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/kotlin/hello-security) which demonstrates the use of Spring Security Kotlin Configuration.| +|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## HttpSecurity + +How does Spring Security know that we want to require all users to be authenticated? +How does Spring Security know we want to support form based authentication? +There is a configuration class that is being invoked behind the scenes called `WebSecurityConfigurerAdapter`. +It has a method called `configure` with the following default implementation: + +``` +fun configure(http: HttpSecurity) { + http { + authorizeRequests { + authorize(anyRequest, authenticated) + } + formLogin { } + httpBasic { } + } +} +``` + +The default configuration above: + +* Ensures that any request to our application requires the user to be authenticated + +* Allows users to authenticate with form based login + +* Allows users to authenticate with HTTP Basic authentication + +You will notice that this configuration is quite similar the XML Namespace configuration: + +``` + + + + + +``` + +## Multiple HttpSecurity + +We can configure multiple HttpSecurity instances just as we can have multiple `` blocks. +The key is to extend the `WebSecurityConfigurerAdapter` multiple times. +For example, the following is an example of having a different configuration for URL’s that start with `/api/`. + +``` +@EnableWebSecurity +class MultiHttpSecurityConfig { + @Bean (1) + public fun userDetailsService(): UserDetailsService { + val users: User.UserBuilder = User.withDefaultPasswordEncoder() + val manager = InMemoryUserDetailsManager() + manager.createUser(users.username("user").password("password").roles("USER").build()) + manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build()) + return manager + } + + @Configuration + @Order(1) (2) + class ApiWebSecurityConfigurationAdapter: WebSecurityConfigurerAdapter() { + override fun configure(http: HttpSecurity) { + http { + securityMatcher("/api/**") (3) + authorizeRequests { + authorize(anyRequest, hasRole("ADMIN")) + } + httpBasic { } + } + } + } + + @Configuration (4) + class FormLoginWebSecurityConfigurerAdapter: WebSecurityConfigurerAdapter() { + override fun configure(http: HttpSecurity) { + http { + authorizeRequests { + authorize(anyRequest, authenticated) + } + formLogin { } + } + } + } +} +``` + +|**1**| Configure Authentication as normal | +|-----|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|**2**| Create an instance of `WebSecurityConfigurerAdapter` that contains `@Order` to specify which `WebSecurityConfigurerAdapter` should be considered first. | +|**3**| The `http.antMatcher` states that this `HttpSecurity` will only be applicable to URLs that start with `/api/` | +|**4**|Create another instance of `WebSecurityConfigurerAdapter`.
If the URL does not start with `/api/` this configuration will be used.
This configuration is considered after `ApiWebSecurityConfigurationAdapter` since it has an `@Order` value after `1` (no `@Order` defaults to last).| + +[Java Configuration](java.html)[Namespace Configuration](xml-namespace.html) + diff --git a/docs/en/spring-security/servlet-configuration-xml-namespace.md b/docs/en/spring-security/servlet-configuration-xml-namespace.md new file mode 100644 index 0000000000000000000000000000000000000000..09bfa80b41bdf5a6a062f8968b021d9e1fa5c8e5 --- /dev/null +++ b/docs/en/spring-security/servlet-configuration-xml-namespace.md @@ -0,0 +1,306 @@ +# Security Namespace Configuration + +## Introduction + +Namespace configuration has been available since version 2.0 of the Spring Framework. +It allows you to supplement the traditional Spring beans application context syntax with elements from additional XML schema. +You can find more information in the Spring [Reference Documentation](https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/). +A namespace element can be used simply to allow a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax which more closely matches the problem domain and hides the underlying complexity from the user. +A simple element may conceal the fact that multiple beans and processing steps are being added to the application context. +For example, adding the following element from the security namespace to an application context will start up an embedded LDAP server for testing use within the application: + +``` + +``` + +This is much simpler than wiring up the equivalent Apache Directory Server beans. +The most common alternative configuration requirements are supported by attributes on the `ldap-server` element and the user is isolated from worrying about which beans they need to create and what the bean property names are.[1].]. +Use of a good XML editor while editing the application context file should provide information on the attributes and elements that are available. +We would recommend that you try out the [Eclipse IDE with Spring Tools](https://spring.io/tools) as it has special features for working with standard Spring namespaces. + +To start using the security namespace in your application context, you need to have the `spring-security-config` jar on your classpath. +Then all you need to do is add the schema declaration to your application context file: + +``` + + ... + +``` + +In many of the examples you will see (and in the sample applications), we will often use "security" as the default namespace rather than "beans", which means we can omit the prefix on all the security namespace elements, making the content easier to read. +You may also want to do this if you have your application context divided up into separate files and have most of your security configuration in one of them. +Your security application context file would then start like this + +``` + + ... + +``` + +We’ll assume this syntax is being used from now on in this chapter. + +### Design of the Namespace + +The namespace is designed to capture the most common uses of the framework and provide a simplified and concise syntax for enabling them within an application. +The design is based around the large-scale dependencies within the framework, and can be divided up into the following areas: + +* *Web/HTTP Security* - the most complex part. + Sets up the filters and related service beans used to apply the framework authentication mechanisms, to secure URLs, render login and error pages and much more. + +* *Business Object (Method) Security* - options for securing the service layer. + +* *AuthenticationManager* - handles authentication requests from other parts of the framework. + +* *AccessDecisionManager* - provides access decisions for web and method security. + A default one will be registered, but you can also choose to use a custom one, declared using normal Spring bean syntax. + +* *AuthenticationProvider*s - mechanisms against which the authentication manager authenticates users. + The namespace provides supports for several standard options and also a means of adding custom beans declared using a traditional syntax. + +* *UserDetailsService* - closely related to authentication providers, but often also required by other beans. + +We’ll see how to configure these in the following sections. + +## Getting Started with Security Namespace Configuration + +In this section, we’ll look at how you can build up a namespace configuration to use some of the main features of the framework. +Let’s assume you initially want to get up and running as quickly as possible and add authentication support and access control to an existing web application, with a few test logins. +Then we’ll look at how to change over to authenticating against a database or other security repository. +In later sections we’ll introduce more advanced namespace configuration options. + +### web.xml Configuration + +The first thing you need to do is add the following filter declaration to your `web.xml` file: + +``` + +springSecurityFilterChain +org.springframework.web.filter.DelegatingFilterProxy + + + +springSecurityFilterChain +/* + +``` + +This provides a hook into the Spring Security web infrastructure.`DelegatingFilterProxy` is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. +In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security. +Note that you should not use this bean name yourself. +Once you’ve added this to your `web.xml`, you’re ready to start editing your application context file. +Web security services are configured using the `` element. + +### A Minimal \ Configuration + +All you need to enable web security to begin with is + +``` + + + + + +``` + +Which says that we want all URLs within our application to be secured, requiring the role `ROLE_USER` to access them, we want to log in to the application using a form with username and password, and that we want a logout URL registered which will allow us to log out of the application.`` element is the parent for all web-related namespace functionality. +The `` element defines a `pattern` which is matched against the URLs of incoming requests using an ant path style syntax [2] for more details on how matches are actually performed.]. +You can also use regular-expression matching as an alternative (see the namespace appendix for more details). +The `access` attribute defines the access requirements for requests matching the given pattern. +With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request. +The prefix "ROLE\_" is a marker which indicates that a simple comparison with the user’s authorities should be made. +In other words, a normal role-based check should be used. +Access-control in Spring Security is not limited to the use of simple roles (hence the use of the prefix to differentiate between different types of security attributes). +We’ll see later how the interpretation can vary [3]. +In Spring Security 3.0, the attribute can also be populated with an [EL expression](../authorization/expression-based.html#el-access). + +| |You can use multiple `` elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used.
So you must put the most specific matches at the top.
You can also add a `method` attribute to limit the match to a particular HTTP method (`GET`, `POST`, `PUT` etc.).| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +To add some users, you can define a set of test data directly in the namespace: + +``` + + + + + + + + + +``` + +This is an example of a secure way of storing the same passwords. +The password is prefixed with `{bcrypt}` to instruct `DelegatingPasswordEncoder`, which supports any configured `PasswordEncoder` for matching, that the passwords are hashed using BCrypt: + +``` + + + + + + + + + + +``` + +If you are familiar with pre-namespace versions of the framework, you can probably already guess roughly what’s going on here. +The `` element is responsible for creating a `FilterChainProxy` and the filter beans which it uses. +Common problems like incorrect filter ordering are no longer an issue as the filter positions are predefined. + +The `` element creates a `DaoAuthenticationProvider` bean and the `` element creates an `InMemoryDaoImpl`. +All `authentication-provider` elements must be children of the `` element, which creates a `ProviderManager` and registers the authentication providers with it. +You can find more detailed information on the beans that are created in the [namespace appendix](../appendix/namespace/index.html#appendix-namespace). +It’s worth cross-checking this if you want to start understanding what the important classes in the framework are and how they are used, particularly if you want to customise things later. + +The configuration above defines two users, their passwords and their roles within the application (which will be used for access control). +It is also possible to load user information from a standard properties file using the `properties` attribute on `user-service`. +See the section on [in-memory authentication](../authentication/passwords/in-memory.html#servlet-authentication-inmemory) for more details on the file format. +Using the `` element means that the user information will be used by the authentication manager to process authentication requests. +You can have multiple `` elements to define different authentication sources and each will be consulted in turn. + +At this point you should be able to start up your application and you will be required to log in to proceed. +Try it out, or try experimenting with the "tutorial" sample application that comes with the project. + +#### Setting a Default Post-Login Destination + +If a form login isn’t prompted by an attempt to access a protected resource, the `default-target-url` option comes into play. +This is the URL the user will be taken to after successfully logging in, and defaults to "/". +You can also configure things so that the user *always* ends up at this page (regardless of whether the login was "on-demand" or they explicitly chose to log in) by setting the `always-use-default-target` attribute to "true". +This is useful if your application always requires that the user starts at a "home" page, for example: + +``` + + + + + +``` + +For even more control over the destination, you can use the `authentication-success-handler-ref` attribute as an alternative to `default-target-url`. +The referenced bean should be an instance of `AuthenticationSuccessHandler`. + +## Advanced Web Features + +### Adding in Your Own Filters + +If you’ve used Spring Security before, you’ll know that the framework maintains a chain of filters in order to apply its services. +You may want to add your own filters to the stack at particular locations or use a Spring Security filter for which there isn’t currently a namespace configuration option (CAS, for example). +Or you might want to use a customized version of a standard namespace filter, such as the `UsernamePasswordAuthenticationFilter` which is created by the `` element, taking advantage of some of the extra configuration options which are available by using the bean explicitly. +How can you do this with namespace configuration, since the filter chain is not directly exposed? + +The order of the filters is always strictly enforced when using the namespace. +When the application context is being created, the filter beans are sorted by the namespace handling code and the standard Spring Security filters each have an alias in the namespace and a well-known position. + +| |In previous versions, the sorting took place after the filter instances had been created, during post-processing of the application context.
In version 3.0+ the sorting is now done at the bean metadata level, before the classes have been instantiated.
This has implications for how you add your own filters to the stack as the entire filter list must be known during the parsing of the `` element, so the syntax has changed slightly in 3.0.| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +The filters, aliases and namespace elements/attributes which create the filters are shown in [Standard Filter Aliases and Ordering](#filter-stack). +The filters are listed in the order in which they occur in the filter chain. + +| Alias | Filter Class | Namespace Element or Attribute | +|------------------------------|-----------------------------------------------------|-------------------------------------------------------| +| CHANNEL\_FILTER | `ChannelProcessingFilter` |`http/[[email protected]](/cdn-cgi/l/email-protection)`| +| SECURITY\_CONTEXT\_FILTER | `SecurityContextPersistenceFilter` | `http` | +| CONCURRENT\_SESSION\_FILTER | `ConcurrentSessionFilter` | `session-management/concurrency-control` | +| HEADERS\_FILTER | `HeaderWriterFilter` | `http/headers` | +| CSRF\_FILTER | `CsrfFilter` | `http/csrf` | +| LOGOUT\_FILTER | `LogoutFilter` | `http/logout` | +| X509\_FILTER | `X509AuthenticationFilter` | `http/x509` | +| PRE\_AUTH\_FILTER |`AbstractPreAuthenticatedProcessingFilter` Subclasses| N/A | +| CAS\_FILTER | `CasAuthenticationFilter` | N/A | +| FORM\_LOGIN\_FILTER | `UsernamePasswordAuthenticationFilter` | `http/form-login` | +| BASIC\_AUTH\_FILTER | `BasicAuthenticationFilter` | `http/http-basic` | +|SERVLET\_API\_SUPPORT\_FILTER | `SecurityContextHolderAwareRequestFilter` | `http/@servlet-api-provision` | +| JAAS\_API\_SUPPORT\_FILTER | `JaasApiIntegrationFilter` | `http/@jaas-api-provision` | +| REMEMBER\_ME\_FILTER | `RememberMeAuthenticationFilter` | `http/remember-me` | +| ANONYMOUS\_FILTER | `AnonymousAuthenticationFilter` | `http/anonymous` | +| SESSION\_MANAGEMENT\_FILTER | `SessionManagementFilter` | `session-management` | +|EXCEPTION\_TRANSLATION\_FILTER| `ExceptionTranslationFilter` | `http` | +|FILTER\_SECURITY\_INTERCEPTOR | `FilterSecurityInterceptor` | `http` | +| SWITCH\_USER\_FILTER | `SwitchUserFilter` | N/A | + +You can add your own filter to the stack, using the `custom-filter` element and one of these names to specify the position your filter should appear at: + +``` + + + + + +``` + +You can also use the `after` or `before` attributes if you want your filter to be inserted before or after another filter in the stack. +The names "FIRST" and "LAST" can be used with the `position` attribute to indicate that you want your filter to appear before or after the entire stack, respectively. + +| |Avoiding filter position conflicts

If you are inserting a custom filter which may occupy the same position as one of the standard filters created by the namespace then it’s important that you don’t include the namespace versions by mistake.
Remove any elements which create filters whose functionality you want to replace.

Note that you can’t replace filters which are created by the use of the `` element itself - `SecurityContextPersistenceFilter`, `ExceptionTranslationFilter` or `FilterSecurityInterceptor`.
Some other filters are added by default, but you can disable them.
An `AnonymousAuthenticationFilter` is added by default and unless you have [session-fixation protection](../authentication/session-management.html#ns-session-fixation) disabled, a `SessionManagementFilter` will also be added to the filter chain.| +|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +If you’re replacing a namespace filter which requires an authentication entry point (i.e. where the authentication process is triggered by an attempt by an unauthenticated user to access to a secured resource), you will need to add a custom entry point bean too. + +## Method Security + +From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. +It provides support for JSR-250 annotation security as well as the framework’s original `@Secured` annotation. +From 3.0 you can also make use of new [expression-based annotations](../authorization/expression-based.html#el-access). +You can apply security to a single bean, using the `intercept-methods` element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts. + +## The Default AccessDecisionManager + +This section assumes you have some knowledge of the underlying architecture for access-control within Spring Security. +If you don’t you can skip it and come back to it later, as this section is only really relevant for people who need to do some customization in order to use more than simple role-based security. + +When you use a namespace configuration, a default instance of `AccessDecisionManager` is automatically registered for you and will be used for making access decisions for method invocations and web URL access, based on the access attributes you specify in your `intercept-url` and `protect-pointcut` declarations (and in annotations if you are using annotation secured methods). + +The default strategy is to use an `AffirmativeBased` `AccessDecisionManager` with a `RoleVoter` and an `AuthenticatedVoter`. +You can find out more about these in the chapter on [authorization](../authorization/architecture.html#authz-arch). + +### Customizing the AccessDecisionManager + +If you need to use a more complicated access control strategy then it is easy to set an alternative for both method and web security. + +For method security, you do this by setting the `access-decision-manager-ref` attribute on `global-method-security` to the `id` of the appropriate `AccessDecisionManager` bean in the application context: + +``` + +... + +``` + +The syntax for web security is the same, but on the `http` element: + +``` + +... + +``` + +--- + +[1](#_footnoteref_1). You can find out more about the use of the `ldap-server` element in the chapter on xref:servlet/authentication/unpwd/ldap.adoc#servlet-authentication-ldap[LDAP Authentication + +[2](#_footnoteref_2). See the section on xref:servlet/exploits/firewall.adoc#servlet-httpfirewall[`HttpFirewall` + +[3](#_footnoteref_3). The interpretation of the comma-separated values in the `access` attribute depends on the implementation of the [AccessDecisionManager](#ns-access-manager) which is used. + +[Kotlin Configuration](kotlin.html)[Testing](../test/index.html) + diff --git a/docs/en/spring-security/servlet-exploits-csrf.md b/docs/en/spring-security/servlet-exploits-csrf.md new file mode 100644 index 0000000000000000000000000000000000000000..57dd9606560a372e47b4f68d5f0ed1dad85bce2c --- /dev/null +++ b/docs/en/spring-security/servlet-exploits-csrf.md @@ -0,0 +1,428 @@ +# Cross Site Request Forgery (CSRF) for Servlet Environments + +This section discusses Spring Security’s [Cross Site Request Forgery (CSRF)](../../features/exploits/csrf.html#csrf) support for servlet environments. + +## Using Spring Security CSRF Protection + +The steps to using Spring Security’s CSRF protection are outlined below: + +* [Use proper HTTP verbs](#servlet-csrf-idempotent) + +* [Configure CSRF Protection](#servlet-csrf-configure) + +* [Include the CSRF Token](#servlet-csrf-include) + +### Use proper HTTP verbs + +The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. +This is covered in detail in [Safe Methods Must be Idempotent](../../features/exploits/csrf.html#csrf-protection-idempotent). + +### Configure CSRF Protection + +The next step is to configure Spring Security’s CSRF protection within your application. +Spring Security’s CSRF protection is enabled by default, but you may need to customize the configuration. +Below are a few common customizations. + +#### Custom CsrfTokenRepository + +By default Spring Security stores the expected CSRF token in the `HttpSession` using `HttpSessionCsrfTokenRepository`. +There can be cases where users will want to configure a custom `CsrfTokenRepository`. +For example, it might be desirable to persist the `CsrfToken` in a cookie to [support a JavaScript based application](#servlet-csrf-include-ajax-auto). + +By default the `CookieCsrfTokenRepository` will write to a cookie named `XSRF-TOKEN` and read it from a header named `X-XSRF-TOKEN` or the HTTP parameter `_csrf`. +These defaults come from [AngularJS](https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection) + +You can configure `CookieCsrfTokenRepository` in XML using the following: + +Example 1. Store CSRF Token in a Cookie with XML Configuration + +``` + + + + + +``` + +| |The sample explicitly sets `cookieHttpOnly=false`.
This is necessary to allow JavaScript (i.e. AngularJS) to read it.
If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit `cookieHttpOnly=false` to improve security.| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +You can configure `CookieCsrfTokenRepository` in Java Configuration using: + +Example 2. Store CSRF Token in a Cookie + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends + WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) { + http + .csrf(csrf -> csrf + .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) + ); + } +} +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + csrf { + csrfTokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse() + } + } + } +} +``` + +| |The sample explicitly sets `cookieHttpOnly=false`.
This is necessary to allow JavaScript (i.e. AngularJS) to read it.
If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit `cookieHttpOnly=false` (by using `new CookieCsrfTokenRepository()` instead) to improve security.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +#### Disable CSRF Protection + +CSRF protection is enabled by default. +However, it is simple to disable CSRF protection if it [makes sense for your application](../../features/exploits/csrf.html#csrf-when). + +The XML configuration below will disable CSRF protection. + +Example 3. Disable CSRF XML Configuration + +``` + + + + +``` + +The Java configuration below will disable CSRF protection. + +Example 4. Disable CSRF + +Java + +``` +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends + WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) { + http + .csrf(csrf -> csrf.disable()); + } +} +``` + +Kotlin + +``` +@Configuration +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + csrf { + disable() + } + } + } +} +``` + +### Include the CSRF Token + +In order for the [synchronizer token pattern](../../features/exploits/csrf.html#csrf-protection-stp) to protect against CSRF attacks, we must include the actual CSRF token in the HTTP request. +This must be included in a part of the request (i.e. form parameter, HTTP header, etc) that is not automatically included in the HTTP request by the browser. + +Spring Security’s [CsrfFilter](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfFilter.html) exposes a [CsrfToken](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfToken.html) as an `HttpServletRequest` attribute named `_csrf`. +This means that any view technology can access the `CsrfToken` to expose the expected token as either a [form](#servlet-csrf-include-form-attr) or [meta tag](#servlet-csrf-include-ajax-meta-attr). +Fortunately, there are integrations listed below that make including the token in [form](#servlet-csrf-include-form) and [ajax](#servlet-csrf-include-ajax) requests even easier. + +#### Form URL Encoded + +In order to post an HTML form the CSRF token must be included in the form as a hidden input. +For example, the rendered HTML might look like: + +Example 5. CSRF Token HTML + +``` + +``` + +Next we will discuss various ways of including the CSRF token in a form as a hidden input. + +##### Automatic CSRF Token Inclusion + +Spring Security’s CSRF support provides integration with Spring’s [RequestDataValueProcessor](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/support/RequestDataValueProcessor.html) via its [CsrfRequestDataValueProcessor](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/servlet/support/csrf/CsrfRequestDataValueProcessor.html). +This means that if you leverage [Spring’s form tag library](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib), [Thymeleaf](https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#integration-with-requestdatavalueprocessor), or any other view technology that integrates with `RequestDataValueProcessor`, then forms that have an unsafe HTTP method (i.e. post) will automatically include the actual CSRF token. + +##### csrfInput Tag + +If you are using JSPs, then you can use [Spring’s form tag library](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib). +However, if that is not an option, you can also easily include the token with the [csrfInput](../integrations/jsp-taglibs.html#taglibs-csrfinput) tag. + +##### CsrfToken Request Attribute + +If the [other options](#servlet-csrf-include) for including the actual CSRF token in the request do not work, you can take advantage of the fact that the `CsrfToken` [is exposed](#servlet-csrf-include) as an `HttpServletRequest` attribute named `_csrf`. + +An example of doing this with a JSP is shown below: + +Example 6. CSRF Token in Form with Request Attribute + +``` + +
+ + +
+``` + +#### Ajax and JSON Requests + +If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. +Instead you can submit the token within a HTTP header. + +In the following sections we will discuss various ways of including the CSRF token as an HTTP request header in JavaScript based applications. + +##### Automatic Inclusion + +Spring Security can easily be [configured](#servlet-csrf-configure-custom-repository) to store the expected CSRF token in a cookie. +By storing the expected CSRF in a cookie, JavaScript frameworks like [AngularJS](https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection) will automatically include the actual CSRF token in the HTTP request headers. + +##### Meta tags + +An alternative pattern to [exposing the CSRF in a cookie](#servlet-csrf-include-form-auto) is to include the CSRF token within your `meta` tags. +The HTML might look something like this: + +Example 7. CSRF meta tag HTML + +``` + + + + + + + +``` + +Once the meta tags contained the CSRF token, the JavaScript code would read the meta tags and include the CSRF token as a header. +If you were using jQuery, this could be done with the following: + +Example 8. AJAX send CSRF Token + +``` +$(function () { + var token = $("meta[name='_csrf']").attr("content"); + var header = $("meta[name='_csrf_header']").attr("content"); + $(document).ajaxSend(function(e, xhr, options) { + xhr.setRequestHeader(header, token); + }); +}); +``` + +###### csrfMeta tag + +If you are using JSPs a simple way to write the CSRF token to the `meta` tags is by leveraging the [csrfMeta](../integrations/jsp-taglibs.html#taglibs-csrfmeta) tag. + +###### CsrfToken Request Attribute + +If the [other options](#servlet-csrf-include) for including the actual CSRF token in the request do not work, you can take advantage of the fact that the `CsrfToken` [is exposed](#servlet-csrf-include) as an `HttpServletRequest` attribute named `_csrf`. +An example of doing this with a JSP is shown below: + +Example 9. CSRF meta tag JSP + +``` + + + + + + + + +``` + +## CSRF Considerations + +There are a few special considerations to consider when implementing protection against CSRF attacks. +This section discusses those considerations as it pertains to servlet environments. +Refer to [CSRF Considerations](../../features/exploits/csrf.html#csrf-considerations) for a more general discussion. + +### Logging In + +It is important to [require CSRF for log in](../../features/exploits/csrf.html#csrf-considerations-login) requests to protect against forging log in attempts. +Spring Security’s servlet support does this out of the box. + +### Logging Out + +It is important to [require CSRF for log out](../../features/exploits/csrf.html#csrf-considerations-logout) requests to protect against forging log out attempts. +If CSRF protection is enabled (default), Spring Security’s `LogoutFilter` to only process HTTP POST. +This ensures that log out requires a CSRF token and that a malicious user cannot forcibly log out your users. + +The easiest approach is to use a form to log out. +If you really want a link, you can use JavaScript to have the link perform a POST (i.e. maybe on a hidden form). +For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that will perform the POST. + +If you really want to use HTTP GET with logout you can do so, but remember this is generally not recommended. +For example, the following Java Configuration will perform logout with the URL `/logout` is requested with any HTTP method: + +Example 10. Log out with HTTP GET + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends + WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) { + http + .logout(logout -> logout + .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) + ); + } +} +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + logout { + logoutRequestMatcher = AntPathRequestMatcher("/logout") + } + } + } +} +``` + +### CSRF and Session Timeouts + +By default Spring Security stores the CSRF token in the `HttpSession`. +This can lead to a situation where the session expires which means there is not an expected CSRF token to validate against. + +We’ve already discussed [general solutions](../../features/exploits/csrf.html#csrf-considerations-login) to session timeouts. +This section discusses the specifics of CSRF timeouts as it pertains to the servlet support. + +It is simple to change storage of the expected CSRF token to be in a cookie. +For details, refer to the [Custom CsrfTokenRepository](#servlet-csrf-configure-custom-repository) section. + +If a token does expire, you might want to customize how it is handled by specifying a custom `AccessDeniedHandler`. +The custom `AccessDeniedHandler` can process the `InvalidCsrfTokenException` any way you like. +For an example of how to customize the `AccessDeniedHandler` refer to the provided links for both [xml](../appendix/namespace/http.html#nsa-access-denied-handler) and [Java configuration](https://github.com/spring-projects/spring-security/tree/5.6.2/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpServerAccessDeniedHandlerTests.java#L64). + +### + +We have [already discussed](../../features/exploits/csrf.html#csrf-considerations-multipart) how protecting multipart requests (file uploads) from CSRF attacks causes a [chicken and the egg](https://en.wikipedia.org/wiki/Chicken_or_the_egg) problem. +This section discusses how to implement placing the CSRF token in the [body](#servlet-csrf-considerations-multipart-body) and [url](#servlet-csrf-considerations-multipart-url) within a servlet application. + +| |More information about using multipart forms with Spring can be found within the [1.1.11. Multipart Resolver](https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web.html#mvc-multipart) section of the Spring reference and the [MultipartFilter javadoc](https://docs.spring.io/spring/docs/5.2.x/javadoc-api/org/springframework/web/multipart/support/MultipartFilter.html).| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +#### Place CSRF Token in the Body + +We have [already discussed](../../features/exploits/csrf.html#csrf-considerations-multipart-body) the tradeoffs of placing the CSRF token in the body. +In this section we will discuss how to configure Spring Security to read the CSRF from the body. + +In order to read the CSRF token from the body, the `MultipartFilter` is specified before the Spring Security filter. +Specifying the `MultipartFilter` before the Spring Security filter means that there is no authorization for invoking the `MultipartFilter` which means anyone can place temporary files on your server. +However, only authorized users will be able to submit a File that is processed by your application. +In general, this is the recommended approach because the temporary file upload should have a negligible impact on most servers. + +To ensure `MultipartFilter` is specified before the Spring Security filter with java configuration, users can override beforeSpringSecurityFilterChain as shown below: + +Example 11. Initializer MultipartFilter + +Java + +``` +public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer { + + @Override + protected void beforeSpringSecurityFilterChain(ServletContext servletContext) { + insertFilters(servletContext, new MultipartFilter()); + } +} +``` + +Kotlin + +``` +class SecurityApplicationInitializer : AbstractSecurityWebApplicationInitializer() { + override fun beforeSpringSecurityFilterChain(servletContext: ServletContext?) { + insertFilters(servletContext, MultipartFilter()) + } +} +``` + +To ensure `MultipartFilter` is specified before the Spring Security filter with XML configuration, users can ensure the \ element of the `MultipartFilter` is placed before the springSecurityFilterChain within the web.xml as shown below: + +Example 12. web.xml - MultipartFilter + +``` + + MultipartFilter + org.springframework.web.multipart.support.MultipartFilter + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + MultipartFilter + /* + + + springSecurityFilterChain + /* + +``` + +#### Include CSRF Token in URL + +If allowing unauthorized users to upload temporary files is not acceptable, an alternative is to place the `MultipartFilter` after the Spring Security filter and include the CSRF as a query parameter in the action attribute of the form. +Since the `CsrfToken` is exposed as an `HttpServletRequest` [request attribute](#servlet-csrf-include), we can use that to create an `action` with the CSRF token in it. +An example with a jsp is shown below + +Example 13. CSRF Token in Action + +``` +
+``` + +### HiddenHttpMethodFilter + +We have [already discussed](../../features/exploits/csrf.html#csrf-considerations-multipart-body) the trade-offs of placing the CSRF token in the body. + +In Spring’s Servlet support, overriding the HTTP method is done using [HiddenHttpMethodFilter](https://docs.spring.io/spring-framework/docs/5.2.x/javadoc-api/org/springframework/web/filter/reactive/HiddenHttpMethodFilter.html). +More information can be found in [HTTP Method Conversion](https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web.html#mvc-rest-method-conversion) section of the reference documentation. + +[Protection Against Exploits](index.html)[Security HTTP Response Headers](headers.html) + diff --git a/docs/en/spring-security/servlet-exploits-firewall.md b/docs/en/spring-security/servlet-exploits-firewall.md new file mode 100644 index 0000000000000000000000000000000000000000..0a97153db92019e87b1698be168517f6a24542a1 --- /dev/null +++ b/docs/en/spring-security/servlet-exploits-firewall.md @@ -0,0 +1,231 @@ +# HttpFirewall + +It’s important to understand what the mechanism is and what URL value is used when testing against the patterns that you define. + +The Servlet Specification defines several properties for the `HttpServletRequest` which are accessible via getter methods, and which we might want to match against. +These are the `contextPath`, `servletPath`, `pathInfo` and `queryString`. +Spring Security is only interested in securing paths within the application, so the `contextPath` is ignored. +Unfortunately, the servlet spec does not define exactly what the values of `servletPath` and `pathInfo` will contain for a particular request URI. +For example, each path segment of a URL may contain parameters, as defined in [RFC 2396](https://www.ietf.org/rfc/rfc2396.txt)[1]. +The Specification does not clearly state whether these should be included in the `servletPath` and `pathInfo` values and the behaviour varies between different servlet containers. +There is a danger that when an application is deployed in a container which does not strip path parameters from these values, an attacker could add them to the requested URL in order to cause a pattern match to succeed or fail unexpectedly.[2]. +Other variations in the incoming URL are also possible. +For example, it could contain path-traversal sequences (like `/../`) or multiple forward slashes (`//`) which could also cause pattern-matches to fail. +Some containers normalize these out before performing the servlet mapping, but others don’t. +To protect against issues like these, `FilterChainProxy` uses an `HttpFirewall` strategy to check and wrap the request. +Un-normalized requests are automatically rejected by default, and path parameters and duplicate slashes are removed for matching purposes.[3]. +It is therefore essential that a `FilterChainProxy` is used to manage the security filter chain. +Note that the `servletPath` and `pathInfo` values are decoded by the container, so your application should not have any valid paths which contain semi-colons, as these parts will be removed for matching purposes. + +As mentioned above, the default strategy is to use Ant-style paths for matching and this is likely to be the best choice for most users. +The strategy is implemented in the class `AntPathRequestMatcher` which uses Spring’s `AntPathMatcher` to perform a case-insensitive match of the pattern against the concatenated `servletPath` and `pathInfo`, ignoring the `queryString`. + +If for some reason, you need a more powerful matching strategy, you can use regular expressions. +The strategy implementation is then `RegexRequestMatcher`. +See the Javadoc for this class for more information. + +In practice we recommend that you use method security at your service layer, to control access to your application, and do not rely entirely on the use of security constraints defined at the web-application level. +URLs change and it is difficult to take account of all the possible URLs that an application might support and how requests might be manipulated. +You should try and restrict yourself to using a few simple ant paths which are simple to understand. +Always try to use a "deny-by-default" approach where you have a catch-all wildcard ( / **or** ) defined last and denying access. + +Security defined at the service layer is much more robust and harder to bypass, so you should always take advantage of Spring Security’s method security options. + +The `HttpFirewall` also prevents [HTTP Response Splitting](https://www.owasp.org/index.php/HTTP_Response_Splitting) by rejecting new line characters in the HTTP Response headers. + +By default the `StrictHttpFirewall` is used. +This implementation rejects requests that appear to be malicious. +If it is too strict for your needs, then you can customize what types of requests are rejected. +However, it is important that you do so knowing that this can open your application up to attacks. +For example, if you wish to leverage Spring MVC’s Matrix Variables, the following configuration could be used: + +Example 1. Allow Matrix Variables + +Java + +``` +@Bean +public StrictHttpFirewall httpFirewall() { + StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowSemicolon(true); + return firewall; +} +``` + +XML + +``` + + + +``` + +Kotlin + +``` +@Bean +fun httpFirewall(): StrictHttpFirewall { + val firewall = StrictHttpFirewall() + firewall.setAllowSemicolon(true) + return firewall +} +``` + +The `StrictHttpFirewall` provides an allowed list of valid HTTP methods that are allowed to protect against [Cross Site Tracing (XST)](https://owasp.org/www-community/attacks/Cross_Site_Tracing) and [HTTP Verb Tampering](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/06-Test_HTTP_Methods). +The default valid methods are "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", and "PUT". +If your application needs to modify the valid methods, you can configure a custom `StrictHttpFirewall` bean. +For example, the following will only allow HTTP "GET" and "POST" methods: + +Example 2. Allow Only GET & POST + +Java + +``` +@Bean +public StrictHttpFirewall httpFirewall() { + StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowedHttpMethods(Arrays.asList("GET", "POST")); + return firewall; +} +``` + +XML + +``` + + + +``` + +Kotlin + +``` +@Bean +fun httpFirewall(): StrictHttpFirewall { + val firewall = StrictHttpFirewall() + firewall.setAllowedHttpMethods(listOf("GET", "POST")) + return firewall +} +``` + +| |If you are using `new MockHttpServletRequest()` it currently creates an HTTP method as an empty String "".
This is an invalid HTTP method and will be rejected by Spring Security.
You can resolve this by replacing it with `new MockHttpServletRequest("GET", "")`.
See [SPR\_16851](https://jira.spring.io/browse/SPR-16851) for an issue requesting to improve this.| +|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +If you must allow any HTTP method (not recommended), you can use `StrictHttpFirewall.setUnsafeAllowAnyHttpMethod(true)`. +This will disable validation of the HTTP method entirely. + +`StrictHttpFirewall` also checks header names and values and parameter names. +It requires that each character have a defined code point and not be a control character. + +This requirement can be relaxed or adjusted as necessary using the following methods: + +* `StrictHttpFirewall#setAllowedHeaderNames(Predicate)` + +* `StrictHttpFirewall#setAllowedHeaderValues(Predicate)` + +* `StrictHttpFirewall#setAllowedParameterNames(Predicate)` + +| |Also, parameter values can be controlled with `setAllowedParameterValues(Predicate)`.| +|---|-------------------------------------------------------------------------------------| + +For example, to switch off this check, you can wire your `StrictHttpFirewall` with `Predicate`s that always return `true`, like so: + +Example 3. Allow Any Header Name, Header Value, and Parameter Name + +Java + +``` +@Bean +public StrictHttpFirewall httpFirewall() { + StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowedHeaderNames((header) -> true); + firewall.setAllowedHeaderValues((header) -> true); + firewall.setAllowedParameterNames((parameter) -> true); + return firewall; +} +``` + +Kotlin + +``` +@Bean +fun httpFirewall(): StrictHttpFirewall { + val firewall = StrictHttpFirewall() + firewall.setAllowedHeaderNames { true } + firewall.setAllowedHeaderValues { true } + firewall.setAllowedParameterNames { true } + return firewall +} +``` + +Or, there might be a specific value that you need to allow. + +For example, iPhone Xʀ uses a `User-Agent` that includes a character not in the ISO-8859-1 charset. +Due to this fact, some application servers will parse this value into two separate characters, the latter being an undefined character. + +You can address this with the `setAllowedHeaderValues` method, as you can see below: + +Example 4. Allow Certain User Agents + +Java + +``` +@Bean +public StrictHttpFirewall httpFirewall() { + StrictHttpFirewall firewall = new StrictHttpFirewall(); + Pattern allowed = Pattern.compile("[\\p{IsAssigned}&&[^\\p{IsControl}]]*"); + Pattern userAgent = ...; + firewall.setAllowedHeaderValues((header) -> allowed.matcher(header).matches() || userAgent.matcher(header).matches()); + return firewall; +} +``` + +Kotlin + +``` +@Bean +fun httpFirewall(): StrictHttpFirewall { + val firewall = StrictHttpFirewall() + val allowed = Pattern.compile("[\\p{IsAssigned}&&[^\\p{IsControl}]]*") + val userAgent = Pattern.compile(...) + firewall.setAllowedHeaderValues { allowed.matcher(it).matches() || userAgent.matcher(it).matches() } + return firewall +} +``` + +In the case of header values, you may instead consider parsing them as UTF-8 at verification time like so: + +Example 5. Parse Headers As UTF-8 + +Java + +``` +firewall.setAllowedHeaderValues((header) -> { + String parsed = new String(header.getBytes(ISO_8859_1), UTF_8); + return allowed.matcher(parsed).matches(); +}); +``` + +Kotlin + +``` +firewall.setAllowedHeaderValues { + val parsed = String(header.getBytes(ISO_8859_1), UTF_8) + return allowed.matcher(parsed).matches() +} +``` + +--- + +[1](#_footnoteref_1). You have probably seen this when a browser doesn’t support cookies and the `jsessionid` parameter is appended to the URL after a semi-colon. However the RFC allows the presence of these parameters in any path segment of the URL + +[2](#_footnoteref_2). The original values will be returned once the request leaves the `FilterChainProxy`, so will still be available to the application. + +[3](#_footnoteref_3). So, for example, an original request path `/secure;hack=1/somefile.html;hack=2` will be returned as `/secure/somefile.html`. + +[HTTP](http.html)[Integrations](../integrations/index.html) + diff --git a/docs/en/spring-security/servlet-exploits-headers.md b/docs/en/spring-security/servlet-exploits-headers.md new file mode 100644 index 0000000000000000000000000000000000000000..6b59a8b891c9cf3fa714323ae5392ea3962d610f --- /dev/null +++ b/docs/en/spring-security/servlet-exploits-headers.md @@ -0,0 +1,1113 @@ +# Security HTTP Response Headers + +[Security HTTP Response Headers](../../features/exploits/headers.html#headers) can be used to increase the security of web applications. +This section is dedicated to servlet based support for Security HTTP Response Headers. + +## Default Security Headers + +Spring Security provides a [default set of Security HTTP Response Headers](../../features/exploits/headers.html#headers-default) to provide secure defaults. +While each of these headers are considered best practice, it should be noted that not all clients utilize the headers, so additional testing is encouraged. + +You can customize specific headers. +For example, assume that you want the defaults except you wish to specify `SAMEORIGIN` for [X-Frame-Options](#servlet-headers-frame-options). + +You can easily do this with the following Configuration: + +Example 1. Customize Default Security Headers + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends + WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) { + http + // ... + .headers(headers -> headers + .frameOptions(frameOptions -> frameOptions + .sameOrigin() + ) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + frameOptions { + sameOrigin = true + } + } + } + } +} +``` + +If you do not want the defaults to be added and want explicit control over what should be used, you can disable the defaults. +An example is provided below: + +If you are using Spring Security’s Configuration the following will only add [Cache Control](../../features/exploits/headers.html#headers-cache-control). + +Example 2. Customize Cache Control Headers + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + // do not use any default headers unless explicitly listed + .defaultsDisabled() + .cacheControl(withDefaults()) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + // do not use any default headers unless explicitly listed + defaultsDisabled = true + cacheControl { + } + } + } + } +} +``` + +If necessary, you can disable all of the HTTP Security response headers with the following Configuration: + +Example 3. Disable All HTTP Security Headers + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers.disable()); + } +} +``` + +XML + +``` + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + disable() + } + } + } +} +``` + +## Cache Control + +Spring Security includes [Cache Control](../../features/exploits/headers.html#headers-cache-control) headers by default. + +However, if you actually want to cache specific responses, your application can selectively invoke [HttpServletResponse.setHeader(String,String)](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#setHeader(java.lang.String,java.lang.String)) to override the header set by Spring Security. +This is useful to ensure things like CSS, JavaScript, and images are properly cached. + +When using Spring Web MVC, this is typically done within your configuration. +Details on how to do this can be found in the [Static Resources](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web.html#mvc-config-static-resources) portion of the Spring Reference documentation + +If necessary, you can also disable Spring Security’s cache control HTTP response headers. + +Example 4. Cache Control Disabled + +Java + +``` +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) { + http + // ... + .headers(headers -> headers + .cacheControl(cache -> cache.disable()) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + headers { + cacheControl { + disable() + } + } + } + } +} +``` + +## Content Type Options + +Spring Security includes [Content-Type](../../features/exploits/headers.html#headers-content-type-options) headers by default. +However, you can disable it with: + +Example 5. Content Type Options Disabled + +Java + +``` +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends + WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) { + http + // ... + .headers(headers -> headers + .contentTypeOptions(contentTypeOptions -> contentTypeOptions.disable()) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + headers { + contentTypeOptions { + disable() + } + } + } + } +} +``` + +## + +Spring Security provides the [Strict Transport Security](../../features/exploits/headers.html#headers-hsts) header by default. +However, you can customize the results explicitly. +For example, the following is an example of explicitly providing HSTS: + +Example 6. Strict Transport Security + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + .httpStrictTransportSecurity(hsts -> hsts + .includeSubDomains(true) + .preload(true) + .maxAgeInSeconds(31536000) + ) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + headers { + httpStrictTransportSecurity { + includeSubDomains = true + preload = true + maxAgeInSeconds = 31536000 + } + } + } + } +} +``` + +## + +For passivity reasons, Spring Security provides servlet support for [HTTP Public Key Pinning](../../features/exploits/headers.html#headers-hpkp) but it is [no longer recommended](../../features/exploits/headers.html#headers-hpkp-deprecated). + +You can enable HPKP headers with the following Configuration: + +Example 7. HTTP Public Key Pinning + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + .httpPublicKeyPinning(hpkp -> hpkp + .includeSubDomains(true) + .reportUri("https://example.net/pkp-report") + .addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=") + ) + ); + } +} +``` + +XML + +``` + + + + + + + d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM= + E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g= + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + headers { + httpPublicKeyPinning { + includeSubDomains = true + reportUri = "https://example.net/pkp-report" + pins = mapOf("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=" to "sha256", + "E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" to "sha256") + } + } + } + } +} +``` + +## X-Frame-Options + +By default, Spring Security disables rendering within an iframe using [X-Frame-Options](../../features/exploits/headers.html#headers-frame-options). + +You can customize frame options to use the same origin within a Configuration using the following: + +Example 8. X-Frame-Options: SAMEORIGIN + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + .frameOptions(frameOptions -> frameOptions + .sameOrigin() + ) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + headers { + frameOptions { + sameOrigin = true + } + } + } + } +} +``` + +## X-XSS-Protection + +By default, Spring Security instructs browsers to block reflected XSS attacks using the \<\. +However, you can change this default. +For example, the following Configuration specifies that Spring Security should no longer instruct browsers to block the content: + +Example 9. X-XSS-Protection Customization + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + .xssProtection(xss -> xss + .block(false) + ) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + // ... + http { + headers { + xssProtection { + block = false + } + } + } + } +} +``` + +## + +Spring Security does not add [Content Security Policy](../../features/exploits/headers.html#headers-csp) by default, because a reasonable default is impossible to know without context of the application. +The web application author must declare the security policy(s) to enforce and/or monitor for the protected resources. + +For example, given the following security policy: + +Example 10. Content Security Policy Example + +``` +Content-Security-Policy: script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/ +``` + +You can enable the CSP header as shown below: + +Example 11. Content Security Policy + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) { + http + // ... + .headers(headers -> headers + .contentSecurityPolicy(csp -> csp + .policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/") + ) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + contentSecurityPolicy { + policyDirectives = "script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/" + } + } + } + } +} +``` + +To enable the CSP `report-only` header, provide the following configuration: + +Example 12. Content Security Policy Report Only + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends + WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + .contentSecurityPolicy(csp -> csp + .policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/") + .reportOnly() + ) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + contentSecurityPolicy { + policyDirectives = "script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/" + reportOnly = true + } + } + } + } +} +``` + +## Referrer Policy + +Spring Security does not add [Referrer Policy](../../features/exploits/headers.html#headers-referrer) headers by default. +You can enable the Referrer Policy header using the configuration as shown below: + +Example 13. Referrer Policy + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) { + http + // ... + .headers(headers -> headers + .referrerPolicy(referrer -> referrer + .policy(ReferrerPolicy.SAME_ORIGIN) + ) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + referrerPolicy { + policy = ReferrerPolicy.SAME_ORIGIN + } + } + } + } +} +``` + +## Feature Policy + +Spring Security does not add [Feature Policy](../../features/exploits/headers.html#headers-feature) headers by default. +The following `Feature-Policy` header: + +Example 14. Feature-Policy Example + +``` +Feature-Policy: geolocation 'self' +``` + +can enable the Feature Policy header using the configuration shown below: + +Example 15. Feature-Policy + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + .featurePolicy("geolocation 'self'") + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + featurePolicy("geolocation 'self'") + } + } + } +} +``` + +## Permissions Policy + +Spring Security does not add [Permissions Policy](../../features/exploits/headers.html#headers-permissions) headers by default. +The following `Permissions-Policy` header: + +Example 16. Permissions-Policy Example + +``` +Permissions-Policy: geolocation=(self) +``` + +can enable the Permissions Policy header using the configuration shown below: + +Example 17. Permissions-Policy + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + .permissionsPolicy(permissions -> permissions + .policy("geolocation=(self)") + ) + ); + } +} +``` + +XML + +``` + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + permissionPolicy { + policy = "geolocation=(self)" + } + } + } + } +} +``` + +## Clear Site Data + +Spring Security does not add [Clear-Site-Data](../../features/exploits/headers.html#headers-clear-site-data) headers by default. +The following Clear-Site-Data header: + +Example 18. Clear-Site-Data Example + +``` +Clear-Site-Data: "cache", "cookies" +``` + +can be sent on log out with the following configuration: + +Example 19. Clear-Site-Data + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .logout() + .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(CACHE, COOKIES))); + } +} +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + // ... + logout { + addLogoutHandler(HeaderWriterLogoutHandler(ClearSiteDataHeaderWriter(CACHE, COOKIES))) + } + } + } +} +``` + +## Custom Headers + +Spring Security has mechanisms to make it convenient to add the more common security headers to your application. +However, it also provides hooks to enable adding custom headers. + +### Static Headers + +There may be times you wish to inject custom security headers into your application that are not supported out of the box. +For example, given the following custom security header: + +``` +X-Custom-Security-Header: header-value +``` + +The headers could be added to the response using the following Configuration: + +Example 20. StaticHeadersWriter + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + .addHeaderWriter(new StaticHeadersWriter("X-Custom-Security-Header","header-value")) + ); + } +} +``` + +XML + +``` + + + + +
+ + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + addHeaderWriter(StaticHeadersWriter("X-Custom-Security-Header","header-value")) + } + } + } +} +``` + +### Headers Writer + +When the namespace or Java configuration does not support the headers you want, you can create a custom `HeadersWriter` instance or even provide a custom implementation of the `HeadersWriter`. + +Let’s take a look at an example of using an custom instance of `XFrameOptionsHeaderWriter`. +If you wanted to explicitly configure [X-Frame-Options](#servlet-headers-frame-options) it could be done with the following Configuration: + +Example 21. Headers Writer + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... + .headers(headers -> headers + .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN)) + ); + } +} +``` + +XML + +``` + + + + +
+ + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + // ... + headers { + addHeaderWriter(XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN)) + } + } + } +} +``` + +### DelegatingRequestMatcherHeaderWriter + +At times you may want to only write a header for certain requests. +For example, perhaps you want to only protect your log in page from being framed. +You could use the `DelegatingRequestMatcherHeaderWriter` to do so. + +An example of using `DelegatingRequestMatcherHeaderWriter` in Java Configuration can be seen below: + +Example 22. DelegatingRequestMatcherHeaderWriter Java Configuration + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends +WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + RequestMatcher matcher = new AntPathRequestMatcher("/login"); + DelegatingRequestMatcherHeaderWriter headerWriter = + new DelegatingRequestMatcherHeaderWriter(matcher,new XFrameOptionsHeaderWriter()); + http + // ... + .headers(headers -> headers + .frameOptions(frameOptions -> frameOptions.disable()) + .addHeaderWriter(headerWriter) + ); + } +} +``` + +XML + +``` + + + + + +
+ + + + + + + + + + + +``` + +Kotlin + +``` +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + val matcher: RequestMatcher = AntPathRequestMatcher("/login") + val headerWriter = DelegatingRequestMatcherHeaderWriter(matcher, XFrameOptionsHeaderWriter()) + http { + headers { + frameOptions { + disable() + } + addHeaderWriter(headerWriter) + } + } + } +} +``` + +[Cross Site Request Forgery (CSRF) for Servlet Environments](csrf.html)[HTTP](http.html) + diff --git a/docs/en/spring-security/servlet-exploits-http.md b/docs/en/spring-security/servlet-exploits-http.md new file mode 100644 index 0000000000000000000000000000000000000000..254e2d8cda0d116fa7097ad51027f37f79be6fb3 --- /dev/null +++ b/docs/en/spring-security/servlet-exploits-http.md @@ -0,0 +1,72 @@ +# HTTP + +All HTTP based communication should be protected [using TLS](../../features/exploits/http.html#http). + +Below you can find details around Servlet specific features that assist with HTTPS usage. + +## Redirect to HTTPS + +If a client makes a request using HTTP rather than HTTPS, Spring Security can be configured to redirect to HTTPS. + +For example, the following Java configuration will redirect any HTTP requests to HTTPS: + +Example 1. Redirect to HTTPS + +Java + +``` +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends + WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) { + http + // ... + .requiresChannel(channel -> channel + .anyRequest().requiresSecure() + ); + } +} +``` + +Kotlin + +``` +@Configuration +@EnableWebSecurity +class SecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + // ... + requiresChannel { + secure(AnyRequestMatcher.INSTANCE, "REQUIRES_SECURE_CHANNEL") + } + } + } +} +``` + +The following XML configuration will redirect all HTTP requests to HTTPS + +Example 2. Redirect to HTTPS with XML Configuration + +``` + + +... + +``` + +## Strict Transport Security + +Spring Security provides support for [Strict Transport Security](headers.html#servlet-headers-hsts) and enables it by default. + +## Proxy Server Configuration + +Spring Security [integrates with proxy servers](../../features/exploits/http.html#http-proxy-server). + +[Security HTTP Response Headers](headers.html)[HttpFirewall](firewall.html) + diff --git a/docs/en/spring-security/servlet-exploits.md b/docs/en/spring-security/servlet-exploits.md new file mode 100644 index 0000000000000000000000000000000000000000..734ac1dbbbcc7fe457495f425c667aa2de934191 --- /dev/null +++ b/docs/en/spring-security/servlet-exploits.md @@ -0,0 +1,13 @@ +# Protection Against Exploits + +This section discusses Servlet specific support for [Spring Security’s protection against common exploits](../../features/exploits/index.html#exploits). + +## Section Summary + +* [Cross Site Request Forgery (CSRF) for Servlet Environments](csrf.html) +* [Security HTTP Response Headers](headers.html) +* [HTTP](http.html) +* [HttpFirewall](firewall.html) + +[SAML2 Metadata](../saml2/metadata.html)[Cross Site Request Forgery (CSRF) for Servlet Environments](csrf.html) + diff --git a/docs/en/spring-security/servlet-getting-started.md b/docs/en/spring-security/servlet-getting-started.md new file mode 100644 index 0000000000000000000000000000000000000000..5d77e87c5e9bd461d600253296e78b8c3357832e --- /dev/null +++ b/docs/en/spring-security/servlet-getting-started.md @@ -0,0 +1,82 @@ +# Hello Spring Security + +This section covers the minimum setup for how to use Spring Security with Spring Boot. + +| |The completed application can be found [in our samples repository](https://github.com/spring-projects/spring-security-samples/tree/5.6.x/servlet/spring-boot/java/hello-security).
For your convenience, you can download a minimal Spring Boot + Spring Security application by [clicking here](https://start.spring.io/starter.zip?type=maven-project&language=java&packaging=jar&jvmVersion=1.8&groupId=example&artifactId=hello-security&name=hello-security&description=Hello%20Security&packageName=example.hello-security&dependencies=web,security).| +|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +## Updating Dependencies + +The only step you need to do is update the dependencies by using [Maven](../getting-spring-security.html#getting-maven-boot) or [Gradle](../getting-spring-security.html#getting-gradle-boot). + +## Starting Hello Spring Security Boot + +You can now [run the Spring Boot application](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-running-with-the-maven-plugin) by using the Maven Plugin’s `run` goal. +The following example shows how to do so (and the beginning of the output from doing so): + +Example 1. Running Spring Boot Application + +``` +$ ./mvn spring-boot:run +... +INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration : + +Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336 + +... +``` + +## Spring Boot Auto Configuration + +Spring Boot automatically: + +* Enables Spring Security’s default configuration, which creates a servlet `Filter` as a bean named `springSecurityFilterChain`. + This bean is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, and so on) within your application. + +* Creates a `UserDetailsService` bean with a username of `user` and a randomly generated password that is logged to the console. + +* Registers the `Filter` with a bean named `springSecurityFilterChain` with the Servlet container for every request. + +Spring Boot is not configuring much, but it does a lot. +A summary of the features follows: + +* Require an authenticated user for any interaction with the application + +* Generate a default login form for you + +* Let the user with a username of `user` and a password that is logged to the console to authenticate with form-based authentication (in the preceding example, the password is `8e557245-73e2-4286-969a-ff57fe326336`) + +* Protects the password storage with BCrypt + +* Lets the user log out + +* [CSRF attack](https://en.wikipedia.org/wiki/Cross-site_request_forgery) prevention + +* [Session Fixation](https://en.wikipedia.org/wiki/Session_fixation) protection + +* Security Header integration + + * [HTTP Strict Transport Security](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) for secure requests + + * [X-Content-Type-Options](https://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx) integration + + * Cache Control (can be overridden later by your application to allow caching of your static resources) + + * [X-XSS-Protection](https://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx) integration + + * X-Frame-Options integration to help prevent [Clickjacking](https://en.wikipedia.org/wiki/Clickjacking) + +* Integrate with the following Servlet API methods: + + * [`HttpServletRequest#getRemoteUser()`](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()) + + * [`HttpServletRequest.html#getUserPrincipal()`](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()) + + * [`HttpServletRequest.html#isUserInRole(java.lang.String)`](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)) + + * [`HttpServletRequest.html#login(java.lang.String, java.lang.String)`](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)) + + * [`HttpServletRequest.html#logout()`](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()) + +[Servlet Applications](index.html)[Architecture](architecture.html) + diff --git a/docs/en/spring-security/servlet-integrations-concurrency.md b/docs/en/spring-security/servlet-integrations-concurrency.md new file mode 100644 index 0000000000000000000000000000000000000000..a9b6d9361b2fc3d23d40d42a234c463a32e834e9 --- /dev/null +++ b/docs/en/spring-security/servlet-integrations-concurrency.md @@ -0,0 +1,173 @@ +# Concurrency Support + +In most environments, Security is stored on a per `Thread` basis. +This means that when work is done on a new `Thread`, the `SecurityContext` is lost. +Spring Security provides some infrastructure to help make this much easier for users. +Spring Security provides low level abstractions for working with Spring Security in multi-threaded environments. +In fact, this is what Spring Security builds on to integration with [`AsyncContext.start(Runnable)`](servlet-api.html#servletapi-start-runnable) and [Spring MVC Async Integration](mvc.html#mvc-async). + +## DelegatingSecurityContextRunnable + +One of the most fundamental building blocks within Spring Security’s concurrency support is the `DelegatingSecurityContextRunnable`. +It wraps a delegate `Runnable` in order to initialize the `SecurityContextHolder` with a specified `SecurityContext` for the delegate. +It then invokes the delegate Runnable ensuring to clear the `SecurityContextHolder` afterwards. +The `DelegatingSecurityContextRunnable` looks something like this: + +``` +public void run() { +try { + SecurityContextHolder.setContext(securityContext); + delegate.run(); +} finally { + SecurityContextHolder.clearContext(); +} +} +``` + +While very simple, it makes it seamless to transfer the SecurityContext from one Thread to another. +This is important since, in most cases, the SecurityContextHolder acts on a per Thread basis. +For example, you might have used Spring Security’s [``](../appendix/namespace/method-security.html#nsa-global-method-security) support to secure one of your services. +You can now easily transfer the `SecurityContext` of the current `Thread` to the `Thread` that invokes the secured service. +An example of how you might do this can be found below: + +``` +Runnable originalRunnable = new Runnable() { +public void run() { + // invoke secured service +} +}; + +SecurityContext context = SecurityContextHolder.getContext(); +DelegatingSecurityContextRunnable wrappedRunnable = + new DelegatingSecurityContextRunnable(originalRunnable, context); + +new Thread(wrappedRunnable).start(); +``` + +The code above performs the following steps: + +* Creates a `Runnable` that will be invoking our secured service. + Notice that it is not aware of Spring Security + +* Obtains the `SecurityContext` that we wish to use from the `SecurityContextHolder` and initializes the `DelegatingSecurityContextRunnable` + +* Use the `DelegatingSecurityContextRunnable` to create a Thread + +* Start the Thread we created + +Since it is quite common to create a `DelegatingSecurityContextRunnable` with the `SecurityContext` from the `SecurityContextHolder` there is a shortcut constructor for it. +The following code is the same as the code above: + +``` +Runnable originalRunnable = new Runnable() { +public void run() { + // invoke secured service +} +}; + +DelegatingSecurityContextRunnable wrappedRunnable = + new DelegatingSecurityContextRunnable(originalRunnable); + +new Thread(wrappedRunnable).start(); +``` + +The code we have is simple to use, but it still requires knowledge that we are using Spring Security. +In the next section we will take a look at how we can utilize `DelegatingSecurityContextExecutor` to hide the fact that we are using Spring Security. + +## DelegatingSecurityContextExecutor + +In the previous section we found that it was easy to use the `DelegatingSecurityContextRunnable`, but it was not ideal since we had to be aware of Spring Security in order to use it. +Let’s take a look at how `DelegatingSecurityContextExecutor` can shield our code from any knowledge that we are using Spring Security. + +The design of `DelegatingSecurityContextExecutor` is very similar to that of `DelegatingSecurityContextRunnable` except it accepts a delegate `Executor` instead of a delegate `Runnable`. +You can see an example of how it might be used below: + +``` +SecurityContext context = SecurityContextHolder.createEmptyContext(); +Authentication authentication = + new UsernamePasswordAuthenticationToken("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER")); +context.setAuthentication(authentication); + +SimpleAsyncTaskExecutor delegateExecutor = + new SimpleAsyncTaskExecutor(); +DelegatingSecurityContextExecutor executor = + new DelegatingSecurityContextExecutor(delegateExecutor, context); + +Runnable originalRunnable = new Runnable() { +public void run() { + // invoke secured service +} +}; + +executor.execute(originalRunnable); +``` + +The code performs the following steps: + +* Creates the `SecurityContext` to be used for our `DelegatingSecurityContextExecutor`. + Note that in this example we simply create the `SecurityContext` by hand. + However, it does not matter where or how we get the `SecurityContext` (i.e. we could obtain it from the `SecurityContextHolder` if we wanted). + +* Creates a delegateExecutor that is in charge of executing submitted `Runnable`s + +* Finally we create a `DelegatingSecurityContextExecutor` which is in charge of wrapping any Runnable that is passed into the execute method with a `DelegatingSecurityContextRunnable`. + It then passes the wrapped Runnable to the delegateExecutor. + In this instance, the same `SecurityContext` will be used for every Runnable submitted to our `DelegatingSecurityContextExecutor`. + This is nice if we are running background tasks that need to be run by a user with elevated privileges. + +* At this point you may be asking yourself "How does this shield my code of any knowledge of Spring Security?" Instead of creating the `SecurityContext` and the `DelegatingSecurityContextExecutor` in our own code, we can inject an already initialized instance of `DelegatingSecurityContextExecutor`. + +``` +@Autowired +private Executor executor; // becomes an instance of our DelegatingSecurityContextExecutor + +public void submitRunnable() { +Runnable originalRunnable = new Runnable() { + public void run() { + // invoke secured service + } +}; +executor.execute(originalRunnable); +} +``` + +Now our code is unaware that the `SecurityContext` is being propagated to the `Thread`, then the `originalRunnable` is run, and then the `SecurityContextHolder` is cleared out. +In this example, the same user is being used to run each thread. +What if we wanted to use the user from `SecurityContextHolder` at the time we invoked `executor.execute(Runnable)` (i.e. the currently logged in user) to process `originalRunnable`? +This can be done by removing the `SecurityContext` argument from our `DelegatingSecurityContextExecutor` constructor. +For example: + +``` +SimpleAsyncTaskExecutor delegateExecutor = new SimpleAsyncTaskExecutor(); +DelegatingSecurityContextExecutor executor = + new DelegatingSecurityContextExecutor(delegateExecutor); +``` + +Now anytime `executor.execute(Runnable)` is executed the `SecurityContext` is first obtained by the `SecurityContextHolder` and then that `SecurityContext` is used to create our `DelegatingSecurityContextRunnable`. +This means that we are running our `Runnable` with the same user that was used to invoke the `executor.execute(Runnable)` code. + +## Spring Security Concurrency Classes + +Refer to the Javadoc for additional integrations with both the Java concurrent APIs and the Spring Task abstractions. +They are quite self-explanatory once you understand the previous code. + +* `DelegatingSecurityContextCallable` + +* `DelegatingSecurityContextExecutor` + +* `DelegatingSecurityContextExecutorService` + +* `DelegatingSecurityContextRunnable` + +* `DelegatingSecurityContextScheduledExecutorService` + +* `DelegatingSecurityContextSchedulingTaskExecutor` + +* `DelegatingSecurityContextAsyncTaskExecutor` + +* `DelegatingSecurityContextTaskExecutor` + +* `DelegatingSecurityContextTaskScheduler` + +[Integrations](index.html)[Jackson](jackson.html) + diff --git a/docs/en/spring-security/servlet-integrations-cors.md b/docs/en/spring-security/servlet-integrations-cors.md new file mode 100644 index 0000000000000000000000000000000000000000..f6d687c813f3bb349dafd269ee0565165c208043 --- /dev/null +++ b/docs/en/spring-security/servlet-integrations-cors.md @@ -0,0 +1,119 @@ +# CORS + +Spring Framework provides [first class support for CORS](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors). +CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the `JSESSIONID`). +If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it. + +The easiest way to ensure that CORS is handled first is to use the `CorsFilter`. +Users can integrate the `CorsFilter` with Spring Security by providing a `CorsConfigurationSource` using the following: + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // by default uses a Bean by the name of corsConfigurationSource + .cors(withDefaults()) + ... + } + + @Bean + CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Arrays.asList("https://example.com")); + configuration.setAllowedMethods(Arrays.asList("GET","POST")); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } +} +``` + +Kotlin + +``` +@EnableWebSecurity +open class WebSecurityConfig : WebSecurityConfigurerAdapter() { + override fun configure(http: HttpSecurity) { + http { + // by default uses a Bean by the name of corsConfigurationSource + cors { } + // ... + } + } + + @Bean + open fun corsConfigurationSource(): CorsConfigurationSource { + val configuration = CorsConfiguration() + configuration.allowedOrigins = listOf("https://example.com") + configuration.allowedMethods = listOf("GET", "POST") + val source = UrlBasedCorsConfigurationSource() + source.registerCorsConfiguration("/**", configuration) + return source + } +} +``` + +or in XML + +``` + + + ... + + + ... + +``` + +If you are using Spring MVC’s CORS support, you can omit specifying the `CorsConfigurationSource` and Spring Security will leverage the CORS configuration provided to Spring MVC. + +Java + +``` +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // if Spring MVC is on classpath and no CorsConfigurationSource is provided, + // Spring Security will use CORS configuration provided to Spring MVC + .cors(withDefaults()) + ... + } +} +``` + +Kotlin + +``` +@EnableWebSecurity +open class WebSecurityConfig : WebSecurityConfigurerAdapter() { + override fun configure(http: HttpSecurity) { + http { + // if Spring MVC is on classpath and no CorsConfigurationSource is provided, + // Spring Security will use CORS configuration provided to Spring MVC + cors { } + // ... + } + } +} +``` + +or in XML + +``` + + + + ... + +``` + +[WebSocket](websocket.html)[JSP Taglib](jsp-taglibs.html) + diff --git a/docs/en/spring-security/servlet-integrations-data.md b/docs/en/spring-security/servlet-integrations-data.md new file mode 100644 index 0000000000000000000000000000000000000000..1e79475dfd34b6b4e5a79d3fd1ad867ca94ebceb --- /dev/null +++ b/docs/en/spring-security/servlet-integrations-data.md @@ -0,0 +1,63 @@ +# Spring Data Integration + +Spring Security provides Spring Data integration that allows referring to the current user within your queries. +It is not only useful but necessary to include the user in the queries to support paged results since filtering the results afterwards would not scale. + +## Spring Data & Spring Security Configuration + +To use this support, add `org.springframework.security:spring-security-data` dependency and provide a bean of type `SecurityEvaluationContextExtension`: + +Java + +``` +@Bean +public SecurityEvaluationContextExtension securityEvaluationContextExtension() { + return new SecurityEvaluationContextExtension(); +} +``` + +Kotlin + +``` +@Bean +fun securityEvaluationContextExtension(): SecurityEvaluationContextExtension { + return SecurityEvaluationContextExtension() +} +``` + +In XML Configuration, this would look like: + +``` + +``` + +## Security Expressions within @Query + +Now Spring Security can be used within your queries. +For example: + +Java + +``` +@Repository +public interface MessageRepository extends PagingAndSortingRepository { + @Query("select m from Message m where m.to.id = ?#{ principal?.id }") + Page findInbox(Pageable pageable); +} +``` + +Kotlin + +``` +@Repository +interface MessageRepository : PagingAndSortingRepository { + @Query("select m from Message m where m.to.id = ?#{ principal?.id }") + fun findInbox(pageable: Pageable): Page +} +``` + +This checks to see if the `Authentication.getPrincipal().getId()` is equal to the recipient of the `Message`. +Note that this example assumes you have customized the principal to be an Object that has an id property. +By exposing the `SecurityEvaluationContextExtension` bean, all of the [Common Security Expressions](../authorization/expression-based.html#common-expressions) are available within the Query. + +[Servlet APIs](servlet-api.html)[Spring MVC](mvc.html) \ No newline at end of file diff --git a/docs/en/spring-security/servlet-integrations-jackson.md b/docs/en/spring-security/servlet-integrations-jackson.md new file mode 100644 index 0000000000000000000000000000000000000000..1d4821f8a520c06ba334e5c8be3837c285152cf1 --- /dev/null +++ b/docs/en/spring-security/servlet-integrations-jackson.md @@ -0,0 +1,24 @@ +# Jackson Support + +Spring Security provides Jackson support for persisting Spring Security related classes. +This can improve the performance of serializing Spring Security related classes when working with distributed sessions (i.e. session replication, Spring Session, etc). + +To use it, register the `SecurityJackson2Modules.getModules(ClassLoader)` with `ObjectMapper` ([jackson-databind](https://github.com/FasterXML/jackson-databind)): + +``` +ObjectMapper mapper = new ObjectMapper(); +ClassLoader loader = getClass().getClassLoader(); +List modules = SecurityJackson2Modules.getModules(loader); +mapper.registerModules(modules); + +// ... use ObjectMapper as normally ... +SecurityContext context = new SecurityContextImpl(); +// ... +String json = mapper.writeValueAsString(context); +``` + +| |The following Spring Security modules provide Jackson support:

* spring-security-core (`CoreJackson2Module`)

* spring-security-web (`WebJackson2Module`, `WebServletJackson2Module`, `WebServerJackson2Module`)

* [spring-security-oauth2-client](#oauth2client) (`OAuth2ClientJackson2Module`)

* spring-security-cas (`CasJackson2Module`)| +|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +[Concurrency](concurrency.html)[Localization](localization.html) + diff --git a/docs/en/spring-security/servlet-integrations-jsp-taglibs.md b/docs/en/spring-security/servlet-integrations-jsp-taglibs.md new file mode 100644 index 0000000000000000000000000000000000000000..0a00b9cc5e113b431826183407c54c8f08331177 --- /dev/null +++ b/docs/en/spring-security/servlet-integrations-jsp-taglibs.md @@ -0,0 +1,197 @@ +# JSP Tag Libraries + +## Declaring the Taglib + +To use any of the tags, you must have the security taglib declared in your JSP: + +``` +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> +``` + +## The authorize Tag + +This tag is used to determine whether its contents should be evaluated or not. +In Spring Security 3.0, it can be used in two ways [1]. +The first approach uses a [web-security expression](../authorization/expression-based.html#el-access-web), specified in the `access` attribute of the tag. +The expression evaluation will be delegated to the `SecurityExpressionHandler` defined in the application context (you should have web expressions enabled in your `` namespace configuration to make sure this service is available). +So, for example, you might have + +``` + + +This content will only be visible to users who have the "supervisor" authority in their list of GrantedAuthoritys. + + +``` + +When used in conjunction with Spring Security’s PermissionEvaluator, the tag can also be used to check permissions. +For example: + +``` + + +This content will only be visible to users who have read or write permission to the Object found as a request attribute named "domain". + + +``` + +A common requirement is to only show a particular link, if the user is actually allowed to click it. +How can we determine in advance whether something will be allowed? This tag can also operate in an alternative mode which allows you to define a particular URL as an attribute. +If the user is allowed to invoke that URL, then the tag body will be evaluated, otherwise it will be skipped. +So you might have something like + +``` + + +This content will only be visible to users who are authorized to send requests to the "/admin" URL. + + +``` + +To use this tag there must also be an instance of `WebInvocationPrivilegeEvaluator` in your application context. +If you are using the namespace, one will automatically be registered. +This is an instance of `DefaultWebInvocationPrivilegeEvaluator`, which creates a dummy web request for the supplied URL and invokes the security interceptor to see whether the request would succeed or fail. +This allows you to delegate to the access-control setup you defined using `intercept-url` declarations within the `` namespace configuration and saves having to duplicate the information (such as the required roles) within your JSPs. +This approach can also be combined with a `method` attribute, supplying the HTTP method, for a more specific match. + +The Boolean result of evaluating the tag (whether it grants or denies access) can be stored in a page context scope variable by setting the `var` attribute to the variable name, avoiding the need for duplicating and re-evaluating the condition at other points in the page. + +### Disabling Tag Authorization for Testing + +Hiding a link in a page for unauthorized users doesn’t prevent them from accessing the URL. +They could just type it into their browser directly, for example. +As part of your testing process, you may want to reveal the hidden areas in order to check that links really are secured at the back end. +If you set the system property `spring.security.disableUISecurity` to `true`, the `authorize` tag will still run but will not hide its contents. +By default it will also surround the content with `…​` tags. +This allows you to display "hidden" content with a particular CSS style such as a different background colour. +Try running the "tutorial" sample application with this property enabled, for example. + +You can also set the properties `spring.security.securedUIPrefix` and `spring.security.securedUISuffix` if you want to change surrounding text from the default `span` tags (or use empty strings to remove it completely). + +## The authentication Tag + +This tag allows access to the current `Authentication` object stored in the security context. +It renders a property of the object directly in the JSP. +So, for example, if the `principal` property of the `Authentication` is an instance of Spring Security’s `UserDetails` object, then using `` will render the name of the current user. + +Of course, it isn’t necessary to use JSP tags for this kind of thing and some people prefer to keep as little logic as possible in the view. +You can access the `Authentication` object in your MVC controller (by calling `SecurityContextHolder.getContext().getAuthentication()`) and add the data directly to your model for rendering by the view. + +## The accesscontrollist Tag + +This tag is only valid when used with Spring Security’s ACL module. +It checks a comma-separated list of required permissions for a specified domain object. +If the current user has all of those permissions, then the tag body will be evaluated. +If they don’t, it will be skipped. +An example might be + +| |In general this tag should be considered deprecated.
Instead use the [The authorize Tag](#taglibs-authorize).| +|---|-----------------------------------------------------------------------------------------------------------------| + +``` + + +This will be shown if the user has all of the permissions represented by the values "1" or "2" on the given object. + + +``` + +The permissions are passed to the `PermissionFactory` defined in the application context, converting them to ACL `Permission` instances, so they may be any format which is supported by the factory - they don’t have to be integers, they could be strings like `READ` or `WRITE`. +If no `PermissionFactory` is found, an instance of `DefaultPermissionFactory` will be used. +The `AclService` from the application context will be used to load the `Acl` instance for the supplied object. +The `Acl` will be invoked with the required permissions to check if all of them are granted. + +This tag also supports the `var` attribute, in the same way as the `authorize` tag. + +## The csrfInput Tag + +If CSRF protection is enabled, this tag inserts a hidden form field with the correct name and value for the CSRF protection token. +If CSRF protection is not enabled, this tag outputs nothing. + +Normally Spring Security automatically inserts a CSRF form field for any `` tags you use, but if for some reason you cannot use ``, `csrfInput` is a handy replacement. + +You should place this tag within an HTML `` block, where you would normally place other input fields. +Do NOT place this tag within a Spring `` block. +Spring Security handles Spring forms automatically. + +``` +
+ + Name:
+ + ... + +``` + +## The csrfMetaTags Tag + +If CSRF protection is enabled, this tag inserts meta tags containing the CSRF protection token form field and header names and CSRF protection token value. +These meta tags are useful for employing CSRF protection within JavaScript in your applications. + +You should place `csrfMetaTags` within an HTML `` block, where you would normally place other meta tags. +Once you use this tag, you can access the form field name, header name, and token value easily using JavaScript. +JQuery is used in this example to make the task easier. + +``` + + + + CSRF Protected JavaScript Page + + +