From aac1f35a91faf5aeaafd980160a1ed3fcc3992cd Mon Sep 17 00:00:00 2001 From: YuCheng Hu Date: Wed, 28 Sep 2022 17:27:37 -0400 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=9C=89=E5=85=B3=20Spring?= =?UTF-8?q?=20Security=20=E7=9A=84=E6=96=87=E6=A1=A3=E5=92=8C=E5=92=8C?= =?UTF-8?q?=E7=90=86=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _sidebar.md | 2 +- community.md | 37 ++ features/authentication/index.md | 11 + features/authentication/password-storage.md | 559 ++++++++++++++++++++ features/authorization/index.md | 14 + features/exploits/http.md | 0 features/exploits/index.md | 7 + features/index.md | 11 + index.html | 2 + index.md | 31 ++ reactive/getting-started.md | 73 +++ reactive/index.md | 0 servlet/architecture.md | 0 servlet/getting-started.md | 79 +++ servlet/index.md | 0 spring-security/index.md | 17 - 16 files changed, 825 insertions(+), 18 deletions(-) create mode 100644 community.md create mode 100644 features/authentication/index.md create mode 100644 features/authentication/password-storage.md create mode 100644 features/authorization/index.md create mode 100644 features/exploits/http.md create mode 100644 features/exploits/index.md create mode 100644 features/index.md create mode 100644 index.md create mode 100644 reactive/getting-started.md create mode 100644 reactive/index.md create mode 100644 servlet/architecture.md create mode 100644 servlet/getting-started.md create mode 100644 servlet/index.md delete mode 100644 spring-security/index.md diff --git a/_sidebar.md b/_sidebar.md index f14812b..961bb6c 100644 --- a/_sidebar.md +++ b/_sidebar.md @@ -1,4 +1,4 @@ - CWIKIUS SPRING SECURITY - [概要和简介](README.md) - - [Spring Security 中文文档](spring-security/index.md) + - [Spring Security 中文文档](index.md) - [联系我们](CONTACT.md) \ No newline at end of file diff --git a/community.md b/community.md new file mode 100644 index 0000000..cbb9fc0 --- /dev/null +++ b/community.md @@ -0,0 +1,37 @@ +[[community]] += Spring Security Community + +Welcome to the Spring Security Community! +This section discusses how you can make the most of our vast community. + + +[[community-help]] +== 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 xref:samples.adoc#samples[sample applications]. +* Ask a question on https://stackoverflow.com/questions/tagged/spring-security[https://stackoverflow.com] with the `spring-security` tag. +* Report bugs and enhancement requests at https://github.com/spring-projects/spring-security/issues + +[[community-becoming-involved]] +== 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 https://github.com/spring-projects/spring-security/blob/main/CONTRIBUTING.adoc[Contributing] documentation. + +[[community-source]] +== Source Code + +You can find Spring Security's source code on GitHub at https://github.com/spring-projects/spring-security/ + +[[community-license]] +== Apache 2 License + +Spring Security is Open Source software released under the https://www.apache.org/licenses/LICENSE-2.0.html[Apache 2.0 license]. + +== Social Media + +You can follow https://twitter.com/SpringSecurity[@SpringSecurity] and the https://twitter.com/SpringSecurity/lists/team[Spring Security team] on Twitter to stay up to date with the latest news. +You can also follow https://twitter.com/SpringCentral[@SpringCentral] to keep up to date with the entire Spring portfolio. \ No newline at end of file diff --git a/features/authentication/index.md b/features/authentication/index.md new file mode 100644 index 0000000..49544b0 --- /dev/null +++ b/features/authentication/index.md @@ -0,0 +1,11 @@ +[[authentication]] += Authentication + +Spring Security provides comprehensive support for https://en.wikipedia.org/wiki/Authentication[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 xref:servlet/authentication/index.adoc#servlet-authentication[Servlet] and WebFlux for details on what is supported for each stack. \ No newline at end of file diff --git a/features/authentication/password-storage.md b/features/authentication/password-storage.md new file mode 100644 index 0000000..898fb2f --- /dev/null +++ b/features/authentication/password-storage.md @@ -0,0 +1,559 @@ +[[authentication-password-storage]] += Password Storage + +Spring Security's `PasswordEncoder` interface is used to perform a one way transformation of a password to allow the password to be stored securely. +Given `PasswordEncoder` is a one way transformation, it is not intended when the password transformation needs to be two way (i.e. storing credentials used to authenticate to a database). +Typically `PasswordEncoder` is used for storing a password that needs to be compared to a user provided password at the time of authentication. + +[[authentication-password-storage-history]] +== Password Storage History + +Throughout the years the standard mechanism for storing passwords has evolved. +In the beginning passwords were stored in plain text. +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 https://en.wikipedia.org/wiki/Rainbow_table[Rainbow Tables]. +Rather than doing the work of guessing each password every time, they computed the password once and stored it in a lookup table. + +To mitigate the effectiveness of Rainbow Tables, developers were encouraged to use salted passwords. +Instead of using just the password as input to the hash function, random bytes (known as salt) would be generated for every users' password. +The salt and the user's password would be ran through the hash function which produced a unique hash. +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 <>, <>, <>, and <>. + +Because adaptive one-way functions are intentionally resource intensive, validating a username and password for every request will degrade performance of an application significantly. +There is nothing Spring Security (or any other library) can do to speed up the validation of the password since security is gained by making the validation resource intensive. +Users are encouraged to exchange the long term credentials (i.e. username and password) for a short term credential (i.e. session, OAuth Token, etc). +The short term credential can be validated quickly without any loss in security. + + +[[authentication-password-storage-dpe]] +== DelegatingPasswordEncoder + +Prior to Spring Security 5.0 the default `PasswordEncoder` was `NoOpPasswordEncoder` which required plain text passwords. +Based upon the <> section you might expect that the default `PasswordEncoder` is now something like `BCryptPasswordEncoder`. +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`. + +.Create Default DelegatingPasswordEncoder +==== +.Java +[source,java,role="primary"] +---- +PasswordEncoder passwordEncoder = +PasswordEncoderFactories.createDelegatingPasswordEncoder(); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val passwordEncoder: PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder() +---- +==== + +Alternatively, you may create your own custom instance. For example: + +.Create Custom DelegatingPasswordEncoder +==== +.Java +[source,java,role="primary"] +---- +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 +[source,kotlin,role="secondary"] +---- +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) +---- +==== + +[[authentication-password-storage-dpe-format]] +=== Password Storage Format + +The general format for a password is: + +.DelegatingPasswordEncoder Storage Format +==== +[source,text,attrs="-attributes"] +---- +{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". + +.DelegatingPasswordEncoder Encoded Passwords Example +==== +[source,text,attrs="-attributes"] +---- +{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` + +[NOTE] +==== +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$`. +==== + +[[authentication-password-storage-dpe-encoding]] +=== Password Encoding + +The `idForEncode` passed into the constructor determines which `PasswordEncoder` will be used for encoding passwords. +In the `DelegatingPasswordEncoder` we constructed above, that means that the result of encoding `password` would be delegated to `BCryptPasswordEncoder` and be prefixed with `+{bcrypt}+`. +The end result would look like: + +.DelegatingPasswordEncoder Encode Example +==== +[source,text,attrs="-attributes"] +---- +{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG +---- +==== + +[[authentication-password-storage-dpe-matching]] +=== Password Matching + +Matching is done based upon the `+{id}+` and the mapping of the `id` to the `PasswordEncoder` provided in the constructor. +Our example in <> provides a working example of how this is done. +By default, the result of invoking `matches(CharSequence, String)` with a password and an `id` that is not mapped (including a null id) will result in an `IllegalArgumentException`. +This behavior can be customized using `DelegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(PasswordEncoder)`. + +By 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. + +[[authentication-password-storage-dep-getting-started]] +=== 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. + +.withDefaultPasswordEncoder Example +==== +.Java +[source,java,role="primary",attrs="-attributes"] +---- +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 +[source,kotlin,role="secondary",attrs="-attributes"] +---- +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. + +.withDefaultPasswordEncoder Reusing the Builder +==== +.Java +[source,java,role="primary"] +---- +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 +[source,kotlin,role="secondary"] +---- +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 <>. + +[[authentication-password-storage-boot-cli]] +=== Encode with Spring Boot CLI + +The easiest way to properly encode your password is to use the https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-cli.html[Spring Boot CLI]. + +For example, the following will encode the password of `password` for use with <>: + +.Spring Boot CLI encodepassword Example +==== +[source,attrs="-attributes"] +---- +spring encodepassword password +{bcrypt}$2a$10$X5wFBtLrL/kHcmrOGGTrGufsBX8CJ0WpQpF3pgeuxBB/H73BK1DW6 +---- +==== + +[[authentication-password-storage-dpe-troubleshoot]] +=== Troubleshooting + +The following error occurs when one of the passwords that are stored has no id as described in <>. + +---- +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 <>. + +Alternatively, you can prefix all of your passwords with the correct id and continue to use `DelegatingPasswordEncoder`. +For example, if you are using BCrypt, you would migrate your password from something like: + +---- +$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG +---- + +to + + +[source,attrs="-attributes"] +---- +{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG +---- + +For a complete listing of the mappings refer to the Javadoc on +https://docs.spring.io/spring-security/site/docs/5.0.x/api/org/springframework/security/crypto/factory/PasswordEncoderFactories.html[PasswordEncoderFactories]. + +[[authentication-password-storage-bcrypt]] +== BCryptPasswordEncoder + +The `BCryptPasswordEncoder` implementation uses the widely supported https://en.wikipedia.org/wiki/Bcrypt[bcrypt] algorithm to hash the passwords. +In order to make it more resistent to password cracking, bcrypt is deliberately slow. +Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. +The default implementation of `BCryptPasswordEncoder` uses strength 10 as mentioned in the Javadoc of https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.html[BCryptPasswordEncoder]. You are encouraged to +tune and test the strength parameter on your own system so that it takes roughly 1 second to verify a password. + +.BCryptPasswordEncoder +==== +.Java +[source,java,role="primary"] +---- +// Create an encoder with strength 16 +BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +// Create an encoder with strength 16 +val encoder = BCryptPasswordEncoder(16) +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +---- +==== + +[[authentication-password-storage-argon2]] +== Argon2PasswordEncoder + +The `Argon2PasswordEncoder` implementation uses the https://en.wikipedia.org/wiki/Argon2[Argon2] algorithm to hash the passwords. +Argon2 is the winner of the https://en.wikipedia.org/wiki/Password_Hashing_Competition[Password Hashing Competition]. +In order to defeat password cracking on custom hardware, Argon2 is a deliberately slow algorithm that requires large amounts of memory. +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. + +.Argon2PasswordEncoder +==== +.Java +[source,java,role="primary"] +---- +// Create an encoder with all the defaults +Argon2PasswordEncoder encoder = new Argon2PasswordEncoder(); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +// Create an encoder with all the defaults +val encoder = Argon2PasswordEncoder() +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +---- +==== + +[[authentication-password-storage-pbkdf2]] +== Pbkdf2PasswordEncoder + +The `Pbkdf2PasswordEncoder` implementation uses the https://en.wikipedia.org/wiki/PBKDF2[PBKDF2] algorithm to hash the passwords. +In order to defeat password cracking PBKDF2 is a deliberately slow algorithm. +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. + +.Pbkdf2PasswordEncoder +==== +.Java +[source,java,role="primary"] +---- +// Create an encoder with all the defaults +Pbkdf2PasswordEncoder encoder = new Pbkdf2PasswordEncoder(); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +// Create an encoder with all the defaults +val encoder = Pbkdf2PasswordEncoder() +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +---- +==== + +[[authentication-password-storage-scrypt]] +== SCryptPasswordEncoder + +The `SCryptPasswordEncoder` implementation uses https://en.wikipedia.org/wiki/Scrypt[scrypt] algorithm to hash the passwords. +In order to defeat password cracking on custom hardware scrypt is a deliberately slow algorithm that requires large amounts of memory. +Like other adaptive one-way functions, it should be tuned to take about 1 second to verify a password on your system. + +.SCryptPasswordEncoder +==== +.Java +[source,java,role="primary"] +---- +// Create an encoder with all the defaults +SCryptPasswordEncoder encoder = new SCryptPasswordEncoder(); +String result = encoder.encode("myPassword"); +assertTrue(encoder.matches("myPassword", result)); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +// Create an encoder with all the defaults +val encoder = SCryptPasswordEncoder() +val result: String = encoder.encode("myPassword") +assertTrue(encoder.matches("myPassword", result)) +---- +==== + +[[authentication-password-storage-other]] +== 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. + +[[authentication-password-storage-configuration]] +== Password Storage Configuration + +Spring Security uses <> by default. +However, this can be customized by exposing a `PasswordEncoder` as a Spring bean. + + +If you are migrating from Spring Security 4.2.x you can revert to the previous behavior by exposing a `NoOpPasswordEncoder` bean. + +[WARNING] +==== +Reverting to `NoOpPasswordEncoder` is not considered to be secure. +You should instead migrate to using `DelegatingPasswordEncoder` to support secure password encoding. +==== + +.NoOpPasswordEncoder +==== +.Java +[source,java,role="primary"] +---- +@Bean +public static PasswordEncoder passwordEncoder() { +return NoOpPasswordEncoder.getInstance(); +} +---- + +.XML +[source,xml,role="secondary"] +---- + +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun passwordEncoder(): PasswordEncoder { +return NoOpPasswordEncoder.getInstance(); +} +---- +==== + +[NOTE] +==== +XML Configuration requires the `NoOpPasswordEncoder` bean name to be `passwordEncoder`. +==== + +[[authentication-change-password-configuration]] +== Change Password Configuration + +Most applications that allow a user to specify a password also require a feature for updating that password. + +https://w3c.github.io/webappsec-change-password-url/[A Well-Known URL for Changing Passwords] 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: + +.Default Change Password Endpoint +==== +.Java +[source,java,role="primary"] +---- +http +.passwordManagement(Customizer.withDefaults()) +---- + +.XML +[source,xml,role="secondary"] +---- + +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +http { +passwordManagement { } +} +---- +==== + +Then, when a password manager navigates to `/.well-known/change-password` then Spring Security will redirect your endpoint, `/change-password`. + +Or, if your endpoint is something other than `/change-password`, you can also specify that like so: + +.Change Password Endpoint +==== +.Java +[source,java,role="primary"] +---- +http +.passwordManagement((management) -> management +.changePasswordPage("/update-password") +) +---- + +.XML +[source,xml,role="secondary"] +---- + +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +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/features/authorization/index.md b/features/authorization/index.md new file mode 100644 index 0000000..351fd4c --- /dev/null +++ b/features/authorization/index.md @@ -0,0 +1,14 @@ +[[authorization]] += Authorization + +Spring Security provides comprehensive support for https://en.wikipedia.org/wiki/Authorization[authorization]. +Authorization is determining who is allowed to access a particular resource. +Spring Security provides https://en.wikipedia.org/wiki/Defense_in_depth_(computing)[defense in depth] by allowing for request based authorization and method based authorization. + +[[authorization-request]] +== Request Based Authorization + +Spring Security provides authorization based upon the request for both xref:servlet/authorization/index.adoc[Servlet] and WebFlux environments. + +[[authorization-method]] +== Method Based Authorization \ No newline at end of file diff --git a/features/exploits/http.md b/features/exploits/http.md new file mode 100644 index 0000000..e69de29 diff --git a/features/exploits/index.md b/features/exploits/index.md new file mode 100644 index 0000000..fa733b9 --- /dev/null +++ b/features/exploits/index.md @@ -0,0 +1,7 @@ +[[exploits]] += Protection Against Exploits +:page-section-summary-toc: 1 + +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. \ No newline at end of file diff --git a/features/index.md b/features/index.md new file mode 100644 index 0000000..49544b0 --- /dev/null +++ b/features/index.md @@ -0,0 +1,11 @@ +[[authentication]] += Authentication + +Spring Security provides comprehensive support for https://en.wikipedia.org/wiki/Authentication[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 xref:servlet/authentication/index.adoc#servlet-authentication[Servlet] and WebFlux for details on what is supported for each stack. \ No newline at end of file diff --git a/index.html b/index.html index 08e0ce7..538ae2b 100644 --- a/index.html +++ b/index.html @@ -29,6 +29,8 @@ /* --sidebar-nav-link-before-content-l1: "😀"; */ /* --sidebar-nav-link-before-content-l2: "💩"; */ --link-color: var(--theme-color); + --link-text-decoration--hover: underline; + --link-text-decoration: ''; } diff --git a/index.md b/index.md new file mode 100644 index 0000000..c552fe9 --- /dev/null +++ b/index.md @@ -0,0 +1,31 @@ +# Spring Security 文档和手册(中文) + +Spring Security 提供了一个 [验证(authentication)](features/authentication/index.md), [授权(authorization)](features/authorization/index.md),和[保护常见攻击](features/exploits/index.md) 的框架。 + +Spring security 是一个强大的,并且可以高度定制的身份验证和访问控制框架,能够同时支持 [imperative](servlet/index.md) 和 [reactive](reactive/index.md) 应用, Spring security 已经成为保护 Spring 应用实事上的标准。 + +有关完整的特性列表,请参考本参考指南中有关[特性(Features)](features/index.md) 部分的内容。 + +## 开始使用 +如果你已经开始准备对你的应用程序进行安全限制,请参考针对[servlet](servlet/getting-started.md) 和 [reactive](reactive/getting-started.md) 部分的内容。 + +?> 这里,提到了 2 个概念 servlet 和 reactive。Spring WebFlux 是 Spring Framework 5.0 中引入的新的响应式web框架。 +与Spring MVC不同,它不需要Servlet API,是完全异步且非阻塞的,并且通过 Reactor 项目实现了 Reactive Streams 规范。 +可以理解,servlet 和 reactive 是 2 个不同的处理方式,通常 MVC 模式是使用 servlet 的。reactive 是响应式,也可以说是反应式,主要特点就是异步处理,是基于 Spring WebFlux 框架的。 + +上面 2 个指南将会帮助你构建第一个使用 Spring Security 的应用程序。 + +如希望了解 Spring Security 是如何工作的,请参考 [Architecture](servlet/architecture.md) 部分的内容。 + +如你还有其他的一些内容,请访问 Spring Security 有关[社区(community)](community.md) 中的内容,通常你能够在这里获得不少的帮助。 + +### 社区和快速导航 + +在下面的列表格,我们列出了一些比较有用的 CWIKIUS 相关软件开发使用教程的导航,欢迎访问下面的链接获得更多的内容和参与讨论 + +| 网站名称 | URL | NOTE | +|----------------|--------------------------------------------------------|----------------------------| +| OSSEZ 社区 | [www.ossez.com](https://www.ossez.com/) | 开放社区,欢迎注册参与讨论 | +| WIKI 维基 | [www.cwiki.us](https://www.cwiki.us/) | 使用 Confluence 部署的 WIKI 知识库 | +| DOCS.OSSEZ.COM | [https://docs.ossez.com/#/](https://docs.ossez.com/#/) | 本手册的编译版本将会部署在这个链接上 | +| CN 博客 | [http://www.cwikius.cn/](http://www.cwikius.cn/) | CWIKIUS.CN 一个有独立思考和温度的清新站 | diff --git a/reactive/getting-started.md b/reactive/getting-started.md new file mode 100644 index 0000000..ed54fb9 --- /dev/null +++ b/reactive/getting-started.md @@ -0,0 +1,73 @@ +[[servlet-hello]] += Hello Spring Security + +This section covers the minimum setup for how to use Spring Security with Spring Boot. + +[NOTE] +==== +The completed application can be found {gh-samples-url}/servlet/spring-boot/java/hello-security[in our samples repository]. +For your convenience, you can download a minimal Spring Boot + Spring Security application by https://start.spring.io/starter.zip?type=maven-project&language=java&packaging=jar&jvmVersion=1.8&groupId=example&artifactId=hello-security&name=hello-security&description=Hello%20Security&packageName=example.hello-security&dependencies=web,security[clicking here]. +==== + +[[servlet-hello-dependencies]] +== Updating Dependencies + +The only step you need to do is update the dependencies by using xref:getting-spring-security.adoc#getting-maven-boot[Maven] or xref:getting-spring-security.adoc#getting-gradle-boot[Gradle]. + +[[servlet-hello-starting]] +== Starting Hello Spring Security Boot + +You can now https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-running-with-the-maven-plugin[run the Spring Boot application] by using the Maven Plugin's `run` goal. +The following example shows how to do so (and the beginning of the output from doing so): + +.Running Spring Boot Application +==== +[source,bash] +---- +$ ./mvn spring-boot:run +... +INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration : + +Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336 + +... +---- +==== + + +[[servlet-hello-auto-configuration]] +== Spring Boot Auto Configuration + +// FIXME: Link to relevant portions of documentation +// FIXME: Link to Spring Boot's Security Auto configuration classes +// FIXME: Add a links for what user's should do next + +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 +* https://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attack] prevention +* https://en.wikipedia.org/wiki/Session_fixation[Session Fixation] protection +* Security Header integration + ** https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security[HTTP Strict Transport Security] for secure requests + ** https://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx[X-Content-Type-Options] integration + ** Cache Control (can be overridden later by your application to allow caching of your static resources) + ** https://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx[X-XSS-Protection] integration + ** X-Frame-Options integration to help prevent https://en.wikipedia.org/wiki/Clickjacking[Clickjacking] +* Integrate with the following Servlet API methods: + ** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[`HttpServletRequest#getRemoteUser()`] +** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[`HttpServletRequest.html#getUserPrincipal()`] +** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[`HttpServletRequest.html#isUserInRole(java.lang.String)`] +** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)[`HttpServletRequest.html#login(java.lang.String, java.lang.String)`] + ** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[`HttpServletRequest.html#logout()`] diff --git a/reactive/index.md b/reactive/index.md new file mode 100644 index 0000000..e69de29 diff --git a/servlet/architecture.md b/servlet/architecture.md new file mode 100644 index 0000000..e69de29 diff --git a/servlet/getting-started.md b/servlet/getting-started.md new file mode 100644 index 0000000..708ea49 --- /dev/null +++ b/servlet/getting-started.md @@ -0,0 +1,79 @@ +[[getting-started]] += Getting Started with WebFlux Applications + +This section covers the minimum setup for how to use Spring Security with Spring Boot in a reactive application. + +[NOTE] +==== +The completed application can be found {gh-samples-url}/reactive/webflux/java/hello-security[in our samples repository]. +For your convenience, you can download a minimal Reactive Spring Boot + Spring Security application by https://start.spring.io/starter.zip?type=maven-project&language=java&packaging=jar&jvmVersion=1.8&groupId=example&artifactId=hello-security&name=hello-security&description=Hello%20Security&packageName=example.hello-security&dependencies=webflux,security[clicking here]. +==== + +[[dependencies]] +== Updating Dependencies + +You can add Spring Security to your Spring Boot project by adding `spring-boot-starter-security`. + +==== +.Maven +[source,xml,role="primary"] +---- + + org.springframework.boot + spring-boot-starter-security + +---- + +.Gradle +[source,groovy,role="secondary"] +---- + implementation 'org.springframework.boot:spring-boot-starter-security' +---- +==== + + +[[servlet-hello-starting]] +== Starting Hello Spring Security Boot + +You can now https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-running-with-the-maven-plugin[run the Spring Boot application] by using the Maven Plugin's `run` goal. +The following example shows how to do so (and the beginning of the output from doing so): + +.Running Spring Boot Application + +==== +.Maven +[source,bash,role="primary"] +---- +$ ./mvnw spring-boot:run +... +INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration : + +Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336 + +... +---- + +.Gradle +[source,bash,role="secondary"] +---- +$ ./gradlew bootRun +... +INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration : + +Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336 + +... +---- +==== + +[[authenticating]] +== Authenticating + +You can access the application at 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 and then confirming you wish to log out. + +[[auto-configuration]] +== 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. diff --git a/servlet/index.md b/servlet/index.md new file mode 100644 index 0000000..e69de29 diff --git a/spring-security/index.md b/spring-security/index.md deleted file mode 100644 index 0026c1f..0000000 --- a/spring-security/index.md +++ /dev/null @@ -1,17 +0,0 @@ -# Spring Security 文档和手册(中文) - -Spring Security is a framework that provides xref:features/authentication/index.adoc[authentication], xref:features/authorization/index.adoc[authorization], and xref:features/exploits/index.adoc[protection against common attacks]. -With first class support for securing both xref:servlet/index.adoc[imperative] and xref:reactive/index.adoc[reactive] applications, it is the de-facto standard for securing Spring-based applications. - -For a complete list of features, see the xref:features/index.adoc[Features] section of the reference. - -### 社区和快速导航 - -在下面的列表格,我们列出了一些比较有用的 CWIKIUS 相关软件开发使用教程的导航,欢迎访问下面的链接获得更多的内容和参与讨论 - -| 网站名称 | URL | NOTE | -|----------------|--------------------------------------------------------|----------------------------| -| OSSEZ 社区 | [www.ossez.com](https://www.ossez.com/) | 开放社区,欢迎注册参与讨论 | -| WIKI 维基 | [www.cwiki.us](https://www.cwiki.us/) | 使用 Confluence 部署的 WIKI 知识库 | -| DOCS.OSSEZ.COM | [https://docs.ossez.com/#/](https://docs.ossez.com/#/) | 本手册的编译版本将会部署在这个链接上 | -| CN 博客 | [http://www.cwikius.cn/](http://www.cwikius.cn/) | CWIKIUS.CN 一个有独立思考和温度的清新站 |